diff --git a/src/orbit/BunchDiagnostics/BunchTwissAnalysis.cc b/src/orbit/BunchDiagnostics/BunchTwissAnalysis.cc index defe117a..d24b20a7 100644 --- a/src/orbit/BunchDiagnostics/BunchTwissAnalysis.cc +++ b/src/orbit/BunchDiagnostics/BunchTwissAnalysis.cc @@ -1,526 +1,480 @@ #include "BunchTwissAnalysis.hh" -#include -#include #include -#include +#include +#include #include "ParticleMacroSize.hh" #include "SyncPart.hh" /** Constructor */ -BunchTwissAnalysis::BunchTwissAnalysis(): CppPyWrapper(NULL) +BunchTwissAnalysis::BunchTwissAnalysis() : CppPyWrapper(nullptr) { - avg_arr = (double* ) malloc (6*sizeof(double)); - corr_arr = (double* ) malloc (36*sizeof(double)); - - avg_arr_MPI = (double* ) malloc (6*sizeof(double)); - corr_arr_MPI = (double* ) malloc (36*sizeof(double)); + count = 0; + _order = 0; - for(int i = 0; i < 6; i++){ - avg_arr[i] = 0.; - avg_arr_MPI[i] = 0.; - } - - for(int i = 0; i < 6; i++){ - for(int j = 0; j < 6; j++){ - corr_arr[i+6*j] = 0.; - corr_arr_MPI[i+6*j] = 0.; - } - } - - count = 0; - _order = 0; - - total_macrosize = 0.; + total_macrosize = 0.; } /** Destructor */ -BunchTwissAnalysis::~BunchTwissAnalysis() -{ - free(avg_arr); - free(corr_arr); - free(avg_arr_MPI); - free(corr_arr_MPI); -} +BunchTwissAnalysis::~BunchTwissAnalysis() = default; /** Performs the Twiss analysis of the bunch */ -void BunchTwissAnalysis::analyzeBunch(Bunch* bunch){ - - //initialization - for(int i = 0; i < 6; i++){ - avg_arr[i] = 0.; - } - - for(int i = 0; i < 6; i++){ - for(int j = 0; j < 6; j++){ - corr_arr[i+6*j] = 0.; - } - } - count = 0; - total_macrosize = 0.; - - bunch->compress(); - double m_size = 0.; - int nParts = bunch->getSize(); - count += nParts; - double** part_coord_arr = bunch->coordArr(); - int has_msize = bunch->hasParticleAttributes("macrosize"); - if(has_msize > 0){ - ParticleMacroSize* macroSizeAttr = (ParticleMacroSize*) bunch->getParticleAttributes("macrosize"); - #pragma omp parallel for reduction(+:total_macrosize) reduction(+:avg_arr[:6]) reduction(+:corr_arr[:36]) - for(int ip = 0; ip < nParts; ip++){ - double const m_size = macroSizeAttr->macrosize(ip); - total_macrosize += m_size; - for(int i = 0; i < 6; i++){ - avg_arr[i] += m_size*part_coord_arr[ip][i]; - } - - for(int i = 0; i < 6; i++){ - for(int j = 0; j < i+1; j++){ - corr_arr[i+6*j] += m_size*part_coord_arr[ip][i]*part_coord_arr[ip][j]; - } - } - } - } else { - m_size = 1.0; - #pragma omp parallel for reduction(+:avg_arr[:6]) reduction(+:corr_arr[:36]) - for(int ip = 0; ip < nParts; ip++){ - for(int i = 0; i < 6; i++){ - avg_arr[i] += part_coord_arr[ip][i]; - } - - for(int i = 0; i < 6; i++){ - for(int j = 0; j < i+1; j++){ - corr_arr[i+6*j] += part_coord_arr[ip][i]*part_coord_arr[ip][j]; - } - } - } - total_macrosize += nParts*m_size; - for(int i = 0; i < 6; i++){ - avg_arr[i] *= m_size; - } - for(int i = 0; i < 6; i++){ - for(int j = 0; j < i+1; j++){ - corr_arr[i+6*j] *= m_size; - } - } - } - - int count_MPI = 0; - ORBIT_MPI_Allreduce(&count,&count_MPI,1,MPI_INT,MPI_SUM,bunch->getMPI_Comm_Local()->comm); - count = count_MPI; - - double total_macrosize_MPI = 0.; - ORBIT_MPI_Allreduce(&total_macrosize,&total_macrosize_MPI,1,MPI_DOUBLE,MPI_SUM,bunch->getMPI_Comm_Local()->comm); - total_macrosize = total_macrosize_MPI; - - ORBIT_MPI_Allreduce(avg_arr,avg_arr_MPI,6,MPI_DOUBLE,MPI_SUM,bunch->getMPI_Comm_Local()->comm); - ORBIT_MPI_Allreduce(corr_arr,corr_arr_MPI,36,MPI_DOUBLE,MPI_SUM,bunch->getMPI_Comm_Local()->comm); - - if(fabs(total_macrosize) > 0.){ - for(int i = 0; i < 6; i++){ - avg_arr[i] = avg_arr_MPI[i]/total_macrosize; - } - - for(int i = 0; i < 6; i++){ - for(int j = 0; j < i+1; j++){ - corr_arr[i+6*j] = corr_arr_MPI[i+6*j]/total_macrosize; - corr_arr[j+6*i] = corr_arr_MPI[i+6*j]/total_macrosize; - } - } - } - - SyncPart* syncPart = bunch->getSyncPart(); - - bunch_momentum = syncPart->getMomentum(); - bunch_beta = syncPart->getBeta(); - bunch_gamma = syncPart->getGamma(); - bunch_kinenergy = syncPart->getEnergy(); - bunch_mass = syncPart->getMass(); +void BunchTwissAnalysis::analyzeBunch(Bunch* bunch) +{ + //initialization + for (int i = 0; i < 6; i++) + { + avg_arr[i] = 0.; + } + + for (int i = 0; i < 6; i++) + { + for (int j = 0; j < 6; j++) + { + corr_arr[i + 6 * j] = 0.; + } + } + count = 0; + total_macrosize = 0.; + + bunch->compress(); + double m_size = 0.; + int nParts = bunch->getSize(); + count += nParts; + double** part_coord_arr = bunch->coordArr(); + int has_msize = bunch->hasParticleAttributes("macrosize"); + if (has_msize > 0) + { + ParticleMacroSize* macroSizeAttr = + (ParticleMacroSize*)bunch->getParticleAttributes("macrosize"); +#pragma omp parallel for reduction(+ : total_macrosize) reduction(+ : avg_arr[ : 6]) \ + reduction(+ : corr_arr[ : 36]) + for (int ip = 0; ip < nParts; ip++) + { + double const m_size = macroSizeAttr->macrosize(ip); + total_macrosize += m_size; + for (int i = 0; i < 6; i++) + { + avg_arr[i] += m_size * part_coord_arr[ip][i]; + } + + for (int i = 0; i < 6; i++) + { + for (int j = 0; j < i + 1; j++) + { + corr_arr[i + 6 * j] += m_size * part_coord_arr[ip][i] * part_coord_arr[ip][j]; + } + } + } + } + else + { + m_size = 1.0; +#pragma omp parallel for reduction(+ : avg_arr[ : 6]) reduction(+ : corr_arr[ : 36]) + for (int ip = 0; ip < nParts; ip++) + { + for (int i = 0; i < 6; i++) + { + avg_arr[i] += part_coord_arr[ip][i]; + } + + for (int i = 0; i < 6; i++) + { + for (int j = 0; j < i + 1; j++) + { + corr_arr[i + 6 * j] += part_coord_arr[ip][i] * part_coord_arr[ip][j]; + } + } + } + total_macrosize += nParts * m_size; + for (int i = 0; i < 6; i++) + { + avg_arr[i] *= m_size; + } + for (int i = 0; i < 6; i++) + { + for (int j = 0; j < i + 1; j++) + { + corr_arr[i + 6 * j] *= m_size; + } + } + } + + ORBIT_MPI_Allreduce(ORBIT_MPI_IN_PLACE, &count, 1, MPI_INT, MPI_SUM, + bunch->getMPI_Comm_Local()->comm); + ORBIT_MPI_Allreduce(ORBIT_MPI_IN_PLACE, &total_macrosize, 1, MPI_DOUBLE, MPI_SUM, + bunch->getMPI_Comm_Local()->comm); + ORBIT_MPI_Allreduce(ORBIT_MPI_IN_PLACE, avg_arr, 6, MPI_DOUBLE, MPI_SUM, + bunch->getMPI_Comm_Local()->comm); + ORBIT_MPI_Allreduce(ORBIT_MPI_IN_PLACE, corr_arr, 36, MPI_DOUBLE, MPI_SUM, + bunch->getMPI_Comm_Local()->comm); + + if (std::fabs(total_macrosize) > 0.) + { + for (int i = 0; i < 6; i++) + { + avg_arr[i] /= total_macrosize; + } + + for (int i = 0; i < 6; i++) + { + for (int j = 0; j < i + 1; j++) + { + corr_arr[i + 6 * j] /= total_macrosize; + corr_arr[j + 6 * i] = corr_arr[i + 6 * j]; + } + } + } + + SyncPart* syncPart = bunch->getSyncPart(); + + bunch_momentum = syncPart->getMomentum(); + bunch_beta = syncPart->getBeta(); + bunch_gamma = syncPart->getGamma(); + bunch_kinenergy = syncPart->getEnergy(); + bunch_mass = syncPart->getMass(); } - /** Performs the bunch moments computations */ -void BunchTwissAnalysis::computeBunchMoments(Bunch* bunch, int order, int dispersionflag, int emitnormflag){ - _order = order; - int i = 0; - int j = 0; - - bunch->compress(); - - double dispterm = 0.; - double xbetaterm = 0.; - double ybetaterm = 0.; - double m_size = 0.; - double xAvg = 0.; - double yAvg = 0.; - total_macrosize = 0; //Total macrosize (can different than number of macroparticles if m_size is specified) - int nParts = bunch->getSize(); - double total_macrosize_MPI = 0.; - double** part_coord_arr = bunch->coordArr(); - int has_msize = bunch->hasParticleAttributes("macrosize"); - - analyzeBunch(bunch); - - if(dispterm > 0){ - if(has_msize > 0){ - ParticleMacroSize* macroSizeAttr = (ParticleMacroSize*) bunch->getParticleAttributes("macrosize"); - double m_size = 0.; - for(int ip = 0; ip < nParts; ip++){ - m_size = macroSizeAttr->macrosize(ip); - total_macrosize += m_size; - if (dispersionflag > 0) { - dispterm = getDispersion(0) * part_coord_arr[ip][5] / (bunch_kinenergy + bunch_mass) / (bunch_beta*bunch_beta); - } - xAvg += m_size*(part_coord_arr[ip][0] - dispterm); - } - } else { - m_size = 1.0; - for(int ip = 0; ip < nParts; ip++){ - if (dispersionflag > 0) { - dispterm = getDispersion(0) * part_coord_arr[ip][5] / (bunch_kinenergy + bunch_mass) / (bunch_beta*bunch_beta); - } - xAvg += part_coord_arr[ip][0] - dispterm; - } - total_macrosize += nParts*m_size; - xAvg *= m_size; - } - - - ORBIT_MPI_Allreduce(&total_macrosize,&total_macrosize_MPI,1,MPI_DOUBLE,MPI_SUM,bunch->getMPI_Comm_Local()->comm); - total_macrosize = total_macrosize_MPI; - - double xAvg_MPI = 0; - ORBIT_MPI_Allreduce(&xAvg,&xAvg_MPI,1,MPI_DOUBLE,MPI_SUM,bunch->getMPI_Comm_Local()->comm); - if(fabs(total_macrosize) > 0.){ - xAvg = xAvg_MPI/total_macrosize; - } - } - else{ - xAvg = getAverage(0); - } - yAvg = getAverage(2); - - double momX [order+1]; - double momY [order+1]; - - momentXY = new double*[order+1]; - - for(i=0; i < order+1; i++) - momentXY[i] = new double[order+1]; - - //initialization - for (int n=0; n < _order+1;n++){ - momX[n] = 0.; - momY[n] = 0.; - } - - for (int n=0; n<_order+1;n++) - for (int m=0; m<_order+1;m++) - momentXY[n][m]=0.; - - momX[0]=1.0; - momY[0]=1.0; - - bunch->compress(); - total_macrosize = 0.; - if(has_msize > 0){ - ParticleMacroSize* macroSizeAttr = (ParticleMacroSize*) bunch->getParticleAttributes("macrosize"); - double m_size = 0.; - for(int ip = 0; ip < nParts; ip++){ - - m_size = macroSizeAttr->macrosize(ip); - total_macrosize += m_size; - - if (dispersionflag > 0) { - dispterm = getDispersion(0) * part_coord_arr[ip][5] / (bunch_kinenergy + bunch_mass) / (bunch_beta*bunch_beta); - } - - if(emitnormflag > 0){ - xbetaterm = sqrt(getBeta(0)*getEmittance(0)); - ybetaterm = sqrt(getBeta(1)*getEmittance(1)); - } - else{ - xbetaterm = sqrt(getBeta(0)); - ybetaterm = sqrt(getBeta(1)); - } - - for(i = 0; i < _order; i++) - momX[i+1] = momX[i]*m_size*((part_coord_arr[ip][0] - dispterm) - xAvg); - - for(i = 0; i< _order; i++) - momY[i+1] = momY[i]*m_size*(part_coord_arr[ip][2] - yAvg); - - for(j = 0; j<_order; j++) - for(i=0 ; i< _order+1-j; i++){ - momentXY[i][j] += momX[i]/pow(xbetaterm, double(i)) * momY[j]/pow(ybetaterm, double(j)); - momentXY[i][j] += momX[i] * momY[j]; - } - } - - } else { - m_size = 1.0; - for(int ip = 0; ip < nParts; ip++){ - - if (dispersionflag > 0) { - dispterm = getDispersion(0) * part_coord_arr[ip][5] / (bunch_kinenergy + bunch_mass) / (bunch_beta*bunch_beta); - } - - if(emitnormflag > 0){ - xbetaterm = sqrt(getBeta(0)*getEmittance(0)); - ybetaterm = sqrt(getBeta(1)*getEmittance(1)); - } - else{ - xbetaterm = sqrt(getBeta(0)); - ybetaterm = sqrt(getBeta(1)); - } - - for(i = 0; i < _order; i++) - momX[i+1] = momX[i]*((part_coord_arr[ip][0] - dispterm) - xAvg); - - for(i = 0; i< _order; i++) - momY[i+1] = momY[i]*(part_coord_arr[ip][2] - yAvg); - - for(j = 0; j<_order; j++) - for(i=0 ; i< _order+1-j; i++) - momentXY[i][j] += momX[i]/pow(xbetaterm, double(i)) * momY[j]/pow(ybetaterm, double(j)); - momentXY[i][j] += momX[i] * momY[j]; - - } - - total_macrosize += nParts*m_size; - - } - - ORBIT_MPI_Allreduce(&total_macrosize,&total_macrosize_MPI,1,MPI_DOUBLE,MPI_SUM,bunch->getMPI_Comm_Local()->comm); - total_macrosize = total_macrosize_MPI; - - //if( nMPIsize_ > 1){ - double* buff_0 = (double *) malloc (sizeof(double)*(_order+1)*(_order+1)); - double* buff_1 = (double *) malloc (sizeof(double)*(_order+1)*(_order+1)); - int count = 0; - for(j=0; j<_order+1; j++){ - for(i=0 ; i< _order+1-j; i++){ - buff_0[count]= momentXY[i][j]; - count++; - } - } - - //MPI_Allreduce(buff_0, buff_1, count, MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD); - - ORBIT_MPI_Allreduce(buff_0, buff_1, count, MPI_DOUBLE, MPI_SUM, bunch->getMPI_Comm_Local()->comm); - - count = 0; - for(j=0; j<_order+1; j++){ - for(i=0 ; i< _order+1-j; i++){ - momentXY[i][j] = buff_1[count]; - count++; - } - } - - free(buff_0); - free(buff_1); - - if(fabs(total_macrosize) > 0.){ - for(i=0; i< _order+1; i++) - for(j=0; j< _order+1-i ; j++) - momentXY[i][j] /= total_macrosize; - } - - momentXY[0][0] = 1.; // 0th moment - momentXY[1][0] = xAvg; - momentXY[0][1] = yAvg; - -//return momentXY; - +void BunchTwissAnalysis::computeBunchMoments(Bunch* bunch, int order, int dispersionflag, + int emitnormflag) +{ + _order = order; + + analyzeBunch(bunch); + + const double dispersionCoeff = + dispersionflag > 0 + ? getDispersion(0) / ((bunch_kinenergy + bunch_mass) * bunch_beta * bunch_beta) + : 0.0; + // The corrected centroid follows directly from the weighted coordinate means. + const double xAvg = getAverage(0) - dispersionCoeff * getAverage(5); + const double yAvg = getAverage(2); + const double xbetaterm = std::sqrt(getBeta(0) * (emitnormflag > 0 ? getEmittance(0) : 1.0)); + const double ybetaterm = std::sqrt(getBeta(1) * (emitnormflag > 0 ? getEmittance(1) : 1.0)); + + const int stride = _order + 1; + momentXY.assign(static_cast(stride) * stride, 0.0); + if (_order <= 2) + { + // analyzeBunch() already reduced all statistics needed for these moments. + momentXY[0] = 1.; + if (_order >= 1) + { + momentXY[1] = xAvg; + momentXY[stride] = yAvg; + } + if (_order == 2 && std::fabs(total_macrosize) > 0.) + { + momentXY[2] = + (getCorrelation(0, 0) - 2. * dispersionCoeff * getCorrelation(0, 5) + + dispersionCoeff * dispersionCoeff * getCorrelation(5, 5)) / + (xbetaterm * xbetaterm); + momentXY[stride + 1] = + (getCorrelation(0, 2) - dispersionCoeff * getCorrelation(2, 5)) / + (xbetaterm * ybetaterm); + momentXY[2 * stride] = getCorrelation(2, 2) / (ybetaterm * ybetaterm); + } + return; + } + + const int nParts = bunch->getSize(); + double** part_coord_arr = bunch->coordArr(); + ParticleMacroSize* weights = + bunch->hasParticleAttributes("macrosize") > 0 + ? static_cast(bunch->getParticleAttributes("macrosize")) + : nullptr; + total_macrosize = 0.; +#pragma omp parallel reduction(+ : total_macrosize) + { + std::vector momX(stride); + std::vector momY(stride); + std::vector localMoments(static_cast(stride) * stride, 0.0); + momX[0] = momY[0] = 1.0; + +#pragma omp for schedule(static) + for (int ip = 0; ip < nParts; ip++) + { + const double w = weights ? weights->macrosize(ip) : 1.0; + total_macrosize += w; + const double dx = + (part_coord_arr[ip][0] - dispersionCoeff * part_coord_arr[ip][5] - xAvg) / + xbetaterm; + const double dy = (part_coord_arr[ip][2] - yAvg) / ybetaterm; + + for (int k = 0; k < _order; k++) + { + momX[k + 1] = momX[k] * dx; + momY[k + 1] = momY[k] * dy; + } + for (int j = 0; j <= _order; j++) + { + for (int i = 0; i <= _order - j; i++) + { + localMoments[static_cast(j) * stride + i] += w * momX[i] * momY[j]; + } + } + } + +// Merge once per thread rather than synchronizing per particle. +#pragma omp critical(BunchTwissAnalysis_moments_merge) + { + for (int j = 0; j <= _order; j++) + { + for (int i = 0; i <= _order - j; i++) + { + momentXY[static_cast(j) * stride + i] += + localMoments[static_cast(j) * stride + i]; + } + } + } + } + + ORBIT_MPI_Allreduce(ORBIT_MPI_IN_PLACE, &total_macrosize, 1, MPI_DOUBLE, MPI_SUM, + bunch->getMPI_Comm_Local()->comm); + + ORBIT_MPI_Allreduce(ORBIT_MPI_IN_PLACE, momentXY.data(), static_cast(momentXY.size()), + MPI_DOUBLE, MPI_SUM, bunch->getMPI_Comm_Local()->comm); + + if (std::fabs(total_macrosize) > 0.) + { + for (double& moment : momentXY) + { + moment /= total_macrosize; + } + } + + momentXY[0] = 1.; // 0th moment + if (_order >= 1) + { + momentXY[1] = xAvg; + momentXY[stride] = yAvg; + } } -double BunchTwissAnalysis::getCorrelation(int ic, int jc){ - if(ic < 0 || ic > 5 || jc < 0 || jc >5) return 0.; - return (corr_arr[ic+6*jc] - avg_arr[ic]* avg_arr[jc]); +double BunchTwissAnalysis::getCorrelation(int ic, int jc) const +{ + if (ic < 0 || ic > 5 || jc < 0 || jc > 5) + return 0.; + return (corr_arr[ic + 6 * jc] - avg_arr[ic] * avg_arr[jc]); } /** Returns the XY moment of the beam */ -double BunchTwissAnalysis::getBunchMoment(int i, int j){ - if(i < 0 || i > _order || j < 0 || j > _order) return 0.; - return momentXY[i][j]; +double BunchTwissAnalysis::getBunchMoment(int i, int j) const +{ + if (i < 0 || i > _order || j < 0 || j > _order || momentXY.empty()) + return 0.; + return momentXY[static_cast(j) * (_order + 1) + i]; } /** Returns the average value for coordinate with index ic */ -double BunchTwissAnalysis::getAverage(int ic){ - if(ic < 0 || ic > 5 ) return 0.; - return avg_arr[ic]; +double BunchTwissAnalysis::getAverage(int ic) const +{ + if (ic < 0 || ic > 5) + return 0.; + return avg_arr[ic]; } /** Returns the total number of analysed macroparticles */ -int BunchTwissAnalysis::getGlobalCount(){ - return count; +int BunchTwissAnalysis::getGlobalCount() const +{ + return count; } /** Returns the total macrosize */ -double BunchTwissAnalysis::getGlobalMacrosize(){ - return total_macrosize; +double BunchTwissAnalysis::getGlobalMacrosize() const +{ + return total_macrosize; } /** Returns the emittance for index 0,1,2 - x,y,z planes. */ -double BunchTwissAnalysis::getEmittance(int ic) +double BunchTwissAnalysis::getEmittance(int ic) const { - // for x and y the pure betatron emittance is computed (subtracting the dispersive contribution) - if(ic < 0 || ic > 2 ) return 0.; - double x2_avg = fabs(this->getCorrelation(2*ic,2*ic)); - double xp2_avg = fabs(this->getCorrelation(2*ic+1,2*ic+1)); - double x_xp_avg = this->getCorrelation(2*ic,2*ic+1); - double x_dE_avg = this->getCorrelation(2*ic,5); - double xp_dE_avg = this->getCorrelation(2*ic+1,5); - double dE2_avg = fabs(this->getCorrelation(5,5)); - double emitt_rms; - if(ic==2 or dE2_avg==0){ - emitt_rms = sqrt(fabs(x2_avg*xp2_avg - x_xp_avg*x_xp_avg)); - } else { - emitt_rms = sqrt(fabs( (x2_avg - x_dE_avg*x_dE_avg/dE2_avg) * (xp2_avg - xp_dE_avg*xp_dE_avg/dE2_avg) - - (x_xp_avg - x_dE_avg*xp_dE_avg/dE2_avg) * (x_xp_avg - x_dE_avg*xp_dE_avg/dE2_avg) )); - } - return emitt_rms; + // for x and y the pure betatron emittance is computed (subtracting the dispersive contribution) + if (ic < 0 || ic > 2) + return 0.; + double x2_avg = std::fabs(this->getCorrelation(2 * ic, 2 * ic)); + double xp2_avg = std::fabs(this->getCorrelation(2 * ic + 1, 2 * ic + 1)); + double x_xp_avg = this->getCorrelation(2 * ic, 2 * ic + 1); + double x_dE_avg = this->getCorrelation(2 * ic, 5); + double xp_dE_avg = this->getCorrelation(2 * ic + 1, 5); + double dE2_avg = std::fabs(this->getCorrelation(5, 5)); + double emitt_rms; + if (ic == 2 or dE2_avg == 0) + { + emitt_rms = std::sqrt(std::fabs(x2_avg * xp2_avg - x_xp_avg * x_xp_avg)); + } + else + { + emitt_rms = std::sqrt(std::fabs((x2_avg - x_dE_avg * x_dE_avg / dE2_avg) * + (xp2_avg - xp_dE_avg * xp_dE_avg / dE2_avg) - + (x_xp_avg - x_dE_avg * xp_dE_avg / dE2_avg) * + (x_xp_avg - x_dE_avg * xp_dE_avg / dE2_avg))); + } + return emitt_rms; } /** Returns the normalized betatron emittance for index 0,1 - x,y planes. */ -double BunchTwissAnalysis::getEmittanceNormalized(int ic) +double BunchTwissAnalysis::getEmittanceNormalized(int ic) const { - if(ic < 0 || ic > 2 ) return 0.; - if(ic == 2) return this->getEmittance(ic); - return this->getEmittance(ic) * bunch_gamma * bunch_beta; + if (ic < 0 || ic > 2) + return 0.; + if (ic == 2) + return this->getEmittance(ic); + return this->getEmittance(ic) * bunch_gamma * bunch_beta; } /** Returns Twiss alpha (without dispersive part for x,y) for index 0,1,2 - x,y,z planes.*/ -double BunchTwissAnalysis::getAlpha(int ic) +double BunchTwissAnalysis::getAlpha(int ic) const { - if(ic < 0 || ic > 2 ) return 0.; - double x_xp_avg = this->getCorrelation(2*ic,2*ic+1); - double alpha; - if(ic == 2){ - alpha = - x_xp_avg/this->getEmittance(ic); - } else { - double x_dE_avg = this->getCorrelation(2*ic, 5); - double xp_dE_avg = this->getCorrelation(2*ic+1, 5); - double dE2_avg = fabs(this->getCorrelation(5, 5)); - alpha = -(x_xp_avg - x_dE_avg * xp_dE_avg / dE2_avg) / this->getEmittance(ic); - } - return alpha; + if (ic < 0 || ic > 2) + return 0.; + double x_xp_avg = this->getCorrelation(2 * ic, 2 * ic + 1); + double alpha; + if (ic == 2) + { + alpha = -x_xp_avg / this->getEmittance(ic); + } + else + { + double x_dE_avg = this->getCorrelation(2 * ic, 5); + double xp_dE_avg = this->getCorrelation(2 * ic + 1, 5); + double dE2_avg = std::fabs(this->getCorrelation(5, 5)); + alpha = -(x_xp_avg - x_dE_avg * xp_dE_avg / dE2_avg) / this->getEmittance(ic); + } + return alpha; } /** Returns Twiss beta (without dispersive part for x,y) for index 0,1,2 - x,y,z planes.*/ -double BunchTwissAnalysis::getBeta(int ic) +double BunchTwissAnalysis::getBeta(int ic) const { - if(ic < 0 || ic > 2 ) return 0.; - double x2_avg = fabs(this->getCorrelation(2*ic,2*ic)); - - double beta; - if(ic == 2){ - beta = x2_avg/this->getEmittance(ic); - } else { - double x_dE_avg = this->getCorrelation(2*ic, 5); - double dE2_avg = fabs(this->getCorrelation(5, 5)); - beta = (x2_avg - x_dE_avg * x_dE_avg / dE2_avg) / this->getEmittance(ic); - } - return beta; + if (ic < 0 || ic > 2) + return 0.; + double x2_avg = std::fabs(this->getCorrelation(2 * ic, 2 * ic)); + + double beta; + if (ic == 2) + { + beta = x2_avg / this->getEmittance(ic); + } + else + { + double x_dE_avg = this->getCorrelation(2 * ic, 5); + double dE2_avg = std::fabs(this->getCorrelation(5, 5)); + beta = (x2_avg - x_dE_avg * x_dE_avg / dE2_avg) / this->getEmittance(ic); + } + return beta; } /** Returns Twiss gamma (without dispersive part for x,y) for index 0,1,2 - x,y,z planes.*/ -double BunchTwissAnalysis::getGamma(int ic) +double BunchTwissAnalysis::getGamma(int ic) const { - if(ic < 0 || ic > 2 ) return 0.; - double xp2_avg = fabs(this->getCorrelation(2*ic+1,2*ic+1)); - double gamma; - if(ic == 2){ - gamma = xp2_avg/this->getEmittance(ic); - } else { - double xp_dE_avg = this->getCorrelation(2*ic+1, 5); - double dE2_avg = fabs(this->getCorrelation(5, 5)); - gamma = (xp2_avg - xp_dE_avg * xp_dE_avg / dE2_avg) / this->getEmittance(ic); - } - return gamma; + if (ic < 0 || ic > 2) + return 0.; + double xp2_avg = std::fabs(this->getCorrelation(2 * ic + 1, 2 * ic + 1)); + double gamma; + if (ic == 2) + { + gamma = xp2_avg / this->getEmittance(ic); + } + else + { + double xp_dE_avg = this->getCorrelation(2 * ic + 1, 5); + double dE2_avg = std::fabs(this->getCorrelation(5, 5)); + gamma = (xp2_avg - xp_dE_avg * xp_dE_avg / dE2_avg) / this->getEmittance(ic); + } + return gamma; } /** Returns Twiss dispersion function for index 0,1 - x,y planes.*/ -double BunchTwissAnalysis::getDispersion(int ic) +double BunchTwissAnalysis::getDispersion(int ic) const { - if(ic < 0 || ic > 1 ) return 0.; - double x_dE_avg = this->getCorrelation(2*ic, 5); - double dE2_avg = fabs(this->getCorrelation(5, 5)); - double dispersion = x_dE_avg/dE2_avg * bunch_momentum * bunch_beta; - return dispersion; + if (ic < 0 || ic > 1) + return 0.; + double x_dE_avg = this->getCorrelation(2 * ic, 5); + double dE2_avg = std::fabs(this->getCorrelation(5, 5)); + double dispersion = x_dE_avg / dE2_avg * bunch_momentum * bunch_beta; + return dispersion; } /** Returns Twiss dispersion_prime function for index 0,1 - x,y planes.*/ -double BunchTwissAnalysis::getDispersionDerivative(int ic) +double BunchTwissAnalysis::getDispersionDerivative(int ic) const { - if(ic < 0 || ic > 1 ) return 0.; - double xp_dE_avg = this->getCorrelation(2*ic+1, 5); - double dE2_avg = fabs(this->getCorrelation(5, 5)); - double dispersion_prime = xp_dE_avg/dE2_avg * bunch_momentum * bunch_beta; - return dispersion_prime; + if (ic < 0 || ic > 1) + return 0.; + double xp_dE_avg = this->getCorrelation(2 * ic + 1, 5); + double dE2_avg = std::fabs(this->getCorrelation(5, 5)); + double dispersion_prime = xp_dE_avg / dE2_avg * bunch_momentum * bunch_beta; + return dispersion_prime; } /** Returns the effective emittance for index 0,1 - x,y planes. */ -double BunchTwissAnalysis::getEffectiveEmittance(int ic) +double BunchTwissAnalysis::getEffectiveEmittance(int ic) const { - if(ic < 0 || ic > 2 ) return 0.; - double x_avg = this->getAverage(2*ic); - double xp_avg = this->getAverage(2*ic+1); - double x2_avg = fabs(this->getCorrelation(2*ic,2*ic)); - double xp2_avg = fabs(this->getCorrelation(2*ic+1,2*ic+1)); - double x_xp_avg = this->getCorrelation(2*ic,2*ic+1); - double emitt_rms = sqrt(fabs(x2_avg*xp2_avg - x_xp_avg*x_xp_avg)); - return emitt_rms; + if (ic < 0 || ic > 2) + return 0.; + double x_avg = this->getAverage(2 * ic); + double xp_avg = this->getAverage(2 * ic + 1); + double x2_avg = std::fabs(this->getCorrelation(2 * ic, 2 * ic)); + double xp2_avg = std::fabs(this->getCorrelation(2 * ic + 1, 2 * ic + 1)); + double x_xp_avg = this->getCorrelation(2 * ic, 2 * ic + 1); + double emitt_rms = std::sqrt(std::fabs(x2_avg * xp2_avg - x_xp_avg * x_xp_avg)); + return emitt_rms; } /** Returns effective Twiss alpha for index 0,1 - x,y planes.*/ -double BunchTwissAnalysis::getEffectiveAlpha(int ic) +double BunchTwissAnalysis::getEffectiveAlpha(int ic) const { - if(ic < 0 || ic > 2 ) return 0.; - double x_avg = this->getAverage(2*ic); - double xp_avg = this->getAverage(2*ic+1); - double x2_avg = fabs(this->getCorrelation(2*ic,2*ic)); - double xp2_avg = fabs(this->getCorrelation(2*ic+1,2*ic+1)); - double x_xp_avg = this->getCorrelation(2*ic,2*ic+1); - double emitt2_rms = x2_avg*xp2_avg - x_xp_avg*x_xp_avg; - if( emitt2_rms <= 0.) return 0.; - double emitt_rms = sqrt(emitt2_rms); - double alpha = - x_xp_avg/emitt_rms; - return alpha; + if (ic < 0 || ic > 2) + return 0.; + double x_avg = this->getAverage(2 * ic); + double xp_avg = this->getAverage(2 * ic + 1); + double x2_avg = std::fabs(this->getCorrelation(2 * ic, 2 * ic)); + double xp2_avg = std::fabs(this->getCorrelation(2 * ic + 1, 2 * ic + 1)); + double x_xp_avg = this->getCorrelation(2 * ic, 2 * ic + 1); + double emitt2_rms = x2_avg * xp2_avg - x_xp_avg * x_xp_avg; + if (emitt2_rms <= 0.) + return 0.; + double emitt_rms = std::sqrt(emitt2_rms); + double alpha = -x_xp_avg / emitt_rms; + return alpha; } /** Returns effective Twiss beta for index 0,1 - x,y planes.*/ -double BunchTwissAnalysis::getEffectiveBeta(int ic) +double BunchTwissAnalysis::getEffectiveBeta(int ic) const { - if(ic < 0 || ic > 2 ) return 0.; - double x_avg = this->getAverage(2*ic); - double xp_avg = this->getAverage(2*ic+1); - double x2_avg = fabs(this->getCorrelation(2*ic,2*ic)); - double xp2_avg = fabs(this->getCorrelation(2*ic+1,2*ic+1)); - double x_xp_avg = this->getCorrelation(2*ic,2*ic+1); - double emitt2_rms = x2_avg*xp2_avg - x_xp_avg*x_xp_avg; - if( emitt2_rms <= 0.) return 0.; - double emitt_rms = sqrt(emitt2_rms); - double beta = x2_avg/emitt_rms; - return beta; + if (ic < 0 || ic > 2) + return 0.; + double x_avg = this->getAverage(2 * ic); + double xp_avg = this->getAverage(2 * ic + 1); + double x2_avg = std::fabs(this->getCorrelation(2 * ic, 2 * ic)); + double xp2_avg = std::fabs(this->getCorrelation(2 * ic + 1, 2 * ic + 1)); + double x_xp_avg = this->getCorrelation(2 * ic, 2 * ic + 1); + double emitt2_rms = x2_avg * xp2_avg - x_xp_avg * x_xp_avg; + if (emitt2_rms <= 0.) + return 0.; + double emitt_rms = std::sqrt(emitt2_rms); + double beta = x2_avg / emitt_rms; + return beta; } /** Returns effective Twiss gamma for index 0,1 - x,y planes.*/ -double BunchTwissAnalysis::getEffectiveGamma(int ic) +double BunchTwissAnalysis::getEffectiveGamma(int ic) const { - if(ic < 0 || ic > 2 ) return 0.; - double x_avg = this->getAverage(2*ic); - double xp_avg = this->getAverage(2*ic+1); - double x2_avg = fabs(this->getCorrelation(2*ic,2*ic)); - double xp2_avg = fabs(this->getCorrelation(2*ic+1,2*ic+1)); - double x_xp_avg = this->getCorrelation(2*ic,2*ic+1); - double emitt2_rms = x2_avg*xp2_avg - x_xp_avg*x_xp_avg; - if( emitt2_rms <= 0.) return DBL_MAX; - double emitt_rms = sqrt(emitt2_rms); - double gamma = xp2_avg/emitt_rms; - return gamma; + if (ic < 0 || ic > 2) + return 0.; + double x_avg = this->getAverage(2 * ic); + double xp_avg = this->getAverage(2 * ic + 1); + double x2_avg = std::fabs(this->getCorrelation(2 * ic, 2 * ic)); + double xp2_avg = std::fabs(this->getCorrelation(2 * ic + 1, 2 * ic + 1)); + double x_xp_avg = this->getCorrelation(2 * ic, 2 * ic + 1); + double emitt2_rms = x2_avg * xp2_avg - x_xp_avg * x_xp_avg; + if (emitt2_rms <= 0.) + return DBL_MAX; + double emitt_rms = std::sqrt(emitt2_rms); + double gamma = xp2_avg / emitt_rms; + return gamma; } diff --git a/src/orbit/BunchDiagnostics/BunchTwissAnalysis.hh b/src/orbit/BunchDiagnostics/BunchTwissAnalysis.hh index deaa20ee..2e290402 100644 --- a/src/orbit/BunchDiagnostics/BunchTwissAnalysis.hh +++ b/src/orbit/BunchDiagnostics/BunchTwissAnalysis.hh @@ -6,7 +6,8 @@ #include "Bunch.hh" -using namespace std; +#include + /** The BunchTwissAnalysis class calculates the average of 6D coordinates and they correlations. @@ -36,55 +37,55 @@ class BunchTwissAnalysis: public OrbitUtils::CppPyWrapper * @param jc Index of the second component (y). * @return The centered correlation value as a double. */ - double getCorrelation(int ic, int jc); + double getCorrelation(int ic, int jc) const; /** Returns the average value for coordinate with index ic */ - double getAverage(int ic); + double getAverage(int ic) const; /** Returns the total number of analysed macroparticles */ - int getGlobalCount(); + int getGlobalCount() const; /** Returns the total macrosize */ - double getGlobalMacrosize(); + double getGlobalMacrosize() const; /** Returns the emittance for index 0,1,2 - x,y,z planes. */ - double getEffectiveEmittance(int ic); + double getEffectiveEmittance(int ic) const; /** Returns Twiss alpha for index 0,1,2 - x,y,z planes.*/ - double getEffectiveAlpha(int ic); + double getEffectiveAlpha(int ic) const; /** Returns Twiss beta for index 0,1,2 - x,y,z planes.*/ - double getEffectiveBeta(int ic); + double getEffectiveBeta(int ic) const; /** Returns Twiss gamma for index 0,1,2 - x,y,z planes.*/ - double getEffectiveGamma(int ic); + double getEffectiveGamma(int ic) const; /** Returns the pure betatron emittance for index 0,1 - x,y planes. */ - double getEmittance(int ic); + double getEmittance(int ic) const; /** Returns the normalized pure betatron emittance for index 0,1 - x,y planes. */ - double getEmittanceNormalized(int ic); + double getEmittanceNormalized(int ic) const; /** Returns Twiss alpha without dispersive part for index 0,1 - x,y planes.*/ - double getAlpha(int ic); + double getAlpha(int ic) const; /** Returns Twiss beta without dispersive part for index 0,1 - x,y planes.*/ - double getBeta(int ic); + double getBeta(int ic) const; /** Returns Twiss gamma without dispersive part for index 0,1 - x,y planes.*/ - double getGamma(int ic); + double getGamma(int ic) const; /** Returns Twiss dispersion function for index 0,1 - x,y planes.*/ - double getDispersion(int ic); + double getDispersion(int ic) const; /** Returns Twiss dispersion_prime function for index 0,1 - x,y planes.*/ - double getDispersionDerivative(int ic); + double getDispersionDerivative(int ic) const; /** Computes the XY moments of the bunch up to a prescribed order */ void computeBunchMoments(Bunch* bunch, int order, int dispersionflag, int emitnormflag); /** Returns the XY moment of the beam */ - double getBunchMoment(int i, int j); + double getBunchMoment(int i, int j) const; private: @@ -95,21 +96,19 @@ class BunchTwissAnalysis: public OrbitUtils::CppPyWrapper double total_macrosize; /** array with average values for 6D coordinates */ - double* avg_arr; - double* avg_arr_MPI; + double avg_arr[6] = {}; /** array with correlations between 6D coordinates. It is a packed 1D array 6*6 = 36. To reach i,j = 0-5 coerrelation use [i+6*j] It is excessive because = etc.*/ - double* corr_arr; - double* corr_arr_MPI; + double corr_arr[36] = {}; - /** array with XY Moments */ - double** momentXY; + /** Contiguous XY moments, indexed by j * (_order + 1) + i. */ + std::vector momentXY; /** order for the moments **/ - double _order; + int _order; /** bunch parameters */ double bunch_momentum; diff --git a/src/orbit/BunchDiagnostics/wrap_bunch_twiss_analysis.cc b/src/orbit/BunchDiagnostics/wrap_bunch_twiss_analysis.cc index ca3efe39..1fbaa8d1 100644 --- a/src/orbit/BunchDiagnostics/wrap_bunch_twiss_analysis.cc +++ b/src/orbit/BunchDiagnostics/wrap_bunch_twiss_analysis.cc @@ -5,6 +5,7 @@ #include "wrap_bunch.hh" #include +#include #include "BunchTwissAnalysis.hh" @@ -20,262 +21,249 @@ extern "C" { Constructor for python class wrapping c++ BunchTwissAnalysis instance. It never will be called directly. */ - static PyObject* BunchTwissAnalysis_new(PyTypeObject *type, PyObject *args, PyObject *kwds){ + static PyObject* BunchTwissAnalysis_new(PyTypeObject *type, PyObject *Py_UNUSED(args), PyObject *Py_UNUSED(kwds)){ pyORBIT_Object* self; - self = (pyORBIT_Object *) type->tp_alloc(type, 0); - self->cpp_obj = NULL; - return (PyObject *) self; + self = reinterpret_cast(type->tp_alloc(type, 0)); + if (!self) + return nullptr; + self->cpp_obj = nullptr; + return reinterpret_cast(self); } /** This is implementation of the __init__ method */ - static int BunchTwissAnalysis_init(pyORBIT_Object *self, PyObject *args, PyObject *kwds){ + static int BunchTwissAnalysis_init(pyORBIT_Object *self, PyObject *Py_UNUSED(args), PyObject *Py_UNUSED(kwds)){ self->cpp_obj = new BunchTwissAnalysis(); - ((BunchTwissAnalysis*) self->cpp_obj)->setPyWrapper((PyObject*) self); + static_cast(self->cpp_obj)->setPyWrapper( + reinterpret_cast(self)); return 0; } - /** Performs the Twiss analysis of the bunch */ - static PyObject* BunchTwissAnalysis_analyzeBunch(PyObject *self, PyObject *args){ - BunchTwissAnalysis* cpp_BunchTwissAnalysis = (BunchTwissAnalysis*)((pyORBIT_Object*) self)->cpp_obj; - PyObject* pyBunch; - if(!PyArg_ParseTuple(args,"O:analyzeBunch",&pyBunch)){ - ORBIT_MPI_Finalize("BunchTwissAnalysis - analyzeBunch(Bunch* bunch) - parameter are needed."); - } - PyObject* pyORBIT_Bunch_Type = wrap_orbit_bunch::getBunchType("Bunch"); - if(!PyObject_IsInstance(pyBunch,pyORBIT_Bunch_Type)){ - ORBIT_MPI_Finalize("BunchTwissAnalysis - analyzeBunch(Bunch* bunch) - method needs a Bunch."); - } - Bunch* cpp_bunch = (Bunch*) ((pyORBIT_Object*)pyBunch)->cpp_obj; - cpp_BunchTwissAnalysis->analyzeBunch(cpp_bunch); - Py_INCREF(Py_None); - return Py_None; - } - - /** Returns the XY moments of the beam up to a prescribed order */ - static PyObject* BunchTwissAnalysis_computeBunchMoments(PyObject *self, PyObject *args){ - BunchTwissAnalysis* cpp_BunchTwissAnalysis = (BunchTwissAnalysis*)((pyORBIT_Object*) self)->cpp_obj; - PyObject* pyBunch; - int order; - int dispterm; - int emitnormterm; - if(!PyArg_ParseTuple(args,"Oiii:computeBunchMoments",&pyBunch,&order,&dispterm,&emitnormterm)){ - ORBIT_MPI_Finalize("BunchTwissAnalysis - computeBunchMoments(Bunch* bunch, int order, int dispterm, int emitnormterm) - parameters are needed."); - } - PyObject* pyORBIT_Bunch_Type = wrap_orbit_bunch::getBunchType("Bunch"); - if(!PyObject_IsInstance(pyBunch,pyORBIT_Bunch_Type)){ - ORBIT_MPI_Finalize("BunchTwissAnalysis - computeBunchMoments(Bunch* bunch, int order, int dispterm, int emitnormterm) - method needs a Bunch."); - } - - Bunch* cpp_bunch = (Bunch*) ((pyORBIT_Object*)pyBunch)->cpp_obj; - cpp_BunchTwissAnalysis->computeBunchMoments(cpp_bunch, order, dispterm, emitnormterm); - Py_INCREF(Py_None); - return Py_None; - - } - - /** It will return the centered correlation <(x-)*(y-)> = - * for coordinates with indeces (ic,jc) */ - static PyObject* BunchTwissAnalysis_getCorrelation(PyObject *self, PyObject *args){ - BunchTwissAnalysis* cpp_BunchTwissAnalysis = (BunchTwissAnalysis*)((pyORBIT_Object*) self)->cpp_obj; - int ic,jc; - if(!PyArg_ParseTuple( args,"ii:getCorrelation",&ic,&jc)){ - error("pyBunchTwissAnalysis.getCorrelation(ic,jc) - parameters are needed"); - } - return Py_BuildValue("d",cpp_BunchTwissAnalysis->getCorrelation(ic,jc)); - } - - /** It will return the (i,j) XY moment of the beam */ - static PyObject* BunchTwissAnalysis_getBunchMoment(PyObject *self, PyObject *args){ - BunchTwissAnalysis* cpp_BunchTwissAnalysis = (BunchTwissAnalysis*)((pyORBIT_Object*) self)->cpp_obj; - int i,j; - if(!PyArg_ParseTuple( args,"ii:getBunchMoment",&i,&j)){ - error("pyBunchTwissAnalysis.getBunchMoment(i,j) - parameters are needed"); - } - return Py_BuildValue("d",cpp_BunchTwissAnalysis->getBunchMoment(i,j)); - } - - /** Returns the average value for coordinate with index ic */ - static PyObject* BunchTwissAnalysis_getAverage(PyObject *self, PyObject *args){ - BunchTwissAnalysis* cpp_BunchTwissAnalysis = (BunchTwissAnalysis*)((pyORBIT_Object*) self)->cpp_obj; - int ic; - if(!PyArg_ParseTuple( args,"i:",&ic)){ - error("pyBunchTwissAnalysis.getAverage(ic) - parameter is needed"); - } - return Py_BuildValue("d",cpp_BunchTwissAnalysis->getAverage(ic)); - } - - /** Returns the total number of analysed macroparticles */ - static PyObject* BunchTwissAnalysis_getGlobalCount(PyObject *self, PyObject *args){ - BunchTwissAnalysis* cpp_BunchTwissAnalysis = (BunchTwissAnalysis*)((pyORBIT_Object*) self)->cpp_obj; - return Py_BuildValue("i",cpp_BunchTwissAnalysis->getGlobalCount()); - } - - /** Returns the total macrosize */ - static PyObject* BunchTwissAnalysis_getGlobalMacrosize(PyObject *self, PyObject *args){ - BunchTwissAnalysis* cpp_BunchTwissAnalysis = (BunchTwissAnalysis*)((pyORBIT_Object*) self)->cpp_obj; - return Py_BuildValue("d",cpp_BunchTwissAnalysis->getGlobalMacrosize()); - } - - //------------------------------------------------------------ - //Twiss functions - //------------------------------------------------------------ - /** It returns the emittance for index 0,1,2 - x,y,z planes*/ - static PyObject* BunchTwissAnalysis_getEmittance(PyObject *self, PyObject *args){ - BunchTwissAnalysis* cpp_BunchTwissAnalysis = (BunchTwissAnalysis*)((pyORBIT_Object*) self)->cpp_obj; - int ic; - if(!PyArg_ParseTuple( args,"i:getEmittance",&ic)){ - error("pyBunchTwissAnalysis.getEmittance(ic) - parameter is needed"); - } - return Py_BuildValue("d",cpp_BunchTwissAnalysis->getEmittance(ic)); - } - - /** It returns the normalized emittance for index 0,1 - x,y planes*/ - static PyObject* BunchTwissAnalysis_getEmittanceNormalized(PyObject *self, PyObject *args){ - BunchTwissAnalysis* cpp_BunchTwissAnalysis = (BunchTwissAnalysis*)((pyORBIT_Object*) self)->cpp_obj; - int ic; - if(!PyArg_ParseTuple( args,"i:getEmittanceNormalized",&ic)){ - error("pyBunchTwissAnalysis.getEmittanceNormalized(ic) - parameter is needed"); - } - return Py_BuildValue("d",cpp_BunchTwissAnalysis->getEmittanceNormalized(ic)); - } - - /** It returns the Twiss alpha for index 0,1,2 - x,y,z planes*/ - static PyObject* BunchTwissAnalysis_getAlpha(PyObject *self, PyObject *args){ - BunchTwissAnalysis* cpp_BunchTwissAnalysis = (BunchTwissAnalysis*)((pyORBIT_Object*) self)->cpp_obj; - int ic; - if(!PyArg_ParseTuple( args,"i:getAlpha",&ic)){ - error("pyBunchTwissAnalysis.getAlpha(ic) - parameter is needed"); - } - return Py_BuildValue("d",cpp_BunchTwissAnalysis->getAlpha(ic)); - } - - /** It returns the Twiss beta for index 0,1,2 - x,y,z planes*/ - static PyObject* BunchTwissAnalysis_getBeta(PyObject *self, PyObject *args){ - BunchTwissAnalysis* cpp_BunchTwissAnalysis = (BunchTwissAnalysis*)((pyORBIT_Object*) self)->cpp_obj; - int ic; - if(!PyArg_ParseTuple( args,"i:getBeta",&ic)){ - error("pyBunchTwissAnalysis.getBeta(ic) - parameter is needed"); - } - return Py_BuildValue("d",cpp_BunchTwissAnalysis->getBeta(ic)); - } - - /** It returns the Twiss gamma for index 0,1,2 - x,y,z planes*/ - static PyObject* BunchTwissAnalysis_getGamma(PyObject *self, PyObject *args){ - BunchTwissAnalysis* cpp_BunchTwissAnalysis = (BunchTwissAnalysis*)((pyORBIT_Object*) self)->cpp_obj; - int ic; - if(!PyArg_ParseTuple( args,"i:getGamma",&ic)){ - error("pyBunchTwissAnalysis.getGamma(ic) - parameter is needed"); - } - return Py_BuildValue("d",cpp_BunchTwissAnalysis->getGamma(ic)); - } - - /** It returns Twiss dispersion function for index 0,1 - x,y planes*/ - static PyObject* BunchTwissAnalysis_getDispersion(PyObject *self, PyObject *args){ - BunchTwissAnalysis* cpp_BunchTwissAnalysis = (BunchTwissAnalysis*)((pyORBIT_Object*) self)->cpp_obj; - int ic; - if(!PyArg_ParseTuple( args,"i:getDispersion",&ic)){ - error("pyBunchTwissAnalysis.getDispersion(ic) - parameter is needed"); - } - return Py_BuildValue("d",cpp_BunchTwissAnalysis->getDispersion(ic)); - } - - /** It returns Twiss dispersion_prime function for index 0,1 - x,y planes*/ - static PyObject* BunchTwissAnalysis_getDispersionDerivative(PyObject *self, PyObject *args){ - BunchTwissAnalysis* cpp_BunchTwissAnalysis = (BunchTwissAnalysis*)((pyORBIT_Object*) self)->cpp_obj; - int ic; - if(!PyArg_ParseTuple( args,"i:getDispersionDerivative",&ic)){ - error("pyBunchTwissAnalysis.getDispersionDerivative(ic) - parameter is needed"); - } - return Py_BuildValue("d",cpp_BunchTwissAnalysis->getDispersionDerivative(ic)); - } - - /** It returns the Twiss array (alpha,beta,gamma,emittance) for index 0,1,2 - x,y,z planes*/ - static PyObject* BunchTwissAnalysis_getTwiss(PyObject *self, PyObject *args){ - BunchTwissAnalysis* cpp_BunchTwissAnalysis = (BunchTwissAnalysis*)((pyORBIT_Object*) self)->cpp_obj; - int ic; - if(!PyArg_ParseTuple( args,"i:getTwiss",&ic)){ - error("pyBunchTwissAnalysis.getTwiss(ic) - parameter is needed"); - } - double alpha = cpp_BunchTwissAnalysis->getAlpha(ic); - double beta = cpp_BunchTwissAnalysis->getBeta(ic); - double gamma = cpp_BunchTwissAnalysis->getGamma(ic); - double emitt = cpp_BunchTwissAnalysis->getEmittance(ic); - return Py_BuildValue("(dddd)",alpha,beta,gamma,emitt); - } - - - /** It returns the effective emittance for index 0,1 - x,y planes*/ - static PyObject* BunchTwissAnalysis_getEffectiveEmittance(PyObject *self, PyObject *args){ - BunchTwissAnalysis* cpp_BunchTwissAnalysis = (BunchTwissAnalysis*)((pyORBIT_Object*) self)->cpp_obj; - int ic; - if(!PyArg_ParseTuple( args,"i:getEffectiveEmittance",&ic)){ - error("pyBunchTwissAnalysis.getEffectiveEmittance(ic) - parameter is needed"); - } - return Py_BuildValue("d",cpp_BunchTwissAnalysis->getEffectiveEmittance(ic)); - } - - /** It returns the effective Twiss alpha for index 0,1 - x,y planes*/ - static PyObject* BunchTwissAnalysis_getEffectiveAlpha(PyObject *self, PyObject *args){ - BunchTwissAnalysis* cpp_BunchTwissAnalysis = (BunchTwissAnalysis*)((pyORBIT_Object*) self)->cpp_obj; - int ic; - if(!PyArg_ParseTuple( args,"i:getEffectiveAlpha",&ic)){ - error("pyBunchTwissAnalysis.getEffectiveAlpha(ic) - parameter is needed"); - } - return Py_BuildValue("d",cpp_BunchTwissAnalysis->getEffectiveAlpha(ic)); - } - - /** It returns the effective Twiss beta for index 0,1 - x,y planes*/ - static PyObject* BunchTwissAnalysis_getEffectiveBeta(PyObject *self, PyObject *args){ - BunchTwissAnalysis* cpp_BunchTwissAnalysis = (BunchTwissAnalysis*)((pyORBIT_Object*) self)->cpp_obj; - int ic; - if(!PyArg_ParseTuple( args,"i:getEffectiveBeta",&ic)){ - error("pyBunchTwissAnalysis.getEffectiveBeta(ic) - parameter is needed"); - } - return Py_BuildValue("d",cpp_BunchTwissAnalysis->getEffectiveBeta(ic)); - } - - /** It returns the effective Twiss gamma for index 0,1 - x,y planes*/ - static PyObject* BunchTwissAnalysis_getEffectiveGamma(PyObject *self, PyObject *args){ - BunchTwissAnalysis* cpp_BunchTwissAnalysis = (BunchTwissAnalysis*)((pyORBIT_Object*) self)->cpp_obj; - int ic; - if(!PyArg_ParseTuple( args,"i:getEffectiveGamma",&ic)){ - error("pyBunchTwissAnalysis.getEffectiveGamma(ic) - parameter is needed"); - } - return Py_BuildValue("d",cpp_BunchTwissAnalysis->getEffectiveGamma(ic)); - } + // Match CPython's callback erasure through a generic function pointer. + static PyCFunction fastCallMethod( + PyObject* (*method)(PyObject*, PyObject* const*, Py_ssize_t)) + { + return reinterpret_cast(reinterpret_cast(method)); + } + + static BunchTwissAnalysis* getAnalysis(PyObject* self) + { + return static_cast( + reinterpret_cast(self)->cpp_obj); + } + + static Bunch* getBunch(PyObject* arg) + { + PyObject* bunchType = wrap_orbit_bunch::getBunchType("Bunch"); + const int isBunch = PyObject_IsInstance(arg, bunchType); + if (isBunch < 0) + return nullptr; + if (!isBunch) + { + PyErr_SetString(PyExc_TypeError, "expected a Bunch"); + return nullptr; + } + return static_cast(reinterpret_cast(arg)->cpp_obj); + } + + // PyLong_AsLong accepts the index protocol; check the narrower C int range too. + static bool asInt(PyObject* arg, int& value) + { + const long converted = PyLong_AsLong(arg); + if (converted == -1 && PyErr_Occurred()) + return false; + if (converted < std::numeric_limits::min() || + converted > std::numeric_limits::max()) + { + PyErr_SetString(PyExc_OverflowError, "Python int does not fit in a C++ int"); + return false; + } + value = static_cast(converted); + return true; + } + + static PyObject* getIndexedValue(PyObject* self, PyObject* arg, + double (BunchTwissAnalysis::*method)(int) const) + { + int index; + if (!asInt(arg, index)) + return nullptr; + return PyFloat_FromDouble((getAnalysis(self)->*method)(index)); + } + + static PyObject* BunchTwissAnalysis_analyzeBunch(PyObject* self, PyObject* arg) + { + Bunch* bunch = getBunch(arg); + if (!bunch) + return nullptr; + getAnalysis(self)->analyzeBunch(bunch); + Py_RETURN_NONE; + } + + static PyObject* BunchTwissAnalysis_computeBunchMoments( + PyObject* self, PyObject* const* args, Py_ssize_t nargs) + { + if (nargs != 4) + { + PyErr_Format(PyExc_TypeError, + "computeBunchMoments() takes exactly 4 arguments (%zd given)", nargs); + return nullptr; + } + int order, dispersion, emitnorm; + if (!asInt(args[1], order) || !asInt(args[2], dispersion) || + !asInt(args[3], emitnorm)) + return nullptr; + Bunch* bunch = getBunch(args[0]); + if (!bunch) + return nullptr; + getAnalysis(self)->computeBunchMoments(bunch, order, dispersion, emitnorm); + Py_RETURN_NONE; + } + + static PyObject* BunchTwissAnalysis_getCorrelation( + PyObject* self, PyObject* const* args, Py_ssize_t nargs) + { + if (nargs != 2) + { + PyErr_Format(PyExc_TypeError, + "getCorrelation() takes exactly 2 arguments (%zd given)", nargs); + return nullptr; + } + int i, j; + if (!asInt(args[0], i) || !asInt(args[1], j)) + return nullptr; + return PyFloat_FromDouble(getAnalysis(self)->getCorrelation(i, j)); + } + + static PyObject* BunchTwissAnalysis_getBunchMoment( + PyObject* self, PyObject* const* args, Py_ssize_t nargs) + { + if (nargs != 2) + { + PyErr_Format(PyExc_TypeError, + "getBunchMoment() takes exactly 2 arguments (%zd given)", nargs); + return nullptr; + } + int i, j; + if (!asInt(args[0], i) || !asInt(args[1], j)) + return nullptr; + return PyFloat_FromDouble(getAnalysis(self)->getBunchMoment(i, j)); + } + + static PyObject* BunchTwissAnalysis_getAverage(PyObject* self, PyObject* arg) + { + return getIndexedValue(self, arg, &BunchTwissAnalysis::getAverage); + } + + static PyObject* BunchTwissAnalysis_getGlobalCount(PyObject* self, PyObject* Py_UNUSED(args)) + { + return PyLong_FromLong(getAnalysis(self)->getGlobalCount()); + } + + static PyObject* BunchTwissAnalysis_getGlobalMacrosize(PyObject* self, PyObject* Py_UNUSED(args)) + { + return PyFloat_FromDouble(getAnalysis(self)->getGlobalMacrosize()); + } + + static PyObject* BunchTwissAnalysis_getEmittance(PyObject* self, PyObject* arg) + { + return getIndexedValue(self, arg, &BunchTwissAnalysis::getEmittance); + } + + static PyObject* BunchTwissAnalysis_getEmittanceNormalized(PyObject* self, PyObject* arg) + { + return getIndexedValue(self, arg, &BunchTwissAnalysis::getEmittanceNormalized); + } + + static PyObject* BunchTwissAnalysis_getAlpha(PyObject* self, PyObject* arg) + { + return getIndexedValue(self, arg, &BunchTwissAnalysis::getAlpha); + } + + static PyObject* BunchTwissAnalysis_getBeta(PyObject* self, PyObject* arg) + { + return getIndexedValue(self, arg, &BunchTwissAnalysis::getBeta); + } + + static PyObject* BunchTwissAnalysis_getGamma(PyObject* self, PyObject* arg) + { + return getIndexedValue(self, arg, &BunchTwissAnalysis::getGamma); + } + + static PyObject* BunchTwissAnalysis_getDispersion(PyObject* self, PyObject* arg) + { + return getIndexedValue(self, arg, &BunchTwissAnalysis::getDispersion); + } + + static PyObject* BunchTwissAnalysis_getDispersionDerivative(PyObject* self, PyObject* arg) + { + return getIndexedValue(self, arg, &BunchTwissAnalysis::getDispersionDerivative); + } + + static PyObject* BunchTwissAnalysis_getTwiss(PyObject* self, PyObject* arg) + { + int index; + if (!asInt(arg, index)) + return nullptr; + BunchTwissAnalysis* analysis = getAnalysis(self); + return Py_BuildValue("(dddd)", analysis->getAlpha(index), analysis->getBeta(index), + analysis->getGamma(index), analysis->getEmittance(index)); + } + + static PyObject* BunchTwissAnalysis_getEffectiveEmittance(PyObject* self, PyObject* arg) + { + return getIndexedValue(self, arg, &BunchTwissAnalysis::getEffectiveEmittance); + } + + static PyObject* BunchTwissAnalysis_getEffectiveAlpha(PyObject* self, PyObject* arg) + { + return getIndexedValue(self, arg, &BunchTwissAnalysis::getEffectiveAlpha); + } + + static PyObject* BunchTwissAnalysis_getEffectiveBeta(PyObject* self, PyObject* arg) + { + return getIndexedValue(self, arg, &BunchTwissAnalysis::getEffectiveBeta); + } + + static PyObject* BunchTwissAnalysis_getEffectiveGamma(PyObject* self, PyObject* arg) + { + return getIndexedValue(self, arg, &BunchTwissAnalysis::getEffectiveGamma); + } //----------------------------------------------------- //destructor for python BunchTwissAnalysis class (__del__ method). //----------------------------------------------------- static void BunchTwissAnalysis_del(pyORBIT_Object* self){ //std::cerr<<"The BunchTwissAnalysis __del__ has been called!"<cpp_obj); - self->ob_base.ob_type->tp_free((PyObject*)self); + delete static_cast(self->cpp_obj); + self->ob_base.ob_type->tp_free(reinterpret_cast(self)); } // defenition of the methods of the python BunchTwissAnalysis wrapper class // they will be vailable from python level - static PyMethodDef BunchTwissAnalysisClassMethods[] = { - { "analyzeBunch", BunchTwissAnalysis_analyzeBunch, METH_VARARGS,"Performs the Twiss analysis of the bunch."}, - { "computeBunchMoments", BunchTwissAnalysis_computeBunchMoments, METH_VARARGS,"Returns the XY moments of the beam up to a prescribed order"}, - { "getCorrelation", BunchTwissAnalysis_getCorrelation, METH_VARARGS,"Returns the centered correlation <(x-)*(y-)> = - * for coordinates with indeces (ic,jc)"}, - { "getBunchMoment", BunchTwissAnalysis_getBunchMoment, METH_VARARGS,"Returns the (i,j) xy moment of the beam"}, - { "getAverage", BunchTwissAnalysis_getAverage, METH_VARARGS,"Returns the average value for coordinate with index ic"}, - { "getGlobalCount", BunchTwissAnalysis_getGlobalCount, METH_VARARGS,"Returns the total number of analysed macroparticles"}, - { "getGlobalMacrosize", BunchTwissAnalysis_getGlobalMacrosize, METH_VARARGS,"Returns the total macrosize"}, - { "getEmittance", BunchTwissAnalysis_getEmittance, METH_VARARGS,"Returns the emittance for index 0,1,2 - x,y,z planes"}, - { "getEmittanceNormalized", BunchTwissAnalysis_getEmittanceNormalized, METH_VARARGS,"Returns the normalized emittance for index 0,1 - x,y planes"}, - { "getAlpha", BunchTwissAnalysis_getAlpha, METH_VARARGS,"Returns Twiss alpha for index 0,1,2 - x,y,z planes"}, - { "getBeta", BunchTwissAnalysis_getBeta, METH_VARARGS,"Returns Twiss beta for index 0,1,2 - x,y,z planes"}, - { "getGamma", BunchTwissAnalysis_getGamma, METH_VARARGS,"Returns Twiss gamma for index 0,1,2 - x,y,z planes"}, - { "getTwiss", BunchTwissAnalysis_getTwiss, METH_VARARGS,"Returns Twiss tuple (alpha,beta,gamma,emitt) for index 0,1,2 - x,y,z planes"}, - { "getDispersion", BunchTwissAnalysis_getDispersion, METH_VARARGS,"Returns Twiss dispersion function for index 0,1 - x,y planes"}, - { "getDispersionDerivative",BunchTwissAnalysis_getDispersionDerivative, METH_VARARGS,"Returns Twiss dispersion' function for index 0,1 - x,y planes"}, - { "getEffectiveEmittance", BunchTwissAnalysis_getEffectiveEmittance, METH_VARARGS,"Returns the effective emittance for index 0,1 - x,y planes"}, - { "getEffectiveAlpha", BunchTwissAnalysis_getEffectiveAlpha, METH_VARARGS,"Returns effective Twiss alpha for index 0,1 - x,y planes"}, - { "getEffectiveBeta", BunchTwissAnalysis_getEffectiveBeta, METH_VARARGS,"Returns effective Twiss beta for index 0,1 - x,y planes"}, - { "getEffectiveGamma", BunchTwissAnalysis_getEffectiveGamma, METH_VARARGS,"Returns effective Twiss gamma for index 0,1 - x,y planes"}, - {NULL} - }; + // clang-format off + static PyMethodDef BunchTwissAnalysisClassMethods[] = { + {"analyzeBunch", BunchTwissAnalysis_analyzeBunch, METH_O, "Performs the Twiss analysis of the bunch."}, + {"computeBunchMoments", fastCallMethod(BunchTwissAnalysis_computeBunchMoments), METH_FASTCALL, "Returns the XY moments of the beam up to a prescribed order"}, + {"getCorrelation", fastCallMethod(BunchTwissAnalysis_getCorrelation), METH_FASTCALL, "Returns the centered correlation between coordinates (ic,jc)"}, + {"getBunchMoment", fastCallMethod(BunchTwissAnalysis_getBunchMoment), METH_FASTCALL, "Returns the (i,j) xy moment of the beam"}, + {"getAverage", BunchTwissAnalysis_getAverage, METH_O, "Returns the average value for coordinate with index ic"}, + {"getGlobalCount", BunchTwissAnalysis_getGlobalCount, METH_NOARGS, "Returns the total number of analysed macroparticles"}, + {"getGlobalMacrosize", BunchTwissAnalysis_getGlobalMacrosize, METH_NOARGS, "Returns the total macrosize"}, + {"getEmittance", BunchTwissAnalysis_getEmittance, METH_O, "Returns the emittance for index 0,1,2 - x,y,z planes"}, + {"getEmittanceNormalized", BunchTwissAnalysis_getEmittanceNormalized, METH_O, "Returns the normalized emittance for index 0,1 - x,y planes"}, + {"getAlpha", BunchTwissAnalysis_getAlpha, METH_O, "Returns Twiss alpha for index 0,1,2 - x,y,z planes"}, + {"getBeta", BunchTwissAnalysis_getBeta, METH_O, "Returns Twiss beta for index 0,1,2 - x,y,z planes"}, + {"getGamma", BunchTwissAnalysis_getGamma, METH_O, "Returns Twiss gamma for index 0,1,2 - x,y,z planes"}, + {"getTwiss", BunchTwissAnalysis_getTwiss, METH_O, "Returns Twiss tuple (alpha,beta,gamma,emitt) for index 0,1,2 - x,y,z planes"}, + {"getDispersion", BunchTwissAnalysis_getDispersion, METH_O, "Returns Twiss dispersion function for index 0,1 - x,y planes"}, + {"getDispersionDerivative", BunchTwissAnalysis_getDispersionDerivative, METH_O, "Returns Twiss dispersion' function for index 0,1 - x,y planes"}, + {"getEffectiveEmittance", BunchTwissAnalysis_getEffectiveEmittance, METH_O, "Returns the effective emittance for index 0,1 - x,y planes"}, + {"getEffectiveAlpha", BunchTwissAnalysis_getEffectiveAlpha, METH_O, "Returns effective Twiss alpha for index 0,1 - x,y planes"}, + {"getEffectiveBeta", BunchTwissAnalysis_getEffectiveBeta, METH_O, "Returns effective Twiss beta for index 0,1 - x,y planes"}, + {"getEffectiveGamma", BunchTwissAnalysis_getEffectiveGamma, METH_O, "Returns effective Twiss gamma for index 0,1 - x,y planes"}, + {nullptr, nullptr, 0, nullptr} + }; + // clang-format on // defenition of the memebers of the python BunchTwissAnalysis wrapper class // they will be vailable from python level @@ -289,7 +277,7 @@ extern "C" { "BunchTwissAnalysis", /*tp_name*/ sizeof(pyORBIT_Object), /*tp_basicsize*/ 0, /*tp_itemsize*/ - (destructor) BunchTwissAnalysis_del , /*tp_dealloc*/ + reinterpret_cast(BunchTwissAnalysis_del) , /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ @@ -320,7 +308,7 @@ extern "C" { 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ - (initproc) BunchTwissAnalysis_init, /* tp_init */ + reinterpret_cast(BunchTwissAnalysis_init), /* tp_init */ 0, /* tp_alloc */ BunchTwissAnalysis_new, /* tp_new */ }; @@ -333,7 +321,7 @@ extern "C" { void initbunchtwissanalysis(PyObject* module){ if (PyType_Ready(&pyORBIT_BunchTwissAnalysis_Type) < 0) return; Py_INCREF(&pyORBIT_BunchTwissAnalysis_Type); - PyModule_AddObject(module, "BunchTwissAnalysis", (PyObject *)&pyORBIT_BunchTwissAnalysis_Type); + PyModule_AddObject(module, "BunchTwissAnalysis", reinterpret_cast(&pyORBIT_BunchTwissAnalysis_Type)); } #ifdef __cplusplus diff --git a/tests/py/orbit/test_bunch_moments.py b/tests/py/orbit/test_bunch_moments.py new file mode 100644 index 00000000..6179d477 --- /dev/null +++ b/tests/py/orbit/test_bunch_moments.py @@ -0,0 +1,82 @@ +"""Regression tests for normalized transverse bunch moments.""" + +import math +import random + +import pytest + +from orbit.core.bunch import Bunch, BunchTwissAnalysis + + +@pytest.mark.parametrize("weighted", [False, True]) +@pytest.mark.parametrize("dispersion", [0, 1]) +@pytest.mark.parametrize("emitnorm", [0, 1]) +def test_bunch_moments(weighted, dispersion, emitnorm): + rng = random.Random(1729) + particles = [ + (rng.uniform(-0.01, 0.02), rng.uniform(-0.003, 0.002), + rng.uniform(-0.02, 0.01), rng.uniform(-0.002, 0.003), + rng.uniform(-0.1, 0.1), rng.uniform(-0.01, 0.02)) + for _ in range(64) + ] + weights = [1.0 + k % 5 for k in range(len(particles))] if weighted else [1.0] * len(particles) + bunch = Bunch() + bunch.mass(0.938272) + bunch.getSyncParticle().kinEnergy(1.0) + if weighted: + bunch.addPartAttr("macrosize") + for k, particle in enumerate(particles): + bunch.addParticle(*particle) + if weighted: + bunch.partAttrValue("macrosize", k, 0, weights[k]) + + total = sum(weights) + means = [sum(w * p[k] for w, p in zip(weights, particles)) / total for k in range(6)] + energy_variance = sum(w * (p[5] - means[5]) ** 2 for w, p in zip(weights, particles)) / total + covariance = sum(w * (p[0] - means[0]) * (p[5] - means[5]) for w, p in zip(weights, particles)) / total + coefficient = covariance / energy_variance if dispersion else 0.0 + x_mean = means[0] - coefficient * means[5] + y_mean = means[2] + + analysis = BunchTwissAnalysis() + analysis.computeBunchMoments(bunch, 4, dispersion, emitnorm) + x_scale = math.sqrt(analysis.getBeta(0) * (analysis.getEmittance(0) if emitnorm else 1.0)) + y_scale = math.sqrt(analysis.getBeta(1) * (analysis.getEmittance(1) if emitnorm else 1.0)) + expected_moments = {} + for j in range(5): + for i in range(5 - j): + if (i, j) == (1, 0): + expected = x_mean + elif (i, j) == (0, 1): + expected = y_mean + else: + expected = sum( + w * ((p[0] - coefficient * p[5] - x_mean) / x_scale) ** i + * ((p[2] - y_mean) / y_scale) ** j + for w, p in zip(weights, particles) + ) / total + expected_moments[i, j] = expected + assert analysis.getBunchMoment(i, j) == pytest.approx(expected, rel=1e-11, abs=1e-12) + + # Reuse the same analysis while shrinking and growing its contiguous storage. + for order in (2, 1, 0, 4): + analysis.computeBunchMoments(bunch, order, dispersion, emitnorm) + assert analysis.getGlobalCount() == len(particles) + assert analysis.getGlobalMacrosize() == pytest.approx(total) + for j in range(order + 1): + for i in range(order + 1): + expected = expected_moments[i, j] if i + j <= order else 0.0 + assert analysis.getBunchMoment(i, j) == pytest.approx(expected, rel=1e-11, abs=1e-12) + + +@pytest.mark.parametrize("order", [0, 1, 2]) +def test_empty_bunch_low_order(order): + bunch = Bunch() + bunch.getSyncParticle().kinEnergy(1.0) + analysis = BunchTwissAnalysis() + analysis.computeBunchMoments(bunch, order, 0, 0) + assert analysis.getGlobalCount() == 0 + assert analysis.getGlobalMacrosize() == 0.0 + for j in range(order + 1): + for i in range(order + 1): + assert analysis.getBunchMoment(i, j) == (1.0 if i == j == 0 else 0.0)