Xmipp  v3.23.11-Nereus
flexible_alignment.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  *
3  * Authors: Slavica Jonic slavica.jonic@impmc.jussieu.fr
4  * Carlos Oscar Sanchez Sorzano coss.eps@ceu.es
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
19  * 02111-1307 USA
20  *
21  * All comments concerning this program package may be sent to the
22  * e-mail address 'xmipp@cnb.uam.es'
23  ***************************************************************************/
24 
25 #include <algorithm>
26 #include <fstream>
27 
29 #include "core/bilib/error.h"
30 #include "core/bilib/configs.h"
32 #include "core/multidim_array.h"
33 #include "core/transformations.h"
34 #include "core/xmipp_image.h"
35 #include "flexible_alignment.h"
36 #include "data/pdb.h"
37 #include "program_extension.h"
38 
39 // Empty constructor =======================================================
41 {
42  rangen = 0;
43  resume = false;
44  currentImgName = "";
46  produces_an_output = true;
47 }
48 
49 // Params definition ============================================================
52  "Compute deformation parameters according to a set of NMA modes");
53  defaultComments["-o"].clear();
54  defaultComments["-o"].addComment(
55  "Metadata with output alignment and deformations");
58  " --pdb <PDB_filename> : PDB Model to compute NMA");
59  addParamsLine(" [--odir <outputDir=\".\">] : Output directory");
60  addParamsLine(" [--resume] : Resume processing");
61  addParamsLine("==Generation of the deformed volumes==");
63  " --modes <filename> : File with a list of mode filenames");
65  " [--defampsampling <s=200>] : Deformation sampling");
67  " [--maxdefamp <s=2000>] : Maximum deformation amplitude");
69  " [--translsampling <s=2>] : Translational sampling");
71  " [--maxtransl <max=10>] : Maximum translation");
73  " [--sampling_rate <Ts=1>] : in Angstroms/pixel");
75  " [--filterVol <cutoff=15.>] : Filter the volume after deforming. Default cut-off is 15 A.");
77  " [--centerPDB] : Center the PDB structure");
79  " [--fixed_Gaussian <std=-1>] : For pseudo atoms fixed_Gaussian must be used.");
81  " : Default standard deviation <std> is read from PDB file.");
82  addParamsLine("==Angular assignment and mode detection==");
84  " [--mask <m=\"\">] : 2D Mask applied to the reference images of the deformed volume");
86  " :+Note that wavelet assignment needs the input images to be of a size power of 2");
88  " [--minAngularSampling <ang=3>] : Minimum angular sampling rate");
90  " [--gaussian_Real <s=0.5>] : Weighting sigma in Real space");
92  " [--zerofreq_weight <s=0.>] : Zero-frequency weight");
93  addParamsLine(" [--sigma <s=10>] : Sigma");
95  " [--max_iter <N=60>] : Maximum number of iterations");
97  "xmipp_nma_alignment -i images.sel --pdb 2tbv.pdb --modes modelist.xmd --sampling_rate 6.4 -o output.xmd --resume");
98  Rerunable::setFileName(fnOutDir+"/nmaDone.xmd");
99 }
100 
101 // Read arguments ==========================================================
104  fnPDB = getParam("--pdb");
105  fnOutDir = getParam("--odir");
106  fnModeList = getParam("--modes");
107  resume = checkParam("--resume");
108  maxdefamp = getDoubleParam("--maxdefamp");
109  defampsampling = getDoubleParam("--defampsampling");
110  translsampling = getDoubleParam("--translsampling");
111  maxtransl = getDoubleParam("--maxtransl");
112  sampling_rate = getDoubleParam("--sampling_rate");
113  fnmask = getParam("--mask");
114  gaussian_Real_sigma = getDoubleParam("--gaussian_Real");
115  weight_zero_freq = getDoubleParam("--zerofreq_weight");
116  do_centerPDB = checkParam("--centerPDB");
117  do_FilterPDBVol = checkParam("--filterVol");
118  if (do_FilterPDBVol)
119  cutoff_LPfilter = getDoubleParam("--filterVol");
120  useFixedGaussian = checkParam("--fixed_Gaussian");
121  //if (useFixedGaussian)
122  sigmaGaussian = getDoubleParam("--fixed_Gaussian");
123  minAngularSampling = getDoubleParam("--minAngularSampling");
124  sigma = getDoubleParam("--sigma");
125  max_no_iter = getIntParam("--max_iter");
126 }
127 
128 // Show ====================================================================
131  std::cout << "Output directory: " << fnOutDir << std::endl
132  << "PDB: " << fnPDB << std::endl
133  << "Resume: " << resume << std::endl
134  << "Mode list: " << fnModeList << std::endl
135  << "Deformation sampling: " << defampsampling << std::endl
136  << "Maximum amplitude: " << maxdefamp << std::endl
137  << "Transl. sampling: " << translsampling << std::endl
138  << "Max. Translation: " << maxtransl << std::endl
139  << "Sampling rate: " << sampling_rate << std::endl
140  << "Mask: " << fnmask << std::endl
141  << "Center PDB: " << do_centerPDB << std::endl
142  << "Filter PDB volume " << do_FilterPDBVol << std::endl
143  << "Use fixed Gaussian: " << useFixedGaussian << std::endl
144  << "Sigma of Gaussian: " << sigmaGaussian << std::endl
145  << "minAngularSampling: " << minAngularSampling << std::endl
146  << "Gaussian Real: " << gaussian_Real_sigma << std::endl
147  << "Zero-frequency weight:" << weight_zero_freq << std::endl
148  << "Sigma: " << sigma << std::endl
149  << "Max. Iter: " << max_no_iter << std::endl;
150 }
151 
152 // Produce side information ================================================
154 
157  numberOfModes = SF.size();
159 
160  // Get the size of the images in the selfile
161  imgSize = xdimOut;
162  // Set the pointer of the program to this object
163  global_flexible_prog = this;
164  //create some neededs files
165  createWorkFiles();
166 }
167 
170  rename(Rerunable::getFileName().c_str(), fn_out.c_str());
171 }
172 
173 // Create deformed PDB =====================================================
175  String program;
176  String arguments;
177  FileName fnRandom;
179  const char *randStr = fnRandom.c_str();
180  program = "xmipp_pdb_nma_deform";
181  arguments = formatString(
182  "--pdb %s -o %s_deformedPDB.pdb --nma %s --deformations ",
183  fnPDB.c_str(), randStr, fnModeList.c_str());
184  for (size_t i = 5; i < VEC_XSIZE(trial); i++)
185  arguments += floatToString(trial(i)) + " ";
186  runSystem(program, arguments, false);
187 
188  return fnRandom;
189 }
190 
191 void ProjectionRefencePoint(Matrix1D<double> &Parameters, int dim, double *R,
192  double *Tr, MultidimArray<double> &proj_help_test,
193  MultidimArray<double> &P_esp_image,
194  //double *S_mu,
195  int Xwidth, int Ywidth, double sigma)
196 {
197 // double *coord_gaussian;
198 // double *ksi_v,*coord_img;
199 // double *ro_ksi_v, *ro_coord_img, *ro_coord_gaussian;
200  //double S_mu;
201  auto psi_max = (int) (sqrt(3) * Ywidth / 2);
202 // int kx,ky;
203  double a0,a1,a2;
204  double centre_Xwidth, centre_Ywidth;
205  double sum2,hlp;
206 
207  proj_help_test.initZeros(Xwidth, Ywidth);
208  std::vector<double> ksi_v(4,0);
209  for (int i = 0; i < dim + 5; i++) {
210  global_flexible_prog->trial(i) = Parameters(i);
211  }
212  std::string command;
213  String program;
214  String arguments;
215  FileName fnRandom;
216  fnRandom.initUniqueName(global_flexible_prog->nameTemplate,
217  global_flexible_prog->fnOutDir);
218  const char *randStr = fnRandom.c_str();
219 
220  program = "xmipp_pdb_nma_deform";
221  arguments = formatString(
222  "--pdb %s -o %s_deformedPDB.pdb --nma %s --deformations ",
223  global_flexible_prog->fnPDB.c_str(), randStr,
224  global_flexible_prog->fnModeList.c_str());
225  for (size_t i = 5; i < VEC_XSIZE(global_flexible_prog->trial); i++) {
226  float aaa = global_flexible_prog->scdefamp * Parameters(i);
227  arguments += floatToString(aaa) + " ";
228  }
229  runSystem(program, arguments, false);
230 
231  String deformed_pdb = formatString("%s_deformedPDB.pdb", randStr);
232  centre_Xwidth = double(Xwidth - 1) / 2.0;
233  centre_Ywidth = double(Ywidth - 1) / 2.0;
234  Matrix1D<double> limit0(3), limitF(3), centerOfMass(3);
235  const char *intensityColumn = " ";
236  computePDBgeometry(global_flexible_prog->fnPDB, centerOfMass, limit0,
237  limitF, intensityColumn);
238  centerOfMass = (limit0 + limitF) / 2;
239  std::ifstream fh_deformedPDB;
240  fh_deformedPDB.open(deformed_pdb.c_str());
241 
242  if (!fh_deformedPDB)
244  (std::string )"Prog_PDBPhantom_Parameters::protein_geometry:"
245  "Cannot open " + deformed_pdb + " for reading");
246 
247  // Process all lines of the filem+".pdb").c_str());
248  if (!fh_deformedPDB)
250  (std::string )"Prog_PDBPhantom_Parameters::protein_geometry:"
251  "Cannot open " + deformed_pdb + " for reading");
252 
253  std::vector<double> ro_ksi_v(4,0);
254  ksi_v[0] = 0.0;
255  ksi_v[1] = 0.0;
256  ksi_v[3] = 1.0;
257 
258  std::vector<double> coord_gaussian(4,0);
259  std::vector<double> ro_coord_gaussian(4,0);
260 
261  coord_gaussian[3] = 1.0;
262 
263  std::vector<double> coord_img(4,0);
264  std::vector<double> ro_coord_img(4,0);
265 
266  coord_img[2] = 0.0;
267  coord_img[3] = 1.0;
268  std::string kind;
269  std::string line;
270  std::string atom_type;
271  int ttt = 0;
272  int kx, ky;
273  // Reading PDB/CIF file
274  PDBPhantom pdb;
275  FileName fileNameDeformedPdb(deformed_pdb.c_str());
276  pdb.read(fileNameDeformedPdb);
277 
278  int nAtom = 0;
279  while (!fh_deformedPDB.eof()) {
280  ttt++;
281  // Read an ATOM line
282  getline(fh_deformedPDB, line);
283  if (line == "")
284  continue;
285  kind = line.substr(0, 4);
286  if (kind != "ATOM" && kind != "HETA")
287  continue;
288 
289  // Extract atom type and position
290  // Typical line:
291  // ATOM 909 CA ALA A 161 58.775 31.984 111.803 1.00 34.78
292  const auto& atom = pdb.atomList[nAtom];
293  atom_type = atom.atomType;
294  double x = atom.x;
295  double y = atom.y;
296  double z = atom.z;
297  coord_gaussian[0] = (x - centerOfMass(0))
298  / (global_flexible_prog->sampling_rate);
299  coord_gaussian[1] = (y - centerOfMass(1))
300  / (global_flexible_prog->sampling_rate);
301  coord_gaussian[2] = (z - centerOfMass(2))
302  / (global_flexible_prog->sampling_rate);
303 
304  for (int ksi = -psi_max; ksi <= psi_max; ksi++) {
305  ksi_v[2] = (double) ksi;
306  MatrixMultiply(R, ksi_v.data(), ro_ksi_v.data(), 4L, 4L, 1L);
307 
308  for (ky = 0; ky < Ywidth; ky++) {
309  coord_img[1] = (double) ky - centre_Ywidth;
310  for (kx = 0; kx < Xwidth; kx++) {
311  coord_img[0] = (double) kx - centre_Xwidth;
312  MatrixMultiply(Tr, coord_img.data(), ro_coord_img.data(), 4L, 4L, 1L);
313 
314  a0 = ro_coord_img[0] + ro_ksi_v[0] + coord_gaussian[0];
315  a1 = ro_coord_img[1] + ro_ksi_v[1] + coord_gaussian[1];
316  a2 = ro_coord_img[2] + ro_ksi_v[2] + coord_gaussian[2];
317  proj_help_test(kx - Xwidth / 2, ky - Ywidth / 2) +=
318  (double) exp(
319  -(a0 * a0 + a1 * a1 + a2 * a2)
320  / (sigma * sigma));
321  }
322  }
323  }
324  nAtom++;
325  }
326 
327  Image<double> test1;
328  test1() = proj_help_test;
329 
330  // Close file
331  fh_deformedPDB.close();
332  // To calculate the value of cost function
333  for (sum2 = 0.0, kx = 0; kx < Xwidth; kx++) {
334  for (ky = 0; ky < Ywidth; ky++) {
335  hlp = (double) (proj_help_test(kx - Xwidth / 2, ky - Ywidth / 2)
336  - P_esp_image(kx - Xwidth / 2, ky - Ywidth / 2));
337  hlp = (double) hlp * hlp;
338  sum2 += (double) hlp;
339  }
340  }
341  global_flexible_prog->costfunctionvalue = (double) sum2;
342 }
343 
344 /* ------------------------------------------------------------------------- */
345 /* Calculate the values of partial valur of P_mu_image */
346 /* ------------------------------------------------------------------------- */
348  Matrix1D<double> &centerOfMass, double *R, double *Tr, double *DR0,
349  double *DR1, double *DR2, MultidimArray<double> &DP_Rz1,
352  MultidimArray<double> &DP_q,
353  //double *cost,
354 // MultidimArray<double> &P_mu_image, MultidimArray<double> &P_esp_image,
355  int Xwidth, int Ywidth) {
356  auto psi_max = (int) (sqrt(3) * 128 / (global_flexible_prog->sampling_rate));
357  double help, a0, a1, a2;
358  help = 0.0;
359  int Line_number = 0;
360  int kx, ky;
361  int dim = global_flexible_prog->numberOfModes;
362  double centre_Xwidth, centre_Ywidth;
363  centre_Xwidth = (double) (Xwidth - 1) / 2.0;
364  centre_Ywidth = (double) (Ywidth - 1) / 2.0;
365 
366  DP_Rz1.initZeros(Xwidth, Ywidth);
367  DP_Ry.initZeros(Xwidth, Ywidth);
368  DP_Rz2.initZeros(Xwidth, Ywidth);
369  DP_x.initZeros(Xwidth, Ywidth);
370  DP_y.initZeros(Xwidth, Ywidth);
371  DP_q.initZeros(dim, Xwidth, Ywidth);
372 
373  std::ifstream ModeFile;
374  //std::string modefilename = modeList[0];
375  std::string modefilename = global_flexible_prog->modeList[0];
376  ModeFile.open(modefilename.c_str());
377  if (ModeFile.fail())
379  (std::string ) modefilename + " for reading");
380  std::string line;
381  while (getline(ModeFile, line)) {
382  Line_number++;
383  }
384  ModeFile.close();
385 
386  std::vector<double> ModeValues(3 * Line_number * dim);
387  std::string x, y, z;
388 
389  for (int i = 0; i < dim; i++) {
390  modefilename = global_flexible_prog->modeList[i];
391  ModeFile.open(modefilename.c_str());
392  int n = 0;
393  while (getline(ModeFile, line)) {
394  x = line.substr(3, 10);
395  y = line.substr(14, 10);
396  z = line.substr(27, 10);
397  ModeValues[i * 3 * Line_number + n * 3 + 0] = atof(x.c_str());
398  ModeValues[i * 3 * Line_number + n * 3 + 1] = atof(y.c_str());
399  ModeValues[i * 3 * Line_number + n * 3 + 2] = atof(z.c_str());
400  n++;
401  }
402  ModeFile.close();
403  }
404 
405  for (int i = 0; i < dim + 5; i++) {
406  global_flexible_prog->trial(i) = Parameters(i);
407  }
408 
409  FileName fnRandom = global_flexible_prog->createDeformedPDB();
410  std::ifstream fh_deformedPDB;
411  fh_deformedPDB.open((fnRandom + "_deformedPDB.pdb").c_str());
412  if (!fh_deformedPDB)
414  (std::string )"Prog_PDBPhantom_Parameters::protein_geometry:" "Cannot open "
415  + fnRandom + "_deformedPDB.pdb" + " for reading");
416 
417  // Process all lines of the file
418  std::vector<double> help_v(4,0);
419  help_v[0] = 0.0;
420  help_v[1] = 0.0;
421  help_v[3] = 1.0;
422 
423  std::vector<double> coord_gaussian(4,0);
424  coord_gaussian[3] = 1.0;
425 
426  std::vector<double> coord_img(4,0);
427  coord_img[2] = 0.0;
428  coord_img[3] = 1.0;
429  int k = 0;
430 
431  // Reading PDB/CIF file
432  PDBPhantom pdb;
433  FileName fileNameDeformedPdb((fnRandom + "_deformedPDB.pdb").c_str());
434  pdb.read(fileNameDeformedPdb);
435 
436  std::string kind;
437  int nAtom = 0;
438  while (!fh_deformedPDB.eof()) {
439  // Read an ATOM line
440  getline(fh_deformedPDB, line);
441  if (line == "")
442  continue;
443  kind = line.substr(0, 4);
444  if (kind != "ATOM")
445  continue;
446 
447  // Extract atom type and position
448  // Typical line:
449  // ATOM 909 CA ALA A 161 58.775 31.984 111.803 1.00 34.78
450  const auto& atom = pdb.atomList[nAtom];
451  char atom_type = atom.atomType;
452  double xPos = atom.x;
453  double yPos = atom.y;
454  double zPos = atom.z;
455 
456  // Correct position
457  coord_gaussian[0] = (xPos - centerOfMass(0))
458  / global_flexible_prog->sampling_rate;
459  coord_gaussian[1] = (yPos - centerOfMass(1))
460  / global_flexible_prog->sampling_rate;
461  coord_gaussian[2] = (zPos - centerOfMass(2))
462  / global_flexible_prog->sampling_rate;
463 
464  //MatrixMultiply( Tr, coord_gaussian, coord_gaussian,4L, 4L, 1L);
465  if (MatrixMultiply(Tr, coord_gaussian.data(), coord_gaussian.data(), 4L, 4L, 1L) == ERROR) {
466  WRITE_ERROR(partialpfunction, "Error returned by MatrixMultiply");
467  return (ERROR);
468  }
469 
470  for (int ksi = -psi_max; ksi <= psi_max; ksi++) {
471  coord_img[3] = (double) ksi;
472  for (kx = 0; kx < Xwidth; kx++) {
473  for (ky = 0; ky < Ywidth; ky++) {
474 
475  coord_img[0] = (double) kx - centre_Xwidth;
476  coord_img[1] = (double) ky - centre_Ywidth;
477 
478  //MatrixTimesVector( Tr, coord_img, help_v,4L, 4L);
479  if (MatrixTimesVector(Tr, coord_img.data(), help_v.data(), 4L, 4L) == ERROR) {
480  WRITE_ERROR(partialpfunction, "Error returned by MatrixMultiply");
481  return (ERROR);
482  }
483  a0 = help_v[0] + coord_gaussian[0];
484  a1 = help_v[1] + coord_gaussian[1];
485  a2 = help_v[2] + coord_gaussian[2];
486 
487  help = (double) exp(
488  -(a0 * a0 + a1 * a1 + a2 * a2)
489  / (global_flexible_prog->sigma
490  * global_flexible_prog->sigma));
491  if (MatrixTimesVector(DR0, coord_img.data(), help_v.data(), 4L, 4L) == ERROR) {
492  WRITE_ERROR(partialpfunction, "Error returned by MatrixMultiply");
493  return (ERROR);
494  }
495 
496  DP_Rz1(kx, ky) += help
497  * (a0 * help_v[0] + a1 * help_v[1]
498  + a2 * help_v[2]);
499  if (MatrixTimesVector(DR1, coord_img.data(), help_v.data(), 4L, 4L) == ERROR) {
500  WRITE_ERROR(partialpfunction, "Error returned by MatrixMultiply");
501  return (ERROR);
502  }
503  DP_Ry(kx, ky) += help
504  * (a0 * help_v[0] + a1 * help_v[1]
505  + a2 * help_v[2]);
506  if (MatrixTimesVector(DR2, coord_img.data(), help_v.data(), 4L, 4L) == ERROR) {
507  WRITE_ERROR(partialpfunction, "Error returned by MatrixMultiply");
508  return (ERROR);
509  }
510  DP_Rz2(kx, ky) += help
511  * (a0 * help_v[0] + a1 * help_v[1]
512  + a2 * help_v[2]);
513  DP_x(kx, ky) += help * (a0 * R[0] + a1 * R[1] + a2 * R[2]); //global_flexible_prog->sctrans * DP_x(kx,ky)
514  DP_y(kx, ky) += help * (a0 * R[4] + a1 * R[5] + a2 * R[6]); //global_flexible_prog->sctrans * DP_y(kx,ky)
515  for (int i = 0; i < dim; i++) {
516  DP_q(i, kx, ky) += global_flexible_prog->scdefamp * help
517  * (a0 * ModeValues[i * 3 * Line_number + k * 3]
518  + a1 * ModeValues[i * 3 * Line_number + k * 3 + 1]
519  + a2 * ModeValues[i * 3 * Line_number + k * 3 + 2]);
520  }
521  }
522  }
523  }
524  k++;
525  nAtom++;
526  }
527  fh_deformedPDB.close();
528  return (!ERROR);
529 }/*end of partialpfunction*/
530 
531 /* ------------------------------------------------------------------------- */
532 /* Gradient and Hessian at pixel */
533 /* ------------------------------------------------------------------------- */
534 void gradhesscost_atpixel(double *Gradient, double *Hessian, double *helpgr,
535  double difference) {
536  int trialSize = VEC_XSIZE(global_flexible_prog->trial);
537 
538  for (int i = 0; i < trialSize; i++) {
539  Gradient[i] += difference * helpgr[i];
540  for (int j = 0; j <= i; j++) {
541  Hessian[i * trialSize + j] += helpgr[j] * helpgr[i];
542  }
543  }
544  //return(!ERROR);
545 }/* End of gradhesscost_atpixel */
546 
547 /* ------------------------------------------------------------------------- */
548 /* Calculate the values of Gradient and Hessian */
549 /* ------------------------------------------------------------------------- */
550 // int Prog_flexali_gauss_prm::return_gradhesscost(
551 int return_gradhesscost(Matrix1D<double> &centerOfMass, double *Gradient,
552  double *Hessian, Matrix1D<double> &Parameters, int dim,
553  MultidimArray<double> &rg_projimage, MultidimArray<double> &P_esp_image,
554  int Xwidth, int Ywidth) {
555  double phi, theta, psi, x0, y0;
556  int i, j;
557  double difference;
558  double SinPhi, CosPhi, SinPsi, CosPsi, SinTheta, CosTheta;
559  int trialSize = VEC_XSIZE(global_flexible_prog->trial);
560  double lambda = 1000.0;
561  double sigmalocal = global_flexible_prog->sigma;
562  int half_Xwidth = Xwidth / 2;
563  int half_Ywidth = Ywidth / 2;
564 
565  //global_flexible_prog->costfunctionvalue = 0.0;
566 
567  for (int i = 0; i < dim + 5; i++) {
568  global_flexible_prog->trial(i) = Parameters(i);
569  }
570  phi = Parameters(0);
571  theta = Parameters(1);
572  psi = Parameters(2);
573  x0 = Parameters(3);
574  y0 = Parameters(4);
575  //defamp = (double *)malloc((size_t) dim * sizeof(double));
576  //if (defamp == (double *)NULL)
577  //{
578  // WRITE_ERROR(return_gradhesscost, "ERROR - Not enough memory for defamp");
579  // return(ERROR);
580  //}
581  SinPhi = sin(phi);
582  CosPhi = cos(phi);
583  SinPsi = sin(psi);
584  CosPsi = cos(psi);
585  SinTheta = sin(theta);
586  CosTheta = cos(theta);
587  std::vector<double> Rz1(16,0);
588  std::vector<double> Ry(16,0);
589  std::vector<double> Rz2(16,0);
590  if (GetIdentitySquareMatrix(Rz2.data(), 4L) == ERROR) {
591  WRITE_ERROR(return_gradhesscost, "Error returned by GetIdentitySquareMatrix");
592  return (ERROR);
593  }
594  double *hlp = Rz2.data();
595  *hlp++ = CosPsi;
596  *hlp = SinPsi;
597  hlp += (std::ptrdiff_t) 3L;
598  *hlp++ = -SinPsi;
599  *hlp = CosPsi;
600 
601  if (GetIdentitySquareMatrix(Rz1.data(), 4L) == ERROR) {
602  WRITE_ERROR(return_gradhesscost, "Error returned by GetIdentitySquareMatrix");
603  return (ERROR);
604  }
605 
606  hlp = Rz1.data();
607  *hlp++ = CosPhi;
608  *hlp = SinPhi;
609  hlp += (std::ptrdiff_t) 3L;
610  *hlp++ = -SinPhi;
611  *hlp = CosPhi;
612  if (GetIdentitySquareMatrix(Ry.data(), 4L) == ERROR) {
613  WRITE_ERROR(return_gradhesscost, "Error returned by GetIdentitySquareMatrix");
614  return (ERROR);
615  }
616 
617  hlp = Ry.data();
618  *hlp = CosTheta;
619  hlp += (std::ptrdiff_t) 2L;
620  *hlp = -SinTheta;
621  hlp += (std::ptrdiff_t) 6L;
622  *hlp = SinTheta;
623  hlp += (std::ptrdiff_t) 2L;
624  *hlp = CosTheta;
625 
626  std::vector<double> R(16,0);
627  if (multiply_3Matrices(Rz2.data(), Ry.data(), Rz1.data(), R.data(), 4L, 4L, 4L, 4L) == ERROR) {
628  WRITE_ERROR(return_gradhesscost, "Error returned by multiply_3Matrices");
629  return (ERROR);
630  }
631 
632  std::vector<double> DRz1(16,0);
633  std::vector<double> DRy(16,0);
634  std::vector<double> DRz2(16,0);
635 
636  hlp = DRz2.data();
637  *hlp++ = -SinPsi;
638  *hlp = CosPsi;
639  hlp += (std::ptrdiff_t) 3L;
640  *hlp++ = -CosPsi;
641  *hlp = -SinPsi;
642 
643  hlp = DRz1.data();
644  *hlp++ = -SinPhi;
645  *hlp = CosPhi;
646  hlp += (std::ptrdiff_t) 3L;
647  *hlp++ = -CosPhi;
648  *hlp = -SinPhi;
649 
650  hlp = DRy.data();
651  *hlp = -SinTheta;
652  hlp += (std::ptrdiff_t) 2L;
653  *hlp = -CosTheta;
654  hlp += (std::ptrdiff_t) 6L;
655  *hlp = CosTheta;
656  hlp += (std::ptrdiff_t) 2L;
657  *hlp = -SinTheta;
658 
659  std::vector<double> DR0(16,0);
660  std::vector<double> DR1(16,0);
661  std::vector<double> DR2(16,0);
662 
663  if (multiply_3Matrices(Rz2.data(), Ry.data(), DRz1.data(), DR0.data(), 4L, 4L, 4L, 4L) == ERROR) {
664  WRITE_ERROR(return_gradhesscost, "Error returned by multiply_3Matrices");
665  return (ERROR);
666  }
667 
668  if (multiply_3Matrices(Rz2.data(), DRy.data(), Rz1.data(), DR1.data(), 4L, 4L, 4L, 4L) == ERROR) {
669  WRITE_ERROR(return_gradhesscost, "Error returned by multiply_3Matrices");
670  return (ERROR);
671  }
672 
673  if (multiply_3Matrices(DRz2.data(), Ry.data(), Rz1.data(), DR2.data(), 4L, 4L, 4L, 4L) == ERROR) {
674  WRITE_ERROR(return_gradhesscost, "Error returned by multiply_3Matrices");
675  return (ERROR);
676  }
677 
678  std::vector<double> Tr(16,0);
679  if (GetIdentitySquareMatrix(Tr.data(), 4L) == ERROR) {
680  WRITE_ERROR(return_gradhesscost, "Error returned by GetIdentitySquareMatrix");
681  return (ERROR);
682  }
683 
684  hlp = Tr.data();
685  hlp += (std::ptrdiff_t) 3L;
686  *hlp = -x0; //global_flexible_prog->sctrans * x0
687  hlp += (std::ptrdiff_t) 5L;
688  *hlp = -y0; //global_flexible_prog->sctrans * y0
689  ProjectionRefencePoint(Parameters, dim, R.data(), Tr.data(), rg_projimage, P_esp_image,
690  Xwidth, Ywidth, sigmalocal);
691 
692  MultidimArray<double> DP_Rx(Xwidth, Ywidth), DP_Ry(Xwidth, Ywidth), DP_Rz2(
693  Xwidth, Ywidth);
694  MultidimArray<double> DP_x(Xwidth, Ywidth), DP_y(Xwidth, Ywidth);
695  MultidimArray<double> DP_q(dim, Xwidth, Ywidth);
696  if (partialpfunction(Parameters, centerOfMass, R.data(), Tr.data(), DR0.data(), DR1.data(), DR2.data(), DP_Rx,
697  DP_Ry, DP_Rz2, DP_x, DP_y, P_esp_image, Xwidth,
698  Ywidth) == ERROR) {
699  WRITE_ERROR(return_gradhesscost, "Error returned by partialpfunction");
700  return (ERROR);
701  }
702 
703  std::vector<double> helpgr(trialSize,0);
704 
705  for (i = 0; i < trialSize; i++) {
706  Gradient[i] = 0.0;
707  for (j = 0; j < trialSize; j++) {
708  Hessian[i * trialSize + j] = 0.0;
709  }
710  }
711 
712  for (int kx = 0; kx < Xwidth; kx++)
713  for (int ky = 0; ky < Ywidth; ky++) {
714  difference = rg_projimage(kx - half_Xwidth, ky - half_Ywidth)
715  - P_esp_image(kx - half_Xwidth, ky - half_Ywidth);
716  helpgr[0] = DP_Rx(kx, ky);
717  helpgr[1] = DP_Ry(kx, ky);
718  helpgr[2] = DP_Rz2(kx, ky);
719  helpgr[3] = DP_x(kx, ky);
720  helpgr[4] = DP_y(kx, ky);
721  for (j = 0; j < dim; j++) {
722  helpgr[5 + j] = DP_q(j, kx, ky);
723  }
724  gradhesscost_atpixel(Gradient, Hessian, helpgr.data(), difference);
725  }
726 
727  for (int i = 0; i < trialSize; i++) {
728  Hessian[i * trialSize + i] += lambda * Hessian[i * trialSize + i];
729  if (i + 1 < trialSize)
730  for (int j = i + 1; j < trialSize; j++) {
731  Hessian[i * trialSize + j] = Hessian[j * trialSize + i];
732  }
733  }
734  return (!ERROR);
735 }/* End of return_gradhesscost */
736 
737 /* ------------------------------------------------------------------------- */
738 /* Optimizer */
739 /* ------------------------------------------------------------------------- */
741  MultidimArray<double> &P_esp_image, Matrix1D<double> &centerOfMass,
742  double *beta, double *alpha,
743  //double *cost,
744  Matrix1D<double> &Parameters, double OldCost, double *lambda,
745  double LambdaScale, long *iter, double tol_angle, double tol_shift,
746  double tol_defamp, int *IteratingStop, size_t Xwidth, size_t Ywidth) {
747 
748  auto ma = (long) VEC_XSIZE(global_flexible_prog->trial);
749  if (ma <= 0) {
750  WRITE_ERROR(levenberg_cst2, "ERROR - degenerated vector");
751  return (ERROR);
752  }
753  double max_defamp;
754  int dim = global_flexible_prog->numberOfModes;
755  int Status = !ERROR;
756 
757  std::vector<double> a(ma,0);
758  for (size_t i = 0; i < ma; i++)
759  a[i] = Parameters(i);
760 
761  std::vector<double> da(ma,0);
762  std::vector<double> u(ma*ma,0);
763  std::vector<double> v(ma*ma,0);
764  std::vector<double> w(ma,0);
765 
766  double *t = u.data();
767  double *uptr = u.data();
768  for (size_t i = 0L; (i < ma); t += (std::ptrdiff_t) (ma + 1L), i++) {
769  for (size_t j = 0L; (j < ma); alpha++, j++) {
770  *uptr++ = -*alpha;
771  }
772 
773  *t *= 1.0 + *lambda;
774  }
775  alpha -= (std::ptrdiff_t) (ma * ma);
776 
777  SingularValueDecomposition(u.data(), ma, ma, w.data(), v.data(), SVDMAXITER, &Status);
778  double wmax = *std::max_element(w.begin(), w.end());
779  double thresh = DBL_EPSILON * wmax;
780  size_t j = ma;
781  while (--j >= 0L) {
782  if (w[j] < thresh) {
783  w[j] = 0.0;
784  for (size_t i = 0; (i < ma); i++) {
785  u[i * ma + j] = 0.0;
786  v[i * ma + j] = 0.0;
787  }
788  }
789  }
790 
791  SingularValueBackSubstitution(u.data(), w.data(), v.data(), ma, ma, beta, da.data(), &Status);
792  double *vptr = (double*) memcpy(v.data(), a.data(), (size_t) ma * sizeof(double));
793  t = vptr + (std::ptrdiff_t) ma;
794  double *aptr = a.data()+(std::ptrdiff_t) ma;
795  double *daptr = da.data()+(std::ptrdiff_t) ma;
796  while (--t >= vptr) {
797  daptr--;
798  *t = *--aptr;
799  *t += *daptr;
800  }
801  for (size_t i = 0; i < ma; i++)
802  Parameters(i) = v[i];
803 
804  return_gradhesscost(centerOfMass, w.data(), u.data(), Parameters, dim, lc_P_mu_image,
805  P_esp_image, Xwidth, Ywidth);
806  double costchanged = global_flexible_prog->costfunctionvalue;
807 
808  size_t i;
809  for (max_defamp = 0.0, i = 0L; i < dim; i++) {
810  double hlp = fabs(a[i + 5] - v[i + 5]);
811  if (hlp > max_defamp)
812  max_defamp = fabs(a[i + 5] - v[i + 5]);
813  }
814 
815  (*iter)++;
816  if (costchanged < OldCost) {
817  if ((fabs(a[0] - v[0]) < tol_angle) && (fabs(a[1] - v[1]) < tol_angle)
818  && (fabs(a[2] - v[2]) < tol_angle)) {
819  if ((fabs(a[3] - v[3]) < tol_shift)
820  && (fabs(a[4] - v[4]) < tol_shift)) {
821  if (max_defamp < tol_defamp) {
822  *IteratingStop = 1;
823  }
824  }
825  }
826  }
827 
828  if (global_flexible_prog->costfunctionvalue_cst == -1.0) {
829  if (costchanged < OldCost) {
830  for (i = 0L; (i < ma); i++) {
831  for (j = 0L; (j < ma); j++)
832  alpha[i * ma + j] = u[i * ma + j];
833  beta[i] = w[i];
834  a[i] = v[i];
835  }
836  global_flexible_prog->costfunctionvalue_cst = costchanged;
837  }
838 
839  return (!ERROR);
840  }
841 
842  for (i = 0L; (i < ma); i++) {
843  for (j = 0L; (j < ma); j++)
844  alpha[i * ma + j] = u[i * ma + j];
845  beta[i] = w[i];
846  a[i] = v[i];
847  }
848  global_flexible_prog->costfunctionvalue_cst = costchanged;
849 
850 #ifndef DBL_MIN
851 #define DBL_MIN 1e-26
852 #endif
853 #ifndef DBL_MAX
854 #define DBL_MAX 1e+26
855 #endif
856 
857  if (costchanged < OldCost) {
858  if (*lambda > DBL_MIN) {
859  *lambda /= LambdaScale;
860  } else {
861  *IteratingStop = 1;
862  }
863  } else {
864  if (*lambda < DBL_MAX) {
865  *lambda *= LambdaScale;
866  } else {
867  *IteratingStop = 1;
868  }
869  }
870  return (!ERROR);
871 } /* End of levenberg_cst2 */
872 
873 /* Registration ------------------------------------------------------------ */
874 //cstregistrationcontinuous(centerOfMass,cost,Parameters,P_mu_image,P_esp_image,Xwidth,Ywidth);
876  //double *cost,
877  Matrix1D<double> &Parameters, MultidimArray<double> &cst_P_mu_image,
878  MultidimArray<double> &P_esp_image, size_t Xwidth, size_t Ywidth) {
879  int DoDesProj, IteratingStop, FlagMaxIter;
880  long MaxIter, MaxIter1, iter;
881  long MaxNumberOfFailures, SatisfNumberOfSuccesses, nSuccess, nFailure;
882  double LambdaScale = 2., OldCost, tol_angle, tol_shift, tol_defamp;
883  double OneIterInSeconds;
884  time_t *tp1 = nullptr;
885  time_t *tp2 = nullptr;
886  auto dim = (long) global_flexible_prog->numberOfModes;
887  long MaxNoIter, MaxNoFailure, SatisfNoSuccess;
888 
889  double lambda = 1000.;
890  time_t time1 = time(tp1);
891  DoDesProj = 0;
892  MaxNoIter = global_flexible_prog->max_no_iter;
893  MaxNoFailure = (long) (0.3 * MaxNoIter);
894  SatisfNoSuccess = (long) (0.7 * MaxNoIter);
895  MaxIter = MaxNoIter;
896  MaxIter1 = MaxIter - 1L;
897 
898  MaxNumberOfFailures = MaxNoFailure;
899  SatisfNumberOfSuccesses = SatisfNoSuccess;
900  tol_angle = 0.0;
901  tol_shift = 0.0;
902  tol_defamp = 0.0;
903 
904  std::vector<double> Gradient(dim + 5,0);
905  std::vector<double> Hessian((dim + 5) * (dim + 5),0);
906 
907  if (DoDesProj && (global_flexible_prog->currentStage == 2)) {
908  Parameters(0) = 10;
909  Parameters(1) = 0;
910  Parameters(2) = 0;
911  Parameters(3) = 0;
912  Parameters(4) = 0;
913  Parameters(5) = 0.5;
914  //Parameters(6)=0;
915  }
916 
917  if (return_gradhesscost(centerOfMass, Gradient.data(), Hessian.data(), Parameters, dim,
918  cst_P_mu_image, P_esp_image, Xwidth, Ywidth) == ERROR) {
919  WRITE_ERROR(cstregistrationcontinuous, "Error returned by return_gradhesscost");
920  return (ERROR);
921  }
922  time_t time2 = time(tp2);
923  OneIterInSeconds = difftime(time2, time1);
924  if (DoDesProj && (global_flexible_prog->currentStage == 2)) {
925  Image<double> Itemp;
926  Itemp() = cst_P_mu_image;
927  Itemp.write("test_refimage.spi");
928  return (!ERROR);
929  }
930  if ((MaxIter == 0L) && (!DoDesProj))
931  return (!ERROR);
932  nSuccess = 0L;
933  nFailure = 0L;
934  OldCost = global_flexible_prog->costfunctionvalue_cst;
935  iter = -1L;
936  IteratingStop = 0;
937  FlagMaxIter = (MaxIter != 1L);
938  if (!FlagMaxIter)
939  global_flexible_prog->costfunctionvalue_cst = -1.0;
940 
941  do {
942  if (levenberg_cst2(cst_P_mu_image, P_esp_image, centerOfMass, Gradient.data(),
943  Hessian.data(), Parameters, OldCost, &lambda, LambdaScale, &iter,
944  tol_angle, tol_shift, tol_defamp, &IteratingStop, Xwidth,
945  Ywidth) == ERROR) {
946  WRITE_ERROR(cstregistrationcontinuous, "Error returned by levenberg_cst2");
947  return (ERROR);
948  }
949 
950  if (global_flexible_prog->costfunctionvalue_cst < OldCost) {
951  OldCost = global_flexible_prog->costfunctionvalue_cst;
952  nSuccess++;
953  if (nSuccess >= SatisfNumberOfSuccesses) {
954  break;
955  }
956  if (IteratingStop) {
957  break;
958  }
959  } else {
960  nFailure++;
961  }
962 
963  } while ((nFailure <= MaxNumberOfFailures) && (iter < MaxIter1)
964  && FlagMaxIter);
965  return (!ERROR);
966 }
967 
969 
970  int dim = numberOfModes;
971  int ModMaxdeDefamp, ModpowDim, help;
972  double SinPhi, CosPhi, SinPsi, CosPsi;
973  double S_muMin = 1e30;
974  //double *cost;
975  costfunctionvalue = 0.0;
976  Matrix1D<double> Parameters(dim + 5);
977  Matrix1D<double> limit0(3), limitF(3), centerOfMass(3);
978  const char *intensityColumn = "Bfactor";
979  computePDBgeometry(fnPDB, centerOfMass, limit0, limitF, intensityColumn);
980  centerOfMass = (limit0 + limitF) / 2;
981 
982  FileName fnRandom;
984  std::string command;
985 
986  // Reduce the image
987  fnDown = formatString("%s_downimg.xmp", fnRandom.c_str());
988  if (pyramidLevel != 0) {
989  Image<double> I;
990  I.read(currentImgName);
992  I.write(fnDown);
993  }
994  Image<double> imgtemp;
995  imgtemp.read(fnDown);
996 
997  imgtemp().setXmippOrigin();
998  MultidimArray<double> P_mu_image;
999  P_mu_image.resize(imgtemp());
1000  int Xwidth = XSIZE(imgtemp());
1001  int Ywidth = YSIZE(imgtemp());
1002  double reduce_rate = 1;
1003 
1004  ModMaxdeDefamp = (int) floor(maxdefamp / defampsampling) + 1;
1005  ModpowDim = (int) pow(ModMaxdeDefamp, dim);
1006 
1007  std::vector<double> Rz1(16,0);
1008  std::vector<double> Ry(16,0);
1009  std::vector<double> Rz2(16,0);
1010  std::vector<double> R(16,0);
1011  std::vector<double> Tr(16,0);
1012 
1013  int phiSteps=360/minAngularSampling;
1014  int thetaSteps=180/minAngularSampling;
1015  int psiSteps=360/minAngularSampling;
1016  int transSteps=maxtransl/translsampling;
1017  for (int iphi = 0; iphi <= phiSteps; iphi++) {
1018  double phi=iphi*minAngularSampling;
1019  Parameters(0) = phi;
1020  trial(0) = phi;
1021  SinPhi = sin(phi / 180 * PI);
1022  CosPhi = cos(phi / 180 * PI);
1023 
1024  GetIdentitySquareMatrix(Ry.data(), 4L);
1025 
1026  double *hlp = Ry.data();
1027  *hlp = CosPhi;
1028  hlp += (std::ptrdiff_t) 2L;
1029  *hlp = -SinPhi;
1030  hlp += (std::ptrdiff_t) 6L;
1031  *hlp = SinPhi;
1032  hlp += (std::ptrdiff_t) 2L;
1033  *hlp = CosPhi;
1034 
1035  for (int itheta = 0; itheta <=thetaSteps; itheta++) {
1036  double theta=itheta*minAngularSampling;
1037  Parameters(1) = theta;
1038  trial(1) = theta;
1039 
1040  GetIdentitySquareMatrix(Rz1.data(), 4L);
1041 
1042  hlp = Rz1.data();
1043  *hlp++ = CosPhi;
1044  *hlp = SinPhi;
1045  hlp += (std::ptrdiff_t) 3L;
1046  *hlp++ = -SinPhi;
1047  *hlp = CosPhi;
1048 
1049  for (int ipsi = 0; ipsi<=psiSteps; ipsi++) {
1050  double psi=ipsi*minAngularSampling;
1051  Parameters(2) = psi;
1052  trial(2) = psi;
1053  SinPsi = sin(psi / 180 * PI);
1054  CosPsi = cos(psi / 180 * PI);
1055 
1056  GetIdentitySquareMatrix(Rz2.data(), 4L);
1057 
1058  hlp = Rz2.data();
1059  *hlp++ = CosPsi;
1060  *hlp = SinPsi;
1061  hlp += (std::ptrdiff_t) 3L;
1062  *hlp++ = -SinPsi;
1063  *hlp = CosPsi;
1064 
1065  multiply_3Matrices(Rz2.data(), Ry.data(), Rz1.data(), R.data(), 4L, 4L, 4L, 4L);
1066 
1067  for (int ix0=0; ix0<=transSteps; ix0++) {
1068  double x0=ix0*translsampling;
1069  Parameters(3) = x0 / reduce_rate;
1070  trial(3) = x0;
1071  for (int iy0=0; iy0<=transSteps; iy0++) {
1072  double y0=iy0*translsampling;
1073  Parameters(4) = y0 / reduce_rate;
1074  trial(4) = y0;
1075 
1076  GetIdentitySquareMatrix(Tr.data(), 4L);
1077  hlp = Tr.data();
1078  hlp += (std::ptrdiff_t) 3L;
1079  *hlp = -x0;
1080  hlp += (std::ptrdiff_t) 5L;
1081  *hlp = -y0;
1082 
1083  MatrixMultiply(R.data(), Tr.data(), Tr.data(), 4L, 4L, 4L);
1084 
1085  for (int i = 0; i < ModpowDim; i++) {
1086  help = i;
1087  for (int j = dim - 1; j >= 0; j--) {
1088  Parameters(j + 5) = (double) (help
1089  % ModMaxdeDefamp) * defampsampling;
1090  trial(j + 5) = (double) (help % ModMaxdeDefamp)
1091  * defampsampling;
1092  help = (int) floor(help / ModMaxdeDefamp);
1093 
1094  }
1095 
1096  ProjectionRefencePoint(Parameters, dim, R.data(), Tr.data(),
1097  P_mu_image, imgtemp(), Xwidth, Ywidth,
1098  sigma);
1099 
1100  if (costfunctionvalue < S_muMin) { //2
1101  S_muMin = costfunctionvalue;
1102  for (int k = 0; k < dim + 5; k++) {
1103  trial_best(k) = trial(k);
1104  }
1105 
1106  }
1107  std::cout << "trial" << trial << " cost="
1108  << costfunctionvalue << std::endl;
1109  std::cout << "trial_best" << trial_best
1110  << " cost_best=" << S_muMin << std::endl;
1111  }
1112  }
1113  }
1114  }
1115  }
1116 
1117  }
1118 
1119  std::cout << "trial" << trial << costfunctionvalue << std::endl;
1120  std::cout << "trial_best" << trial_best << S_muMin << std::endl;
1121  for (int i = 0; i < dim + 5; i++) {
1122  trial(i) = trial_best(i);
1123  parameters(i) = trial_best(i);
1124  }
1125 
1126  MetaDataVec DF_out_discrete;
1127  size_t id = DF_out_discrete.addObject();
1128  DF_out_discrete.setValue(MDL_IMAGE, currentImgName, id);
1129  std::vector<double> aux;
1130  aux.resize(VEC_XSIZE(parameters));
1132  aux[i] = parameters(i);
1133  DF_out_discrete.setValue(MDL_NMA, aux, id);
1134  DF_out_discrete.write("result_angular_discrete.xmd");
1135 }
1136 
1137 // Continuous assignment ===================================================
1139  costfunctionvalue = 0.0;
1140  costfunctionvalue_cst = 0.0;
1141 
1142  Matrix1D<double> Parameters;
1143 
1144  Parameters = trial_best;
1145 
1146  std::string command;
1147  if (pyramidLevel == 0) {
1148  // Make links
1149  FileName fnRandom;
1151  fnDown = formatString("%s_downimg.xmp", fnRandom.c_str());
1152 
1153  Image<double> I;
1154  I.read(currentImgName);
1156  I.write(fnDown);
1157  }
1158 
1159  //std::string arguments;
1160  //arguments = formatString("%s_downimg.xmp",fnRandom.c_str());
1161  Image<double> imgtemp;
1162  imgtemp.read(fnDown);
1163 
1164  imgtemp().setXmippOrigin();
1165  MultidimArray<double> P_mu_image, P_esp_image;
1166  P_esp_image = imgtemp();
1167  P_mu_image.resize(imgtemp());
1168  int Xwidth = XSIZE(imgtemp());
1169  int Ywidth = YSIZE(imgtemp());
1170  //double P_mu_image[Xwidth*Xwidth];
1171  Matrix1D<double> limit0(3), limitF(3), centerOfMass(3);
1172  const char *intensityColumn = "Bfactor";
1173  //Matrix1D<double> test=centerOfMass;
1174  computePDBgeometry(fnPDB, centerOfMass, limit0, limitF, intensityColumn);
1175 
1176  centerOfMass = (limit0 + limitF) / 2;
1177 
1178  cstregistrationcontinuous(centerOfMass, Parameters, P_mu_image, P_esp_image,
1179  Xwidth, Ywidth);
1180  /* Insert code for continious alignment */
1181 
1182  trial(3) *= pow(2.0, (double) pyramidLevel);
1183  trial(4) *= pow(2.0, (double) pyramidLevel);
1184 
1185  trial_best = trial;
1186 
1187  double outcost = costfunctionvalue_cst;
1188  return outcost;
1189 }
1190 
1191 // Compute fitness =========================================================
1193  int pyramidLevelDisc = 1;
1194  int pyramidLevelCont = (currentStage == 1) ? 1 : 0;
1195 
1196  if (currentStage == 1) {
1197  performCompleteSearch(pyramidLevelDisc);
1198  } else {
1199  //link(currentImgName.c_str(), fnDown.c_str());
1200  }
1201  double fitness = performContinuousAssignment(pyramidLevelCont);
1202 
1203  std::cout << "Fitness" << std::endl;
1204  return fitness;
1205 }
1206 
1208  const FileName &fnImgOut, const MDRow &rowIn, MDRow &rowOut) {
1209  static size_t imageCounter = 0;
1210  ++imageCounter;
1211 
1212  int dim = numberOfModes;
1213 
1214  parameters.initZeros(dim + 5);
1215  currentImgName = fnImg;
1216  snprintf(nameTemplate, 256, "_node%d_img%ld_XXXXXX", rangen,
1217  (long int) imageCounter);
1218 
1219  trial.initZeros(dim + 5);
1220  trial_best.initZeros(dim + 5);
1221 
1222  currentStage = 1;
1223 #ifdef DEBUG
1224 
1225  std::cerr << std::endl << "DEBUG: ===== Node: " << rangen
1226  <<" processing image " << fnImg <<"(" << objId << ")"
1227  << " at stage: " << currentStage << std::endl;
1228 #endif
1229 
1230  eval(); // FIXME is this call necessary?
1232 
1233  currentStage = 2;
1234 #ifdef DEBUG
1235 
1236  std::cerr << std::endl << "DEBUG: ===== Node: " << rangen
1237  <<" processing image " << fnImg <<"(" << objId << ")"
1238  << " at stage: " << currentStage << std::endl;
1239 #endif
1240 
1241  double fitness = eval();
1242 
1243  trial = trial_best;
1245 
1248 
1249  writeImageParameters(fnImg);
1250 }
1251 
1253 
1254  MetaDataVec md;
1255  size_t objId = md.addObject();
1256  md.setValue(MDL_IMAGE, fnImg, objId);
1257  md.setValue(MDL_ENABLED, 1, objId);
1258  md.setValue(MDL_ANGLE_ROT, parameters(0), objId);
1259  md.setValue(MDL_ANGLE_TILT, parameters(1), objId);
1260  md.setValue(MDL_ANGLE_PSI, parameters(2), objId);
1261  md.setValue(MDL_SHIFT_X, parameters(3), objId);
1262  md.setValue(MDL_SHIFT_Y, parameters(4), objId);
1263 
1264  int dim = numberOfModes;
1265  std::vector<double> vectortemp;
1266 
1267  for (int j = 5; j < 5 + dim; j++)
1268  vectortemp.push_back(parameters(j));
1269  md.setValue(MDL_NMA, vectortemp, objId);
1270  md.setValue(MDL_COST, parameters(5 + dim), objId);
1272 }
void read(const FileName &fnPDB)
Read phantom from either a PDB of CIF file.
Definition: pdb.cpp:503
Just to locate unclassified errors.
Definition: xmipp_error.h:192
ProgFlexibleAlignment * global_flexible_prog
virtual void processImage(const FileName &fnImg, const FileName &fnImgOut, const MDRow &rowIn, MDRow &rowOut)
Rotation angle of an image (double,degrees)
#define YSIZE(v)
#define DBL_EPSILON
int cstregistrationcontinuous(Matrix1D< double > &centerOfMass, Matrix1D< double > &Parameters, MultidimArray< double > &cst_P_mu_image, MultidimArray< double > &P_esp_image, size_t Xwidth, size_t Ywidth)
void resize(size_t Ndim, size_t Zdim, size_t Ydim, size_t Xdim, bool copy=true)
void ProjectionRefencePoint(Matrix1D< double > &Parameters, int dim, double *R, double *Tr, MultidimArray< double > &proj_help_test, MultidimArray< double > &P_esp_image, int Xwidth, int Ywidth, double sigma)
double getDoubleParam(const char *param, int arg=0)
double weight_zero_freq
Weight for zero frequency.
__host__ __device__ float2 floor(const float2 v)
bool do_FilterPDBVol
Low-pass filter the volume from PDB.
#define REPORT_ERROR(nerr, ErrormMsg)
Definition: xmipp_error.h:211
#define VEC_XSIZE(m)
Definition: matrix1d.h:77
void readParams()
Read arguments from command line.
void performCompleteSearch(int pyramidLevel)
double beta(const double a, const double b)
void sqrt(Image< double > &op)
Tilting angle of an image (double,degrees)
static double * y
Shift for the image in the X axis (double)
double gaussian_Real_sigma
Gaussian weight sigma in real space.
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)
FileName fnmask
Mask file.
int MatrixTimesVector(double *A, double *B, double *X, long Lines, long Columns)
double maxtransl
Maximum translation.
Special label to be used when gathering MDs in MpiMetadataPrograms.
doublereal * w
void write(const FileName &outFile, WriteModeMetaData mode=MD_OVERWRITE) const
double cutoff_LPfilter
Low-pass cut-off frequency.
void setFileName(const FileName &fn)
void initUniqueName(const char *templateStr="xmippTemp_XXXXXX", const String &fnDir="")
glob_prnt iter
#define WRITE_ERROR(FunctionName, String)
Definition: error.h:27
void runSystem(const String &program, const String &arguments, bool useSystem)
String floatToString(float F, int _width, int _prec)
void gradhesscost_atpixel(double *Gradient, double *Hessian, double *helpgr, double difference)
double minAngularSampling
Min angular sampling rate.
bool do_centerPDB
Center PDB.
Matrix1D< double > trial_best
int MatrixMultiply(double *A, double *B, double *X, long Lines, long CommonSize, long Columns)
doublereal * x
size_t size() const override
#define i
Is this image enabled? (int [-1 or 1])
ql0001_ & k(htemp+1),(cvec+1),(atemp+1),(bj+1),(bl+1),(bu+1),(x+1),(clamda+1), &iout, infoqp, &zero,(w+1), &lenw,(iw+1), &leniw, &glob_grd.epsmac
virtual void writeImageParameters(const FileName &fnImg)
double theta
virtual void createWorkFiles()
#define FOR_ALL_ELEMENTS_IN_MATRIX1D(v)
Definition: matrix1d.h:72
FileName createDeformedPDB() const
const FileName & getFileName() const
#define y0
const char * getParam(const char *param, int arg=0)
double * lambda
#define x0
if(fabs(c[*nmax+ *nmax *c_dim1])==0.e0)
bool setValue(const MDObject &mdValueIn, size_t id)
size_t addObject() override
FileName fnPDB
PDB file.
double scdefamp
Scaling factor to scale deformation amplitude.
int levenberg_cst2(MultidimArray< double > &lc_P_mu_image, MultidimArray< double > &P_esp_image, Matrix1D< double > &centerOfMass, double *beta, double *alpha, Matrix1D< double > &Parameters, double OldCost, double *lambda, double LambdaScale, long *iter, double tol_angle, double tol_shift, double tol_defamp, int *IteratingStop, size_t Xwidth, size_t Ywidth)
Matrix1D< double > parameters
Cost for the image (double)
void resize(size_t Xdim, bool copy=true)
Definition: matrix1d.h:410
#define ERROR
Definition: configs.h:24
#define XSIZE(v)
void computePDBgeometry(const std::string &fnPDB, Matrix1D< double > &centerOfMass, Matrix1D< double > &limit0, Matrix1D< double > &limitF, const std::string &intensityColumn)
Definition: pdb.cpp:238
std::vector< std::string > modeList
Normal mode displacements (vector double)
bool produces_an_output
Indicate that a unique final output is produced.
double z
void addExampleLine(const char *example, bool verbatim=true)
int SingularValueBackSubstitution(double *U, double W[], double *V, long Lines, long Columns, double B[], double X[], int *Status)
ProgFlexibleAlignment()
Empty constructor.
void initZeros()
Definition: matrix1d.h:592
int return_gradhesscost(Matrix1D< double > &centerOfMass, double *Gradient, double *Hessian, Matrix1D< double > &Parameters, int dim, MultidimArray< double > &rg_projimage, MultidimArray< double > &P_esp_image, int Xwidth, int Ywidth)
Matrix1D< double > trial
#define j
Matrix1D< double > bestStage1
int max_no_iter
Max iteration number.
double sigmaGaussian
Fixed Gaussian standard deviation.
void getColumnValues(const MDLabel label, std::vector< MDObject > &valuesOut) const override
void show() const override
void append(const FileName &outFile) const
std::string String
Definition: xmipp_strings.h:34
double psi(const double x)
double performContinuousAssignment(int pyramidLevel)
std::vector< Atom > atomList
List of atoms.
Definition: pdb.h:131
int SingularValueDecomposition(double *U, long Lines, long Columns, double W[], double *V, long MaxIterations, int *Status)
String formatString(const char *format,...)
int GetIdentitySquareMatrix(double *A, long Size)
double translsampling
Translation sampling.
#define SVDMAXITER
double maxdefamp
Maximum deformation amplitude.
doublereal * u
int multiply_3Matrices(double *A, double *B, double *C, double *X, long Lines, long CommonSizeH, long CommonSizeW, long Columns)
#define DBL_MIN
bool checkParam(const char *param)
FileName fnModeList
File zith a list of modes.
int read(const FileName &name, DataMode datamode=DATA, size_t select_img=ALL_IMAGES, bool mapData=false, int mode=WRITE_READONLY)
void defineParams()
Define params.
bool each_image_produces_an_output
Indicate that an output is produced for each image in the input.
int partialpfunction(Matrix1D< double > &Parameters, Matrix1D< double > &centerOfMass, double *R, double *Tr, double *DR0, double *DR1, double *DR2, MultidimArray< double > &DP_Rz1, MultidimArray< double > &DP_Ry, MultidimArray< double > &DP_Rz2, MultidimArray< double > &DP_x, MultidimArray< double > &DP_y, MultidimArray< double > &DP_q, int Xwidth, int Ywidth)
Shift for the image in the Y axis (double)
void addUsageLine(const char *line, bool verbatim=false)
void initZeros(const MultidimArray< T1 > &op)
FileName fnOutDir
Output directory.
bool useFixedGaussian
Use fixed Gaussian instead of scattering factors.
#define PI
Definition: tools.h:43
void selfPyramidReduce(int SplineDegree, MultidimArrayGeneric &V1, int levels)
double sampling_rate
Sampling rate.
int getIntParam(const char *param, int arg=0)
#define DBL_MAX
File with an NMA mode.
int * n
Name of an image (std::string)
double fitness(double *p)
doublereal * a
void addParamsLine(const String &line)
std::map< String, CommentList > defaultComments
Definition: xmipp_program.h:83
double defampsampling
Deformation sampling.