Bsoft  2.1.0
Bernard's software package
mg_subtomo.cpp
Go to the documentation of this file.
1 
17 #include "Bimage.h"
18 #include "mg_subtomo.h"
19 #include "mg_select.h"
20 #include "rwimg.h"
21 #include "mg_processing.h"
22 #include "linked_list.h"
23 #include "utilities.h"
24 
25 // Declaration of global variables
26 extern int verbose; // Level of output to the screen
27 
28 // It creates two temporary images the size of the input image - usually a tomogram
29 // A rotated template
30 // The cross correlation map
31 Bparticle* img_search_view(Bimage* p, Bimage* ptemp, Bimage* pmask, View view,
32  double hires, double lores, double shiftlimit, double mindist,
33  double threshold, int maxhits, int refinepeaks,
35 {
36  // View corresponds to a rotation matrix that takes the particle to the standard orientation
37  // need to transpose this matrix to rotate the template from the standard orientation on the particle
38  Matrix3 mat = view.matrix();
39  mat = mat.transpose();
40 
41  // Transform the template to the box with size of the reconstruction
42  Bimage* ptemprot = ptemp->rotate(p->size(), mat);
43 
44  // Correlate the template and the map
45  Bimage* pcc = ptemprot->cross_correlate(p, hires, lores, pmask, planf, planb);
46 
47  delete ptemprot;
48 
49  Bparticle* goodpeaks = img_find_refine_peaks(pcc, view, shiftlimit, 0, 0,
50  mindist, threshold, maxhits, refinepeaks);
51 
52  delete pcc;
53 
54  return goodpeaks;
55 }
56 
57 // It creates three temporary images the size of the template image
58 // A cropped input image
59 // An optional real space mask to apply to the cropped input image - deleted before generating more images
60 // A rotated template
61 // The cross correlation map
62 Bparticle* img_refine_view(Bimage* pcrop, Bimage* ptemp, Bimage* pmask, Bimage* pmask2,
63  View view, double hires, double lores, double shiftlimit,
64  double shiftlimitz, double shiftlimitxy, double mindist, int refinepeaks,
66 {
67 // Vector3<double> scale(1,1,1), trans;
68 
69  // View corresponds to a rotation matrix that takes the particle to the standard orientation
70  // need to transpose this matrix to rotate the template from the standard orientation on the particle
71  Matrix3 mat = view.matrix();
72  mat = mat.transpose();
73 
74  Bimage* pcropmasked = pcrop->copy();
75 
76  // Rotate the real space mask to the current view
77  if ( pmask2 ) {
78  Bimage* pmask2rot = pmask2->rotate(pmask2->size(), mat);
79  pcropmasked->multiply(pmask2rot);
80  delete pmask2rot;
81  }
82 
83  // Rotate the template to the current view
84  Bimage* ptemprot = ptemp->rotate(ptemp->size(), mat);
85 
86  // Correlate the template and the map
87  Bimage* pcc = ptemprot->cross_correlate(pcropmasked, hires, lores, pmask, planf, planb);
88 
89  delete ptemprot;
90  delete pcropmasked;
91 
92  Bparticle* peak = NULL;
93  long i(0);
94 
95  // If no shift allowed, just return the CCC at the origin
96  if ( shiftlimit == 0 && shiftlimitz == 0 && shiftlimitxy == 0) {
97  peak = particle_add(&peak, 1);
98  peak->view = view;
99  peak->fom[0] = (*pcc)[i];
100  }
101  // Shifts allowed so the hit is looked around origin, with the radius of shiftlimit, or within a cylinder
102  else {
103  peak = img_find_refine_peaks(pcc, view,
104  shiftlimit, shiftlimitz, shiftlimitxy,
105  mindist, -1, -1, refinepeaks);
106  }
107 
108  delete pcc;
109 
110  return peak;
111 }
112 
113 /************************************************************************
114 @brief Searches a 3D density map for a template
115 @author Juha Huiskonen
116 @param *rec reconstruction parameters.
117 @param *p the image.
118 @param *ptemp the template to be searched for.
119 @param *pmask reciprocal space mask for cross-correlation (ignored if NULL).
120 @param *pmask2 real space mask for cross-correlation (ignored if NULL).
121 @param alpha_step angular step size around view vector (radians).
122 @param theta_step angular step size around view vector (radians).
123 @param phi_step angular step size around view vector (radians).
124 @param angle_limit angular limit for refinement in alpha (radians).
125 @param thetaphi_limit angular limit for refinement in theta & phi (radians).
126 @param hires high resolution limit.
127 @param lores low resolution limit.
128 @param shiftlimit maximum shift from the original position (binned units).
129 @param mindist minimun distance for cc peaks (binned units).
130 @param maxhits maximum number of hits
131 @param bin binning for map, template and mask
132 @param *sym symmetry to generate a list of views for search mode
133 @param refinepeaks flag to run several iterations in refine
134 @param ccmax_file file for cross-correlation map (max ccc for each position and rotation of the template)
135 @return double the best correlation coefficient.
136 
137  The template is rotated and cross-correlated to find fits above the
138  threshold.
139 
140 **/
142  Bimage* p, Bimage* ptemp, Bimage* pmask, Bimage* pmask2,
143  double alpha_step, double theta_step, double phi_step,
144  double alpha_limit, double thetaphi_limit,
145  double hires, double lores, double shiftlimit, double mindist,
146  double threshold, int maxhits, Vector3<long> bin, Bsymmetry* sym,
147  int refinepeaks, Bstring ccmax_file)
148 {
149  if ( !pmask ) { cerr << "Warning: No reciprocal space mask given." << endl; }
150  if ( !pmask2 ) { cerr << "Warning: No real space mask given." << endl; }
151 
152  // Search whole rec by default
153  if ( shiftlimit < 0 ) {
154  if ( verbose & VERB_PROCESS )
155  cout << endl << "Shift limit not specified, searching the whole reconstruction." << endl;
156  shiftlimit = p->size().length()/2;
157  }
158 
159  // Minimum distance between ccc peaks is the size of the template by default
160  if ( mindist <= 0 ) { mindist = 2*ptemp->maximum_included_radius(); }
161 
162  // Clear any previous particle records
163  if ( rec->part ) particle_kill(rec->part);
164  rec->fpart = 0;
165  rec->part = NULL;
166 
167  // Origin of the template (already binned units)
168  Vector3<double> origin = ptemp->image->origin();
169 
170  // Normalize and mask template
171  if ( verbose & VERB_PROCESS ) { cout << endl << "Normalizing the template." << endl; }
172  ptemp->rescale_to_avg_std(0, 1);
173 
174  if ( pmask2 ) {
175  if ( verbose & VERB_PROCESS ) { cout << endl << "Masking the template." << endl; }
176  ptemp->multiply(pmask2);
177  }
178 
179  // Normalize map
180  if ( verbose & VERB_PROCESS ) { cout << endl << "Normalizing the map." << endl; }
181  p->rescale_to_avg_std(0, 1);
182 
183  // Search mode
184  if ( verbose & VERB_PROCESS ) { cout << endl << "Running in search mode." << endl; }
185  cout << endl;
186 
187  // Views to consider in Search
188  View refview;
189  View* allviews = NULL; // all views for search/refinement
190  if ( sym->point < 102 ) {
191  allviews = views_within_limits(refview, theta_step, phi_step, alpha_step, thetaphi_limit, alpha_limit);
192  } else {
193  allviews = asymmetric_unit_views(sym, theta_step, phi_step, alpha_step, 1);
194  }
195 
196  long nviews = count_list((char *)allviews);
197 
198 // if ( verbose & VERB_PROCESS ) {
199  if ( verbose ) {
200  cout << "Searching for the template in the map:" << endl;
201  cout << "Map: " << p->file_name() << endl;
202  cout << "Template: " << ptemp->file_name() << endl;
203  cout << "Map size: " << p->size() << endl;
204  cout << "Template size: " << ptemp->size() << endl;
205  cout << "Template origin: " << setprecision(4) << origin << endl;
206  cout << "Binning: " << bin << endl;
207  cout << "Search radius: " << shiftlimit << endl;
208  cout << "Minimum separation distance: " << mindist << endl;
209  if ( pmask2)
210  cout << "Real space mask: " << pmask2->file_name() << endl;
211  if ( pmask )
212  cout << "Reciprocal space mask: " << pmask->file_name() << endl;
213  cout << "Alpha step size: " << alpha_step*180.0/M_PI << " degrees" << endl;
214  cout << "Theta step size: " << theta_step*180.0/M_PI << " degrees" << endl;
215  cout << "Phi step size: " << phi_step*180.0/M_PI << " degrees" << endl;
216  cout << "Limit in alpha: " << alpha_limit*180.0/M_PI << " degrees" << endl;
217  if ( sym )
218  cout << "Symmetry: " << sym->label << endl;
219  else
220  cout << "Limit in theta & phi: " << thetaphi_limit*180.0/M_PI << " degrees" << endl;
221  cout << "Number of views: " << nviews << endl;
222  if ( ccmax_file.length() )
223  cout << "Cross correlation map: " << ccmax_file << endl;
224  cout << endl;
225  }
226 
227  if ( pmask )
228  pmask->mask_fspace_resize(p->size());
229 
230  long i, ipart(0);
231  View* v = NULL;
232  View* view_arr = new View[nviews];
233  for ( i=0, v=allviews; v; v=v->next, i++ ) view_arr[i] = *v;
234 
235  Bparticle* part = NULL;
236  Bparticle** part_arr = new Bparticle*[nviews];
237 
238  fft_plan planf = p->fft_setup(FFTW_FORWARD, 1);
239  fft_plan planb = p->fft_setup(FFTW_BACKWARD, 1);
240 
241  if ( verbose & VERB_RESULT )
242  cout << "#\tViewX\tViewY\tViewZ\tViewA\tNpart" << endl;
243 
244  // Loop through all views for the current particle and iteration
245 #ifdef HAVE_GCD
246  dispatch_queue_t myq = dispatch_queue_create(NULL, NULL);
247  dispatch_apply(nviews, dispatch_get_global_queue(0, 0), ^(size_t i){
248  part_arr[i] = img_search_view(p, ptemp, pmask, view_arr[i], hires, lores,
249  shiftlimit, mindist, threshold, maxhits, refinepeaks, planf, planb);
250  long np = count_list((char *) part_arr[i]);
251  dispatch_sync(myq, ^{
252  if ( verbose & VERB_RESULT )
253  cout << i+1 << tab << view_arr[i] << tab << np << endl << flush;
254  });
255  });
256 #else
257 #pragma omp parallel for
258  for ( long i=0; i < nviews; i++ ) {
259  part_arr[i] = img_search_view(p, ptemp, pmask, view_arr[i], hires, lores,
260  shiftlimit, mindist, threshold, maxhits, refinepeaks, planf, planb);
261  long np = count_list((char *) part_arr[i]);
262  #pragma omp critical
263  {
264  if ( verbose & VERB_RESULT )
265  cout << i+1 << tab << view_arr[i] << tab << np << endl << flush;
266  }
267  }
268 #endif
269 
272 
273  if ( verbose )
274  cout << "Transferring the particles found to the reconstruction" << endl;
275  for ( i=0; i < nviews; i++ ) if ( part_arr[i] ) {
276  if ( !rec->part ) rec->part = part = part_arr[i];
277  else part->next = part_arr[i];
278  for ( ; part->next; part = part->next ) ;
279  }
280 
281  Vector3<double> translate;
282 
283  for ( ipart=0, part = rec->part; part; part = part->next ) {
284  part->id = ++ipart;
285  part->ori = origin * bin;
286  translate = origin - part->loc;
287  translate = vector3_set_PBC(translate, p->size());
288  part->loc = translate * bin;
289  if ( verbose & VERB_FULL )
290  cout << ipart << tab << setprecision(2)
291  << part->loc << tab << setprecision(4) << part->view << tab << part->fom[0] << endl;
292  }
293 
294  kill_list((char *) allviews, sizeof(View));
295  delete[] view_arr;
296  delete[] part_arr;
297 
298  if ( rec->box_size.volume() < 1 )
299  rec->box_size = ptemp->size() * bin;
300 
301  return particle_count(rec->part);
302 }
303 
335  Bimage* p, Bimage* ptemp, Bimage* pmask, Bimage* pmask2,
336  double alpha_step_orig, double theta_step_orig, double phi_step_orig,
337  double alpha_limit_orig, double thetaphi_limit_orig,
338  double hires, double lores, double shiftlimit_orig,
339  double shiftlimitz_orig, double shiftlimitxy_orig, double mindist,
340  Vector3<long> bin, Bsymmetry* sym, int iters, int refinepeaks, Bstring ccmax_file)
341 {
342  if ( !pmask ) { cerr << "Warning: No reciprocal space mask given." << endl; }
343  if ( !pmask2 ) { cerr << "Warning: No real space mask given." << endl; }
344 
345  // Refine shifts within 1/2 template by default
346  if ( shiftlimit_orig < 0 ) {
347  if ( verbose & VERB_PROCESS )
348  cout << endl << "Shift limit not specified, using half the size of the template." << endl;
349  shiftlimit_orig = ptemp->maximum_included_radius();
350  }
351 
352  if ( mindist <= 0 ) { mindist = 2*ptemp->maximum_included_radius(); }
353 
354  // Normalize and mask template
355  if ( verbose & VERB_PROCESS ) { cout << endl << "Normalizing the template." << endl; }
356  ptemp->rescale_to_avg_std(0, 1);
357 
358  if ( pmask2 ) {
359  if ( verbose & VERB_PROCESS ) { cout << endl << "Masking the template." << endl; }
360  ptemp->multiply(pmask2);
361  }
362 
363  // Normalize map
364  if ( verbose & VERB_PROCESS ) { cout << endl << "Normalizing the map." << endl; }
365  p->rescale_to_avg_std(0, 1);
366 
367  // Refine mode
368  if ( verbose & VERB_PROCESS ) { cout << "Running in refine mode" << endl; }
369 
370  if ( sym->point > 101 && iters > 1) {
371  iters = 1;
372  cerr << "Warning: Symmetry selected, running only one iteration." << endl;
373  }
374 
375  if ( verbose & VERB_RESULT ){ cout << endl << "Padding the template to a larger box." << endl;}
376 
377  double maxshift = shiftlimit_orig + shiftlimitz_orig + shiftlimitxy_orig;
378 
379  // Origin of the template (already binned units)
380  Vector3<double> origin = ptemp->image->origin();
381 
382  Vector3<double> scale(1,1,1);
383  Vector3<double> translate = Vector3<double>(maxshift,maxshift,maxshift);
384  View refview;
385  Matrix3 mat = refview.matrix();
386  Vector3<long> ptempsize = ptemp->size() + Vector3<long>(2*(long)maxshift, 2*(long)maxshift, 2*(long)maxshift);
387  ptemp->resize(ptempsize, translate, FILL_BACKGROUND, 0);
388  ptemp->origin(origin+translate);
389  Vector3<double> neworigin = ptemp->image->origin();
390 
391  if ( pmask )
392  pmask->mask_fspace_resize(p->size());
393 
394  if ( pmask2 ) {
395  if ( verbose & VERB_RESULT ){ cout << endl << "Padding the real space mask to a larger box." << endl;}
396  pmask2->resize(ptempsize, translate, FILL_BACKGROUND, 0);
397  }
398 
399  if ( verbose ) {
400  cout << endl << "Refining the template in the map around the starting view:" << endl;
401  cout << "Map: " << p->file_name() << endl;
402  cout << "Template: " << ptemp->file_name() << endl;
403  cout << "Map size: " << p->size() << endl;
404  cout << "Template size: " << ptemp->size() << endl;
405  cout << "Template origin: " << setprecision(4) << ptemp->image->origin() << endl;
406  cout << "Binning: " << bin << endl;
407  cout << "Maximum translation: " << shiftlimit_orig << " pixels" << endl;
408  if ( shiftlimitz_orig > 0 )
409  cout << "Additional shift along view: " << shiftlimitz_orig << endl;
410  if ( shiftlimitxy_orig > 0 )
411  cout << "Additional shift orthogonal view: " << shiftlimitxy_orig << endl;
412  if ( pmask2)
413  cout << "Real space mask: " << pmask2->file_name() << endl;
414  if ( pmask )
415  cout << "Reciprocal space mask: " << pmask->file_name() << endl;
416  cout << "Alpha step size: " << alpha_step_orig*180.0/M_PI << " degrees" << endl;
417  cout << "Theta step size: " << theta_step_orig*180.0/M_PI << " degrees" << endl;
418  cout << "Phi step size: " << phi_step_orig*180.0/M_PI << " degrees" << endl;
419  cout << "Limit in alpha: " << alpha_limit_orig*180.0/M_PI << " degrees" << endl;
420  if ( sym->point < 102 )
421  cout << "Limit in theta & phi: " << thetaphi_limit_orig*180.0/M_PI << " degrees" << endl;;
422  cout << endl;
423  }
424 
425  long iter, nviews, i, ibest(0);
426  long npart = particle_count(rec->part);
427  double shiftlimit, shiftlimitz, shiftlimitxy;
428  double alpha_step,theta_step,phi_step;
429  double alpha_limit, thetaphi_limit;
430  double best_cc;
431  Vector3<double> bestshift;
432  View bestview;
433  View* v = NULL;
434  View* allviews = NULL;
435  Bparticle* part = NULL;
436  Bimage* pcrop = NULL;
437 
438  fft_plan planf = fft_setup_plan(ptempsize, FFTW_FORWARD, 1);
439  fft_plan planb = fft_setup_plan(ptempsize, FFTW_BACKWARD, 1);
440 
441  for ( part = rec->part; part; part = part->next ) if ( part->sel > 0 ) {
442 
443  if ( verbose )
444  cout << "Particle: " << part->id << " of " << npart << endl;
445 
446  if ( verbose & VERB_PROCESS ) {
447  cout << "Starting location: " << part->loc << endl;
448  cout << "Starting view: " << part->view << endl;
449  }
450 
451 
452  // Reset angle step sizes to originals for the current particle (halved after each iteration)
453  alpha_step = alpha_step_orig;
454  theta_step = theta_step_orig;
455  phi_step = phi_step_orig;
456  thetaphi_limit = thetaphi_limit_orig;
457  alpha_limit = alpha_limit_orig;
458  shiftlimit = shiftlimit_orig;
459  shiftlimitxy = shiftlimitxy_orig;
460  shiftlimitz = shiftlimitz_orig;
461 
462  // The initially best view is the given view
463  bestview = part->view;
464 
465  for ( iter=1; iter <= iters; iter++) {
466 
467  // Views around the current best view to consider in refinement
468  if ( sym->point < 102 ) {
469  allviews = views_within_limits(bestview, theta_step, phi_step, alpha_step, thetaphi_limit, alpha_limit);
470  } else {
471  allviews = asymmetric_unit_views(sym, theta_step, phi_step, alpha_step, 1);
472  }
473 
474  nviews = count_list((char *)allviews);
475 
476  if ( verbose & VERB_PROCESS ) {
477  cout << "Iteration: " << iter << " of " << iters << endl;
478  cout << "Alpha step size: " << alpha_step*180.0/M_PI << " degrees" << endl;
479  cout << "Theta step size: " << theta_step*180.0/M_PI << " degrees" << endl;
480  cout << "Phi step size: " << phi_step*180.0/M_PI << " degrees" << endl;
481  cout << "Limit in alpha: " << alpha_limit*180.0/M_PI << " degrees" << endl;
482  if ( sym->point < 102 )
483  cout << "Limit in theta & phi: " << thetaphi_limit*180.0/M_PI << " degrees" << endl;;
484  cout << "Number of views: " << nviews << endl;
485  cout << endl;
486  }
487 
488  // Crop reconstruction to the same size of a box as the template using the refined location
489  if ( verbose & VERB_FULL ){ cout << endl << "Cropping the map." << endl << endl;}
490  translate = -part->loc;
491  if ( bin[0] ) { translate /= bin; }
492  translate = translate + neworigin;
493  mat = refview.matrix();
494  pcrop = p->transform(ptempsize, scale, Vector3<double>(0,0,0), translate, mat, FILL_BACKGROUND, 0);
495 
496  // Normalize cropped map
497  pcrop->rescale_to_avg_std(0, 1);
498  pcrop->origin(Vector3<double>(0,0,0));
499 
500  // Since we are contracting around the previous best point, the best orientation is always found from the current views
501  best_cc = -1;
502 
503  View* view_arr = new View[nviews];
504  for ( i=0, v=allviews; v; v=v->next, i++ ) view_arr[i] = *v;
505 
506  Bparticle** part_arr = new Bparticle*[nviews];
507 
508 #ifdef HAVE_GCD
509  dispatch_apply(nviews, dispatch_get_global_queue(0, 0), ^(size_t i){
510  part_arr[i] = img_refine_view(pcrop, ptemp, pmask, pmask2, view_arr[i],
511  hires, lores, shiftlimit, shiftlimitz, shiftlimitxy,
512  mindist, refinepeaks, planf, planb);
513  });
514 #else
515 #pragma omp parallel for
516  for ( i=0; i < nviews; i++ ) {
517  part_arr[i] = img_refine_view(pcrop, ptemp, pmask, pmask2, view_arr[i],
518  hires, lores, shiftlimit, shiftlimitz, shiftlimitxy,
519  mindist, refinepeaks, planf, planb);
520  }
521 #endif
522 
523  for ( i=0; i < nviews; i++ ) {
524  if ( part_arr[i]->fom[0] > best_cc ) {
525  best_cc = part_arr[i]->fom[0];
526  ibest = i;
527  bestview = part_arr[i]->view;
528  bestshift = part_arr[i]->loc;
529  }
530  particle_kill(part_arr[i]);
531  }
532 
533  delete[] view_arr;
534  delete[] part_arr;
535 
536  translate = -bestshift;
537 
538  // wrap translation vectors (still working with binned units)
539  translate = vector3_origin_to_shift(translate, pcrop->size());
540 
541  // Half the angle steps angle limits and shift limits for the next iteration
542  alpha_step /= 2;
543  theta_step /= 2;
544  phi_step /= 2;
545  alpha_limit /= 2;
546  thetaphi_limit /= 2;
547  shiftlimit /= 2;
548  shiftlimitz /= 2;
549  shiftlimitxy /= 2;
550 
551  kill_list((char *) allviews, sizeof(View));
552 
553  // Take binning into account in the translation
554  if ( bin[0] ) { translate *= bin; }
555 
556  // Update refined orientation and origin + fom
557  part->view = bestview;
558  part->loc = part->loc + translate;
559  part->fom[0] = best_cc;
560 
561  delete pcrop;
562 
563  if ( verbose )
564  cout << " \r" << flush << iter << tab << ibest+1 << tab << part->loc << tab << bestview << tab << best_cc << endl;
565 
566  } // for ( iter=1; iter <= iters; iter++)
567 
568 // if ( verbose )
569 // cout << endl << "Final:\t" << ibest << tab << part->loc << tab <<
570 // bestview << tab << best_cc << endl;
571 
572  } // if ( part->sel > 0 )
573 
576 
577  if ( rec->box_size.volume() < 1 )
578  rec->box_size = ptemp->size() * bin;
579 
580  return particle_count(rec->part);
581 }
582 
601 Bparticle* img_find_refine_peaks(Bimage* pcc, View view, double shift_limit,
602  double shift_along, double shift_orthogonal, double mindist,
603  double threshold, int maxhits, int refinepeaks)
604 {
605  double peakcc;
606  Bparticle* goodpeaks = NULL;
607  Bparticle* peak = NULL;
608  int hits(0);
609 
610  do {
611  // shift vectors are in actual pixel coordinates (no wrapping)
612  peakcc = img_find_peak_subtomo(pcc, view, shift_limit, shift_along, shift_orthogonal);
613 
614  if ( refinepeaks ) { pcc->refine_peak(); }
615 
616  if ( (peakcc >= threshold) || (threshold < 0) ) {
617 
618  hits++;
619 
620  peak = particle_add(&goodpeaks, hits);
621  peak->loc = pcc->image->origin();
622  peak->view = view;
623  peak->fom[0] = peakcc;
624 
625  if ( verbose && maxhits > 1 )
626  cout << hits << tab << peak->loc << tab << view << tab << peakcc << endl;
627 
628  if ( verbose & VERB_PROCESS )
629  cout << "Found a cross-correlation peak:\t" << peak->loc << tab << peakcc << endl;
630 
631  // return only the global maximum
632  if (threshold < 0) { break; }
633 
634  // Enough particles found
635  if (maxhits > 0 && hits >= maxhits) { break; }
636 
637  }
638 
639  pcc->shell_wrap(0, pcc->image->origin(), 0, mindist, 0, FILL_USER, 0);
640 
641  } while ( peakcc >= threshold );
642 
643  //write_img("temp_pcc.spi", pcc);
644 
645  if ( hits == 0 ) {
646  if ( verbose & VERB_PROCESS )
647  cout << "No cross-correlation peaks found above the threshold (the maximum was " << peakcc << ")" << endl;
648  }
649 
650  return goodpeaks;
651 }
652 
668 double img_find_peak_subtomo(Bimage* p, View view, double shift,
669  double shift_along, double shift_orthogonal)
670 {
671  if ( !p->data_pointer() ) return 0;
672 
673  if ( shift < 0 ) shift = 1e30;
674 
675  long i(0), x, y, z;
676  long xh = p->sizeX()/2, yh = p->sizeY()/2, zh = p->sizeZ()/2;
677  double x2, y2, z2, r2;
678  double value(0), max;
679  double shift2 = shift*shift;
680  Vector3<double> peak;
681  Vector3<double> origin(0,0,0);
682  Vector3<double> point;
683  Vector3<double> endpoint1;
684  Vector3<double> endpoint2;
685  Vector3<double> closestpoint;
686 
687  view = view.backward();
688 
689  if ( shift_along > 0 ) {
690  endpoint1 = Vector3<double>(view[0] * shift_along, view[1] * shift_along, view[2] * shift_along);
691  endpoint2 = Vector3<double>(-view[0] * shift_along, -view[1] * shift_along, -view[2] * shift_along);
692  }
693 
694  max = -1e37;
695  for ( z=0; z<p->sizeZ(); z++ ) {
696  z2 = origin[2] - z;
697  if ( z2 < -zh ) z2 += p->sizeZ();
698  if ( z2 > zh ) z2 -= p->sizeZ();
699 
700  for ( y=0; y<p->sizeY(); y++ ) {
701  y2 = origin[1] - y;
702  if ( y2 < -yh ) y2 += p->sizeY();
703  if ( y2 > yh ) y2 -= p->sizeY();
704 
705  for ( x=0; x<p->sizeX(); x++, i++ ) {
706  x2 = origin[0] - x;
707  if ( x2 < -xh ) x2 += p->sizeX();
708  if ( x2 > xh ) x2 -= p->sizeX();
709 
710  value = (*p)[i];
711 
712  if ( shift_along > 0 ) {
713  point = Vector3<double>((double)x2, (double)y2, (double)z2);
714  // squared distance to the closest point on the line segment
715  r2 = closest_point_line_distance2(point, endpoint1, endpoint2);
716  }
717  else if ( shift_orthogonal > 0 ) {
718  point = Vector3<double>((double)x2, (double)y2, (double)z2);
719  // squared distance to the closest point on the disc
720  r2 = closest_point_disc_distance2(point, Vector3<double>(0,0,0), view, shift_orthogonal);
721  }
722  else {
723  // squared distance to the origin
724  r2 = x2*x2 + y2*y2 + z2*z2;
725  }
726  if ( r2 > shift2 ) value = 0;
727  if ( max < value ) {
728  if ( r2 > shift2 ) value = 0;
729  max = value;
730  peak = Vector3<double>(x,y,z);
731  }
732  }
733  }
734  }
735  p->image->origin(peak);
736  p->image->FOM(max);
737  if ( verbose & VERB_FULL )
738  cout << "Peak: " << peak << tab << max << endl;
739 
740  return max;
741 }
742 
756 {
757  double l2, t;
758  Vector3<double> closest_point;
759  Vector3<double> line;
760 
761  line = w-v;
762  l2 = line.length2();
763 
764  // parametric value of vector to the closest point is t = scalar(p - v, w - v) / l*l
765  t = (p-v).scalar(line) / l2;
766 
767  // the closest point is end point v
768  if ( t < 0 ) { closest_point = v; }
769 
770  // the closest point is end point w
771  else if ( t > 1 ) { closest_point = w; }
772 
773  // the closest point is the projection of p that is v + t*line
774  else { closest_point = Vector3<double>( v[0] + t * line[0],
775  v[1] + t * line[1],
776  v[2] + t * line[2]);
777  }
778  return closest_point;
779 }
780 
795 {
796  double l2, t;
797  Vector3<double> closest_point;
798  Vector3<double> line;
799 
800  line = w-v;
801  l2 = line.length2();
802 
803  // parametric value of vector to the closest point is t = scalar(p - v, w - v) / l*l
804  t = (p-v).scalar(line) / l2;
805 
806  // the closest point is end point v
807  if ( t < 0 ) { closest_point = v; }
808 
809  // the closest point is end point w
810  else if ( t > 1 ) { closest_point = w; }
811 
812  // the closest point is the projection of p that is v + t*line
813  else { closest_point = Vector3<double>( v[0] + t * line[0],
814  v[1] + t * line[1],
815  v[2] + t * line[2]);
816  }
817  return (closest_point-p).length2();
818 }
819 
820 
836 {
837  Vector3<double> pprime; // projection of p on to the plane
838 
839  double p_to_pprime2; // squared distance from p' to the original point p
840 
841  double pprime_to_q2; // squared distance from p' to the center of the disc q
842  double pprime_to_q; // distance from p' to the center of the disc q
843 
844  double pprime_to_c2; // squared distance from p' to the circumference of the disc c
845  double p_to_c2; // squared distance from p to the circumference of the disc c
846 
847  double radius2 = radius * radius;
848  double a, c;
849 
850  c = q[0]*view[0] + q[1]*view[1] + q[2]*view[2];
851 
852  a = (view[0] * p[0] + view[1] * p[1] + view[2] * p[2]) - c;
853  pprime = Vector3<double>(p[0] - a * view[0], p[1] - a * view[1], p[2] - a * view[2]);
854 
855  pprime_to_q2 = (pprime-q).length2();
856  p_to_pprime2 = (p-pprime).length2();
857 
858  if (pprime_to_q2 > radius2) {
859 
860  pprime_to_q = (pprime-q).length();
861  pprime_to_c2 = (pprime_to_q - radius) * (pprime_to_q - radius);
862 
863  p_to_c2 = pprime_to_c2 + p_to_pprime2;
864 
865  return p_to_c2;
866  }
867  else {
868  return p_to_pprime2;
869  }
870 }
871 
907 Sphere locations_fit_sphere(Bparticle* part, int N, double Nstop)
908 {
909  Sphere sphere;
910  long Pnpoints(0);
911  Bparticle* p = NULL;
912 
913  double PXsum=0, PXsumsq=0, PXsumcube=0;
914  double PYsum=0, PYsumsq=0, PYsumcube=0;
915  double PZsum=0, PZsumsq=0, PZsumcube=0;
916 
917  double PXYsum=0, PXZsum=0, PYZsum=0;
918  double PX2Ysum=0, PX2Zsum=0, PY2Xsum=0, PY2Zsum=0, PZ2Xsum=0, PZ2Ysum=0;
919 
920  Pnpoints = count_list((char *)part);
921  double x, y, z;
922 
923  for ( p = part; p; p = p-> next ) {
924 
925  x = p->loc[0];
926  y = p->loc[1];
927  z = p->loc[2];
928 
929  PXsum += x;
930  PXsumsq += x * x;
931  PXsumcube += x * x * x;
932 
933  PYsum += y;
934  PYsumsq += y * y;
935  PYsumcube += y * y * y;
936 
937  PZsum += z;
938  PZsumsq += z * z;
939  PZsumcube += z * z * z;
940 
941  PXYsum += x * y;
942  PXZsum += x * z;
943  PYZsum += y * z;
944 
945  PX2Ysum += x * x * y;
946  PX2Zsum += x * x * z;
947  PY2Xsum += y * y * x;
948  PY2Zsum += y * y * z;
949  PZ2Xsum += z * z * x;
950  PZ2Ysum += z * z * y;
951  }
952 
953  double Xn = PXsum/Pnpoints; //sum( X[n] )
954  double Xn2 = PXsumsq/Pnpoints; //sum( X[n]^2 )
955  double Xn3 = PXsumcube/Pnpoints; //sum( X[n]^3 )
956  double Yn = PYsum/Pnpoints; //sum( Y[n] )
957  double Yn2 = PYsumsq/Pnpoints; //sum( Y[n]^2 )
958  double Yn3 = PYsumcube/Pnpoints; //sum( Y[n]^3 )
959  double Zn = PZsum/Pnpoints; //sum( Z[n] )
960  double Zn2 = PZsumsq/Pnpoints; //sum( Z[n]^2 )
961  double Zn3 = PZsumcube/Pnpoints; //sum( Z[n]^3 )
962 
963  double XY = PXYsum/Pnpoints; //sum( X[n] * Y[n] )
964  double XZ = PXZsum/Pnpoints; //sum( X[n] * Z[n] )
965  double YZ = PYZsum/Pnpoints; //sum( Y[n] * Z[n] )
966  double X2Y = PX2Ysum/Pnpoints; //sum( X[n]^2 * Y[n] )
967  double X2Z = PX2Zsum/Pnpoints; //sum( X[n]^2 * Z[n] )
968  double Y2X = PY2Xsum/Pnpoints; //sum( Y[n]^2 * X[n] )
969  double Y2Z = PY2Zsum/Pnpoints; //sum( Y[n]^2 * Z[n] )
970  double Z2X = PZ2Xsum/Pnpoints; //sum( Z[n]^2 * X[n] )
971  double Z2Y = PZ2Ysum/Pnpoints; //sum( Z[n]^2 * Y[n] )
972 
973  //Reduction of multiplications
974  double F0 = Xn2 + Yn2 + Zn2;
975  double F1 = 0.5*F0;
976  double F2 = -8.0*(Xn3 + Y2X + Z2X);
977  double F3 = -8.0*(X2Y + Yn3 + Z2Y);
978  double F4 = -8.0*(X2Z + Y2Z + Zn3);
979 
980  //Set initial conditions:
981  double A = Xn;
982  double B = Yn;
983  double C = Zn;
984 
985  //First iteration computation:
986  double A2 = A*A;
987  double B2 = B*B;
988  double C2 = C*C;
989  double QS = A2 + B2 + C2;
990  double QB = - 2*(A*Xn + B*Yn + C*Zn);
991 
992  //Set initial conditions:
993  double Rsq = F0 + QB + QS;
994 
995  //First iteration computation:
996  double Q0 = 0.5*(QS - Rsq);
997  double Q1 = F1 + Q0;
998  double Q2 = 8*( QS - Rsq + QB + F0 );
999  double aA,aB,aC,nA,nB,nC,dA,dB,dC;
1000 
1001  //Iterate N times, ignore stop condition.
1002  int n(0);
1003  while( n != N ){
1004  n++;
1005 
1006  //Compute denominator:
1007  aA = Q2 + 16*(A2 - 2*A*Xn + Xn2);
1008  aB = Q2 + 16*(B2 - 2*B*Yn + Yn2);
1009  aC = Q2 + 16*(C2 - 2*C*Zn + Zn2);
1010  aA = (aA == 0) ? 1.0 : aA;
1011  aB = (aB == 0) ? 1.0 : aB;
1012  aC = (aC == 0) ? 1.0 : aC;
1013 
1014 
1015  //Compute next iteration
1016  nA = A - ((F2 + 16*( B*XY + C*XZ + Xn*(-A2 - Q0) + A*(Xn2 + Q1 - C*Zn - B*Yn) ) )/aA);
1017  nB = B - ((F3 + 16*( A*XY + C*YZ + Yn*(-B2 - Q0) + B*(Yn2 + Q1 - A*Xn - C*Zn) ) )/aB);
1018  nC = C - ((F4 + 16*( A*XZ + B*YZ + Zn*(-C2 - Q0) + C*(Zn2 + Q1 - A*Xn - B*Yn) ) )/aC);
1019 
1020  //Check for stop condition
1021  dA = (nA - A);
1022  dB = (nB - B);
1023  dC = (nC - C);
1024  if( (dA*dA + dB*dB + dC*dC) <= Nstop ){ break; }
1025 
1026  //Compute next iteration's values
1027  A = nA;
1028  B = nB;
1029  C = nC;
1030  A2 = A*A;
1031  B2 = B*B;
1032  C2 = C*C;
1033  QS = A2 + B2 + C2;
1034  QB = - 2*(A*Xn + B*Yn + C*Zn);
1035  Rsq = F0 + QB + QS;
1036  Q0 = 0.5*(QS - Rsq);
1037  Q1 = F1 + Q0;
1038  Q2 = 8*( QS - Rsq + QB + F0 );
1039  }
1040 
1041  double R = sqrt(Rsq);
1042  sphere.A = A;
1043  sphere.B = B;
1044  sphere.C = C;
1045  sphere.R = R;
1046 
1047  return (sphere);
1048 }
1049 
1050 
length2
double length2(vector< T > v)
Definition: Vector3.h:519
Bimage::fft_setup
fft_plan fft_setup(fft_direction dir, int opt=0)
Sets up a plan for fast Fourier transforms.
Definition: Bimage_fft.cpp:29
closest_point_line
Vector3< double > closest_point_line(Vector3< double > p, Vector3< double > v, Vector3< double > w)
Calculates the closest point on a line segment from a given point.
Definition: mg_subtomo.cpp:755
Breconstruction::part
Bparticle * part
Definition: mg_processing.h:307
img_find_refine_peaks
Bparticle * img_find_refine_peaks(Bimage *pcc, View view, double shift_limit, double shift_along, double shift_orthogonal, double mindist, double threshold, int maxhits, int refinepeaks)
Finds peaks in an image to the nearest voxel iteratively.
Definition: mg_subtomo.cpp:601
View::next
View * next
Definition: View.h:28
Bimage::sizeZ
void sizeZ(long nz)
Definition: Bimage.h:392
Breconstruction::fpart
Bstring fpart
Definition: mg_processing.h:291
vector3_origin_to_shift
Vector3< T1 > vector3_origin_to_shift(Vector3< T1 > origin, Vector3< T2 > size)
Definition: Vector3.h:669
Bsymmetry::point
int point
Definition: symmetry.h:39
kill_list
long kill_list(char *list, unsigned long size)
Frees all the items in a linked list.
Definition: linked_list.cpp:214
Bparticle::view
View view
Definition: mg_processing.h:102
Bimage::cross_correlate
Bimage * cross_correlate(Bimage *p, double hires, double lores, fft_plan planf, fft_plan planb)
Calculates a cross-correlation map by Fast Fourier transformation.
Definition: Bimage_correlate.cpp:363
Bstring
Definition: Bstring.h:29
Bparticle
Definition: mg_processing.h:90
Matrix3::transpose
Matrix3 transpose() const
Definition: Matrix3.h:268
img_find_peak_subtomo
double img_find_peak_subtomo(Bimage *p, View view, double shift, double shift_along, double shift_orthogonal)
Finds the peak in an image to the nearest voxel.
Definition: mg_subtomo.cpp:668
reconstruction_refine_subtomo
long reconstruction_refine_subtomo(Breconstruction *rec, Bimage *p, Bimage *ptemp, Bimage *pmask, Bimage *pmask2, double alpha_step_orig, double theta_step_orig, double phi_step_orig, double alpha_limit_orig, double thetaphi_limit_orig, double hires, double lores, double shiftlimit_orig, double shiftlimitz_orig, double shiftlimitxy_orig, double mindist, Vector3< long > bin, Bsymmetry *sym, int iters, int refinepeaks, Bstring ccmax_file)
Refines the view vectors for particles already in the project.
Definition: mg_subtomo.cpp:334
Bimage::copy
Bimage * copy()
Copies the header information and data of an image into a new image structure.
Definition: Bimage.cpp:2702
Vector3< long >
Bimage::sizeX
void sizeX(long nx)
Definition: Bimage.h:390
mg_select.h
Header file for micrograph processing.
Bparticle::fom
double fom[NFOM]
Definition: mg_processing.h:103
FILL_USER
#define FILL_USER
Definition: utilities.h:176
Bimage::size
Vector3< long > size() const
Definition: Bimage.h:386
Breconstruction::box_size
Vector3< long > box_size
Definition: mg_processing.h:299
Bimage::transform
int transform(Vector3< double > scale, Vector3< double > origin, Vector3< double > translate, Matrix3 mat, int fill_type=0, double fill=0)
Transforms an image by translation, rotation, scaling and skewing, in place.
Definition: Bimage_transform.cpp:37
asymmetric_unit_views
View * asymmetric_unit_views(Bsymmetry *sym, double theta_step, double phi_step, int flag)
Initializes a well-distributed set of views in an asymmetric unit.
Definition: symmetry.cpp:564
View
Definition: View.h:26
Bsub_image::FOM
double FOM()
Definition: Bimage.h:165
length
double length(vector< T > v)
Definition: Vector3.h:530
Bimage::image
Bsub_image * image
Definition: Bimage.h:202
VERB_PROCESS
#define VERB_PROCESS
Definition: utilities.h:111
Bsymmetry
Definition: symmetry.h:38
count_list
long count_list(char *list)
Counts the number of items in a linked list.
Definition: linked_list.cpp:235
Bimage::refine_peak
int refine_peak()
Refines the position of a peak to sub-voxel resolution.
Definition: Bimage_correlate.cpp:1615
planf
fft_plan planf
Definition: bico.cpp:24
Bimage::shell_wrap
int shell_wrap(long nn, Vector3< double > center, double minrad, double maxrad, double width, int fill_type=0, double fill=0)
Fills a shell within an image with a uniform value with wrapping.
Definition: Bimage_edit.cpp:656
Bimage::mask_fspace_resize
Vector3< double > mask_fspace_resize(Vector3< long > nusize)
Resizes a reciprocal space mask.
Definition: Bimage_mask.cpp:684
Matrix3
Definition: Matrix3.h:18
Bsub_image::origin
void origin(double x, double y, double z)
Definition: Bimage.h:136
Bimage::multiply
void multiply(long j, Complex< double > cv)
Definition: Bimage.h:325
View::backward
View backward()
Definition: View.h:118
img_search_view
Bparticle * img_search_view(Bimage *p, Bimage *ptemp, Bimage *pmask, View view, double hires, double lores, double shiftlimit, double mindist, double threshold, int maxhits, int refinepeaks, fft_plan planf, fft_plan planb)
Definition: mg_subtomo.cpp:31
Bimage::sizeY
void sizeY(long ny)
Definition: Bimage.h:391
fft_destroy_plan
int fft_destroy_plan(fft_plan plan)
Deallocates a plan for fast Fourier transforms.
Definition: fft.cpp:87
Bimage::rotate
int rotate()
Rotates an image using parameters defined in the image in place.
Definition: Bimage_transform.cpp:255
VERB_RESULT
#define VERB_RESULT
Definition: utilities.h:109
Bimage
General image parameter class.
Definition: Bimage.h:177
locations_fit_sphere
Sphere locations_fit_sphere(Bparticle *part, int N, double Nstop)
Least squares fit a sphere to 3D data (particle locations)
Definition: mg_subtomo.cpp:907
Bparticle::sel
long sel
Definition: mg_processing.h:104
Bimage.h
Header file for image class.
vector3_set_PBC
Vector3< T1 > vector3_set_PBC(Vector3< T1 > coord, Vector3< T2 > box)
Definition: Vector3.h:684
Bparticle::loc
Vector3< double > loc
Definition: mg_processing.h:100
views_within_limits
View * views_within_limits(View theview, double theta_step, double phi_step, double alpha_step, double view_angle_limit, double alpha_angle_limit)
Generates a list of views within an angular distance from the input view.
Definition: View.cpp:207
Sphere
Definition: mg_subtomo.h:20
Bimage::file_name
void file_name(string s)
Definition: Bimage.h:245
M_PI
#define M_PI
Definition: utilities.h:63
utilities.h
Header file for general utilities.
tab
ostream & tab(ostream &out)
Definition: utilities.cpp:22
Breconstruction
Definition: mg_processing.h:283
fft_setup_plan
fft_plan fft_setup_plan(long x, long y, long z, fft_direction dir, int opt)
Sets up a plan for fast Fourier transforms.
Definition: fft.cpp:31
Bstring::length
long length() const
Definition: Bstring.cpp:263
Bimage::origin
void origin(double ox, double oy, double oz)
Definition: Bimage.h:570
closest_point_line_distance2
double closest_point_line_distance2(Vector3< double > p, Vector3< double > v, Vector3< double > w)
Calculates the squared distance to the closest point on a line segment from a given point.
Definition: mg_subtomo.cpp:794
Vector3::volume
double volume()
Definition: Vector3.h:237
particle_add
Bparticle * particle_add(Bparticle **part, int pid)
Adds a particle parameter structure to a linked list.
Definition: mg_processing.cpp:221
rwimg.h
Header file for 2D and 3D image I/O.
Bparticle::ori
Vector3< double > ori
Definition: mg_processing.h:101
mg_processing.h
Header file for micrograph processing.
fft_plan
fftwf_plan fft_plan
Definition: fft.h:20
verbose
int verbose
Bparticle::next
Bparticle * next
Definition: mg_processing.h:91
linked_list.h
Header file for generalized linked list functions.
VERB_FULL
#define VERB_FULL
Definition: utilities.h:113
Bimage::data_pointer
unsigned char * data_pointer()
Definition: Bimage.h:284
FILL_BACKGROUND
#define FILL_BACKGROUND
Definition: utilities.h:178
planb
fft_plan planb
Definition: bico.cpp:24
reconstruction_search_subtomo
long reconstruction_search_subtomo(Breconstruction *rec, Bimage *p, Bimage *ptemp, Bimage *pmask, Bimage *pmask2, double alpha_step, double theta_step, double phi_step, double alpha_limit, double thetaphi_limit, double hires, double lores, double shiftlimit, double mindist, double threshold, int maxhits, Vector3< long > bin, Bsymmetry *sym, int refinepeaks, Bstring ccmax_file)
Definition: mg_subtomo.cpp:141
View::matrix
Matrix3 matrix()
Definition: View.h:153
Bsymmetry::label
Bstring label
Definition: symmetry.h:41
particle_kill
int particle_kill(Bparticle *part)
Frees a list of particles.
Definition: mg_processing.cpp:528
Vector3::length
double length()
Definition: Vector3.h:222
particle_count
long particle_count(Bparticle *part)
Counts the number of particles in a linked list.
Definition: mg_select.cpp:755
mg_subtomo.h
Header file for functions finding particles (subtomograms) in a tomogram.
sphere
int sphere(Bimage *p)
Definition: radon_util.cpp:114
Bimage::maximum_included_radius
double maximum_included_radius()
Returns the radius of the enclosed sphere or circle.
Definition: Bimage.cpp:2058
scalar
double scalar(vector< T1 > &v1, vector< T2 > &v2)
Definition: Vector3.h:613
Bparticle::id
int id
Definition: mg_processing.h:93
img_refine_view
Bparticle * img_refine_view(Bimage *pcrop, Bimage *ptemp, Bimage *pmask, Bimage *pmask2, View view, double hires, double lores, double shiftlimit, double shiftlimitz, double shiftlimitxy, double mindist, int refinepeaks, fft_plan planf, fft_plan planb)
Definition: mg_subtomo.cpp:62
Vector3::length2
double length2()
Definition: Vector3.h:221
Bimage::resize
int resize(Vector3< long > nusize, Vector3< long > translate, int fill_type=0, double fill=0)
Resizes without interpolation or rescaling.
Definition: Bimage_resize.cpp:28
closest_point_disc_distance2
double closest_point_disc_distance2(Vector3< double > p, Vector3< double > q, View view, double radius)
Calculates the squared distance to the closest point on a disc from a given point.
Definition: mg_subtomo.cpp:835
Bimage::rescale_to_avg_std
int rescale_to_avg_std(double nuavg, double nustd)
Rescales the image data to a given average and standard deviation.
Definition: Bimage_rescale.cpp:163