Bsoft  2.1.0
Bernard's software package
Bimage_correlate.cpp
Go to the documentation of this file.
1 
11 #include "Bimage.h"
12 #include "rwimg.h"
13 #include "matrix_linear.h"
14 #include "math_util.h"
15 #include "qsort_functions.h"
16 #include "timer.h"
17 #include "utilities.h"
18 
19 // Declaration of global variables
20 extern int verbose; // Level of output to the screen
21 
37 {
38  if ( c > 1 || p->channels() > 1 ) {
39  cerr << "Error: Only single channel images are supported for correlation!" << endl;
40  return -1.0;
41  }
42 
43  if ( n > 1 || p->images() > 1 ) {
44  cerr << "Error: Only single images are supported for correlation!" << endl;
45  return -1.0;
46  }
47 
48  if ( !check_if_same_size(p) ) {
49  error_show("Bimage::correlate", __FILE__, __LINE__);
50  return -1;
51  }
52 
53  long i;
54  double v1, v2, cc(0), sx(0), sy(0), sx2(0), sy2(0), sxy(0);
55 
56  for ( i=0; i<datasize; i++ ) {
57  v1 = (*this)[i];
58  v2 = (*p)[i];
59  sx += v1;
60  sy += v2;
61  sx2 += v1*v1;
62  sy2 += v2*v2;
63  sxy += v1*v2;
64  }
65 
66  double varx = sx2 - sx*sx/datasize;
67  double vary = sy2 - sy*sy/datasize;
68 
69  if ( varx > 0 && vary > 0 )
70  cc = (sxy - sx*sy/datasize)/sqrt(varx*vary);
71 
72  return cc;
73 }
74 
90 double Bimage::correlate(Bimage* p, double rmin, double rmax, Bimage* pmask, int flag)
91 {
92  if ( n > 1 || p->images() > 1 ) {
93  cerr << "Error: Only single images are supported for correlation!" << endl;
94  return -1.0;
95  }
96 
97  if ( !check_if_same_size(p) ) {
98  error_show("Bimage::correlate", __FILE__, __LINE__);
99  return -1;
100  }
101 
102  if ( std <= 0 || p->std <= 0 ) return -1;
103 
104  if ( rmin > x/2 ) rmin = 0;
105  if ( rmax <= rmin ) rmax = size().max();
106 
107  if ( verbose & VERB_PROCESS ) {
108  cout << "Calculating a correlation map:" << endl;
109  cout << "Origin: " << image->origin() << endl;
110  cout << "Radii: " << rmin << " - " << rmax << endl;
111  if ( pmask )
112  cout << "Mask: " << pmask->file_name() << endl;
113  }
114 
115  int use_this;
116  long i, xx, yy, zz, ns(0);
117  double v1, v2, dx, dy, dz, d2, rmin2(rmin*rmin), rmax2(rmax*rmax);
118  double avg1(0), avg2(0), std1(0), std2(0), c12(0), denom, cc(0);
119 
120  for ( i=zz=0; zz<z; zz++ ) {
121  dz = (double)zz - image->origin()[2];
122  dz *= dz;
123  for ( yy=0; yy<y; yy++ ) {
124  dy = (double)yy - image->origin()[1];
125  dy *= dy;
126  for ( xx=0; xx<x; xx++, i++ ) {
127  dx = (double)xx - image->origin()[0];
128  dx *= dx;
129  d2 = dx + dy + dz;
130  use_this = 1;
131  if ( pmask && (*pmask)[i] < 1 ) use_this = 0;
132  if ( d2 < rmin2 || d2 > rmax2 ) use_this = 0;
133  if ( use_this ) {
134  v1 = (*this)[i];
135  v2 = (*p)[i];
136  avg1 += v1;
137  avg2 += v2;
138  std1 += v1*v1;
139  std2 += v2*v2;
140  c12 += v1*v2;
141  ns++;
142  } else if ( flag ) {
143  p->set(i, 0);
144  }
145  }
146  }
147  }
148 
149  if ( ns ) {
150  avg1 /= ns;
151  avg2 /= ns;
152  std1 = std1/ns - avg1*avg1;
153  std2 = std2/ns - avg2*avg2;
154  if ( std1 > 0 ) std1 = sqrt(std1);
155  else std1 = 0;
156  if ( std2 > 0 ) std2 = sqrt(std2);
157  else std2 = 0;
158  c12 /= ns;
159  }
160 
161  denom = std1*std2;
162  if ( denom <= 0 ) {
163 // cerr << "Error in Bimage::correlate: One or both standard deviations are zero!" << endl;
164  return 0;
165  }
166 
167  denom = 1/denom;
168 
169  cc = (c12 - avg1*avg2) * denom;
170 
171  if (flag ) {
172  for ( i=0; i<datasize; i++ ) if ( (*p)[i] )
173  p->set(i, ((*this)[i] - avg1)*((*p)[i] - avg2)*denom);
174  p->statistics();
175  }
176 
177  if ( verbose & VERB_PROCESS ) {
178  cout << "Averages: " << avg1 << " " << avg2 << endl;
179  cout << "Standard deviations: " << std1 << " " << std2 << endl;
180  cout << "Correlation: " << cc << " (" << ns << ")" << endl << endl;
181  }
182 
183  return cc;
184 }
185 
195 double Bimage::rotate_correlate(Vector3<double> axis, double angle)
196 {
197  Bimage* p = rotate(size(), axis, angle);
198 
199  double CC = correlate(p);
200 
201  delete p;
202 
203  return CC;
204 }
205 
219 {
220  if ( n > 1 || p->images() > 1 ) {
221  cerr << "Error: Only single images are supported for R factor calculation!" << endl;
222  return -1.0;
223  }
224 
225  if ( !check_if_same_size(p) ) {
226  error_show("Bimage::R_factor", __FILE__, __LINE__);
227  return -1;
228  }
229 
230  long i;
231  double R(0);
232  double sx(0), sy(0), sx2(0), sy2(0), sxy(0);
233 
234  for ( i=0; i<datasize; i++ ) {
235  sx += (*this)[i];
236  sy += (*p)[i];
237  sx2 += (*this)[i]*(*this)[i];
238  sy2 += (*p)[i]*(*p)[i];
239  sxy += (*this)[i]*(*p)[i];
240  }
241 
242  R = sqrt((sx2 - 2*sxy + sy2)/sqrt((sx2 - sx*sx/datasize)*(sy2 - sy*sy/datasize)));
243 
244  return R;
245 }
246 
247 
265 int Bimage::auto_correlate(double hires, double lores)
266 {
267  if ( hires > lores ) swap(hires, lores);
268 
269  long nn, i, xx, yy, zz;
270  long ix, iy, iz;
271  double s2, sx2, sy2, sz2, smin2(0), smax2(0), sum, scale;
273  Vector3<double> realsize(real_size());
274 
275  if ( lores > 0 ) smin2 = 1/(lores*lores);
276 
277  if ( hires > 0 ) {
278  smax2 = 1/(hires*hires);
279  } else {
280  if ( x > 1 ) smax2 += 1.0/(4.0*u[0]*u[0]);
281  if ( y > 1 ) smax2 += 1.0/(4.0*u[1]*u[1]);
282  if ( z > 1 ) smax2 += 1.0/(4.0*u[2]*u[2]);
283  hires = 1/sqrt(smax2);
284  }
285 
286  if ( verbose & VERB_FULL ) {
287  cout << "Auto-correlation:" << endl;
288  if ( lores > 0 )
289  cout << "Resolution range: " << hires << " - " << lores << " A" << endl;
290  else
291  cout << "No resolution limits" << endl;
292  cout << endl;
293  }
294 
295  fft();
296 
297  Complex<double> cv;
298 // set(0, cv);
299 
300  for ( i=nn=0; nn<n; nn++ ) {
301  sum = 0;
302  for ( zz=0; zz<z; zz++ ) {
303  iz = zz;
304  if ( zz > (z - 1)/2 ) iz -= z;
305  sz2 = iz/realsize[2];
306  sz2 *= sz2;
307  for ( yy=0; yy<y; yy++ ) {
308  iy = yy;
309  if ( yy > (y - 1)/2 ) iy -= y;
310  sy2 = iy/realsize[1];
311  sy2 *= sy2;
312  for ( xx=0; xx<x; xx++, i++ ) {
313  ix = xx;
314  if ( xx > (x - 1)/2 ) ix -= x;
315  sx2 = ix/realsize[0];
316  sx2 *= sx2;
317  s2 = sx2 + sy2 + sz2;
318  if ( s2 >= smin2 && s2 <= smax2 ) {
319  cv = (complex(i)).power();
320  sum += cv.real();
321  } else {
322  cv = 0;
323  }
324  set(i, cv);
325  }
326  }
327  }
328  if ( sum ) {
329  scale = sqrt(x*y*z)/sum;
330 // cout << "scale=" << scale << endl;
331  multiply(nn, scale);
332  }
333  image[nn].origin(0.0,0.0,0.0);
334  }
335 
336 // cout << "backtransforming" << endl;
337 
338  fft_back();
339 
340  return 0;
341 }
342 
363 Bimage* Bimage::cross_correlate(Bimage* p, double hires, double lores,
365 {
366  if ( lores > 0 && hires > lores ) swap(hires, lores);
367 
368  Bimage* pc = pack_two_in_complex(p);
369  if ( !pc ) return NULL;
370 
371  if ( verbose & VERB_FULL ) {
372  cout << "Cross-correlation:" << endl;
373  if ( lores > 0 || hires > 0 ) {
374  cout << "Resolution range: " << hires << " - ";
375  if ( lores > 0 ) cout << lores << " A" << endl;
376  else cout << "inf A" << endl;
377  } else
378  cout << "No resolution limits" << endl;
379  cout << endl;
380  }
381 
382  pc->fft(planf, 0);
383 
384 // pc->set(0, Complex<double>(0,0));
385 
386  pc->combined_complex_product_implicit_mask(hires, lores);
387 
388  pc->fft(planb, 0);
389 
390  pc->complex_to_real();
391 
392  long nn;
393  for ( nn=0; nn<pc->images(); nn++ )
394  pc->image[nn].origin(p->image[nn].origin() - image[nn].origin());
395 
396  return pc;
397 }
398 
417 Bimage* Bimage::cross_correlate(Bimage* p, double hires, double lores, Bimage* pmask)
418 {
419  if ( lores > 0 && hires > lores ) swap(hires, lores);
420 
421  Bimage* pc = pack_two_in_complex(p);
422  if ( !pc ) return NULL;
423 
424  if ( verbose & VERB_FULL ) {
425  cout << "Cross-correlation:" << endl;
426  if ( lores > 0 || hires > 0 ) {
427  cout << "Resolution range: " << hires << " - ";
428  if ( lores > 0 ) cout << lores << " A" << endl;
429  else cout << "inf A" << endl;
430  } else
431  cout << "No resolution limits" << endl;
432  if ( pmask )
433  cout << "With a mask: " << pmask->file_name() << endl;
434  cout << endl;
435  }
436 
437  pc->fft(FFTW_FORWARD, 0);
438 
439 // pc->set(0, Complex<double>(0,0));
440 
441  pc->combined_complex_product(hires, lores, pmask);
442 
443  pc->fft(FFTW_BACKWARD, 0);
444 
445  pc->complex_to_real();
446 
447  long nn;
448  for ( nn=0; nn<pc->images(); nn++ )
449  pc->image[nn].origin(p->image[nn].origin() - image[nn].origin());
450 
451 // write_img("pcc.mrc", pc, 0);
452 
453  return pc;
454 }
455 
467 {
468  long i;
469  Vector3<long> k;
470  double phi, cc(0);
471  Complex<double> cv;
472 
473  shift = shift*TWOPI;
474  shift /= size();
475 
476  for ( i=k[2]=0; k[2]<z; ++k[2] ) {
477  for ( k[1]=0; k[1]<y; ++k[1] ) {
478  for ( k[0]=0; k[0]<x; ++k[0], ++i ) {
479  phi = (shift * k).sum();
480  cv = complex(i);
481  cc += cv.real()*cos(phi) - cv.imag()*sin(phi);
482 // cout << k << tab << phi << endl;
483  }
484  }
485  }
486 
487  return cc;
488 }
489 
502 {
503  long i, nn(0);
504  double ds(1), cc(0), ccmax(0);
505  Vector3<double> sh, bestshift;
506  Vector3<long> smn, smx(shift_limit,shift_limit,shift_limit);
507  smx = smx.min(size()/2);
508  smn = -smx;
509  Vector3<long> size = smx - smn + 1;
510  cout << size << tab << smn << tab << smx << endl;
511 
512  Bimage* pc = new Bimage(Double, TSimple, size, 1);
513 
514  for ( i=0, sh[2]=smn[2]; sh[2]<=smx[2]; sh[2]+=ds ) {
515  for ( sh[1]=smn[1]; sh[1]<=smx[1]; sh[1]+=ds ) {
516  for ( sh[0]=smn[0]; sh[0]<=smx[0]; sh[0]+=ds, ++i ) {
517  cc = correlation_coefficient(sh);
518  if ( ccmax < cc ) {
519  ccmax = cc;
520  bestshift = sh;
521  cout << setprecision(4) << ds << tab << sh << tab << cc << endl;
522  }
523  pc->set(i, cc);
524  }
525  }
526  }
527 
528  pc->origin(bestshift+size/2);
529  bestshift += pc->fit_peak();
530 
531  image[nn].origin(bestshift);
532  image[nn].FOM(ccmax);
533 
534 // write_img("cck.mrc", pc, 0);
535 
536  delete pc;
537 
538  return bestshift;
539 }
540 
559 Bimage* Bimage::cross_correlate_fspace(Bimage* p, double hires, double lores, double shift_limit)
560 {
561  if ( lores > 0 && hires > lores ) swap(hires, lores);
562 
563  Bimage* pc = pack_two_in_complex(p);
564  if ( !pc ) return NULL;
565 
566  if ( verbose & VERB_FULL ) {
567  cout << "Cross-correlation:" << endl;
568  if ( lores > 0 || hires > 0 ) {
569  cout << "Resolution range: " << hires << " - ";
570  if ( lores > 0 ) cout << lores << " A" << endl;
571  else cout << "inf A" << endl;
572  } else
573  cout << "No resolution limits" << endl;
574 // if ( pmask )
575 // cout << "With a mask: " << pmask->file_name() << endl;
576  cout << endl;
577  }
578 
579  pc->fft(FFTW_FORWARD, 0);
580 
581 // pc->set(0, Complex<double>(0,0));
582 
583  pc->combined_complex_product(hires, lores, NULL);
584 
585  Vector3<double> shift = pc->find_shift_in_transform(shift_limit);
586 
587  long nn;
588  for ( nn=0; nn<pc->images(); nn++ )
589  pc->image[nn].origin(shift);
590 
591 // write_img("pcc.mrc", pc, 0);
592 
593  return pc;
594 }
595 
596 
597 Bimage* Bimage::cross_correlate(Bimage* p, double hires, double lores,
599 {
600  if ( lores > 0 && hires > lores ) swap(hires, lores);
601 
602  Bimage* pc = pack_two_in_complex(p);
603  if ( !pc ) return NULL;
604 
605  if ( verbose & VERB_FULL ) {
606  cout << "Cross-correlation:" << endl;
607  if ( lores > 0 || hires > 0 ) {
608  cout << "Resolution range: " << hires << " - ";
609  if ( lores > 0 ) cout << lores << " A" << endl;
610  else cout << "inf A" << endl;
611  } else
612  cout << "No resolution limits" << endl;
613  if ( pmask )
614  cout << "With a mask: " << pmask->file_name() << endl;
615  cout << endl;
616  }
617 
618  pc->fft(planf, 0);
619 
620 // pc->set(0, Complex<double>(0,0));
621 
622  pc->combined_complex_product(hires, lores, pmask);
623 
624  pc->fft(planb, 0);
625 
626  pc->complex_to_real();
627 
628  if ( pc->image->maximum() > 1 ) {
629  cerr << "Error in cross_correlate: maximum > 1: " << image->maximum() << endl;
630  bexit(-1);
631  }
632 
633  long nn;
634  for ( nn=0; nn<pc->images(); nn++ )
635  pc->image[nn].origin(p->image[nn].origin() - image[nn].origin());
636 
638 
639  return pc;
640 }
641 
668  double lores, fft_plan planf, fft_plan planb)
669 {
670  if ( hires > lores ) swap(hires, lores);
671 
672  Bimage* pc = pack_two_in_complex(p);
673  if ( !pc ) return NULL;
674 
675  check_resolution(hires);
676 
677  if ( verbose & VERB_FULL ) {
678  cout << "Two-way cross-correlation:" << endl;
679  cout << "Resolution range: " << hires << " - " << lores << " A" << endl;
680  cout << endl;
681  }
682 
683  pc->fft(planf, 0);
684 
685  Complex<double> cv;
686  pc->set(0, cv);
687 
688  pc->complex_bandpass(hires, lores);
689 
690  Bimage* pc2 = pc->unpack_combined_transform();
691 
692  pc->complex_normalize();
693  pc2->complex_normalize();
694 
695  Bimage* pc1 = pc->copy();
696 
697  pc->complex_conjugate_product(pc2);
698  pc1->complex_product(pc2);
699 
700 // write_img("pc.map", pc, 0);
701 // bexit(0);
702 
703  delete pc2;
704 
705  pc->fft(planb, 0);
706  pc1->fft(planb, 0);
707 
708  pc->complex_to_real();
709  pc1->complex_to_real();
710 
711 // cout << pc->maximum() << tab << pc1->maximum() << endl;
712 
713  if ( pc1->maximum() > pc->maximum() ) {
714  delete pc;
715  pc = pc1;
716  pc->image->view_angle(M_PI);
717  } else {
718  delete pc1;
719  pc->image->view_angle(0);
720  }
721 
723 
724  long nn;
725  for ( nn=0; nn<pc->images(); nn++ )
726  pc->image[nn].origin(p->image[nn].origin() - image[nn].origin());
727 
728  return pc;
729 }
730 
749 {
750  Bimage* pc = pack_two_in_complex(p);
751  if ( !pc ) return NULL;
752 
753  if ( verbose & VERB_FULL ) {
754  cout << "Cross-correlation with validation:" << endl;
755  if ( pmask )
756  cout << "With a mask: " << pmask->file_name() << endl;
757  cout << endl;
758  }
759 
760  pc->fft(FFTW_FORWARD, 0);
761 
762  Complex<double> cv;
763  pc->set(0, cv);
764 
765  long nn;
766  for ( nn=0; nn<pc->images(); nn++ )
767  pc->image[nn].origin(p->image[nn].origin() - image[nn].origin());
768 
769  if ( pmask ) pc->complex_apply_dual_mask(pmask);
770 
773 
774  pc->fft(FFTW_BACKWARD, 0);
775  pc->next->fft(FFTW_BACKWARD, 0);
776 
777  pc->complex_to_real();
778  pc->next->complex_to_real();
779 
780  return pc;
781 }
782 
783 /*
784 @brief Searches a 2D/3D density map for a template using a specific view.
785 @param *p the image.
786 @param *pref the template to be searched for.
787 @param view view.
788 @param hires high resolution limit.
789 @param lores low resolution limit.
790 @param search_radius radius for shift search.
791 @param *pmask mask for cross-correlation (ignored if NULL).
792 @param &cc the best correlation coefficient
793 @param planf FFT forward plan.
794 @param planb FFT backward plan.
795 @return Vector3<double> best shift to impose on the image.
796 
797  The template is rotated to the view and cross-correlated to find
798  a set of high-scoring fits.
799  The views must be calculated externally to allow for custom sets.
800 **/
802  double hires, double lores, double search_radius, Bimage* pmask,
803  double& cc, fft_plan planf, fft_plan planb)
804 {
805  Vector3<double> shift(-1e37,-1e37,-1e37);
806 
807  if ( !check_if_same_size(pref) ) {
808  error_show("Bimage::rotate_cross_correlate", __FILE__, __LINE__);
809  return shift;
810  }
811 
812  Matrix3 mat = view.matrix();
813  mat = mat.transpose();
814 
815  Bimage* prot = pref->rotate(pref->size(), mat);
816 
817  Bimage* pcc = cross_correlate(prot, hires, lores, pmask, planf, planb);
818 
819  pcc->find_peak(search_radius, 0);
820 
821  if ( verbose & VERB_DEBUG ) {
822  cout << "DEBUG Bimage::rotate_cross_correlate: found origin = " << pcc->image->origin() << endl;
823  cout << "DEBUG Bimage::rotate_cross_correlate: cc = " << pcc->image->FOM() << endl;
824  }
825 
826  pcc->refine_peak();
827 
828 // if ( verbose & VERB_DEBUG )
829 // cout << "DEBUG Bimage::rotate_cross_correlate: refined origin = " << pcc->image->origin() << endl;
830 
831  shift = -pcc->image->origin();
832  cc = pcc->image->FOM();
833 
834  delete prot;
835  delete pcc;
836 
837  return shift;
838 }
839 
840 /*
841 @brief Rotates a 2D reference image and cross-correlates with an image.
842 @param *pref reference 2D image.
843 @param angle rotation angle.
844 @param res_hi high resolution limit.
845 @param res_lo low resolution limit.
846 @param shift_limit maximum shift from nominal origin of box.
847 @param planf FFT forward plan.
848 @param planb FFT backward plan.
849 @return double correlation coefficient.
850 
851  The reference image is first rotated by the given angle.
852  Two cross-correlations are done to account for a 180° ambiguity in
853  the angle when it is derived from a polar power spectrum.
854  The shift is then determined from the best cross-correlation map.
855  The image origin is written into the image structure.
856  The correlation coefficient return is the cross-correlation peak.
857  The input images must be equal-sized square 2D images.
858 **/
860  double angle, double res_hi, double res_lo, double shift_limit,
862 {
863 // cout << pref->image->origin() << endl;
864 
865  Bimage* prot = pref->rotate(pref->size(), fabs(angle));
866 
867  Bimage* pcc = cross_correlate_two_way(prot, res_hi, res_lo, planf, planb);
868 
869  delete prot;
870 
871  pcc->origin(0.0, 0.0, 0.0);
872 
873  pcc->find_peak(shift_limit, 0);
874 
875  pcc->refine_peak();
876 
877  if ( angle > 0 ) image->view_angle(angle + pcc->image->view_angle());
878  else image->view_angle(angle - pcc->image->view_angle());
879 
880 // cout << pcc->image->origin() << tab << pcc->image->FOM() << endl;
881 
882  if ( fabs(pcc->image->view_angle()) > M_PI_2 ) {
883 // image->origin(pref->image->origin() - pcc->image->origin());
884  origin(pref->image->origin() - pcc->image->origin());
885  } else {
886 // image->origin(pref->image->origin() + pcc->image->origin());
887  origin(pref->image->origin() + pcc->image->origin());
888  }
889 
890  image->FOM(pcc->image->FOM());
891 
892  delete pcc;
893 
894  if ( verbose & VERB_DEBUG ) {
895  cout << "DEBUG Bimage::rotate_cross_correlate_two_way: fom=" << image->FOM() << endl;
896  cout << "DEBUG Bimage::rotate_cross_correlate_two_way: ori=" << image->origin() << endl;
897  }
898 
899  return image->FOM();
900 }
901 
902 
929 int Bimage::find_shift(Bimage* pref, Bimage* pmask, double hires,
930  double lores, double radius, double sigma, int refine_flag)
931 {
932  if ( verbose & VERB_FULL ) {
933  if ( refine_flag )
934  cout << "Finding shift by cross-correlation and polynomial fitting" << endl << endl;
935  else
936  cout << "Finding shift by cross-correlation" << endl << endl;
937  }
938 
939  Bimage* pc = cross_correlate(pref, hires, lores, pmask);
940  if ( !pc ) return -1;
941 
942  if ( verbose & VERB_DEBUG )
943  write_img("cc.map", pc, 0);
944 
945  long nn;
946  pc->find_peak(radius, sigma);
947 
948  if ( refine_flag ) pc->refine_peak();
949 
950  for ( nn=0; nn<pc->images(); nn++ ) {
951  image[nn].origin(pref->image[nn].origin() + pc->image[nn].origin());
952  image[nn].FOM(pc->image[nn].FOM());
953  }
954 
955  if ( verbose & VERB_FULL ) {
956  cout << "Image\t ox\t oy\t oz\t CC" << endl;
957  for ( nn=0; nn<n; nn++ )
958  cout << nn+1 << tab << image[nn].origin()
959  << tab << image[nn].FOM() << endl;
960  cout << endl;
961  }
962 
963  delete pc;
964 
965  return 0;
966 }
967 
968 Vector3<double> Bimage::find_shift(Bimage* pref, Bimage* pmask, double hires,
969  double lores, double radius, double sigma, int refine_flag, double& cc)
970 {
971  if ( verbose & VERB_FULL ) {
972  if ( refine_flag )
973  cout << "Finding shift by cross-correlation and polynomial fitting" << endl << endl;
974  else
975  cout << "Finding shift by cross-correlation" << endl << endl;
976  }
977 
979 
980  Bimage* pc = cross_correlate(pref, hires, lores, pmask);
981  if ( !pc ) return shift;
982 
983  if ( verbose & VERB_DEBUG )
984  write_img("cc.map", pc, 0);
985 
986  pc->find_peak(radius, sigma);
987 
988  if ( refine_flag ) pc->refine_peak();
989 
990  shift = pc->image->origin();
991 
992  cc = pc->image->FOM();
993 
994  delete pc;
995 
996  return shift;
997 }
998 
1029  double lores, double radius, double sigma, int refine_flag,
1031 {
1032  if ( verbose & VERB_FULL ) {
1033  if ( refine_flag )
1034  cout << "Finding shift by cross-correlation and polynomial fitting" << endl << endl;
1035  else
1036  cout << "Finding shift by cross-correlation" << endl << endl;
1037  }
1038 
1040 
1041  Bimage* pc = cross_correlate(pref, hires, lores, planf, planb);
1042  if ( !pc ) return shift;
1043 
1044  if ( verbose & VERB_DEBUG )
1045  write_img("cc.map", pc, 0);
1046 
1047  pc->find_peak(radius, sigma);
1048 
1049  if ( refine_flag ) pc->refine_peak();
1050 
1051  shift = pc->image->origin();
1052 
1053  image->FOM(pc->image->FOM());
1054 
1055  delete pc;
1056 
1057  return shift;
1058 }
1059 
1091 Vector3<double> Bimage::find_shift(Bimage* pref, Bimage* pmask, double hires,
1092  double lores, double radius, double sigma, int refine_flag,
1093  fft_plan planf, fft_plan planb, double& cc)
1094 {
1095  if ( verbose & VERB_FULL ) {
1096  if ( refine_flag )
1097  cout << "Finding shift by cross-correlation and polynomial fitting" << endl << endl;
1098  else
1099  cout << "Finding shift by cross-correlation" << endl << endl;
1100  }
1101 
1103 
1104  Bimage* pc = cross_correlate(pref, hires, lores, pmask, planf, planb);
1105  if ( !pc ) return shift;
1106 
1107  if ( verbose & VERB_DEBUG )
1108  write_img("cc.map", pc, 0);
1109 
1110  pc->find_peak(radius, sigma);
1111 
1112  if ( refine_flag ) pc->refine_peak();
1113 
1114  shift = pc->image->origin();
1115 
1116  cc = pc->image->FOM();
1117 
1118  if ( cc > 1 ) {
1119  cerr << "Error in find_shift: cc > 1: " << cc << endl;
1120  bexit(-1);
1121  }
1122 
1123  delete pc;
1124 
1125  return shift;
1126 }
1127 
1145  double hi_res, double lo_res, double shift_limit,
1147 {
1148  double cc(0);
1149  Bimage* p1 = extract(nn);
1150 
1151  Vector3<double> shift = p1->find_shift(pref, pmask, hi_res, lo_res, shift_limit, 0, 1, planf, planb, cc);
1152 
1153  delete p1;
1154 
1155  image[nn].origin(pref->image->origin()+shift);
1156 
1157  image[nn].FOM(cc);
1158 
1159  return shift;
1160 }
1161 
1178  double hires, double lores, int bin, fft_plan planf, fft_plan planb)
1179 {
1180  Bimage* pc = bin_copy(bin);
1181 
1182  Bimage* pt = ptemp->bin_copy(bin);
1183  pt->pad(pc->size(), FILL_USER, 0);
1184 
1185  Bimage* pm = NULL;
1186  if ( pmask ) pm = pmask->pad_copy(pc->size(), FILL_USER, 0);
1187 
1189 
1190  if ( verbose & VERB_PROCESS ) {
1191 // cout << "Number of templates: " << pt->images() << endl;
1192  cout << "Template origin: " << pt->image->origin() << endl;
1193  cout << "Template avg & std: " << pt->average() <<
1194  tab << pt->standard_deviation() << endl;
1195  }
1196 
1197  Bimage* pcc = pc->cross_correlate(pt, hires, lores, pm, planf, planb);
1198 
1199  delete pc;
1200  delete pt;
1201  delete pm;
1202 
1203  pcc->shift_wrap(shift);
1204 
1205  pcc->statistics();
1206 
1207  return pcc;
1208 }
1209 
1235 int Bimage::find_center(Bimage* pmask, double hires,
1236  double lores, double radius, double sigma, int refine_flag)
1237 {
1238  if ( verbose & VERB_FULL ) {
1239  if ( refine_flag )
1240  cout << "Finding center by cross-correlation and polynomial fitting" << endl << endl;
1241  else
1242  cout << "Finding center by cross-correlation" << endl << endl;
1243  }
1244 
1245  Bimage* pc = copy();
1246 
1247  pc->fft(FFTW_FORWARD, 0);
1248 
1249  Complex<double> cv;
1250  pc->set(0, cv);
1251  if ( pmask ) pc->complex_apply_mask(pmask);
1252 
1253  if ( hires > sampling(0)[0] ) pc->complex_bandpass(hires, lores);
1254 
1255  pc->complex_normalize();
1256 
1257  pc->complex_product(pc);
1258 
1259  pc->fft(FFTW_BACKWARD, 0);
1260 
1261  pc->complex_to_real();
1262 
1263  if ( verbose & VERB_DEBUG )
1264  write_img("cc.map", pc, 0);
1265 
1266  long nn;
1267 
1268  pc->origin(0.0,0.0,0.0);
1269  pc->find_peak(radius, sigma);
1270 
1271  if ( refine_flag ) pc->refine_peak();
1272 
1273  for ( nn=0; nn<n; nn++ ) {
1274  image[nn].origin(pc->image[nn].origin()/2 + size()/2);
1275  image[nn].FOM(pc->image[nn].FOM());
1276  }
1277 
1278  delete pc;
1279 
1280  if ( verbose & VERB_FULL ) {
1281  cout << "Image\t ox\t oy\t oz\t CC" << endl;
1282  for ( nn=0; nn<n; nn++ )
1283  cout << nn+1 << tab << image[nn].origin()
1284  << tab << image[nn].FOM() << endl;
1285  cout << endl;
1286  }
1287 
1288  return 0;
1289 }
1290 
1309  double hires, double lores, double radius, double sigma,
1310  int refine_flag, fft_plan planf, fft_plan planb, double& cc)
1311 {
1312  if ( radius <= 0 ) radius = x/4;
1313 
1314  Bimage* p = rotate(size(), mat);
1315 
1316  Vector3<double> shift = find_shift(p, NULL, hires, lores, radius, sigma, 1, planf, planb, cc);
1317 
1319  mat = Matrix3(1) - mat;
1320  mat = mat.singular_value_decomposition();
1321  origin = mat * shift + image->origin();
1322 
1323  delete p;
1324 
1325  return origin;
1326 }
1327 
1340 int Bimage::find_peak(double radius, double sigma)
1341 {
1342  if ( !d.uc ) return -1;
1343 
1344 // information();
1345 // write_img("cc.map", p, 0);
1346 // bexit(0);
1347 
1348  if ( radius < 0 ) radius = 1e30;
1349  else if ( radius < 1 ) radius = 0.9;
1350 // if ( sigma < 1e-30 ) sigma = 2e-30;
1351 
1352  if ( verbose & VERB_DEBUG )
1353  cout << "DEBUG Bimage::find_peak: radius=" << radius << endl;
1354 
1355  long i, nn, xx, yy, zz;
1356  long xh(x/2), yh(y/2), zh(z/2);
1357  double x2, y2, z2, r;
1358  double value, maxval, fac(GOLDEN/sigma);
1359  Vector3<double> ori, peak;
1360 
1361  if ( verbose & VERB_FULL ) {
1362  cout << "Finding the brightest voxel:" << endl;
1363  cout << "Radius & sigma: " << radius << " " << sigma << endl;
1364  cout << "Origin: " << image->origin() << endl;
1365  cout << "n\tx\ty\tz\tv" << endl;
1366  }
1367 
1368  for ( i=nn=0; nn<n; nn++ ) {
1369  ori = image[nn].origin();
1370  if ( x <= 1 ) ori[0] = 0;
1371  if ( y <= 1 ) ori[1] = 0;
1372  if ( z <= 1 ) ori[2] = 0;
1373  if ( verbose & VERB_DEBUG )
1374  cout << "DEBUG Bimage::find_peak: ori=" << ori << endl;
1375  maxval = -1e37;
1376  peak = ori;
1377  for ( zz=0; zz<z; zz++ ) {
1378  z2 = ori[2] - zz;
1379  if ( z2 < -zh ) z2 += z;
1380  if ( z2 > zh ) z2 -= z;
1381  z2 *= z2;
1382  for ( yy=0; yy<y; yy++ ) {
1383  y2 = ori[1] - yy;
1384  if ( y2 < -yh ) y2 += y;
1385  if ( y2 > yh ) y2 -= y;
1386  y2 *= y2;
1387  for ( xx=0; xx<x; xx++, i++ ) {
1388  x2 = ori[0] - xx;
1389  if ( x2 < -xh ) x2 += x;
1390  if ( x2 > xh ) x2 -= x;
1391  x2 *= x2;
1392  r = sqrt(x2 + y2 + z2) - radius;
1393  value = (*this)[i];
1394  if ( sigma > 1e-30 ) value *= 1/(1 + exp(fac*r));
1395  if ( r <= 0 && maxval < value ) {
1396  maxval = value;
1397  peak = Vector3<double>(double(xx), double(yy), double(zz));
1398  }
1399 // if ( r < 0 )
1400 // cout << xx << tab << yy << tab << zz << tab << r << tab << value << tab << maxval << endl;
1401  }
1402  }
1403  }
1404  image[nn].FOM(maxval);
1405  image[nn].origin(peak);
1406  if ( verbose & VERB_DEBUG ) {
1407  cout << "DEBUG Bimage::find_peak: peak=" << peak << endl;
1408  cout << "DEBUG Bimage::find_peak: maxval=" << maxval << endl;
1409  }
1410  if ( maxval > 1 ) {
1411  cerr << "Error in find_peak: maxval > 1: " << maxval << endl;
1412  bexit(-1);
1413  }
1414  if ( verbose & VERB_FULL )
1415  cout << nn+1 << tab << image[nn].origin() << tab << image[nn].FOM() << endl;
1416  }
1417  if ( verbose & VERB_FULL ) cout << endl;
1418 
1419  return 0;
1420 }
1421 
1432 {
1433 // cout << "origin = " << image->origin() << endl;
1434 
1435 // write_img("cck.mrc", this, 0);
1436 
1437  long i, j, k, nterm(9);
1438  long xx, yy, zz;
1439  double vm(get(0, image->origin()));
1440  Matrix a(nterm,nterm);
1441 
1442  vector<double> b(nterm);
1443  vector<double> vec(nterm);
1444 
1445  for ( i=0; i<image_size(); ++i ) add(i, -vm);
1446 
1447  for ( j=0; j<nterm; ++j ) { // Clear the matrix and vector
1448  for ( k=0; k<nterm; ++k ) a[j][k] = 0;
1449  b[j] = 0;
1450  }
1451 
1452  for ( i=zz=0; zz<z; ++zz ) {
1453  vec[2] = zz - image->origin()[2];
1454  vec[8] = vec[2]*vec[2];
1455  for ( yy=0; yy<y; ++yy ) {
1456  vec[1] = yy - image->origin()[1];
1457  vec[5] = vec[1]*vec[2];
1458  vec[7] = vec[1]*vec[1];
1459  for ( xx=0; xx<x; ++xx, ++i ) {
1460  vec[0] = xx - image->origin()[0];
1461  vec[3] = vec[0]*vec[1];
1462  vec[4] = vec[0]*vec[2];
1463  vec[6] = vec[0]*vec[0];
1464  for ( j=0; j<nterm; ++j ) b[j] += vec[j]*(*this)[i];
1465  for ( j=0; j<nterm; ++j )
1466  for ( k=0; k<=j; ++k ) a[j][k] += vec[j]*vec[k];
1467  }
1468  }
1469  }
1470 
1471  for ( j=0; j<nterm; ++j )
1472  for ( k=j+1; k<nterm; ++k ) a[j][k] = a[k][j];
1473  for ( j=0; j<nterm; ++j )
1474  if ( fabs(a[j][j]) < 1e-37 ) a[j][j] = 1;
1475 
1476  if ( verbose & VERB_DEBUG ) {
1477  cout << "DEBUG Bimage::fit_peak: Input matrix:" << endl;
1478  cout << a;
1479  cout << "DEBUG Bimage::fit_peak: Input vector:";
1480  for ( j=0; j<nterm; ++j ) cout << tab << b[j];
1481  cout << endl;
1482  }
1483 
1484 // a.LU_decomposition(b);
1486 
1487  if ( verbose & VERB_DEBUG ) {
1488  cout << "DEBUG Bimage::fit_peak: Ouput matrix:" << endl;
1489  cout << a;
1490  cout << "DEBUG Bimage::fit_peak: Coefficients: ";
1491  for ( j=0; j<nterm; ++j ) cout << tab << b[j];
1492  cout << endl;
1493  }
1494 
1495  Matrix c(3,3);
1496  vector<double> d(3);
1497  for ( j=0; j<3; ++j ) d[j] = -b[j];
1498  c[0][0] = 2*b[6];
1499  c[0][1] = c[1][0] = b[3];
1500  c[0][2] = c[2][0] = b[4];
1501  c[1][1] = 2*b[7];
1502  c[1][2] = c[2][1] = b[5];
1503  c[2][2] = 2*b[8];
1504 
1505  c.LU_decomposition(d);
1506 /*
1507  vector<double> ev = c.jacobi_rotation();
1508  c.eigen_sort(ev);
1509  cout << c << endl;
1510  for ( auto it = ev.begin(); it != ev.end(); ++it ) cout << tab << *it;
1511  cout << endl;
1512 */
1513  Vector3<double> peak;
1514 
1515  double cc = vm + b[0]*d[0] + b[1]*d[1] + b[2]*d[2]
1516  + b[3]*d[0]*d[1] + b[4]*d[0]*d[2] + b[5]*d[1]*d[2]
1517  + b[6]*d[0]*d[0] + b[7]*d[1]*d[1] + b[8]*d[2]*d[2];
1518 
1519  if ( cc > 1 )
1520  cc = vm;
1521  else
1522  peak = Vector3<double>(d[0], d[1], d[2]);
1523 
1524  if ( verbose & VERB_DEBUG ) {
1525  cout << "DEBUG Bimage::fit_peak: Shift: ";
1526  for ( j=0; j<3; ++j ) cout << tab << d[j];
1527  cout << tab << cc << endl;
1528  }
1529 
1530  image->FOM(cc);
1531  if ( cc > 1 ) {
1532  cerr << "Error in fit_peak: cc = " << cc << endl;
1533  cerr << "peak = " << peak << endl;
1534  write_img("pf.mrc", this, 0);
1535  bexit(-1);
1536  }
1537 
1538 /*
1539  double R(0);
1540  Bimage* pt = copy();
1541  for ( i=zz=0; zz<z; ++zz ) {
1542  d[3] = zz - image->origin()[2];
1543  for ( yy=0; yy<y; ++yy ) {
1544  d[2] = yy - image->origin()[1];
1545  for ( xx=0; xx<x; ++xx, ++i ) {
1546  d[1] = xx - image->origin()[0];
1547  cc = vm + b[0]*d[0] + b[1]*d[1] + b[2]*d[2]
1548  + b[3]*d[0]*d[1] + b[4]*d[0]*d[2] + b[5]*d[1]*d[2]
1549  + b[6]*d[0]*d[0] + b[7]*d[1]*d[1] + b[8]*d[2]*d[2];
1550  pt->set(i, cc);
1551  cc -= (*this)[i];
1552  R += cc*cc;
1553  }
1554  }
1555  }
1556  write_img("cckc.mrc", pt, 0);
1557  delete pt;
1558  R /= size().volume();
1559  cout << "R2 = " << R << endl;
1560 */
1561 
1562  return peak;
1563 }
1564 
1575 {
1576  if ( !d.uc ) return -1;
1577 
1578  change_type(Float);
1579 
1580  long nn, kernel_size(2);
1581  Vector3<long> ksize(2*kernel_size+1,2*kernel_size+1,2*kernel_size+1);
1583  Matrix3 mat(1);
1584 
1585  if ( verbose & VERB_FULL ) {
1586  cout << "Finding the shift in each image" << endl;
1587  cout << "n\tx\ty\tz" << endl;
1588  }
1589 
1590  for ( nn=0; nn<n; nn++ ) {
1591 // cout << "refine_peak: origin = " << image[nn].origin() << endl;
1592  Bimage* pc = extract_wrap(nn, image[nn].origin(), ksize, ksize/2, mat);
1593  shift = image[nn].origin() + pc->fit_peak();
1595  image[nn].origin(shift);
1596  image[nn].FOM(pc->image->FOM());
1597  delete pc;
1598  if ( verbose & VERB_FULL )
1599  cout << nn+1 << tab << shift << endl;
1600  }
1601  if ( verbose & VERB_FULL ) cout << endl;
1602 
1603  return 0;
1604 }
1605 
1616 {
1617  if ( !d.uc ) return -1;
1618 
1619  change_type(Float);
1620 
1621  long i, j, nn, kernel_size(5), nterm(7);
1622  long xx, yy, zz, xlo, xhi, ylo, yhi, zlo, zhi, ix, iy, iz;
1623  Vector3<long> int_shift;
1625  Matrix a(nterm,nterm);
1626  vector<double> b(nterm);
1627  vector<double> vec(nterm);
1628 
1629  if ( verbose & VERB_FULL ) {
1630  cout << "Finding the shift in each image" << endl;
1631  cout << "n\tx\ty\tz\tv" << endl;
1632  }
1633 
1634  for ( nn=0; nn<n; nn++ ) {
1635  shift = image[nn].origin();
1636  int_shift[0] = (long) shift[0];
1637  int_shift[1] = (long) shift[1];
1638  int_shift[2] = (long) shift[2];
1639  xlo = (long) (shift[0] - kernel_size);
1640  xhi = (long) (shift[0] + kernel_size);
1641  if ( xhi - xlo >= x ) {
1642  xlo = 0;
1643  xhi = x - 1;
1644  }
1645  ylo = (long) (shift[1] - kernel_size);
1646  yhi = (long) (shift[1] + kernel_size);
1647  if ( yhi - ylo >= y ) {
1648  ylo = 0;
1649  yhi = y - 1;
1650  }
1651  zlo = (long) (shift[2] - kernel_size);
1652  zhi = (long) (shift[2] + kernel_size);
1653  if ( zhi - zlo >= z ) {
1654  zlo = 0;
1655  zhi = z - 1;
1656  }
1657  if ( verbose & VERB_DEBUG )
1658  cout << "DEBUG Bimage::refine_peak: kernel limits = " <<
1659  xlo << tab << xhi << tab << ylo << tab << yhi << tab << zlo << tab << zhi << endl;
1660  for ( i=0; i<nterm; i++ ) { // Clear the matrix and vector
1661  for ( j=0; j<nterm; j++ ) a[i][j] = 0;
1662  b[i] = 0;
1663  }
1664  vec[0] = 1;
1665  for ( zz=zlo; zz<=zhi; zz++ ) {
1666  iz = zz;
1667  if ( iz < 0 ) iz += z;
1668  if ( iz >= (long)z ) iz -= z;
1669  vec[3] = zz;
1670  vec[6] = zz*zz;
1671  for ( yy=ylo; yy<=yhi; yy++ ) {
1672  iy = yy;
1673  if ( iy < 0 ) iy += y;
1674  if ( iy >= (long)y ) iy -= y;
1675  vec[2] = yy;
1676  vec[5] = yy*yy;
1677  for ( xx=xlo; xx<=xhi; xx++ ) {
1678  ix = xx;
1679  if ( ix < 0 ) ix += x;
1680  if ( ix >= (long)x ) ix -= x;
1681  i = index(0,ix,iy,iz,nn);
1682  vec[1] = xx;
1683  vec[4] = xx*xx;
1684  if ( !isfinite((*this)[i]) ) {
1685  error_show("Error in Bimage::refine_peak", __FILE__, __LINE__);
1686  cerr << ix << " " << iy << " " << iz << " " << (*this)[i] << endl;
1687  return -9;
1688  }
1689  for ( j=0; j<nterm; j++ ) b[j] += vec[j]*(*this)[i];
1690  for ( i=0; i<nterm; i++ )
1691  for ( j=0; j<=i; j++ ) a[i][j] += vec[i]*vec[j];
1692  }
1693  }
1694  }
1695  for ( i=0; i<nterm-1; i++ )
1696  for ( j=i+1; j<nterm; j++ ) a[i][j] = a[j][i];
1697  for ( i=0; i<nterm; i++ )
1698  if ( fabs(a[i][i]) < 1e-37 ) a[i][i] = 1;
1699  if ( verbose & VERB_DEBUG ) {
1700  cout << "DEBUG Bimage::refine_peak: Input matrix:" << endl;
1701  cout << a;
1702  cout << "DEBUG Bimage::refine_peak: Input vector:";
1703  for ( i=0; i<nterm; i++ ) cout << tab << b[i];
1704  cout << endl;
1705  }
1706  a.LU_decomposition(b);
1707  if ( verbose & VERB_DEBUG )
1708  cout << "DEBUG Bimage::refine_peak: Coefficients: " <<
1709  b[0] << tab << b[1] << tab << b[2] << tab << b[3] << tab << b[4] << tab << b[5] << tab << b[6] << endl;
1710  if ( b[4] ) shift[0] = -0.5*b[1]/b[4];
1711  if ( b[5] ) shift[1] = -0.5*b[2]/b[5];
1712  if ( b[6] ) shift[2] = -0.5*b[3]/b[6];
1713  if ( fabs(shift[0] - int_shift[0]) > 2 ) shift[0] = image[nn].origin()[0];
1714  if ( fabs(shift[1] - int_shift[1]) > 2 ) shift[1] = image[nn].origin()[1];
1715  if ( fabs(shift[2] - int_shift[2]) > 2 ) shift[2] = image[nn].origin()[2];
1717  image[nn].origin(shift);
1718  if ( verbose & VERB_FULL )
1719  cout << n+1 << tab << shift << endl;
1720  }
1721  if ( verbose & VERB_FULL ) cout << endl;
1722 
1723  return 0;
1724 }
1725 
1739 Bimage* Bimage::find_peaks(long kernelsize)
1740 {
1741  if ( kernelsize < 3 ) kernelsize = 3;
1742  if ( kernelsize%2 == 0 ) kernelsize++;
1743 
1744  long i, ii, ip, xx, yy, zz, nn, np(0);
1745  long xlo, xhi, ylo, yhi, zlo, zhi, kx, ky, kz, ix, iy, iz;
1746  double max;
1747  Vector3<long> hk(size()/2);
1748 
1749  hk = hk.min(kernelsize/2);
1750 
1751  if ( verbose & VERB_PROCESS )
1752  cout << "Finding peaks:" << endl;
1753 
1754  if ( verbose & VERB_DEBUG )
1755  cout << "DEBUG Bimage::find_peaks: hk=" << hk << endl;
1756 
1757  Bimage* pfom = new Bimage(Float, TSimple, size(), n);
1758 
1759  for ( i=nn=0; nn<n; nn++ ) {
1760  for ( zz=0; zz<z; zz++ ) {
1761  zlo = zz - hk[2];
1762  zhi = zz + hk[2];
1763  for ( yy=0; yy<y; yy++ ) {
1764  ylo = yy - hk[1];
1765  yhi = yy + hk[1];
1766  for ( xx=0; xx<x; xx++, i++ ) {
1767  xlo = xx - hk[0];
1768  xhi = xx + hk[0];
1769  max = (*this)[i];
1770  if ( max > 0 ) {
1771  // Highest voxel search in the kernel
1772  ip = i;
1773  for ( kz=zlo; kz<=zhi; kz++ ) {
1774  iz = kz;
1775  if ( iz < 0 ) iz += z; // Periodic boundaries
1776  if ( iz >= z ) iz -= z;
1777  for ( ky=ylo; ky<=yhi; ky++ ) {
1778  iy = ky;
1779  if ( iy < 0 ) iy += y; // Periodic boundaries
1780  if ( iy >= y ) iy -= y;
1781  for ( kx=xlo; kx<=xhi; kx++ ) {
1782  ix = kx;
1783  if ( ix < 0 ) ix += x; // Periodic boundaries
1784  if ( ix >= x ) ix -= x;
1785  ii = index(ix, iy, iz, nn);
1786  if ( max < (*this)[ii] ) {
1787  max = (*this)[ii];
1788  ip = ii;
1789  }
1790  }
1791  }
1792  }
1793  if ( ip == i ) {
1794  pfom->set(i, max);
1795  np++;
1796  }
1797  }
1798  }
1799  }
1800  }
1801  }
1802 
1803  if ( verbose & VERB_PROCESS )
1804  cout << "Peaks found: " << np << endl << endl;
1805 
1806  pfom->statistics();
1807 
1808  return pfom;
1809 }
1810 
1828 Vector3<double>* Bimage::find_peaks(double excl_dist, long& ncoor,
1829  double& threshold_min, double& threshold_max, double pix_min, double pix_max)
1830 {
1831  if ( threshold_min < min ) threshold_min = min;
1832  if ( threshold_max > max ) threshold_max = max;
1833 
1834  long rad = (long) excl_dist/2;
1835 
1836  Vector3<long> tile(size());
1837  tile = tile.min(rad);
1838 
1839  Vector3<long> start;
1840  start = start.max(tile);
1841  start = start.min(size()-1);
1842 
1843  Vector3<long> end(size()-tile);
1844  end = end.max(1);
1845 
1846  Vector3<double> ori(rad, rad, rad);
1847  ori = ori.min(size());
1848 
1849  if ( verbose & VERB_PROCESS ) {
1850  cout << "Finding peaks in the cross-correlation map:" << endl;
1851  cout << "Exclusion distance: " << excl_dist << endl;
1852  cout << "Thresholds: " << threshold_min << " - " << threshold_max << endl;
1853  cout << "Tile size: " << tile << endl;
1854  cout << "Starting coordinates: " << start << endl;
1855  cout << "Ending coordinates: " << end << endl;
1856  }
1857 
1858  long i, k, l, nc, xx, yy, zz, tx, ty, tz, nn;
1859  long nt = ((x-1)/tile[0]+1)*((y-1)/tile[1]+1)*((z-1)/tile[2]+1);
1860  double max(-1e30), v;
1861  Vector3<long>* ct = new Vector3<long>[nt];
1862  double* cc = new double[nt];
1863 
1864  if ( verbose & VERB_FULL )
1865  cout << "Allocated number of coordinates: " << nt << endl;
1866 
1867  for ( nn=0, nc=0; nn<n; nn++ ) {
1868  for ( zz=start[2]; zz<end[2]; zz+=rad ) {
1869  for ( yy=start[1]; yy<end[1]; yy+=rad ) {
1870  for ( xx=start[0]; xx<end[0]; xx+=rad ) {
1871  cc[nc] = -1e30;
1872  for ( tz=zz; tz<zz+tile[2] && tz<end[2]; tz++ ) {
1873  for ( ty=yy; ty<yy+tile[1] && ty<end[1]; ty++ ) {
1874  for ( tx=xx; tx<xx+tile[0] && tx<end[0]; tx++ ) {
1875  i = index(0,tx,ty,tz,nn);
1876  v = (*this)[i];
1877  if ( v > threshold_min && v <= threshold_max && cc[nc] < v ) {
1878  cc[nc] = v;
1879  ct[nc][0] = tx;
1880  ct[nc][1] = ty;
1881  ct[nc][2] = tz;
1882  }
1883  }
1884  }
1885  }
1886  if ( cc[nc] > threshold_min && cc[nc] <= threshold_max ) {
1887 // sigma = peak_sigma(nn, ct[nc], 15);
1888 // cout << nc << tab << cc[nc] << tab << ct[nc] << tab << sigma << endl;
1889 // if ( sigma > pix_min && sigma < pix_max ) {
1890 // if ( max < cc[nc] ) max = cc[nc];
1891  nc++;
1892 // }
1893  } else cc[nc] = -1e30;
1894  }
1895  }
1896  }
1897  }
1898 
1899  if ( threshold_min < 1e-6 ) threshold_min = kmeans_threshold(nc, cc);
1900  image->FOM(threshold_min);
1901 
1902  if ( verbose & VERB_PROCESS ) {
1903  cout << "Number of peaks found: " << nc << endl;
1904  cout << "Maximum CC: " << max << endl;
1905  cout << "Threshold: " << threshold_min << endl;
1906  }
1907 
1908  for ( k=0, ncoor=0; k<nc; k++ ) if ( cc[k] > threshold_min ) {
1909  for ( l=k+1; l<nc; l++ ) if ( cc[l] > threshold_min ) {
1910  if ( (ct[k] - ct[l]).length() < excl_dist ) {
1911  if ( cc[k] > cc[l] ) cc[l] = threshold_min - 1;
1912  else cc[k] = threshold_min - 1;
1913  }
1914  }
1915  if ( cc[k] > threshold_min ) ++ncoor;
1916  }
1917 
1918  Vector3<double>* coor = new Vector3<double>[ncoor];
1919 
1920  for ( i=k=0; k<nc; k++ ) if ( cc[k] >= threshold_min )
1921  coor[i++] = ct[k];
1922 
1923  delete[] ct;
1924  delete[] cc;
1925 
1926  if ( verbose & VERB_PROCESS )
1927  cout << "Number of peaks found: " << ncoor << endl << endl;
1928 
1929  return coor;
1930 }
1931 
1951 {
1952  long i, j, imax(0), imgsize(x*y*z);
1953  double v, vmax(min), vmax2(min), zavg(0), zstd(0), pval(0);
1954  Vector3<long> coor, cmax, cmax2;
1955 
1956  for ( i=nn*imgsize, j=0; j<imgsize; i++, j++ ) {
1957  v = (*this)[i];
1958  if ( vmax < v ) {
1959  vmax2 = vmax;
1960 // imax2 = imax;
1961  vmax = v;
1962  imax = i;
1963  } else if ( vmax2 < v ) {
1964  coor = coordinates(i);
1965  cmax = coordinates(imax);
1966  if ( coor.distance(cmax) > 1 ) {
1967  vmax2 = v;
1968 // imax2 = i;
1969  }
1970  }
1971  v = fishers_z_transform(v);
1972  zavg += v;
1973  zstd += v*v;
1974  }
1975 
1976  zavg /= imgsize;
1977  zstd = zstd/imgsize - zavg*zavg;
1978  if ( zstd <= 0 ) {
1979  zstd = 0;
1980  } else {
1981  zstd = sqrt(zstd);
1982  pval = erfc(0.5 * (fishers_z_transform(vmax) - fishers_z_transform(vmax2))/zstd);
1983  }
1984  if ( !isfinite(pval) ) pval = 0;
1985 
1986  if ( verbose & VERB_DEBUG ) {
1987  cout << "DEBUG Bimage::ccmap_confidence: z std:\t" << zstd << tab << 1/(sqrt(imgsize - 3.0)) << endl;
1988  cout << "DEBUG Bimage::ccmap_confidence: maxima:\t" << vmax << tab << vmax2 << endl;
1989  }
1990 
1991  return pval;
1992 }
1993 
2006 double Bimage::peak_sigma(long nn, Vector3<long> coor, long kernel_size)
2007 {
2008  long xx, yy, zz, nv(0);
2009  double sigma(0), dx2, dy2, dz2, r2, v, vmax(get(nn,coor));
2010  Vector3<long> k(kernel_size, kernel_size, kernel_size);
2011  k = k.min(size());
2012  Vector3<long> h(k/2), cmin(coor-h), cmax(coor+h+1);
2013  cmin = cmin.max(0);
2014  cmax = cmax.min(size());
2015 
2016 // cout << vmax << tab << cmin << tab << cmax << endl;
2017 
2018  for ( zz=cmin[2]; zz<cmax[2]; zz++ ) {
2019  dz2 = coor[2] - zz;
2020  dz2 *= dz2;
2021  for ( yy=cmin[1]; yy<cmax[1]; yy++ ) {
2022  dy2 = coor[1] - yy;
2023  dy2 *= dy2;
2024  for ( xx=cmin[0]; xx<cmax[0]; xx++ ) {
2025  dx2 = coor[0] - xx;
2026  dx2 *= dx2;
2027  r2 = dx2 + dy2 + dz2;
2028  if ( r2 ) {
2029  v = get(nn, xx, yy, zz);
2030 // cout << r2 << tab << vmax << tab << v << tab << log(vmax/v) << endl;
2031  if ( v > 0 && v < vmax ) {
2032  sigma += r2/log(vmax/v);
2033  nv++;
2034  }
2035  }
2036  }
2037  }
2038  }
2039 
2040  if ( nv ) sigma = sqrt(sigma/(2*nv));
2041 //cout << nv << tab << sigma << endl;
2042 //bexit(-1);
2043  return sigma;
2044 }
Bimage::R_factor
double R_factor(Bimage *p)
Calculates an R factor between two images.
Definition: Bimage_correlate.cpp:218
Bimage::coordinates
void coordinates(long i, long &nx, long &ny, long &nz)
Definition: Bimage.h:429
qsort_functions.h
Header file for utility functions for use in qsort calls.
Bimage::real_size
Vector3< double > real_size()
Definition: Bimage.h:500
matrix_linear.h
Header file for matrix functions.
Bimage::correlation_coefficient
double correlation_coefficient(Vector3< double > shift)
Calculates a coefficient from a Fourier correlation transform given a shift.
Definition: Bimage_correlate.cpp:466
VERB_DEBUG
#define VERB_DEBUG
Definition: utilities.h:116
Bimage::find_peaks
Bimage * find_peaks(long kernelsize)
Finds peaks in a map with periodic boundaries.
Definition: Bimage_correlate.cpp:1739
vector3_origin_to_shift
Vector3< T1 > vector3_origin_to_shift(Vector3< T1 > origin, Vector3< T2 > size)
Definition: Vector3.h:669
Bimage::shift
int shift(Vector3< double > vec, int fill_type=0, double fill=0)
Shifts an image.
Definition: Bimage_transform.cpp:589
Bimage::get
double get(long nn, long xx, long yy, long zz, long cc=0)
Returns the data value at the given coordinates.
Definition: Bimage.cpp:960
Matrix3::singular_value_decomposition
Matrix3 singular_value_decomposition()
Definition: Matrix3.h:320
Complex
Definition: Complex.h:23
Complex::real
Type real()
Definition: Complex.h:101
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
Bimage::set
void set(long j, double v)
Sets a single value at the given index.
Definition: Bimage.cpp:1118
Bimage::next
Bimage * next
Definition: Bimage.h:179
Matrix3::transpose
Matrix3 transpose() const
Definition: Matrix3.h:268
Bsub_image::view_angle
void view_angle(double d)
Definition: Bimage.h:161
Bimage::find_center
int find_center(Bimage *pmask, double hires, double lores, double radius, double sigma, int refine_flag)
Finds the center of mass of an image by cross-correlation with its inverse.
Definition: Bimage_correlate.cpp:1235
Bimage::Bimage
Bimage()
Initializes an image.
Definition: Bimage.cpp:43
Bimage::find_template
Bimage * find_template(Bimage *ptemp, Bimage *pmask, double hires, double lores, int bin, fft_plan planf, fft_plan planb)
Finds one or more matches to a template.
Definition: Bimage_correlate.cpp:1177
Bimage::extract_wrap
Bimage * extract_wrap(long nn, Vector3< double > loc, Vector3< long > size, Vector3< double > origin, Matrix3 mat)
Extracts a region of one sub-image into new image structure with wrapping.
Definition: Bimage_extract.cpp:151
Bimage::copy
Bimage * copy()
Copies the header information and data of an image into a new image structure.
Definition: Bimage.cpp:2702
Bimage::find_shift_in_transform
Vector3< double > find_shift_in_transform(double shift_limit)
Finds the shift by brute force backtransformation for selected shifts.
Definition: Bimage_correlate.cpp:501
Vector3< double >
Bimage::pack_two_in_complex
Bimage * pack_two_in_complex(Bimage *p)
Packs two real images into one complex image.
Definition: Bimage_complex.cpp:679
Bimage::find_peak
int find_peak(double radius=1e30, double sigma=0)
Finds the peak in an image to the nearest voxel.
Definition: Bimage_correlate.cpp:1340
bexit
int bexit(int value)
Exit function for cleanup and debugging.
Definition: utilities.cpp:280
TypePointer::uc
unsigned char * uc
Definition: Bimage.h:70
Bimage::sum
void sum(long m, Bimage **p)
Sums an array of images with their FOM blocks.
Definition: Bimage_combine.cpp:23
GOLDEN
#define GOLDEN
Definition: utilities.h:85
Bimage::cross_correlate_validate
Bimage * cross_correlate_validate(Bimage *p, Bimage *pmask)
Calculates a masked cross-correlation map by Fast Fourier transformation.
Definition: Bimage_correlate.cpp:748
error_show
int error_show(string message, string file, int line)
Displays the error with file and line reference.
Definition: utilities.cpp:719
FILL_USER
#define FILL_USER
Definition: utilities.h:176
Bimage::size
Vector3< long > size() const
Definition: Bimage.h:386
Bimage::fft_back
int fft_back()
Definition: Bimage.h:831
View
Definition: View.h:26
Bimage::shift_wrap
int shift_wrap(Vector3< double > vec)
Shifts an image.
Definition: Bimage_transform.cpp:641
Bimage::find_shift
int find_shift(Bimage *pref, Bimage *pmask, double hires, double lores, double radius, double sigma, int refine_flag)
Calculates a cross-correlation map to find the shift for the pair of images.
Definition: Bimage_correlate.cpp:929
Bsub_image::FOM
double FOM()
Definition: Bimage.h:165
Bimage::rotate_find_shift
Vector3< double > rotate_find_shift(Matrix3 mat, double hires, double lores, double radius, double sigma, int refine_flag, fft_plan planf, fft_plan planb, double &cc)
Rotates and find shift by cross-correlation.
Definition: Bimage_correlate.cpp:1308
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
Bimage::maximum
double maximum()
Definition: Bimage.h:542
M_PI_2
#define M_PI_2
Definition: utilities.h:66
Bimage::standard_deviation
double standard_deviation()
Definition: Bimage.h:544
Bimage::ccmap_confidence
double ccmap_confidence(long nn)
Calculates a confidence level to associate with a cross-correlation peak.
Definition: Bimage_correlate.cpp:1950
Bimage::refine_peak
int refine_peak()
Refines the position of a peak to sub-voxel resolution.
Definition: Bimage_correlate.cpp:1615
Bimage::complex_apply_dual_mask
int complex_apply_dual_mask(Bimage *pmask)
Applies a dual mask to a complex image.
Definition: Bimage_complex.cpp:581
planf
fft_plan planf
Definition: bico.cpp:24
Vector3::distance
double distance(const Vector3 &v)
Definition: Vector3.h:227
Bimage::images
long images()
Definition: Bimage.h:504
Bsub_image::maximum
double maximum()
Definition: Bimage.h:118
Bimage::unpack_combined_transform
Bimage * unpack_combined_transform()
Unpacks a complex transform obtained from two real images.
Definition: Bimage_complex.cpp:749
Matrix3
Definition: Matrix3.h:18
Matrix::singular_value_decomposition
double singular_value_decomposition()
Singular value decomposition of a matrix .
Definition: matrix.cpp:177
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
TSimple
@ TSimple
Definition: Bimage.h:59
write_img
int write_img(const char *filename, Bimage *p, int compression)
General driver function to write multiple image formats.
Definition: rwimg.cpp:281
Bimage::add
void add(long j, double v)
Definition: Bimage.h:321
Bimage::combined_complex_product_implicit_mask
int combined_complex_product_implicit_mask(double hires, double lores)
Calculates the complex conjugate product of a complex image resulting from combining and Fourier tran...
Definition: Bimage_complex.cpp:1090
Bimage::correlate
double correlate(Bimage *p)
Calculates correlation coefficient between two images.
Definition: Bimage_correlate.cpp:36
Bimage::fft
int fft()
Definition: Bimage.h:830
Bimage::image_size
long image_size()
Definition: Bimage.h:290
verbose
int verbose
Bimage::rotate
int rotate()
Rotates an image using parameters defined in the image in place.
Definition: Bimage_transform.cpp:255
Bimage::fourier_type
FourierType fourier_type()
Definition: Bimage.h:380
Bimage::bin_copy
Bimage * bin_copy(long b)
Definition: Bimage.h:1298
Bimage::cross_correlate_fspace
Bimage * cross_correlate_fspace(Bimage *p, double hires, double lores, double shift_limit)
Calculates a cross-correlation map by Fast Fourier transformation.
Definition: Bimage_correlate.cpp:559
Bimage::rotate_cross_correlate
Vector3< double > rotate_cross_correlate(Bimage *pref, View view, double hires, double lores, double search_radius, Bimage *pmask, double &cc, fft_plan planf, fft_plan planb)
Definition: Bimage_correlate.cpp:801
Bimage
General image parameter class.
Definition: Bimage.h:177
Bimage::average
double average(long cc, double xf, double yf, double zf, long nn, double iscale)
Averages in 3D when scaling is less than 1.
Definition: Bimage.cpp:1371
timer.h
Utilities for timing functions.
Bimage::power
void power(double v)
Calculates the power of an image.
Definition: Bimage.cpp:3291
Matrix::LU_decomposition
double LU_decomposition()
Matrix inversion by LU decomposition.
Definition: matrix.cpp:78
Bimage::complex
Complex< double > complex(long j)
Returns a complex value at the given index.
Definition: Bimage.cpp:1027
Complex::imag
Type imag()
Definition: Complex.h:102
Bimage.h
Header file for image class.
Bimage::file_name
void file_name(string s)
Definition: Bimage.h:245
Bimage::peak_sigma
double peak_sigma(long nn, Vector3< long > coor, long kernel_size)
Calculates a sigma value for a cross-correlation peak.
Definition: Bimage_correlate.cpp:2006
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
Bimage::check_resolution
void check_resolution(double &resolution)
Checks that the resolution falls within reasonable limits.
Definition: Bimage.cpp:635
Bimage::pad_copy
Bimage * pad_copy(long sz, int fill_type=0, double fill=0)
Pads an image to a new size with a given fill value.
Definition: Bimage_resize.cpp:388
Bimage::complex_normalize
double complex_normalize()
Normalizes the power in a complex image.
Definition: Bimage_complex.cpp:225
isfinite
bool isfinite(complex< T > &value)
Bimage::origin
void origin(double ox, double oy, double oz)
Definition: Bimage.h:570
Bimage::change_type
void change_type(char letter)
Get the data type indicated by a single letter code.
Definition: Bimage.cpp:1765
Bimage::index
long index(long nx, long ny) const
Definition: Bimage.h:396
Bimage::refine_peak_new
int refine_peak_new()
Refines the position of a peak to sub-voxel resolution.
Definition: Bimage_correlate.cpp:1574
rwimg.h
Header file for 2D and 3D image I/O.
Bimage::rotate_cross_correlate_two_way
double rotate_cross_correlate_two_way(Bimage *pref, double angle, double res_hi, double res_lo, double shift_limit, fft_plan planf, fft_plan planb)
Definition: Bimage_correlate.cpp:859
Bimage::complex_conjugate_product
int complex_conjugate_product(Bimage *p)
Calculates the product of a complex image with the conjugate of a second.
Definition: Bimage_complex.cpp:460
Bimage::cross_correlate_two_way
Bimage * cross_correlate_two_way(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:667
Bimage::extract
Bimage * extract(long nn)
Extracts one sub-image into new image structure.
Definition: Bimage_extract.cpp:21
fft_plan
fftwf_plan fft_plan
Definition: fft.h:20
Bsub_image::sampling
void sampling(double x, double y, double z)
Definition: Bimage.h:127
kmeans_threshold
double kmeans_threshold(long n, double *v)
Finds a threshold that partitions an array into foreground and background clusters.
Definition: math_util.cpp:345
math_util.h
Header file for general utilities.
VERB_FULL
#define VERB_FULL
Definition: utilities.h:113
Bimage::sampling
vector< Vector3< double > > sampling()
Definition: Bimage.h:529
Vector3::min
Type min()
Definition: Vector3.h:169
Bimage::rotate_correlate
double rotate_correlate(Vector3< double > axis, double angle)
Rotates a copy of an image and correlates it with the original.
Definition: Bimage_correlate.cpp:195
Bimage::pad
int pad(long sz, int fill_type=0, double fill=0)
Pads an image to a new size with a given fill value.
Definition: Bimage_resize.cpp:347
Bimage::complex_product
int complex_product(Bimage *p)
Calculates the complex product of two complex images.
Definition: Bimage_complex.cpp:430
planb
fft_plan planb
Definition: bico.cpp:24
fishers_z_transform
double fishers_z_transform(double value)
Calculates Fisher's z-transform.
Definition: math_util.cpp:249
Double
@ Double
Definition: utilities.h:162
Bimage::complex_apply_mask
int complex_apply_mask(Bimage *pmask)
Applies a mask to a complex image.
Definition: Bimage_complex.cpp:521
Matrix
Definition: Matrix.h:22
Float
@ Float
Definition: utilities.h:161
Bimage::channels
long channels()
Definition: Bimage.h:384
Bimage::complex_bandpass
int complex_bandpass(double hires, double lores)
Bandpasses a Fourier transform.
Definition: Bimage_complex.cpp:615
Bimage::combined_complex_product
int combined_complex_product()
Calculates the complex conjugate product of a complex image resulting from combining and Fourier tran...
Definition: Bimage_complex.cpp:813
Bimage::fit_peak
Vector3< double > fit_peak()
Fits an elliptic parabole to locate the position of the peak to sub-voxel resolution.
Definition: Bimage_correlate.cpp:1431
NoTransform
@ NoTransform
Definition: Bimage.h:41
Bimage::view
void view(double vx, double vy, double vz, double va)
Definition: Bimage.h:596
Bimage::complex_to_real
void complex_to_real()
The real part of a complex image is written to a simple image.
Definition: Bimage_complex.cpp:50
Bimage::statistics
long statistics()
Calculates the statistics for an image.
Definition: Bimage_stats.cpp:22
Bimage::check_if_same_size
bool check_if_same_size(Bimage *p)
Check if two images are the same size.
Definition: Bimage.cpp:566
Bimage::auto_correlate
int auto_correlate(double hires, double lores)
Calculates an autocorrelation map by Fast Fourier transformation.
Definition: Bimage_correlate.cpp:265
TWOPI
#define TWOPI
Definition: utilities.h:72
Vector3::max
Type max()
Definition: Vector3.h:175