/* Filter generation ------------------------------------------------------- */ void Steerable::generate1DFilters(double sigma, const MultidimArray<double> &Vtomograph, std::vector< MultidimArray<double> > &hx1, std::vector< MultidimArray<double> > &hy1, std::vector< MultidimArray<double> > &hz1){ // Initialization MultidimArray<double> aux; aux.initZeros(XSIZE(Vtomograph)); aux.setXmippOrigin(); for (int i=0; i<6; i++) hx1.push_back(aux); aux.initZeros(YSIZE(Vtomograph)); aux.setXmippOrigin(); for (int i=0; i<6; i++) hy1.push_back(aux); aux.initZeros(ZSIZE(Vtomograph)); aux.setXmippOrigin(); for (int i=0; i<6; i++) hz1.push_back(aux); double sigma2=sigma*sigma; double k1 = 1.0/pow((2.0*PI*sigma),(3.0/2.0)); double k2 = -1.0/(sigma2); FOR_ALL_ELEMENTS_IN_ARRAY1D(hx1[0]) { double i2=i*i; double g = -exp(-i2/(2.0*sigma2)); hx1[0](i) = k1*k2*g*(1.0-(i2/sigma2)); hx1[1](i) = k1*k2*g; hx1[2](i) = k1*k2*g; hx1[3](i) = k1*k2*k2*g*i; hx1[4](i) = k1*k2*k2*g*i; hx1[5](i) = k1*k2*k2*g; } FOR_ALL_ELEMENTS_IN_ARRAY1D(hy1[0]) { double i2=i*i; double g = -exp(-i2/(2.0*sigma2)); hy1[0](i) = g; hy1[1](i) = g*(1.0-(i2/sigma2)); hy1[2](i) = g; hy1[3](i) = g*i; hy1[4](i) = g; hy1[5](i) = g*i; } FOR_ALL_ELEMENTS_IN_ARRAY1D(hz1[0]) { double i2=i*i; double g = -exp(-i2/(2.0*sigma2)); hz1[0](i) = g; hz1[1](i) = g; hz1[2](i) = g*(1.0-(i2/sigma2)); hz1[3](i) = g; hz1[4](i) = g*i; hz1[5](i) = g*i; } }
void symmetriseMap(MultidimArray<DOUBLE> &img, FileName &fn_sym, bool do_wrap) { if (img.getDim() != 3) REPORT_ERROR("symmetriseMap ERROR: symmetriseMap can only be run on 3D maps!"); img.setXmippOrigin(); SymList SL; SL.read_sym_file(fn_sym); Matrix2D<DOUBLE> L(4, 4), R(4, 4); // A matrix from the list MultidimArray<DOUBLE> sum, aux; sum = img; aux.resize(img); for (int isym = 0; isym < SL.SymsNo(); isym++) { SL.get_matrices(isym, L, R); applyGeometry(img, aux, R, IS_INV, do_wrap); sum += aux; } // Overwrite the input img = sum / (SL.SymsNo() + 1); }
/* Constructor */ PyObject * FourierProjector_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) { FourierProjectorObject *self = (FourierProjectorObject*) type->tp_alloc(type, 0); XMIPP_TRY if (self != NULL) { PyObject *image = NULL; double padding_factor, max_freq, spline_degree; if (PyArg_ParseTuple(args, "O|ddd", &image, &padding_factor, &max_freq, &spline_degree)) { Image_Value(image).getDimensions(self->dims); MultidimArray<double> *pdata; Image_Value(image).data->getMultidimArrayPointer(pdata); pdata->setXmippOrigin(); self->fourier_projector = new FourierProjector(*(pdata), padding_factor, max_freq, spline_degree); } } XMIPP_CATCH return (PyObject *) self; }
void Projector::griddingCorrect(MultidimArray<DOUBLE> &vol_in) { // Correct real-space map by dividing it by the Fourier transform of the interpolator(s) vol_in.setXmippOrigin(); FOR_ALL_ELEMENTS_IN_ARRAY3D(vol_in) { DOUBLE r = sqrt((DOUBLE)(k*k+i*i+j*j)); // if r==0: do nothing (i.e. divide by 1) if (r > 0.) { DOUBLE rval = r / (ori_size * padding_factor); DOUBLE sinc = sin(PI * rval) / ( PI * rval); //DOUBLE ftblob = blob_Fourier_val(rval, blob) / blob_Fourier_val(0., blob); // Interpolation (goes with "interpolator") to go from arbitrary to fine grid if (interpolator==NEAREST_NEIGHBOUR && r_min_nn == 0) { // NN interpolation is convolution with a rectangular pulse, which FT is a sinc function A3D_ELEM(vol_in, k, i, j) /= sinc; } else if (interpolator==TRILINEAR || (interpolator==NEAREST_NEIGHBOUR && r_min_nn > 0) ) { // trilinear interpolation is convolution with a triangular pulse, which FT is a sinc^2 function A3D_ELEM(vol_in, k, i, j) /= sinc * sinc; } else REPORT_ERROR("BUG Projector::griddingCorrect: unrecognised interpolator scheme."); //#define DEBUG_GRIDDING_CORRECT #ifdef DEBUG_GRIDDING_CORRECT if (k==0 && i==0 && j > 0) std::cerr << " j= " << j << " sinc= " << sinc << std::endl; #endif } } }
void FourierProjector::produceSideInfo() { // Zero padding MultidimArray<double> Vpadded; int paddedDim=(int)(paddingFactor*volumeSize); // JMRT: TODO: I think it is a very poor design to modify the volume passed // in the construct, it will be padded anyway, so new memory should be allocated volume->window(Vpadded,FIRST_XMIPP_INDEX(paddedDim),FIRST_XMIPP_INDEX(paddedDim),FIRST_XMIPP_INDEX(paddedDim), LAST_XMIPP_INDEX(paddedDim),LAST_XMIPP_INDEX(paddedDim),LAST_XMIPP_INDEX(paddedDim)); volume->clear(); // Make Fourier transform, shift the volume origin to the volume center and center it MultidimArray< std::complex<double> > Vfourier; transformer3D.completeFourierTransform(Vpadded,Vfourier); ShiftFFT(Vfourier, FIRST_XMIPP_INDEX(XSIZE(Vpadded)), FIRST_XMIPP_INDEX(YSIZE(Vpadded)), FIRST_XMIPP_INDEX(ZSIZE(Vpadded))); CenterFFT(Vfourier,true); Vfourier.setXmippOrigin(); // Compensate for the Fourier normalization factor double K=(double)(XSIZE(Vpadded)*XSIZE(Vpadded)*XSIZE(Vpadded))/(double)(volumeSize*volumeSize); FOR_ALL_DIRECT_ELEMENTS_IN_MULTIDIMARRAY(Vfourier) DIRECT_MULTIDIM_ELEM(Vfourier,n)*=K; Vpadded.clear(); // Compute Bspline coefficients if (BSplineDeg==3) { MultidimArray< double > VfourierRealAux, VfourierImagAux; Complex2RealImag(Vfourier, VfourierRealAux, VfourierImagAux); Vfourier.clear(); produceSplineCoefficients(BSPLINE3,VfourierRealCoefs,VfourierRealAux); produceSplineCoefficients(BSPLINE3,VfourierImagCoefs,VfourierImagAux); //VfourierRealAux.clear(); //VfourierImagAux.clear(); } else Complex2RealImag(Vfourier, VfourierRealCoefs, VfourierImagCoefs); // Allocate memory for the 2D Fourier transform projection().initZeros(volumeSize,volumeSize); projection().setXmippOrigin(); transformer2D.FourierTransform(projection(),projectionFourier,false); // Calculate phase shift terms phaseShiftImgA.initZeros(projectionFourier); phaseShiftImgB.initZeros(projectionFourier); double shift=-FIRST_XMIPP_INDEX(volumeSize); double xxshift = -2 * PI * shift / volumeSize; for (size_t i=0; i<YSIZE(projectionFourier); ++i) { double phasey=(double)(i) * xxshift; for (size_t j=0; j<XSIZE(projectionFourier); ++j) { // Phase shift to move the origin of the image to the corner double dotp = (double)(j) * xxshift + phasey; sincos(dotp,&DIRECT_A2D_ELEM(phaseShiftImgB,i,j),&DIRECT_A2D_ELEM(phaseShiftImgA,i,j)); } } }
void Steerable::generate3DFilter(MultidimArray<double>& h3D, std::vector< MultidimArray<double> > &hx1, std::vector< MultidimArray<double> > &hy1, std::vector< MultidimArray<double> > &hz1) { h3D.initZeros(XSIZE(hz1[0]),XSIZE(hy1[0]),XSIZE(hx1[0])); h3D.setXmippOrigin(); FOR_ALL_ELEMENTS_IN_ARRAY3D(h3D) for (int n=0; n<6; n++) h3D(k,i,j)+=(hz1[n](k)*hy1[n](i)*hx1[n](j)); }
void CTF::getCenteredImage(MultidimArray<DOUBLE> &result, DOUBLE Tm, bool do_abs, bool do_only_flip_phases, bool do_intact_until_first_peak, bool do_damping) { result.setXmippOrigin(); DOUBLE xs = (DOUBLE)XSIZE(result) * Tm; DOUBLE ys = (DOUBLE)YSIZE(result) * Tm; FOR_ALL_ELEMENTS_IN_ARRAY2D(result) { DOUBLE x = (DOUBLE)j / xs; DOUBLE y = (DOUBLE)i / ys; A2D_ELEM(result, i, j) = getCTF(x, y, do_abs, do_only_flip_phases, do_intact_until_first_peak, do_damping); } }
void FourierProjector::produceSideInfo() { // Zero padding MultidimArray<double> Vpadded; int paddedDim=(int)(paddingFactor*volumeSize); volume->window(Vpadded,FIRST_XMIPP_INDEX(paddedDim),FIRST_XMIPP_INDEX(paddedDim),FIRST_XMIPP_INDEX(paddedDim), LAST_XMIPP_INDEX(paddedDim),LAST_XMIPP_INDEX(paddedDim),LAST_XMIPP_INDEX(paddedDim)); volume->clear(); // Make Fourier transform, shift the volume origin to the volume center and center it MultidimArray< std::complex<double> > Vfourier; transformer3D.completeFourierTransform(Vpadded,Vfourier); ShiftFFT(Vfourier, FIRST_XMIPP_INDEX(XSIZE(Vpadded)), FIRST_XMIPP_INDEX(YSIZE(Vpadded)), FIRST_XMIPP_INDEX(ZSIZE(Vpadded))); CenterFFT(Vfourier,true); Vfourier.setXmippOrigin(); // Compensate for the Fourier normalization factor double K=(double)(XSIZE(Vpadded)*XSIZE(Vpadded)*XSIZE(Vpadded))/(double)(volumeSize*volumeSize); FOR_ALL_DIRECT_ELEMENTS_IN_MULTIDIMARRAY(Vfourier) DIRECT_MULTIDIM_ELEM(Vfourier,n)*=K; Vpadded.clear(); // Compute Bspline coefficients if (BSplineDeg==3) { MultidimArray< double > VfourierRealAux, VfourierImagAux; Complex2RealImag(Vfourier, VfourierRealAux, VfourierImagAux); Vfourier.clear(); produceSplineCoefficients(BSPLINE3,VfourierRealCoefs,VfourierRealAux); produceSplineCoefficients(BSPLINE3,VfourierImagCoefs,VfourierImagAux); //VfourierRealAux.clear(); //VfourierImagAux.clear(); } else Complex2RealImag(Vfourier, VfourierRealCoefs, VfourierImagCoefs); // Allocate memory for the 2D Fourier transform projection().initZeros(volumeSize,volumeSize); projection().setXmippOrigin(); transformer2D.FourierTransform(projection(),projectionFourier,false); }
//#define DEBUG void normalize_tomography(MultidimArray<double> &I, double tilt, double &mui, double &sigmai, bool tiltMask, bool tomography0, double mu0, double sigma0) { // Tilt series are always 2D I.checkDimension(2); const int L=2; // Build a mask using the tilt angle I.setXmippOrigin(); MultidimArray<int> mask; mask.initZeros(I); int Xdimtilt=(int)XMIPP_MIN(FLOOR(0.5*(XSIZE(I)*cos(DEG2RAD(tilt)))), 0.5*(XSIZE(I)-(2*L+1))); int N=0; for (int i=STARTINGY(I); i<=FINISHINGY(I); i++) for (int j=-Xdimtilt; j<=Xdimtilt;j++) { A2D_ELEM(mask,i,j)=1; N++; } // Estimate the local variance MultidimArray<double> localVariance; localVariance.initZeros(I); double meanVariance=0; FOR_ALL_ELEMENTS_IN_ARRAY2D(I) { // Center a mask of size 5x5 and estimate the variance within the mask double meanPiece=0, variancePiece=0; double Npiece=0; for (int ii=i-L; ii<=i+L; ii++) { if (INSIDEY(I,ii)) for (int jj=j-L; jj<=j+L; jj++) { if (INSIDEX(I,jj)) { double pixval=A2D_ELEM(I,ii,jj); meanPiece+=pixval; variancePiece+=pixval*pixval; ++Npiece; } } } meanPiece/=Npiece; variancePiece=variancePiece/(Npiece-1)- Npiece/(Npiece-1)*meanPiece*meanPiece; A2D_ELEM(localVariance,i,j)=variancePiece; meanVariance+=variancePiece; } meanVariance*=1.0/N; // Test the hypothesis that the variance in this piece is // the same as the variance in the whole image double iFu=1/icdf_FSnedecor(4*L*L+4*L,N-1,0.975); double iFl=1/icdf_FSnedecor(4*L*L+4*L,N-1,0.025); double iMeanVariance=1.0/meanVariance; FOR_ALL_ELEMENTS_IN_ARRAY2D(localVariance) { if (A2D_ELEM(localVariance,i,j)==0) A2D_ELEM(mask,i,j)=-2; if (A2D_ELEM(mask,i,j)==1) { double ratio=A2D_ELEM(localVariance,i,j)*iMeanVariance; double thl=ratio*iFu; double thu=ratio*iFl; if (thl>1 || thu<1) A2D_ELEM(mask,i,j)=-1; } } #ifdef DEBUG Image<double> save; save()=I; save.write("PPP.xmp"); save()=localVariance; save.write("PPPLocalVariance.xmp"); Image<int> savemask; savemask()=mask; savemask.write("PPPmask.xmp"); #endif // Compute the statistics again in the reduced mask double avg, stddev, min, max; computeStats_within_binary_mask(mask, I, min, max, avg, stddev); double cosTilt=cos(DEG2RAD(tilt)); double iCosTilt=1.0/cosTilt; if (tomography0) { double iadjustedStddev=1.0/(sigma0*cosTilt); FOR_ALL_ELEMENTS_IN_ARRAY2D(I) switch (A2D_ELEM(mask,i,j)) { case -2: A2D_ELEM(I,i,j)=0; break; case 0: if (tiltMask) A2D_ELEM(I,i,j)=0; else A2D_ELEM(I,i,j)=(A2D_ELEM(I,i,j)*iCosTilt-mu0)*iadjustedStddev; break; case -1: case 1: A2D_ELEM(I,i,j)=(A2D_ELEM(I,i,j)*iCosTilt-mu0)*iadjustedStddev; break; } } else {
// Fill data array with oversampled Fourier transform, and calculate its power spectrum void Projector::computeFourierTransformMap(MultidimArray<DOUBLE> &vol_in, MultidimArray<DOUBLE> &power_spectrum, int current_size, int nr_threads, bool do_gridding) { MultidimArray<DOUBLE> Mpad; MultidimArray<Complex > Faux; FourierTransformer transformer; // DEBUGGING: multi-threaded FFTWs are giving me a headache? // For a long while: switch them off! //transformer.setThreadsNumber(nr_threads); DOUBLE normfft; // Size of padded real-space volume int padoridim = padding_factor * ori_size; // Initialize data array of the oversampled transform ref_dim = vol_in.getDim(); // Make Mpad switch (ref_dim) { case 2: Mpad.initZeros(padoridim, padoridim); normfft = (DOUBLE)(padding_factor * padding_factor); break; case 3: Mpad.initZeros(padoridim, padoridim, padoridim); if (data_dim ==3) normfft = (DOUBLE)(padding_factor * padding_factor * padding_factor); else normfft = (DOUBLE)(padding_factor * padding_factor * padding_factor * ori_size); break; default: REPORT_ERROR("Projector::computeFourierTransformMap%%ERROR: Dimension of the data array should be 2 or 3"); } // First do a gridding pre-correction on the real-space map: // Divide by the inverse Fourier transform of the interpolator in Fourier-space // 10feb11: at least in 2D case, this seems to be the wrong thing to do!!! // TODO: check what is best for subtomo! if (do_gridding)// && data_dim != 3) griddingCorrect(vol_in); // Pad translated map with zeros vol_in.setXmippOrigin(); Mpad.setXmippOrigin(); FOR_ALL_ELEMENTS_IN_ARRAY3D(vol_in) // This will also work for 2D A3D_ELEM(Mpad, k, i, j) = A3D_ELEM(vol_in, k, i, j); // Translate padded map to put origin of FT in the center CenterFFT(Mpad, true); // Calculate the oversampled Fourier transform transformer.FourierTransform(Mpad, Faux, false); // Free memory: Mpad no longer needed Mpad.clear(); // Resize data array to the right size and initialise to zero initZeros(current_size); // Fill data only for those points with distance to origin less than max_r // (other points will be zero because of initZeros() call above // Also calculate radial power spectrum power_spectrum.initZeros(ori_size / 2 + 1); MultidimArray<DOUBLE> counter(power_spectrum); counter.initZeros(); int max_r2 = r_max * r_max * padding_factor * padding_factor; FOR_ALL_ELEMENTS_IN_FFTW_TRANSFORM(Faux) // This will also work for 2D { int r2 = kp*kp + ip*ip + jp*jp; // The Fourier Transforms are all "normalised" for 2D transforms of size = ori_size x ori_size if (r2 <= max_r2) { // Set data array A3D_ELEM(data, kp, ip, jp) = DIRECT_A3D_ELEM(Faux, k, i, j) * normfft; // Calculate power spectrum int ires = ROUND( sqrt((DOUBLE)r2) / padding_factor ); // Factor two because of two-dimensionality of the complex plane DIRECT_A1D_ELEM(power_spectrum, ires) += norm(A3D_ELEM(data, kp, ip, jp)) / 2.; DIRECT_A1D_ELEM(counter, ires) += 1.; } } // Calculate radial average of power spectrum FOR_ALL_DIRECT_ELEMENTS_IN_ARRAY1D(power_spectrum) { if (DIRECT_A1D_ELEM(counter, i) < 1.) DIRECT_A1D_ELEM(power_spectrum, i) = 0.; else DIRECT_A1D_ELEM(power_spectrum, i) /= DIRECT_A1D_ELEM(counter, i); } transformer.cleanup(); }
//majorAxis and minorAxis is the estimated particle size in px void ProgSortByStatistics::processInprocessInputPrepareSPTH(MetaData &SF, bool trained) { //#define DEBUG PCAMahalanobisAnalyzer tempPcaAnalyzer0; PCAMahalanobisAnalyzer tempPcaAnalyzer1; PCAMahalanobisAnalyzer tempPcaAnalyzer2; PCAMahalanobisAnalyzer tempPcaAnalyzer3; PCAMahalanobisAnalyzer tempPcaAnalyzer4; //Morphology tempPcaAnalyzer0.clear(); //Signal to noise ratio tempPcaAnalyzer1.clear(); tempPcaAnalyzer2.clear(); tempPcaAnalyzer3.clear(); //Histogram analysis, to detect black points and saturated parts tempPcaAnalyzer4.clear(); double sign = 1;//;-1; int numNorm = 3; int numDescriptors0=numNorm; int numDescriptors2=4; int numDescriptors3=11; int numDescriptors4 = 10; MultidimArray<float> v0(numDescriptors0); MultidimArray<float> v2(numDescriptors2); MultidimArray<float> v3(numDescriptors3); MultidimArray<float> v4(numDescriptors4); if (verbose>0) { std::cout << " Sorting particle set by new xmipp method..." << std::endl; } int nr_imgs = SF.size(); if (verbose>0) init_progress_bar(nr_imgs); int c = XMIPP_MAX(1, nr_imgs / 60); int imgno = 0, imgnoPCA=0; bool thereIsEnable=SF.containsLabel(MDL_ENABLED); bool first=true; // We assume that at least there is one particle size_t Xdim, Ydim, Zdim, Ndim; getImageSize(SF,Xdim,Ydim,Zdim,Ndim); //Initialization: MultidimArray<double> nI, modI, tempI, tempM, ROI; MultidimArray<bool> mask; nI.resizeNoCopy(Ydim,Xdim); modI.resizeNoCopy(Ydim,Xdim); tempI.resizeNoCopy(Ydim,Xdim); tempM.resizeNoCopy(Ydim,Xdim); mask.resizeNoCopy(Ydim,Xdim); mask.initConstant(true); MultidimArray<double> autoCorr(2*Ydim,2*Xdim); MultidimArray<double> smallAutoCorr; Histogram1D hist; Matrix2D<double> U,V,temp; Matrix1D<double> D; MultidimArray<int> radial_count; MultidimArray<double> radial_avg; Matrix1D<int> center(2); MultidimArray<int> distance; int dim; center.initZeros(); v0.initZeros(numDescriptors0); v2.initZeros(numDescriptors2); v3.initZeros(numDescriptors3); v4.initZeros(numDescriptors4); ROI.resizeNoCopy(Ydim,Xdim); ROI.setXmippOrigin(); FOR_ALL_ELEMENTS_IN_ARRAY2D(ROI) { double temp = std::sqrt(i*i+j*j); if ( temp < (Xdim/2)) A2D_ELEM(ROI,i,j)= 1; else A2D_ELEM(ROI,i,j)= 0; } Image<double> img; FourierTransformer transformer(FFTW_BACKWARD); FOR_ALL_OBJECTS_IN_METADATA(SF) { if (thereIsEnable) { int enabled; SF.getValue(MDL_ENABLED,enabled,__iter.objId); if ( (enabled==-1) ) { imgno++; continue; } } img.readApplyGeo(SF,__iter.objId); if (targetXdim!=-1 && targetXdim!=XSIZE(img())) selfScaleToSize(LINEAR,img(),targetXdim,targetXdim,1); MultidimArray<double> &mI=img(); mI.setXmippOrigin(); mI.statisticsAdjust(0,1); mask.setXmippOrigin(); //The size of v1 depends on the image size and must be declared here int numDescriptors1 = XSIZE(mI)/2; //=100; MultidimArray<float> v1(numDescriptors1); v1.initZeros(numDescriptors1); double var = 1; normalize(transformer,mI,tempI,modI,0,var,mask); modI.setXmippOrigin(); tempI.setXmippOrigin(); nI = sign*tempI*(modI*modI); tempM = (modI*modI); A1D_ELEM(v0,0) = (tempM*ROI).sum(); int index = 1; var+=2; while (index < numNorm) { normalize(transformer,mI,tempI,modI,0,var,mask); modI.setXmippOrigin(); tempI.setXmippOrigin(); nI += sign*tempI*(modI*modI); tempM += (modI*modI); A1D_ELEM(v0,index) = (tempM*ROI).sum(); index++; var+=2; } nI /= tempM; tempPcaAnalyzer0.addVector(v0); nI=(nI*ROI); auto_correlation_matrix(mI,autoCorr); if (first) { radialAveragePrecomputeDistance(autoCorr, center, distance, dim); first=false; } fastRadialAverage(autoCorr, distance, dim, radial_avg, radial_count); for (int n = 0; n < numDescriptors1; ++n) A1D_ELEM(v1,n)=(float)DIRECT_A1D_ELEM(radial_avg,n); tempPcaAnalyzer1.addVector(v1); #ifdef DEBUG //String name = "000005@Images/Extracted/run_002/extra/BPV_1386.stk"; String name = "000010@Images/Extracted/run_001/extra/KLH_Dataset_I_Training_0028.stk"; //String name = "001160@Images/Extracted/run_001/DefaultFamily5"; std::cout << img.name() << std::endl; if (img.name()==name2) { FileName fpName = "test_1.txt"; mI.write(fpName); fpName = "test_2.txt"; nI.write(fpName); fpName = "test_3.txt"; tempM.write(fpName); fpName = "test_4.txt"; ROI.write(fpName); //exit(1); } #endif nI.binarize(0); int im = labelImage2D(nI,nI,8); compute_hist(nI, hist, 0, im, im+1); size_t l; int k,i,j; hist.maxIndex(l,k,i,j); A1D_ELEM(hist,j)=0; hist.maxIndex(l,k,i,j); nI.binarizeRange(j-1,j+1); double x0=0,y0=0,majorAxis=0,minorAxis=0,ellipAng=0; size_t area=0; fitEllipse(nI,x0,y0,majorAxis,minorAxis,ellipAng,area); A1D_ELEM(v2,0)=majorAxis/((img().xdim) ); A1D_ELEM(v2,1)=minorAxis/((img().xdim) ); A1D_ELEM(v2,2)= (fabs((img().xdim)/2-x0)+fabs((img().ydim)/2-y0))/((img().xdim)/2); A1D_ELEM(v2,3)=area/( (double)((img().xdim)/2)*((img().ydim)/2) ); for (int n=0 ; n < numDescriptors2 ; n++) { if ( std::isnan(std::abs(A1D_ELEM(v2,n)))) A1D_ELEM(v2,n)=0; } tempPcaAnalyzer2.addVector(v2); //mI.setXmippOrigin(); //auto_correlation_matrix(mI*ROI,autoCorr); //auto_correlation_matrix(nI,autoCorr); autoCorr.window(smallAutoCorr,-5,-5, 5, 5); smallAutoCorr.copy(temp); svdcmp(temp,U,D,V); for (int n = 0; n < numDescriptors3; ++n) A1D_ELEM(v3,n)=(float)VEC_ELEM(D,n); //A1D_ELEM(v3,n)=(float)VEC_ELEM(D,n)/VEC_ELEM(D,0); tempPcaAnalyzer3.addVector(v3); double minVal=0.; double maxVal=0.; mI.computeDoubleMinMax(minVal,maxVal); compute_hist(mI, hist, minVal, maxVal, 100); for (int n=0 ; n <= numDescriptors4-1 ; n++) { A1D_ELEM(v4,n)= (hist.percentil((n+1)*10)); } tempPcaAnalyzer4.addVector(v4); #ifdef DEBUG if (img.name()==name1) { FileName fpName = "test.txt"; mI.write(fpName); fpName = "test3.txt"; nI.write(fpName); } #endif imgno++; imgnoPCA++; if (imgno % c == 0 && verbose>0) progress_bar(imgno); } tempPcaAnalyzer0.evaluateZScore(2,20,trained); tempPcaAnalyzer1.evaluateZScore(2,20,trained); tempPcaAnalyzer2.evaluateZScore(2,20,trained); tempPcaAnalyzer3.evaluateZScore(2,20,trained); tempPcaAnalyzer4.evaluateZScore(2,20,trained); pcaAnalyzer.push_back(tempPcaAnalyzer0); pcaAnalyzer.push_back(tempPcaAnalyzer1); pcaAnalyzer.push_back(tempPcaAnalyzer1); pcaAnalyzer.push_back(tempPcaAnalyzer3); pcaAnalyzer.push_back(tempPcaAnalyzer4); }
void PolyZernikes::fit(const Matrix1D<int> & coef, MultidimArray<double> & im, MultidimArray<double> &weight, MultidimArray<bool> & ROI, int verbose) { this->create(coef); size_t xdim = XSIZE(im); size_t ydim = YSIZE(im); //int numZer = (size_t)coef.sum(); int numZer = (size_t)coef.sum(); //Actually polOrder corresponds to the polynomial order +1 int polOrder=(int)ZERNIKE_ORDER(coef.size()); im.setXmippOrigin(); Matrix2D<double> polValue(polOrder,polOrder); //First argument means number of images //Second argument means number of pixels WeightedLeastSquaresHelper weightedLeastSquaresHelper; Matrix2D<double>& zerMat=weightedLeastSquaresHelper.A; zerMat.resizeNoCopy((size_t)ROI.sum(), numZer); double iMaxDim2 = 2./std::max(xdim,ydim); size_t pixel_idx=0; weightedLeastSquaresHelper.b.resizeNoCopy((size_t)ROI.sum()); weightedLeastSquaresHelper.w.resizeNoCopy(weightedLeastSquaresHelper.b); FOR_ALL_ELEMENTS_IN_ARRAY2D(im) { if ( (A2D_ELEM(ROI,i,j))) { //For one i we swap the different j double y=i*iMaxDim2; double x=j*iMaxDim2; //polValue = [ 0 y y2 y3 ... // x xy xy2 xy3 ... // x2 x2y x2y2 x2y3 ] //dMij(polValue,py,px) py es fila, px es columna for (int py = 0; py < polOrder; ++py) { double ypy=std::pow(y,py); for (int px = 0; px < polOrder; ++px) dMij(polValue,px,py) = ypy*std::pow(x,px); } Matrix2D<int> *fMat; //We generate the representation of the Zernike polynomials for (int k=0; k < numZer; ++k) { fMat = &fMatV[k]; if (fMat == NULL) continue; double temp = 0; for (size_t px = 0; px < (*fMat).Xdim(); ++px) for (size_t py = 0; py < (*fMat).Ydim(); ++py) temp += dMij(*fMat,py,px)*dMij(polValue,py,px); dMij(zerMat,pixel_idx,k) = temp; } VEC_ELEM(weightedLeastSquaresHelper.b,pixel_idx)=A2D_ELEM(im,i,j); VEC_ELEM(weightedLeastSquaresHelper.w,pixel_idx)=std::abs(A2D_ELEM(weight,i,j)); ++pixel_idx; } } Matrix1D<double> zernikeCoefficients; weightedLeastSquares(weightedLeastSquaresHelper, zernikeCoefficients); fittedCoeffs = zernikeCoefficients; // Pointer to the image to be fitted MultidimArray<double> reconstructed; reconstructed.resizeNoCopy(im); pixel_idx=0; FOR_ALL_ELEMENTS_IN_ARRAY2D(im) if (A2D_ELEM(ROI,i,j)) { double temp=0; for (int k=0; k < numZer; ++k) temp+=dMij(zerMat,pixel_idx,k)*VEC_ELEM(fittedCoeffs,k); A2D_ELEM(reconstructed,i,j)=temp; if ( fabs(A2D_ELEM(reconstructed,i,j)-A2D_ELEM(im,i,j)) > PI) A2D_ELEM(ROI,i,j) = false; ++pixel_idx; } pixel_idx=0; if (verbose > 0) { Image<double> save; save()=reconstructed; save.write("reconstructedZernikes.xmp"); ROI.write("ROI.txt"); } }
void PolyZernikes::zernikePols(const Matrix1D<int> coef, MultidimArray<double> & im, MultidimArray<bool> & ROI, int verbose) { this->create(coef); int polOrder=(int)ZERNIKE_ORDER(coef.size()); int numZer = coef.size(); int xdim = XSIZE(im); int ydim = YSIZE(im); im.setXmippOrigin(); Matrix2D<double> polValue(polOrder,polOrder); double iMaxDim2 = 2./std::max(xdim,ydim); double temp = 0; FOR_ALL_ELEMENTS_IN_ARRAY2D(im) { if (A2D_ELEM(ROI,i,j)) { //For one i we swap the different j double y=i*iMaxDim2; double x=j*iMaxDim2; //polValue = [ 0 y y2 y3 ... // x xy xy2 xy3 ... // x2 x2y x2y2 x2y3 ] //dMij(polValue,py,px) py es fila, px es columna for (int py = 0; py < polOrder; ++py) { double ypy=std::pow(y,py); for (int px = 0; px < polOrder; ++px) dMij(polValue,px,py) = ypy*std::pow(x,px); } Matrix2D<int> *fMat; //We generate the representation of the Zernike polynomials for (int k=0; k < numZer; ++k) { fMat = &fMatV[k]; if ( (dMij(*fMat,0,0) == 0) && MAT_SIZE(*fMat) == 1 ) continue; for (size_t px = 0; px < (*fMat).Xdim(); ++px) for (size_t py = 0; py < (*fMat).Ydim(); ++py) temp += dMij(*fMat,py,px)*dMij(polValue,py,px)*VEC_ELEM(coef,k); } A2D_ELEM(im,i,j) = temp; temp = 0; } } STARTINGX(im)=STARTINGY(im)=0; if (verbose == 1) { Image<double> save; save()=im; save.write("PPP1.xmp"); } }