Xmipp  v3.23.11-Nereus
angular_continuous_assign2.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  *
3  * Authors: Carlos Oscar Sanchez Sorzano coss@cnb.csic.es
4  *
5  * Unidad de Bioinformatica of Centro Nacional de Biotecnologia , CSIC
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
20  * 02111-1307 USA
21  *
22  * All comments concerning this program package may be sent to the
23  * e-mail address 'xmipp@cnb.csic.es'
24  ***************************************************************************/
25 
27 #include "core/transformations.h"
30 #include "data/mask.h"
31 
32 // Empty constructor =======================================================
34 {
35  produces_a_metadata = true;
37  projector = nullptr;
38  ctfImage = nullptr;
39  rank = 0;
40 }
41 
43 {
44  delete projector;
45  delete ctfImage;
46 }
47 
48 // Read arguments ==========================================================
50 {
52  fnVol = getParam("--ref");
53  maxShift = getDoubleParam("--max_shift");
54  maxScale = getDoubleParam("--max_scale");
55  maxDefocusChange = getDoubleParam("--max_defocus_change");
56  maxAngularChange = getDoubleParam("--max_angular_change");
57  maxResol = getDoubleParam("--max_resolution");
58  maxA = getDoubleParam("--max_gray_scale");
59  maxB = getDoubleParam("--max_gray_shift");
60  Ts = getDoubleParam("--sampling");
61  Rmax = getIntParam("--Rmax");
62  pad = getIntParam("--padding");
63  optimizeGrayValues = checkParam("--optimizeGray");
64  optimizeShift = checkParam("--optimizeShift");
65  optimizeScale = checkParam("--optimizeScale");
66  optimizeAngles = checkParam("--optimizeAngles");
67  optimizeDefocus = checkParam("--optimizeDefocus");
68  ignoreCTF = checkParam("--ignoreCTF");
69  originalImageLabel = getParam("--applyTo");
70  phaseFlipped = checkParam("--phaseFlipped");
71  // penalization = getDoubleParam("--penalization");
72  fnResiduals = getParam("--oresiduals");
73  fnProjections = getParam("--oprojections");
74  sameDefocus = checkParam("--sameDefocus");
75  keep_input_columns = true; // each output metadata row is a deep copy of the input metadata row
76 }
77 
78 // Show ====================================================================
80 {
81  if (!verbose)
82  return;
84  std::cout
85  << "Reference volume: " << fnVol << std::endl
86  << "Max. Shift: " << maxShift << std::endl
87  << "Max. Scale: " << maxScale << std::endl
88  << "Max. Angular Change: " << maxAngularChange << std::endl
89  << "Max. Resolution: " << maxResol << std::endl
90  << "Max. Defocus Change: " << maxDefocusChange << std::endl
91  << "Max. Gray Scale: " << maxA << std::endl
92  << "Max. Gray Shift: " << maxB << std::endl
93  << "Sampling: " << Ts << std::endl
94  << "Max. Radius: " << Rmax << std::endl
95  << "Padding factor: " << pad << std::endl
96  << "Optimize gray: " << optimizeGrayValues << std::endl
97  << "Optimize shifts: " << optimizeShift << std::endl
98  << "Optimize scale: " << optimizeScale << std::endl
99  << "Optimize angles: " << optimizeAngles << std::endl
100  << "Optimize defocus: " << optimizeDefocus << std::endl
101  << "Ignore CTF: " << ignoreCTF << std::endl
102  << "Apply to: " << originalImageLabel << std::endl
103  << "Phase flipped: " << phaseFlipped << std::endl
104  // << "Penalization: " << penalization << std::endl
105  << "Force same defocus: " << sameDefocus << std::endl
106  << "Output residuals: " << fnResiduals << std::endl
107  << "Output projections: " << fnProjections << std::endl
108  ;
109 }
110 
111 // usage ===================================================================
113 {
114  addUsageLine("Make a continuous angular assignment");
115  defaultComments["-i"].clear();
116  defaultComments["-i"].addComment("Metadata with initial alignment");
117  defaultComments["-o"].clear();
118  defaultComments["-o"].addComment("Stack of images prepared for 3D reconstruction");
120  addParamsLine(" --ref <volume> : Reference volume");
121  addParamsLine(" [--max_shift <s=-1>] : Maximum shift allowed in pixels");
122  addParamsLine(" [--max_scale <s=0.02>] : Maximum scale change");
123  addParamsLine(" [--max_angular_change <a=5>] : Maximum angular change allowed (in degrees)");
124  addParamsLine(" [--max_defocus_change <d=500>] : Maximum defocus change allowed (in Angstroms)");
125  addParamsLine(" [--max_resolution <f=4>] : Maximum resolution (A)");
126  addParamsLine(" [--max_gray_scale <a=0.05>] : Maximum gray scale change");
127  addParamsLine(" [--max_gray_shift <b=0.05>] : Maximum gray shift change as a factor of the image standard deviation");
128  addParamsLine(" [--sampling <Ts=1>] : Sampling rate (A/pixel)");
129  addParamsLine(" [--Rmax <R=-1>] : Maximum radius (px). -1=Half of volume size");
130  addParamsLine(" [--padding <p=2>] : Padding factor");
131  addParamsLine(" [--optimizeGray] : Optimize gray values");
132  addParamsLine(" [--optimizeShift] : Optimize shift");
133  addParamsLine(" [--optimizeScale] : Optimize scale");
134  addParamsLine(" [--optimizeAngles] : Optimize angles");
135  addParamsLine(" [--optimizeDefocus] : Optimize defocus");
136  addParamsLine(" [--ignoreCTF] : Ignore CTF");
137  addParamsLine(" [--applyTo <label=image>] : Which is the source of images to apply the final transformation");
138  addParamsLine(" [--phaseFlipped] : Input images have been phase flipped");
139  // addParamsLine(" [--penalization <l=100>] : Penalization for the average term");
140  addParamsLine(" [--sameDefocus] : Force defocusU = defocusV");
141  addParamsLine(" [--oresiduals <stack=\"\">] : Output stack for the residuals");
142  addParamsLine(" [--oprojections <stack=\"\">] : Output stack for the projections");
143  addExampleLine("A typical use is:",false);
144  addExampleLine("xmipp_angular_continuous_assign2 -i anglesFromDiscreteAssignment.xmd --ref reference.vol -o assigned_angles.stk");
145 }
146 
148 {
150  if (fnResiduals!="")
152  if (fnProjections!="")
154 }
155 
156 // Produce side information ================================================
158 {
159  // Read the reference volume
160  Image<double> V;
161  if (rank==0)
162  {
163  V.read(fnVol);
164  V().setXmippOrigin();
165  Xdim=XSIZE(V());
166  }
167  else
168  {
169  size_t ydim, zdim, ndim;
170  getImageSize(fnVol, Xdim, ydim, zdim, ndim);
171  }
172 
173  Ip().initZeros(Xdim,Xdim);
174  E().initZeros(Xdim,Xdim);
175  Ifilteredp().initZeros(Xdim,Xdim);
176  Ifilteredp().setXmippOrigin();
177 
178  // Construct mask
179  if (Rmax<0)
180  Rmax=Xdim/2;
181  Mask mask;
182  mask.type = BINARY_CIRCULAR_MASK;
183  mask.mode = INNER_MASK;
184  mask.R1 = Rmax;
185  mask.generate_mask(Xdim,Xdim);
186  mask2D=mask.get_binary_mask();
187  iMask2Dsum=1.0/mask2D.sum();
188 
189  // Construct reference covariance
193  covarianceMatrix(E(),C0);
195  {
196  double val=MAT_ELEM(C0,i,j);
197  if (val<0.5)
198  MAT_ELEM(C0,i,j)=0;
199  else
200  MAT_ELEM(C0,i,j)=1;
201  }
202 
203  // Construct projector
204  if (rank==0)
206  else
208 
209  // Low pass filter
212  filter.raised_w=0.02;
213 
214  // Transformation matrix
215  A.initIdentity(3);
216 
217  // Continuous cost
218  if (optimizeGrayValues)
220  else
222 }
223 
224 //#define DEBUG
225 void ProgAngularContinuousAssign2::updateCTFImage(double defocusU, double defocusV, double angle)
226 {
227  ctf.K=1; // get pure CTF with no envelope
228  currentDefocusU=ctf.DeltafU=defocusU;
229  currentDefocusV=ctf.DeltafV=defocusV;
232  if (ctfImage==nullptr)
233  {
235  ctfImage->resizeNoCopy(I());
237 
238  ctfEnvelope = std::make_unique<MultidimArray<double>>();
239  ctfEnvelope->resizeNoCopy(I());
241  }
242  ctf.generateCTF((int)YSIZE(I()),(int)XSIZE(I()),*ctfImage,Ts);
243  ctf.generateEnvelope((int)YSIZE(I()),(int)XSIZE(I()),*ctfEnvelope,Ts);
244  if (phaseFlipped)
246  A2D_ELEM(*ctfImage,i,j)=fabs(A2D_ELEM(*ctfImage,i,j));
247 }
248 
249 //#define DEBUG
250 //#define DEBUG2
251 double tranformImage(ProgAngularContinuousAssign2 *prm, double rot, double tilt, double psi,
252  double a, double b, const Matrix2D<double> &A, double deltaDefocusU, double deltaDefocusV, double deltaDefocusAngle, int degree)
253 {
254  if (prm->hasCTF)
255  {
256  double defocusU=prm->old_defocusU+deltaDefocusU;
257  double defocusV;
258  if (prm->sameDefocus){
259  defocusV=defocusU;
260  }
261  else
262  defocusV=prm->old_defocusV+deltaDefocusV;
263  double angle=prm->old_defocusAngle+deltaDefocusAngle;
264  if (defocusU!=prm->currentDefocusU || defocusV!=prm->currentDefocusV || angle!=prm->currentAngle)
265  prm->updateCTFImage(defocusU,defocusV,angle);
266  }
267  projectVolume(*(prm->projector), prm->P, (int)XSIZE(prm->I()), (int)XSIZE(prm->I()), rot, tilt, psi, (const MultidimArray<double> *)prm->ctfImage);
268  if (prm->old_flip)
269  {
270  MAT_ELEM(A,0,0)*=-1;
271  MAT_ELEM(A,0,1)*=-1;
272  MAT_ELEM(A,0,2)*=-1;
273  }
274 
275  applyGeometry(degree,prm->Ifilteredp(),prm->Ifiltered(),A,xmipp_transformation::IS_NOT_INV,xmipp_transformation::DONT_WRAP,0.);
276  const MultidimArray<double> &mP=prm->P();
277  const MultidimArray<int> &mMask2D=prm->mask2D;
278  MultidimArray<double> &mIfilteredp=prm->Ifilteredp();
279  MultidimArray<double> &mE=prm->E();
280  mE.initZeros();
281  if (prm->contCost==CONTCOST_L1)
282  {
284  {
285  if (DIRECT_MULTIDIM_ELEM(mMask2D,n))
286  {
287  DIRECT_MULTIDIM_ELEM(mIfilteredp,n)=DIRECT_MULTIDIM_ELEM(mIfilteredp,n);
288  double val=(a*DIRECT_MULTIDIM_ELEM(mP,n)+b)-DIRECT_MULTIDIM_ELEM(mIfilteredp,n);
289  DIRECT_MULTIDIM_ELEM(mE,n)=val;
290  }
291  else
292  DIRECT_MULTIDIM_ELEM(mIfilteredp,n)=0;
293  }
294  }
295  else
296  {
298  {
299  if (DIRECT_MULTIDIM_ELEM(mMask2D,n))
300  {
301  double val=DIRECT_MULTIDIM_ELEM(mP,n)-DIRECT_MULTIDIM_ELEM(mIfilteredp,n);
302  DIRECT_MULTIDIM_ELEM(mE,n)=val;
303  }
304  else
305  DIRECT_MULTIDIM_ELEM(mIfilteredp,n)=0;
306  }
307  }
308 
309  double cost=0.0;
310  if (prm->contCost==CONTCOST_L1)
311  {
313  cost+=fabs(DIRECT_A2D_ELEM(mE,i,j));
314  cost*=prm->iMask2Dsum;
315  }
316  else
317  cost=-correlationIndex(mIfilteredp,mP,&mMask2D);
318 
319  //covarianceMatrix(mE, prm->C);
320  //double div=computeCovarianceMatrixDivergence(prm->C0,prm->C)/MAT_XSIZE(prm->C);
321 #ifdef DEBUG
322  std::cout << "A=" << A << std::endl;
323  Image<double> save;
324  save()=a*prm->P()+b;
325  save.write("PPPtheo.xmp");
326  save()=prm->Ifilteredp();
327  save.write("PPPfilteredp.xmp");
328  save()=prm->Ifiltered();
329  save.write("PPPfiltered.xmp");
330  save()=prm->E();
331  save.write("PPPe.xmp");
332  //save()=prm->C;
333  //save.write("PPPc.xmp");
334  //save()=prm->C0;
335  //save.write("PPPc0.xmp");
336  //std::cout << "Cost=" << cost << " Div=" << div << " avg=" << avg << std::endl;
337  std::cout << "Cost=" << cost << std::endl;
338  std::cout << "Press any key" << std::endl;
339  char c; std::cin >> c;
340 #endif
341  //return div+prm->penalization*fabs(avg);
342  //return cost+prm->penalization*fabs(avg);
343  //return div;
344  return cost;
345 }
346 
347 
348 double continuous2cost(double *x, void *_prm)
349 {
350  double a=x[1];
351  double b=x[2];
352  double deltax=x[3];
353  double deltay=x[4];
354  double scalex=x[5];
355  double scaley=x[6];
356  double scaleAngle=x[7];
357  double deltaRot=x[8];
358  double deltaTilt=x[9];
359  double deltaPsi=x[10];
360  double deltaDefocusU=x[11];
361  double deltaDefocusV=x[12];
362  double deltaDefocusAngle=x[13];
363  auto *prm=(ProgAngularContinuousAssign2 *)_prm;
364  if (prm->maxShift>0 && deltax*deltax+deltay*deltay>prm->maxShift*prm->maxShift)
365  return 1e38;
366  if (fabs(scalex)>prm->maxScale || fabs(scaley)>prm->maxScale)
367  return 1e38;
368  if (fabs(deltaRot)>prm->maxAngularChange || fabs(deltaTilt)>prm->maxAngularChange || fabs(deltaPsi)>prm->maxAngularChange)
369  return 1e38;
370  if (fabs(a-prm->old_grayA)>prm->maxA)
371  return 1e38;
372  if (fabs(b)>prm->maxB*prm->Istddev)
373  return 1e38;
374  if (fabs(deltaDefocusU)>prm->maxDefocusChange || fabs(deltaDefocusV)>prm->maxDefocusChange)
375  return 1e38;
376 // MAT_ELEM(prm->A,0,0)=1+scalex;
377 // MAT_ELEM(prm->A,1,1)=1+scaley;
378 // In Matlab
379 // syms sx sy t
380 // R=[cos(t) -sin(t); sin(t) cos(t)]
381 // S=[1+sx 0; 0 1+sy]
382 // simple(transpose(R)*S*R)
383 // [ sx - sx*sin(t)^2 + sy*sin(t)^2 + 1, -sin(2*t)*(sx/2 - sy/2)]
384 // [ -sin(2*t)*(sx/2 - sy/2), sy + sx*sin(t)^2 - sy*sin(t)^2 + 1]
385  double sin2_t=sin(scaleAngle)*sin(scaleAngle);
386  double sin_2t=sin(2*scaleAngle);
387  MAT_ELEM(prm->A,0,0)=1+scalex+(scaley-scalex)*sin2_t;
388  MAT_ELEM(prm->A,0,1)=0.5*(scaley-scalex)*sin_2t;
389  MAT_ELEM(prm->A,1,0)=MAT_ELEM(prm->A,0,1);
390  MAT_ELEM(prm->A,1,1)=1+scaley-(scaley-scalex)*sin2_t;
391  MAT_ELEM(prm->A,0,2)=prm->old_shiftX+deltax;
392  MAT_ELEM(prm->A,1,2)=prm->old_shiftY+deltay;
393  return tranformImage(prm,prm->old_rot+deltaRot, prm->old_tilt+deltaTilt, prm->old_psi+deltaPsi,
394  a, b, prm->A, deltaDefocusU, deltaDefocusV, deltaDefocusAngle, xmipp_transformation::LINEAR);
395 }
396 
397 // Predict =================================================================
398 //#define DEBUG
399 void ProgAngularContinuousAssign2::processImage(const FileName &fnImg, const FileName &fnImgOut, const MDRow &rowIn, MDRow &rowOut)
400 {
401  // Read input image and initial parameters
402 // ApplyGeoParams geoParams;
403 // geoParams.only_apply_shifts=false;
404 // geoParams.wrap=DONT_WRAP;
405 
406  //AJ some definitions
407  double corrIdx=0.0;
408  double corrMask = 0.0;
409  double corrWeight = 0.0;
410  double imedDist = 0.0;
411 
412  if (verbose>=2)
413  std::cout << "Processing " << fnImg << std::endl;
414  I.read(fnImg);
415  I().setXmippOrigin();
416  Istddev=I().computeStddev();
417 
418  Ifiltered()=I();
420 
426  old_flip = rowIn.getValueOrDefault(MDL_FLIP, false);
427  double old_scaleX=0, old_scaleY=0, old_scaleAngle=0;
428  old_grayA=1;
429  old_grayB=0;
431  {
432  old_scaleX = rowIn.getValue<double>(MDL_CONTINUOUS_SCALE_X);
433  old_scaleY = rowIn.getValue<double>(MDL_CONTINUOUS_SCALE_Y);
435  old_scaleAngle = rowIn.getValue<double>(MDL_CONTINUOUS_SCALE_ANGLE);
436  old_shiftX = rowIn.getValue<double>(MDL_CONTINUOUS_X);
437  old_shiftY = rowIn.getValue<double>(MDL_CONTINUOUS_Y);
438  old_flip = rowIn.getValue<bool>(MDL_CONTINUOUS_FLIP);
439  }
440 
442  {
443  old_grayA = rowIn.getValue<double>(MDL_CONTINUOUS_GRAY_A);
444  old_grayB = rowIn.getValue<double>(MDL_CONTINUOUS_GRAY_B);
445  }
446 
448  {
449  hasCTF=true;
450  ctf.readFromMdRow(rowIn);
460  }
461  else
462  hasCTF=false;
463 
464  Matrix1D<double> p(13), steps(13);
465  // COSS: Gray values are optimized in transform_image_adjust_gray_values
466  if (optimizeGrayValues)
467  {
468  p(0)=old_grayA; // a in I'=a*I+b
469  p(1)=old_grayB; // b in I'=a*I+b
470  }
471  else
472  {
473  p(0)=1; // a in I'=a*I+b
474  p(1)=0; // b in I'=a*I+b
475  }
476  p(4)=old_scaleX;
477  p(5)=old_scaleY;
478  p(6)=old_scaleAngle;
479 
480  // default values
481  if (fnResiduals != "") {
482  rowOut.setValue<String>(MDL_IMAGE_RESIDUAL, "");
483  }
484  if (fnProjections != "") {
485  rowOut.setValue<String>(MDL_IMAGE_REF, "");
486  }
487 
488  // Optimize
489  double cost=-1;
490  if (fabs(old_scaleX)>maxScale || fabs(old_scaleY)>maxScale)
491  rowOut.setValue(MDL_ENABLED,-1);
492  else
493  {
494  try
495  {
496  cost=1e38;
497  int iter;
498  steps.initZeros();
499  if (optimizeGrayValues)
500  steps(0)=steps(1)=1.;
501  if (optimizeShift)
502  steps(2)=steps(3)=1.;
503  if (optimizeScale)
504  steps(4)=steps(5)=steps(6)=1.;
505  if (optimizeAngles)
506  steps(7)=steps(8)=steps(9)=1.;
507  if (optimizeDefocus) {
508  if (sameDefocus)
509  steps(10)=steps(12)=1.;
510  else {
511  steps(10)=steps(11)=steps(12)=1.;
512  if (hasCTF)
513  {
517  }
518  else
520  }
521  }
522  powellOptimizer(p, 1, 13, &continuous2cost, this, 0.01, cost, iter, steps, verbose>=2);
523  if (cost>1e30 || (cost>0 && contCost==CONTCOST_CORR))
524  {
525  rowOut.setValue(MDL_ENABLED,-1);
526  p.initZeros();
527  if (optimizeGrayValues)
528  {
529  p(0)=old_grayA; // a in I'=a*I+b
530  p(1)=old_grayB; // b in I'=a*I+b
531  }
532  else
533  {
534  p(0)=1;
535  p(1)=0;
536  }
537  p(4)=old_scaleX;
538  p(5)=old_scaleY;
539  p(6)=old_scaleAngle;
540  }
541  else
542  {
543  //Calculating several similarity measures between P and Ifilteredp (correlations and imed)
544  corrIdx = correlationIndex(P(), Ifilteredp());
545  corrMask = correlationMasked(P(), Ifilteredp());
546  corrWeight = correlationWeighted(P(), Ifilteredp());
547  imedDist = imedDistance(P(), Ifilteredp());
548 
549  if (fnResiduals!="")
550  {
551  FileName fnResidual;
552  fnResidual.compose(fnImgOut.getPrefixNumber(),fnResiduals);
553  E.write(fnResidual);
554  rowOut.setValue(MDL_IMAGE_RESIDUAL,fnResidual);
555  }
556  if (fnProjections!="")
557  {
558  FileName fnProjection;
559  fnProjection.compose(fnImgOut.getPrefixNumber(),fnProjections);
560  P.write(fnProjection);
561  rowOut.setValue(MDL_IMAGE_REF,fnProjection);
562  }
563  }
564  if (contCost==CONTCOST_CORR)
565  cost=-cost;
566  if (verbose>=2)
567  std::cout << "I'=" << p(0) << "*I" << "+" << p(1) << " Dshift=(" << p(2) << "," << p(3) << ") "
568  << "scale=(" << 1+p(4) << "," << 1+p(5) << ", angle=" << p(6) << ") Drot=" << p(7) << " Dtilt=" << p(8)
569  << " Dpsi=" << p(9) << " DU=" << p(10) << " DV=" << p(11) << " Dalpha=" << p(12) << std::endl;
570  // Apply
571  FileName fnOrig;
573  I.read(fnImg);
574  if (XSIZE(Ip())!=XSIZE(I()))
575  {
577  I()=Ip();
578  }
579  A(0,2)=p(2)+old_shiftX;
580  A(1,2)=p(3)+old_shiftY;
581  double scalex=p(4);
582  double scaley=p(5);
583  double scaleAngle=p(6);
584  double sin2_t=sin(scaleAngle)*sin(scaleAngle);
585  double sin_2t=sin(2*scaleAngle);
586  A(0,0)=1+scalex+(scaley-scalex)*sin2_t;
587  A(0,1)=0.5*(scaley-scalex)*sin_2t;
588  A(1,0)=A(0,1);
589  A(1,1)=1+scaley-(scaley-scalex)*sin2_t;
590 // A(0,0)=1+p(4);
591 // A(1,1)=1+p(5);
592 
593  if (old_flip)
594  {
595  MAT_ELEM(A,0,0)*=-1;
596  MAT_ELEM(A,0,1)*=-1;
597  MAT_ELEM(A,0,2)*=-1;
598  }
599  applyGeometry(xmipp_transformation::BSPLINE3,Ip(),I(),A,xmipp_transformation::IS_NOT_INV,xmipp_transformation::DONT_WRAP);
600  if (optimizeGrayValues)
601  {
602  MultidimArray<double> &mIp=Ip();
603  double ia=1.0/p(0);
604  double b=p(1);
606  {
609  else
610  DIRECT_MULTIDIM_ELEM(mIp,n)=0.0;
611  }
612  }
613  Ip.write(fnImgOut);
614  }
615  catch (XmippError &XE)
616  {
617  std::cerr << XE.what() << std::endl;
618  std::cerr << "Warning: Cannot refine " << fnImg << std::endl;
619  rowOut.setValue(MDL_ENABLED,-1);
620  }
621  }
622  rowOut.setValue(MDL_IMAGE_ORIGINAL, fnImg);
623  rowOut.setValue(MDL_IMAGE, fnImgOut);
624  rowOut.setValue(MDL_ANGLE_ROT, old_rot+p(7));
625  rowOut.setValue(MDL_ANGLE_TILT, old_tilt+p(8));
626  rowOut.setValue(MDL_ANGLE_PSI, old_psi+p(9));
627  rowOut.setValue(MDL_SHIFT_X, 0.);
628  rowOut.setValue(MDL_SHIFT_Y, 0.);
629  rowOut.setValue(MDL_FLIP, false);
630  rowOut.setValue(MDL_COST, cost);
631  if (optimizeGrayValues)
632  {
633  rowOut.setValue(MDL_CONTINUOUS_GRAY_A,p(0));
634  rowOut.setValue(MDL_CONTINUOUS_GRAY_B,p(1));
635  }
636  rowOut.setValue(MDL_CONTINUOUS_SCALE_X,p(4));
637  rowOut.setValue(MDL_CONTINUOUS_SCALE_Y,p(5));
639  rowOut.setValue(MDL_CONTINUOUS_X,p(2)+old_shiftX);
640  rowOut.setValue(MDL_CONTINUOUS_Y,p(3)+old_shiftY);
642  if (hasCTF)
643  {
644  rowOut.setValue(MDL_CTF_DEFOCUSU,old_defocusU+p(10));
645  if (sameDefocus)
646  rowOut.setValue(MDL_CTF_DEFOCUSV,old_defocusU+p(10));
647  else
648  rowOut.setValue(MDL_CTF_DEFOCUSV,old_defocusV+p(11));
650  if (sameDefocus)
651  rowOut.setValue(MDL_CTF_DEFOCUS_CHANGE,0.5*(p(10)+p(10)));
652  else
653  rowOut.setValue(MDL_CTF_DEFOCUS_CHANGE,0.5*(p(10)+p(11)));
654  if (old_defocusU+p(10)<0 || old_defocusU+p(11)<0)
655  rowOut.setValue(MDL_ENABLED,-1);
656  }
657  //Saving correlation and imed values in the metadata
658  rowOut.setValue(MDL_CORRELATION_IDX, corrIdx);
659  rowOut.setValue(MDL_CORRELATION_MASK, corrMask);
660  rowOut.setValue(MDL_CORRELATION_WEIGHT, corrWeight);
661  rowOut.setValue(MDL_IMED, imedDist);
662 
663 
664 #ifdef DEBUG
665  std::cout << "p=" << p << std::endl;
666  MetaDataVec MDaux;
667  MDaux.addRow(rowOut);
668  MDaux.write("PPPmd.xmd");
669  Image<double> save;
670  save()=P();
671  save.write("PPPprojection.xmp");
672  save()=I();
673  save.write("PPPexperimental.xmp");
674  //save()=C;
675  //save.write("PPPC.xmp");
676  Ip.write("PPPexperimentalp.xmp");
677  Ifiltered.write("PPPexperimentalFiltered.xmp");
678  Ifilteredp.write("PPPexperimentalFilteredp.xmp");
679  E.write("PPPresidual.xmp");
680  std::cout << A << std::endl;
681  std::cout << fnImgOut << " rewritten\n";
682  std::cout << "Press any key" << std::endl;
683  char c; std::cin >> c;
684 #endif
685 }
686 #undef DEBUG
687 
689 {
690  MetaData &ptrMdOut = getOutputMd();
691  ptrMdOut.removeDisabled();
692  if (contCost==CONTCOST_L1)
693  {
694  double minCost=1e38;
695  for (size_t objId : ptrMdOut.ids())
696  {
697  double cost;
698  ptrMdOut.getValue(MDL_COST,cost,objId);
699  if (cost<minCost)
700  minCost=cost;
701  }
702  for (size_t objId : ptrMdOut.ids())
703  {
704  double cost;
705  ptrMdOut.getValue(MDL_COST,cost,objId);
706  ptrMdOut.setValue(MDL_WEIGHT_CONTINUOUS2,minCost/cost,objId);
707  }
708  }
709  else
710  {
711  double maxCost=-1e38;
712  for (size_t objId : ptrMdOut.ids())
713  {
714  double cost;
715  ptrMdOut.getValue(MDL_COST,cost,objId);
716  if (cost>maxCost)
717  maxCost=cost;
718  }
719  for (size_t objId : ptrMdOut.ids())
720  {
721  double cost;
722  ptrMdOut.getValue(MDL_COST,cost,objId);
723  ptrMdOut.setValue(MDL_WEIGHT_CONTINUOUS2,cost/maxCost,objId);
724  }
725  }
726 
727  ptrMdOut.write(fn_out.replaceExtension("xmd"));
728 }
#define FOR_ALL_ELEMENTS_IN_MATRIX2D(m)
Definition: matrix2d.h:104
scale y of continuous assignment
X shift of continuous assignment.
Rotation angle of an image (double,degrees)
#define YSIZE(v)
#define A2D_ELEM(v, i, j)
Defocus U (Angstroms)
weighted correlation value between a particle and its assigned projection taking into the difference ...
scale angle of continuous assignment
double getDoubleParam(const char *param, int arg=0)
static MDLabel str2Label(const String &labelName)
double tranformImage(ProgAngularContinuousAssign2 *prm, double rot, double tilt, double psi, double a, double b, const Matrix2D< double > &A, double deltaDefocusU, double deltaDefocusV, double deltaDefocusAngle, int degree)
void generateEnvelope(int Ydim, int Xdim, MultidimArray< T > &CTF, double Ts=-1)
Definition: ctf.h:1271
size_t mdInSize
Number of input elements.
void inverseFourierTransform()
Definition: xmipp_fftw.cpp:329
std::unique_ptr< MultidimArray< double > > ctfEnvelope
ProgAngularContinuousAssign2()
Empty constructor.
FileName replaceExtension(const String &newExt) const
Defocus angle (degrees)
#define FOR_ALL_DIRECT_ELEMENTS_IN_ARRAY2D(m)
doublereal * c
void resizeNoCopy(const MultidimArray< T1 > &v)
double correlationMasked(const MultidimArray< double > &I1, const MultidimArray< double > &I2)
Definition: filters.cpp:1397
Flip of continuous assignment.
Definition: mask.h:360
virtual void write(const FileName &outFile, WriteModeMetaData mode=MD_OVERWRITE) const =0
Tilting angle of an image (double,degrees)
double DeltafV
Defocus in V (in Angstroms). Negative values are underfocused.
Definition: ctf.h:830
Shift for the image in the X axis (double)
void applyGeometry(int SplineDegree, MultidimArray< std::complex< double > > &V2, const MultidimArray< std::complex< double > > &V1, const Matrix2D< double > &A, bool inv, bool wrap, std::complex< double > outside, MultidimArray< double > *BcoeffsPtr)
#define DIRECT_A2D_ELEM(v, i, j)
void write(const FileName &name="", size_t select_img=ALL_IMAGES, bool isStack=false, int mode=WRITE_OVERWRITE, CastWriteMode castMode=CW_CAST, int _swapWrite=0)
double correlationIndex(const MultidimArray< T > &x, const MultidimArray< T > &y, const MultidimArray< int > *mask=NULL, MultidimArray< double > *Contributions=NULL)
void getImageSize(const MetaData &md, size_t &Xdim, size_t &Ydim, size_t &Zdim, size_t &Ndim, MDLabel image_label)
constexpr int CONTCOST_L1
void compose(const String &str, const size_t no, const String &ext="")
Special label to be used when gathering MDs in MpiMetadataPrograms.
Name for the CTF Model (std::string)
void write(const FileName &outFile, WriteModeMetaData mode=MD_OVERWRITE) const
void powellOptimizer(Matrix1D< double > &p, int i0, int n, double(*f)(double *x, void *), void *prm, double ftol, double &fret, int &iter, const Matrix1D< double > &steps, bool show)
glob_prnt iter
virtual IdIteratorProxy< false > ids()
Y shift of continuous assignment.
correlation value between a particle and its assigned projection
#define STARTINGX(v)
virtual bool getValue(MDObject &mdValueOut, size_t id) const =0
doublereal * x
#define i
Is this image enabled? (int [-1 or 1])
size_t addRow(const MDRow &row) override
#define FOR_ALL_ELEMENTS_IN_ARRAY2D(m)
void processImage(const FileName &fnImg, const FileName &fnImgOut, const MDRow &rowIn, MDRow &rowOut)
double DeltafU
Global gain. By default, 1.
Definition: ctf.h:828
#define STARTINGY(v)
#define MAT_ELEM(m, i, j)
Definition: matrix2d.h:116
double azimuthal_angle
Azimuthal angle (between X and U) in degrees.
Definition: ctf.h:832
void readParams()
Read argument from command line.
doublereal * b
T & getValue(MDLabel label)
Name of an image from which MDL_IMAGE is coming from.
double continuous2cost(double *x, void *_prm)
const char * getParam(const char *param, int arg=0)
a value of continuous assignment
double correlationWeighted(MultidimArray< double > &I1, MultidimArray< double > &I2)
Definition: filters.cpp:1457
Cost for the image (double)
size_t getPrefixNumber(size_t pos=0) const
double R1
Definition: mask.h:413
Flip the image? (bool)
double imedDistance(const MultidimArray< double > &I1, const MultidimArray< double > &I2)
Definition: filters.cpp:1269
#define XSIZE(v)
#define FOR_ALL_DIRECT_ELEMENTS_IN_MULTIDIMARRAY(v)
int type
Definition: mask.h:402
#define DIRECT_MULTIDIM_ELEM(v, n)
void addExampleLine(const char *example, bool verbatim=true)
Name of a residual image associated to this image.
void projectVolume(FourierProjector &projector, Projection &P, int Ydim, int Xdim, double rot, double tilt, double psi, const MultidimArray< double > *ctf)
double maxShift
Maximum shift.
void readFromMdRow(const MDRow &row, bool disable_if_not_K=true)
Definition: ctf.cpp:1172
void createEmptyFile(const FileName &filename, int xdim, int ydim, int Zdim, size_t select_img, bool isStack, int mode, int _swapWrite, const MDRowVec *md)
int verbose
Verbosity level.
void initZeros()
Definition: matrix1d.h:592
void FourierTransform(T &v, T1 &V, bool getCopy=true)
Definition: xmipp_fftw.h:166
#define j
void scaleToSize(int SplineDegree, MultidimArrayGeneric &V2, const MultidimArrayGeneric &V1, int Xdim, int Ydim, int Zdim)
double steps
const T & getValueOrDefault(MDLabel label, const T &def) const
void generateCTF(const MultidimArray< T1 > &sample_image, MultidimArray< T2 > &CTF, double Ts=-1)
Definition: ctf.h:1194
double K
Global gain. By default, 1.
Definition: ctf.h:238
bool setValue(const MDLabel label, const T &valueIn, size_t id)
Weight due to angular continuous assignment.
void setValue(MDLabel label, const T &d, bool addLabel=true)
void show() const override
void generate_mask(bool apply_geo=false)
Definition: mask.cpp:1577
b value of continuous assignment
virtual bool containsLabel(MDLabel label) const =0
virtual void removeDisabled()
#define BINARY_CIRCULAR_MASK
Definition: mask.h:365
std::string String
Definition: xmipp_strings.h:34
void produceSideInfo()
Produce Side information.
Definition: ctf.cpp:1392
double psi(const double x)
double rnd_gaus()
bool keep_input_columns
Keep input metadata columns.
bool checkParam(const char *param)
scale x of continuous assignment
int read(const FileName &name, DataMode datamode=DATA, size_t select_img=ALL_IMAGES, bool mapData=false, int mode=WRITE_READONLY)
ProgClassifyCL2D * prm
Defocus change with respect to previous defoucs (Angstroms)
bool each_image_produces_an_output
Indicate that an output is produced for each image in the input.
Shift for the image in the Y axis (double)
void addUsageLine(const char *line, bool verbatim=false)
void initZeros(const MultidimArray< T1 > &op)
const MultidimArray< int > & get_binary_mask() const
Definition: mask.h:707
int getIntParam(const char *param, int arg=0)
Defocus V (Angstroms)
int * n
Name of an image (std::string)
MultidimArray< std::complex< double > > fftE
bool produces_a_metadata
Indicate that the unique final output file is a Metadata.
doublereal * a
double sum() const
Name of of the class image from which MDL_IMAGE is coming from.
#define LOWPASS
void addParamsLine(const String &line)
void initIdentity()
Definition: matrix2d.h:673
void updateCTFImage(double defocusU, double defocusV, double angle)
int mode
Definition: mask.h:407
void applyMaskSpace(MultidimArray< double > &v)
void covarianceMatrix(const MultidimArray< double > &I, Matrix2D< double > &C)
Definition: filters.cpp:1582
imed value between a particle and its assigned projection
masked correlation value between a particle and its assigned projection inside the region with pixel ...
constexpr int CONTCOST_CORR
std::map< String, CommentList > defaultComments
Definition: xmipp_program.h:83
constexpr int INNER_MASK
Definition: mask.h:47