Bsoft  2.1.0
Bernard's software package
mg_align.cpp
Go to the documentation of this file.
1 
9 #include "Bimage.h"
10 #include "mg_align.h"
11 #include "rwimg.h"
12 #include "mg_processing.h"
13 #include "mg_img_proc.h"
14 #include "mg_select.h"
15 #include "marker.h"
16 #include "ps_marker.h"
17 #include "linked_list.h"
18 #include "utilities.h"
19 
20 #include <sys/stat.h>
21 
22 // Declaration of global variables
23 extern int verbose; // Level of output to the screen
24 
40 {
41  if ( refset < 0 ) refset = 0;
42 
43  int i;
44  long nmg, npart, nmg_max = 1000;
45  Transform t;
46 
47  Bfield* field;
48  Bmicrograph* mg;
49  Bparticle* part;
50 
51  Bmarker** set = new Bmarker*[nmg_max];
52  Bmarker* m = NULL;
53 
54  Vector3<double> origin;
55 
56  if ( verbose & VERB_LABEL )
57  cout << "Aligning micrograph particle coordinates for series of micrographs." << endl;
58  if ( verbose & VERB_PROCESS )
59  cout << "Particles\tX-shift\tY-shift\tX-scale\tY-scale\tAngle" << endl;
60 
61  for ( field=project->field; field; field=field->next ) {
62  for ( i=1, mg=field->mg; mg->next && i < refset; mg=mg->next ) i++;
63  origin = micrograph_get_nominal_origin(mg);
64  nmg = field_count_micrographs(field);
65  npart = micrograph_count_particles(field->mg);
66  for ( i=0, mg=field->mg; mg; mg=mg->next, i++ ) {
67  for ( part=mg->part; part; part=part->next ) {
68  m = (Bmarker *) add_item((char **) &m, sizeof(Bmarker));
69  if ( !set[i] ) set[i] = m;
70  m->loc = part->loc;
71  m->sel = 1;
72  m->fom = 1;
73  }
74  }
75  for ( i=0, mg=field->mg->next; mg; mg=mg->next, i++ ) if ( i != refset ) {
76  t = markers_find_rottrans(set[refset], set[i], 0.01);
77  mg->rot_angle = t.angle;
78  mg->origin = origin + t.trans;
79  mg->scale = t.scale;
80  if ( verbose & VERB_PROCESS )
81  cout << npart << tab << t.trans[0] << tab << t.trans[1] << tab << t.trans[2] << tab <<
82  t.scale[0] << tab << t.scale[1] << tab << t.scale[2] << tab << t.angle*180.0/M_PI << endl;
83  }
84  for ( i=0; i<nmg; i++ )
85  kill_list((char *) set[i], sizeof(Bmarker));
86  }
87 
88  delete[] set;
89 
90  return 0;
91 }
92 
93 /*
94 @brief Aligns the second image to the first.
95 @param *p1 first image.
96 @param *p2 second image (transformed)
97 @param tile_size 3-valued vector for the size of sub-images.
98 @param res_lo low resolution limit for cross-correlation.
99 @param res_hi high resolution limit for cross-correlation.
100 @param max_shift maximum shift allowed (default 1/4 of tile).
101 @param filter_flag flag to filter micrograph extremes.
102 @param refine_flag flag to turn on refinement of shift.
103 @return Transform structure with shift, scale, rotation angle, and R factor.
104 
105  The second image is transformed to fit on the first image.
106 
107 */
109  double res_lo, double res_hi, double max_shift, int filter_flag, int refine_flag)
110 {
111  long i, iter, maxiter(5);
112  Vector3<double> shift;
113  Transform t, best_t;
114  best_t.fom = 1e37;
115 
116  Vector3<long> start1, common_size, step_size;
117 
118  // Find the largest area covering both images
119  common_size = p1->size().min(p2->size());
120  common_size = common_size.max(1);
121 
122  // Ensure the tile fits into the images
123  tile_size = tile_size.max(1);
124  tile_size = tile_size.min(common_size);
125  if ( tile_size[0] >= common_size[0] && common_size[0] > 1 ) {
126  tile_size[0] = (int) (0.4*common_size[0]);
127 // start1[0] = (common_size[0] - tile_size[0])/2;
128  }
129  if ( tile_size[1] >= common_size[1] && common_size[1] > 1 ) {
130  tile_size[1] = (int) (0.4*common_size[1]);
131 // start1[1] = (common_size[1] - tile_size[1])/2;
132  }
133  if ( tile_size[2] >= common_size[2] && common_size[2] > 1 ) {
134  tile_size[2] = (int) (0.4*common_size[2]);
135 // start1[2] = (common_size[2] - tile_size[2])/2;
136  }
137 
138  if ( max_shift < 1 ) max_shift = tile_size[0]/4;
139 
140  Vector3<double> half_tile;
141  half_tile[0] = (tile_size[0] - 1)/2;
142  half_tile[1] = (tile_size[1] - 1)/2;
143  half_tile[2] = (tile_size[2] - 1)/2;
144 
145  Bimage* pex1 = NULL;
146  Bimage* pex2 = NULL;
147  Bmarker* set1 = NULL;
148  Bmarker* set2 = NULL;
149  Bmarker* m1 = NULL;
150  Bmarker* m2 = NULL;
151 // Bstring filename = p1->file_name().pre_rev('.') + "_" + p2->file_name().pre_rev('.') + ".ps";
152  Bstring fn1(p1->file_name()), fn2(p2->file_name());
153  Bstring filename(fn1.base() + "_" + fn2.base() + ".ps");
154 
155  if ( verbose & VERB_LABEL ) {
156  cout << "Aligning images ";
157  if ( refine_flag ) cout << "with ";
158  else cout << "without ";
159  cout << "shift refinement." << endl << endl;
160  }
161 
162  if ( common_size[0] > 2*tile_size[0] )
163  start1[0] = (common_size[0]
164  - (int) (tile_size[0]*(common_size[0]/tile_size[0])))/2;
165  if ( common_size[1] > 2*tile_size[1] )
166  start1[1] = (common_size[1]
167  - (int) (tile_size[1]*(common_size[1]/tile_size[1])))/2;
168  if ( common_size[2] > 2*tile_size[2] )
169  start1[2] = (common_size[2]
170  - (int) (tile_size[2]*(common_size[2]/tile_size[2])))/2;
171 
172  if ( verbose & VERB_PROCESS ) {
173  cout << "Common size: " << common_size << endl;
174  cout << "Tile size: " << tile_size << endl;
175  cout << "Maximum shift: " << max_shift << endl;
176  cout << "Reference start: " << start1 << endl << endl;
177  }
178 
179  if ( res_hi < 0.1 || res_hi > tile_size[0]*p1->sampling(0)[0] )
180  res_hi = 4.0*p1->sampling(0)[0];
181 
182  if ( filter_flag ) {
183  p1->filter_extremes();
184  p2->filter_extremes();
185  }
186 
187  pex1 = p1->extract_tiles(0, start1, common_size, tile_size, step_size, 0);
188 
189 // Vector3<long>* tile_start = new Vector3<long>[pex1->images()];
190  vector<Vector3<long>> tile_start(pex1->images());
191 
192  for ( i=0; i<pex1->images(); i++ ) {
193  m1 = (Bmarker *) add_item((char **) &m1, sizeof(Bmarker));
194  m2 = (Bmarker *) add_item((char **) &m2, sizeof(Bmarker));
195  if ( !set1 ) set1 = m1;
196  if ( !set2 ) set2 = m2;
197  m1->sel = m2->sel = 1;
198  m1->fom = m2->fom = 1;
199  m1->loc = pex1->image[i].origin() + half_tile;
200  tile_start[i] = pex1->image[i].origin();
201  }
202 
203  for ( iter=0; iter<maxiter && best_t.fom>0.1; iter++ ) {
204  pex2 = p2->extract_tiles(0, tile_start, tile_size);
205  // Determines the shift of the second image onto the first
206  pex1->find_shift(pex2, NULL, res_hi, res_lo, max_shift, 0, refine_flag);
207  for ( i=0, m2=set2; i<pex1->images(); i++, m2=m2->next ) {
208  shift = pex1->image[i].origin() - pex2->image[i].origin();
209  if ( shift[0] > half_tile[0] ) shift[0] -= tile_size[0];
210  if ( shift[1] > half_tile[1] ) shift[1] -= tile_size[1];
211  if ( shift[2] > half_tile[2] ) shift[2] -= tile_size[2];
212  // To get the location in the second image, the shift must be subtracted
213  m2->loc = tile_start[i] + half_tile - shift;
214  }
215  t = markers_find_rottrans(set1, set2, 0.01);
216  if ( verbose & VERB_PROCESS )
217  cout << "Fit " << iter+1 << ":\t" << p1->file_name() << tab << p2->file_name() << tab
218  << t.trans << tab
219  << t.scale << tab
220  << t.angle*180.0/M_PI << tab << t.fom << endl;
221  if ( best_t.fom > t.fom ) best_t = t;
222  else iter = maxiter;
223  for ( i=0, m1=set1, m2=set2; i<pex1->images(); i++, m1=m1->next, m2=m2->next ) {
224  m2->loc[0] = best_t.scale[0]*(m1->loc[0]*cos(best_t.angle) -
225  m1->loc[1]*sin(best_t.angle)) + t.trans[0] + 0.5;
226  m2->loc[1] = best_t.scale[1]*(m1->loc[0]*sin(best_t.angle) +
227  m1->loc[1]*cos(best_t.angle)) + t.trans[1] + 0.5;
228  m2->loc[2] = best_t.scale[2]*m1->loc[2] + t.trans[2];
229  tile_start[i] = m2->loc - half_tile;
230  }
231  delete pex2;
232  }
233 
234  if ( verbose & VERB_RESULT )
235  cout << "Best fit:\t" <<
236  p1->file_name() << tab << p2->file_name() << tab <<
237  best_t.trans << tab <<
238  best_t.scale << tab <<
239  best_t.angle*180.0/M_PI << tab << best_t.fom << endl;
240 
241  delete pex1;
242 
243  ps_marker_errors(filename, set1, set2, t, p1->size(), 20);
244 
245  kill_list((char *) set1, sizeof(Bmarker));
246  kill_list((char *) set2, sizeof(Bmarker));
247 
248  return best_t;
249 }
250 
251 Bimage* img_sum_subset(Bimage* p, Bstring& subset, double dose_per_frame)
252 {
253  long n, ns(0);
254  double dose(0);
255  vector<int> numsel = select_numbers(subset, p->images());
256 
257  Bimage* p1;
258  Bimage* pa = p->copy_header(1);
259  pa->data_type(Float);
260  pa->sampling(p->sampling(0));
261  pa->data_alloc_and_clear();
262 
263  for ( n=0; n<p->images(); n++ ) {
264  dose += dose_per_frame;
265  if ( numsel[n] ) {
266  if ( verbose & VERB_PROCESS )
267  cout << "Adding frame " << n << endl;
268  p1 = p->extract(n);
269  p1->change_type(Float);
270  pa->add(p1);
271  (*pa)["dose"] = dose;
272  delete p1;
273  ns++;
274  }
275  }
276 
277  double var1(p->standard_deviation()*p->standard_deviation());
278  double var(pa->standard_deviation()*pa->standard_deviation());
279  double snr(0);
280  if ( var < ns*ns*var1 ) snr = (var - ns*var1)/(ns*var1 - var/ns);
281 
282  pa->image->FOM(snr);
283 
284  return pa;
285 }
286 
287 
320  Vector3<long> tile_size, double res_lo, double res_hi,
321  double max_shift, int filter_flag, int refine_flag)
322 {
323  long i;
324 
325  Bfield* field;
326  Bmicrograph* mg, *mg_ref;
327 
328  Bimage* p = NULL;
329  Bimage* p2 = NULL;
330 
331  Transform t;
332 
333  if ( verbose ) {
334  cout << "Aligning micrographs for micrograph series ";
335  if ( refine_flag ) cout << "with ";
336  else cout << "without ";
337  cout << "shift refinement." << endl << endl;
338  }
339 
340  for ( field=project->field; field; field=field->next ) if ( field->mg ) {
341  for ( i=1, mg = mg_ref = field->mg; mg->next && i < refset; mg=mg->next, i++ ) ;
342  if ( mg ) mg_ref = mg;
343  p = read_img(mg_ref->fmg, 1, mg->img_num);
344  if ( !p ) {
345  cerr << "Error in mg_align_micrographs: File " << mg_ref->fmg << " not read!" << endl;
346  return -1;
347  }
348  if ( mg_ref->pixel_size[0] > 0.1 ) p->sampling(mg_ref->pixel_size);
349  mg_ref->origin = p->size()/2;
350  t = Transform();
351  mg_ref->rot_angle = 0;
352  mg_ref->scale = t.scale;
353  for ( mg=field->mg; mg; mg=mg->next ) {
354  if ( mg_ref != mg ) {
355  p2 = read_img(mg->fmg, 1, mg->img_num);
356  if ( !p ) {
357  cerr << "Error in mg_align_micrographs: File " << mg->fmg << " not read!" << endl;
358  return -1;
359  }
360  if ( mg->pixel_size[0] > 0.1 ) p2->sampling(mg->pixel_size);
361  mg->origin = mg_ref->origin;
362  t = Transform();
363  // The alignment transforms the second image
364 // cout << "aligning:" << tab << p->file_name() << tab << p2->file_name() << endl;
365  t = img_align(p, p2, tile_size, res_lo, res_hi, max_shift, filter_flag, refine_flag);
366  mg->rot_angle = t.angle;
367  mg->origin += t.trans;
368  mg->scale = t.scale;
369  mg->matrix = Matrix3(t.axis, -t.angle);
370  mg_apply_transform(mg_ref, mg);
371  delete p2;
372  }
373  }
374  delete p;
375  }
376 
377  return 0;
378 }
379 
380 /*
381 @author Samuel Payne and Bernard Heymann
382 @brief Finds local minimums in a grey scale image and uses those as features
383 @param *p image (modified to floating point).
384 @param extract_method The method to determine the center of the particle
385 @param target_num Max number of desired features (-1 will return all)
386 @param threshold Threshold value used to determine whether
387  a pixel is considered a feature.
388 @return Bmarker* a set containing xyz coordinates of features
389 
390  The input image is expected to have been cleaned in the following manner.
391  With each suggestion is listed the corresponding bsoft function call.
392  1. Any extremes such as white lettering, or black edges have been removed.
393  bfilter -e filname filename
394  2. Edge filter to smooth out the edges.
395  bedge -x<xsize>,<ysize>,<zsize> -o150,150,0 -g75 filename filename
396  3. Bandpass filtered to reduce the noise.
397  bfilter -b1000,2000 -df filename filename
398 
399  The algorithm finds blocks of dark grey. The features are black dots
400  in the image, which could be particles, but don't have to be. As long
401  as the picking is consistent, it does not matter what is picked.
402  (it could be a pickle). The method used to find the center of the feature
403  depends on the input. (0=Center of Mass, 1=Center of Area, 2=Darkest pixel)
404 
405 **/
406 Bmarker* img_extract_features(Bimage* p, int extract_method,
407  int target_num, double threshold)
408 {
409  // The extreme considered as a feature depends on the relative threshold
410  int sign = 1;
411  if ( threshold < p->average() ) sign = -1;
412 
413  long i, j, x, y, z, n;
414  long count(0);
415  Vector3<long> coor;
416  double temp;
417 
418  if ( verbose & VERB_LABEL ) {
419  cout << "Using the ";
420  switch ( extract_method ) {
421  case 1: cout << "center of mass "; break;
422  case 2: cout << "center of volume "; break;
423  case 3: cout << "highest pixel density "; break;
424  default: cout << "center of mass "; break;
425  }
426  cout << "to determine the feature coordinates in " << p->file_name() << endl;
427  }
428 
429  // Definition of features based on regions beyond a threshold
430  Bimage* pmask = p->regions(threshold, 0);
431  count = (long) pmask->maximum();
432 
433  if ( verbose & VERB_LABEL )
434  cout << "Features extracted: " << count << endl << endl;
435 
436  if ( count < 1 ) {
437  delete pmask;
438  return NULL;
439  }
440 
441  Bmarker* set = NULL;
442  Bmarker* m = NULL;
443  Bmarker** lut = new Bmarker*[count];
444 
445  for ( i=0; i<count; i++ ) {
446  m = (Bmarker *) add_item((char **) &m, sizeof(Bmarker));
447  if ( !set ) set = m;
448  m->id = i+1;
449  m->sel = i+1;
450  lut[i] = m;
451  }
452 
453  for ( i=n=0; n<p->images(); n++ ) {
454  for ( z=0; z<p->sizeZ(); z++ ) {
455  coor[2] = z;
456  for ( y=0; y<p->sizeY(); y++ ) {
457  coor[1] = y;
458  for ( x=0; x<p->sizeX(); x++, i++ ) {
459  coor[0] = x;
460  if ( (*pmask)[i] > 0 ) { //meaning that it belongs to a group
461  j = (long) ((*pmask)[i]-1);
462  m = lut[j];
463 // cout << "Region " << i << ": " << (*pmask)[i] << endl;
464  temp = fabs((*p)[i]);
465  if ( extract_method == 1 ) {
466  m->loc += coor * temp;
467  m->fom += temp;
468  } else if ( extract_method == 2 ) {
469  m->loc += coor;
470  m->fom += 1;
471  }
472  if ( sign*(*p)[i] > sign*m->fom ) {
473  m->fom = (*p)[i];
474  if ( extract_method == 3 ) {
475  m->loc = coor;
476  }
477  }
478  m->img_num = n;
479  }
480  }
481  }
482  }
483  }
484 
485  delete pmask;
486  delete[] lut;
487 
488  cout << "Feature marker list generated" << endl;
489 
490  markers_limit(target_num, sign, &set);
491 
492 // if ( verbose & VERB_FULL )
493  cout << "Feature\tx\ty\tz\tex\tey\tez\tFOM" << endl;
494 
495  for ( m=set; m; m=m->next ) {
496  if ( extract_method == 1 || extract_method == 2 )
497  m->loc /= m->fom;
498  m->err = m->loc - p->size() /2;
499 // if ( verbose & VERB_FULL )
500  cout << m->id << tab << m->loc << tab <<
501  m->err << tab << m->fom << endl;
502  }
503  if ( verbose & VERB_FULL )
504  cout << endl;
505 
506  if ( verbose & VERB_DEBUG ) {
507  cout << "\nDEBUG img_extract_features: The Feature set" << endl;
508  for ( m=set; m; m=m->next )
509  cout << "Feature " << m->id << ": " << m->loc << tab << m->fom << endl;
510  pmask = p->mask_by_threshold(threshold);
511  Bstring filename(p->file_name());
512  filename = filename.base() + "_features.pif";
513  write_img(filename, pmask, 0);
514  delete pmask;
515  }
516 
517 
518  return set;
519 }
520 
521 
546  double res_low, double res_high, double thresh, int extract_method)
547 {
548  long i, refset(-1), nmg;
549  Vector3<long> size;
550  Vector3<double> origin;
551  double width;
552  Transform* tlist = NULL;
553  Transform* t = NULL;
554 
555  Bfield* field;
556  Bmicrograph* mg, *mg_ref = NULL;
557 
558  long nmg_max = field_count_micrographs(project->field);
559  if ( nmg_max < 5 ) nmg_max = 5;
560 
561  Bmarker** set = new Bmarker*[nmg_max];
562 
563  Bimage* p = NULL;
564 
565  if ( verbose & VERB_LABEL )
566  cout << "Aligning micrographs for micrograph series using features." << endl;
567 
568  for ( field=project->field; field; field=field->next ) {
569  nmg = field_count_micrographs(field);
570  if ( refset < 0 ) refset = 0;
571  for ( i=0, mg=field->mg; mg; mg=mg->next, i++ ) {
572  if ( mg->part ) refset = i;
573  if ( i == refset ) mg_ref = mg;
574  p = read_img(mg->fmg, 1, 0);
575  mg->origin = p->size()/2;
576  // Before features are extracted, the image must be filtered for extreme
577  // values, the edge smoothed and finally bandpass-filtered.
578  p->filter_extremes();
579  width = 0.05*p->sizeX();
580  if ( p->sizeY() > p->sizeX() ) width = 0.05*p->sizeY();
581  origin = p->size() * 0.1;
582  if ( origin[0] > p->sizeX() - 1 ) origin[0] = p->sizeX() - 1;
583  if ( origin[1] > p->sizeY() - 1 ) origin[1] = p->sizeY() - 1;
584  if ( origin[2] > p->sizeZ() - 1 ) origin[2] = p->sizeZ() - 1;
585  size[0] = (int) (p->sizeX() - 2*origin[0]);
586  size[1] = (int) (p->sizeY() - 2*origin[1]);
587  size[2] = (int) (p->sizeZ() - 2*origin[2]);
588  if ( size[0] > p->sizeX() ) size[0] = p->sizeX();
589  if ( size[1] > p->sizeY() ) size[1] = p->sizeY();
590  if ( size[2] > p->sizeZ() ) size[2] = p->sizeZ();
591  p->shape(0, size, origin, width, FILL_AVERAGE, p->average());
592  p->fspace_bandpass(res_high, res_low, 0);
593  set[i] = img_extract_features(p, extract_method, max_features, thresh);
594  if ( set[i] == NULL) {
595  error_show("Error in mg_align_feature_extraction", __FILE__, __LINE__);
596  cerr << "Unable to extract any features from " << p->file_name() << endl;
597  return -1;
598  }
599  size = p->size();
600  delete p;
601  }
602  tlist = markers_map_and_find_transform(set, nmg, refset, size);
603  if ( !t->fom ) {
604  error_show("Error in mg_align_feature_extraction", __FILE__, __LINE__);
605  cerr << "Transformation parameters not found!" << endl;
606  return -1;
607  }
608  for ( i=0, mg=field->mg, t=tlist; mg; mg=mg->next, t=t->next, i++ ) if ( i != refset ) {
609  mg->rot_angle = t->angle;
610  mg->origin = mg->origin + t->trans;
611  mg->scale = t->scale;
612  mg_apply_transform(mg_ref, mg);
613  }
614  for ( i=0, mg=field->mg; mg; mg=mg->next, i++ )
615  kill_list((char *)set[i], sizeof(Bmarker));
616  }
617 
618  delete[] set;
619  kill_list((char *) tlist, sizeof(Transform));
620 
621  return 0;
622 }
623 
635 {
636  if ( mg_ref == mg_apply ) return 0;
637 
638  long npref = micrograph_count_particles(mg_ref);
639  long npapp = micrograph_count_particles(mg_apply);
640  long nfref = filament_node_count(mg_ref->fil);
641  long nfapp = filament_node_count(mg_apply->fil);
642  Bparticle *part_ref, *part_app;
643  Bbadarea *bad_ref, *bad_app;
644  Bfilament *fil_ref, *fil_app;
645  Bfilnode *fn_ref, *fn_app;
646  Bmarker *mark_ref, *mark_app;
647 
648 // double angle = mg_ref->rot_angle - mg_apply->rot_angle;
649 // double cos_ang = cos(angle), sin_ang = sin(angle);
650 // Vector3<float> shift = mg_ref->origin - mg_apply->origin;
651 // Vector3<float> scale = mg_ref->scale / mg_apply->scale;
652 
653  double angle = mg_apply->rot_angle - mg_ref->rot_angle;
654  double cos_ang = cos(angle), sin_ang = sin(angle);
655  Vector3<double> shift = mg_apply->origin - mg_ref->origin;
656  Vector3<double> scale = mg_apply->scale / mg_ref->scale;
657  Vector3<double> loc;
658 
659 // if ( npref < 1 ) {
660 // cerr << "Warning: No particle coordinates for reference micrograph " << mg_ref->id << endl;
661 // return 0;
662 // }
663 
664  if ( verbose & VERB_PROCESS ) {
665  cout << "Applying transform parameters to micrographs:" << endl;
666  cout << "Reference micrograph: " << mg_ref->id << endl;
667  cout << "Transform micrograph: " << mg_apply->id << endl;
668  cout << "Shift: " << shift << endl;
669  cout << "Scale: " << scale << endl;
670  cout << "Rotation angle: " << angle*180.0/M_PI << endl << endl;
671  } else if ( verbose & VERB_LABEL )
672  cout << "Applying transform parameters to micrographs" << endl << endl;
673 
674  mg_apply->box_size = mg_ref->box_size;
675  mg_apply->bad_radius = mg_ref->bad_radius;
676  mg_apply->filament_width = mg_ref->filament_width;
677  mg_apply->fil_node_radius = mg_ref->fil_node_radius;
678  mg_apply->mark_radius = mg_ref->mark_radius;
679 
680  if ( npapp != npref ) {
681  particle_kill(mg_apply->part);
682  mg_apply->part = part_app = NULL;
683  for ( part_ref=mg_ref->part; part_ref; part_ref=part_ref->next ) {
684  part_app = particle_add(&part_app, part_ref->id);
685  if ( !mg_apply->part ) mg_apply->part = part_app;
686  }
687  }
688 
689  if ( mg_ref->part ) {
690  for ( part_ref=mg_ref->part, part_app=mg_apply->part; part_ref;
691  part_ref=part_ref->next, part_app=part_app->next ) {
692  part_app->id = part_ref->id;
693  loc = scale*(part_ref->loc + shift);
694  part_app->loc[0] = loc[0] * cos_ang - loc[1] * sin_ang;
695  part_app->loc[1] = loc[0] * sin_ang + loc[1] * cos_ang;
696  }
697  }
698 
699  if ( mg_apply->bad ) {
700  kill_list((char *) mg_apply->bad, sizeof(Bbadarea));
701  mg_apply->bad = NULL;
702  }
703 
704  if ( mg_ref->bad ) {
705  for ( bad_ref=mg_ref->bad; bad_ref; bad_ref=bad_ref->next ) {
706  bad_app = (Bbadarea *) add_item((char **) &mg_apply->bad, sizeof(Bbadarea));
707  loc = scale*(bad_ref->loc + shift);
708  bad_app->loc[0] = loc[0] * cos_ang - loc[1] * sin_ang;
709  bad_app->loc[1] = loc[0] * sin_ang + loc[1] * cos_ang;
710  }
711  }
712 
713  if ( nfapp != nfref ) {
714  filament_kill(mg_apply->fil);
715  mg_apply->fil = fil_app = NULL;
716  for ( fil_ref=mg_ref->fil; fil_ref; fil_ref=fil_ref->next ) {
717  fil_app = filament_add(&fil_app, fil_ref->id);
718  if ( !mg_apply->fil ) mg_apply->fil = fil_app;
719  fil_app->node = fn_app = NULL;
720  for ( fn_ref = fil_ref->node; fn_ref; fn_ref = fn_ref->next ) {
721  fn_app = filament_node_add(&fn_app, fn_ref->id);
722  if ( !fil_app->node ) fil_app->node = fn_app;
723  }
724  }
725  }
726 
727  if ( mg_ref->fil ) {
728  for ( fil_ref=mg_ref->fil, fil_app=mg_apply->fil; fil_ref;
729  fil_ref=fil_ref->next, fil_app=fil_app->next ) {
730  fil_app->id = fil_ref->id;
731  for ( fn_ref=fil_ref->node, fn_app=fil_app->node; fn_ref;
732  fn_ref=fn_ref->next, fn_app=fn_app->next ) {
733  fn_app->id = fn_ref->id;
734  loc = scale*(fn_ref->loc + shift);
735  fn_app->loc[0] = loc[0] * cos_ang - loc[1] * sin_ang;
736  fn_app->loc[1] = loc[0] * sin_ang + loc[1] * cos_ang;
737  }
738  }
739  }
740 
741  if ( mg_apply->mark ) {
742  kill_list((char *) mg_apply->mark, sizeof(Bmarker));
743  mg_apply->mark = NULL;
744  }
745 
746  if ( mg_ref->mark ) {
747  for ( mark_ref=mg_ref->mark; mark_ref; mark_ref=mark_ref->next ) {
748  mark_app = (Bmarker *) add_item((char **) &mg_apply->mark, sizeof(Bmarker));
749  loc = scale*(mark_ref->loc + shift);
750  mark_app->loc[0] = loc[0] * cos_ang - loc[1] * sin_ang;
751  mark_app->loc[1] = loc[0] * sin_ang + loc[1] * cos_ang;
752  mark_app->sel = mark_ref->sel;
753  mark_app->fom = mark_ref->fom;
754  }
755  }
756 
757  return 0;
758 }
759 
766 int mg_merge_focal_series(Bproject* project, int use_old_origins)
767 {
768  int i, ifield(0);
769  double cc;
770 
771  Bimage* p = NULL; // Particle image
772  Bimage* pt = NULL; // Temporary image
773  Bimage* pref = NULL; // Particle reference image
774  Bimage* ptr = NULL; // Temporary reference image
775  Bimage* psum = NULL; // Particle sum image
776 
777 // Vector3<float>* shift = NULL; // Shift vectors
778 // Vector3<float>* origin = NULL; // Origin vectors
779 
780  Bfield* field;
781  Bmicrograph *mg, *mg2, *mg_ref;
782  Bparticle *part, *part_ref;
783  Bstring filename;
784  Bstring insert("_merged.");
785  Vector3<double> origin, scale(1,1,1), axis(0,0,1), shift;
786  Matrix3 mat;
787 
788  for ( ifield = 0, field=project->field; field; field=field->next, ifield++ ) {
789  // Find the closest-to-focus particle image
790  for ( mg_ref = mg = field->mg; mg; mg = mg->next )
791  if ( mg_ref->ctf && mg->ctf )
792  if ( mg_ref->ctf->defocus_average() < mg->ctf->defocus_average() ) mg_ref = mg;
793  pref = read_img(mg_ref->fpart, 1, -1);
794  if ( !pref )
795  return error_show("Error in mg_merge_focal_series", __FILE__, __LINE__);
796  pref->origin(pref->size()/2);
797  pref->change_type(Float);
798  psum = pref->copy();
799  for ( mg = field->mg; mg; mg = mg->next ) if ( mg != mg_ref ) {
800  p = read_img(mg->fpart, 1, -1);
801  if ( !p )
802  return error_show("Error in mg_merge_focal_series", __FILE__, __LINE__);
803  p->origin(p->size()/2);
804  p->change_type(Float);
805 /* origin = new Vector3<float>[p->images()];
806  if ( use_old_origins ) {
807  shift = new Vector3<float>[p->images()];
808  for ( i=0, part = mg->part, part_ref = mg_ref->part; part;
809  i++, part = part->next, part_ref = part_ref->next ) {
810  shift[i] = part_ref->ori - part->ori;
811  origin[i] = part->ori;
812  }
813  } else {
814 // shift = img_find_shift(pref, p, NULL, p->sampling()[0]*2, 1e10, p->sizeX()/4.0, 0, 1, NULL);
815 // for ( i=0, part = mg->part; part; i++, part = part->next )
816 // origin[i] = mg->origin - shift[i];
817  p->find_shift(pref, NULL, p->sampling()[0]*2, 1e10, p->sizeX()/4.0, 0, 1);
818  for ( i=0, part = mg->part; part; i++, part = part->next )
819  origin[i] = mg->origin + pref->image[i].origin() - p->image[i].origin();
820  }
821  img_unique_shift_global_rotate(p, shift, origin, mg->rot_angle - mg_ref->rot_angle);
822  delete[] shift;
823  delete[] origin;
824 // img_add(psum, p, 1, 0);
825 */
826  mat = Matrix3(axis, mg->rot_angle - mg_ref->rot_angle);
827  for ( i=0, part = mg->part, part_ref = mg_ref->part; part;
828  i++, part = part->next, part_ref = part_ref->next ) {
829  pt = p->extract(i);
830  if ( use_old_origins ) {
831  shift = part_ref->ori - part->ori;
832  origin = part->ori;
833  } else {
834  ptr = pref->extract(i);
835  shift = pt->find_shift(ptr, NULL, ptr->sampling(0)[0]*2, 1e10, ptr->sizeX()/4.0, 0, 1, cc);
836  origin = ptr->image->origin() - shift;
837  delete ptr;
838  }
839  pt->transform(scale, origin, shift, mat, FILL_BACKGROUND, 0);
840  p->replace(i, pt);
841  }
842  psum->add(p);
843  delete p;
844  }
845  delete pref;
846  filename = mg_ref->fpart;
847  filename = filename.pre_rev('.') + insert + filename.post_rev('.');
848  if ( verbose & VERB_DEBUG )
849  cout << "DEBUG mg_merge_focal_series: mg=" << mg_ref->id << " filename=" << filename << endl;
850  write_img(filename, psum, 0);
851  delete psum;
852  for ( mg = field->mg; mg; ) {
853  mg2 = mg->next;
854  if ( mg != mg_ref ) micrograph_kill(mg);
855  mg = mg2;
856  }
857  field->mg = mg_ref;
858  mg_ref->next = NULL;
859  mg_ref->block = ifield;
860  mg_ref->fpart = filename;
861  }
862 
863  return 0;
864 }
865 
867  Bstring& imgfile, DataType datatype, Bstring& subset)
868 {
869  long i, n;
870  Bmicrograph* mg;
871  Vector3<double> ori;
872  Bimage* p;
873  Bimage* pavg = NULL;
874  Bimage* pstd = NULL;
875  Vector3<double> scale(1,1,1);
876  Matrix3 mat(1);
877  Vector3<double> nori;
878 
879  for ( n=0, mg = field->mg; mg; mg = mg->next, n++ ) ;
880 // int* numsel = new int[n];
881 // select_numbers(subset, n, numsel);
882  vector<int> numsel = select_numbers(subset, n);
883 
884  for ( i=n=0, mg = field->mg; mg; mg = mg->next, i++ ) if ( numsel[i] ){
885  p = read_img(mg->fmg, 1, mg->img_num);
886  if ( datatype == Unknown_Type ) datatype = p->data_type();
887  if ( datatype > p->data_type() ) p->change_type(datatype);
888  if ( pgr ) p->multiply(pgr);
890  ori = p->size()/2;
891  p->transform(scale, nori, (ori - mg->origin), mat, FILL_BACKGROUND, 0);
892  p->change_type(datatype);
893  if ( !pavg ) pavg = p->copy();
894  else pavg->add(p);
895  p->square();
896  if ( !pstd ) pstd = p->copy();
897  else pstd->add(p);
898  delete p;
899  n++;
900  }
901 
902 // delete[] numsel;
903 
904  if ( n ) {
905  pavg->multiply(1.0L/n);
906  pstd->multiply(1.0L/n);
907  } else {
908  field->select = 0;
909  return -1;
910  }
911 
912  double snr = pavg->standard_deviation()*pavg->standard_deviation();
913 
914  mg = field->mg;
915  micrograph_kill(mg->next);
916  mg->next = NULL;
917 
918  View view = View(mg->matrix);
919  pavg->image->origin(ori);
920  pavg->image->view(view);
921  if ( mg->pixel_size[0] ) pavg->sampling(mg->pixel_size);
922 
923  if ( imgfile.length() && pavg ) {
924  write_img(imgfile, pavg, 0);
925  mg->fmg = imgfile;
926  mg->img_num = 0;
927  }
928 
929  pavg->square();
930  pstd->subtract(pavg);
931  snr /= pstd->average();
932 
933  delete pavg;
934  delete pstd;
935 
936  field->fom = snr;
937 
938  return snr;
939 }
940 
953  Bstring& imgfile, DataType datatype)
954 {
955  long i, nmg;
956  Bfield* field = project->field;
957  Bmicrograph* mg = field->mg;
958  Bimage* p, *pone, *paln;
959  Vector3<double> origin;
960  Vector3<double> scale(1,1,1);
961  Matrix3 mat(1);
962  Vector3<double> nori;
963  View view;
964 
965  for ( field = project->field; field; field = field->next ) {
966  for ( nmg=0, mg = field->mg; mg; mg = mg->next ) nmg++;
967  mg = field->mg;
968  p = read_img(mg->fmg, 0, -1);
969  if ( datatype == Unknown_Type ) datatype = p->data_type();
970  paln = new Bimage(datatype, p->compound_type(), p->sizeX(), p->sizeY(), 1, nmg);
971  if ( p->sizeZ() > 1 || p->images() > 1 ) {
972  delete p;
973  p = read_img(mg->fmg, 1, -1);
974  if ( p->sizeZ() > 1 ) p->slices_to_images();
975  } else {
976  delete p;
977  p = NULL;
978  }
979  if ( pgr ) p->multiply(pgr);
980  if ( project->field->next )
981  imgfile = mg->fmg.pre_rev('.') + "_aln." + mg->fmg.post_rev('.');
982  for ( i=0, mg = field->mg; mg; mg = mg->next, i++ ) {
983  view = View(mg->matrix);
984  if ( p ) pone = p->extract(i);
985  else pone = read_img(mg->fmg, 1, mg->img_num);
986  if ( datatype > pone->data_type() ) pone->change_type(datatype);
987  origin = pone->size()/2;
988  if ( origin != mg->origin ) {
989  pone->calculate_background();
990  pone->transform(scale, nori, (origin - mg->origin), mat, FILL_BACKGROUND, 0);
991  }
992  pone->change_type(datatype);
993  paln->replace(i, pone);
994  paln->image[i].origin(origin);
995  paln->image[i].view(view);
996  if ( mg->pixel_size[0] ) paln->sampling(mg->pixel_size);
997  if ( imgfile.length() ) {
998  mg->fmg = imgfile;
999  mg->img_num = i;
1000  mg->origin = origin;
1001  }
1002  delete pone;
1003  }
1004  if ( imgfile.length() && paln )
1005  write_img(imgfile, paln, 0);
1006  delete paln;
1007  }
1008 
1009  return 0;
1010 }
1011 
1025  Bstring& imgfile, DataType datatype, Bstring& subset)
1026 {
1027  Bfield* field = project->field;
1028  long n, nfield(0);
1029  double snr_avg(0);
1030 
1031  if ( verbose & VERB_RESULT ) {
1032  cout << "Writing micrograph average to " << imgfile << endl;
1033  if ( subset.length() )
1034  cout << "Subset: " << subset << endl;
1035  }
1036 
1037  Bstring path;
1038  if ( imgfile.contains("/") ) path = imgfile.pre_rev('/') + "/";
1039 
1040  for ( field = project->field; field; field = field->next ) nfield++;
1041 
1042  Bfield** farr = new Bfield*[nfield];
1043  for ( n=0, field = project->field; field; field = field->next, n++ )
1044  farr[n] = field;
1045 
1046 #ifdef HAVE_GCD
1047  dispatch_apply(nfield, dispatch_get_global_queue(0, 0), ^(size_t i){
1048  Bmicrograph* mg = farr[i]->mg;
1049  Bstring newname(imgfile);
1050  if ( project->field->next ) {
1051  newname = mg->fmg.pre_rev('.') + "_avg." + mg->fmg.post_rev('.');
1052  if ( path.length() ) newname = path + newname.post_rev('/');
1053  }
1054  field_write_aligned_average(farr[i], pgr, newname, datatype, subset);
1055  });
1056 #else
1057 #pragma omp parallel for
1058  for ( long i=0; i<nfield; i++ ) {
1059  Bmicrograph* mg = farr[i]->mg;
1060  Bstring newname(imgfile);
1061  if ( project->field->next ) {
1062  newname = mg->fmg.pre_rev('.') + "_avg." + mg->fmg.post_rev('.');
1063  if ( path.length() ) newname = path + newname.post_rev('/');
1064  }
1065  field_write_aligned_average(farr[i], pgr, newname, datatype, subset);
1066  }
1067 #endif
1068 
1069  delete[] farr;
1070 
1071  if ( verbose & VERB_RESULT )
1072  cout << "Field\tSNR" << endl;
1073 
1074  for ( n=0, field = project->field; field; field = field->next ) {
1075  snr_avg += field->fom;
1076  n++;
1077  if ( verbose & VERB_RESULT )
1078  cout << field->id << tab << field->fom << endl;
1079  }
1080 
1081  if ( n ) snr_avg /= n;
1082 
1083  return snr_avg;
1084 }
1085 double mg_align_frames(Bmicrograph* mg, int ref_num, Bimage* pgr,
1086  Bimage* pmask, double hi_res, double lo_res,
1087  double shift_limit, double edge_width, double gauss_width,
1088  Vector3<long> bin, JSvalue& dose_frac, Bstring& subset, int flag)
1089 {
1090  Bimage* p = read_img(mg->fframe, 1, -1);
1091 
1092  p->sampling(mg->pixel_size);
1093 
1094  if ( p->sizeZ() > 1 ) p->slices_to_images();
1095 
1096  if ( p->images() < 2 ) {
1097  delete p;
1098  return 0;
1099  }
1100 
1101  double exposure(0), dose_per_frame(0);
1102  if ( dose_frac.exists("exposure") )
1103  exposure = dose_frac["exposure"].real();
1104  else if ( dose_frac.exists("frame_rate") )
1105  exposure = p->images()/dose_frac["frame_rate"].real();
1106 
1107  if ( dose_frac.exists("dose_per_frame") )
1108  dose_per_frame = dose_frac["dose_per_frame"].real();
1109 
1110  if ( pgr ) {
1111  if ( verbose )
1112  cout << "Multiplying with " << pgr->file_name() << endl;
1113  p->multiply(pgr);
1114  }
1115 
1116  if ( verbose )
1117  cout << "Aligning frames from micrograph " << mg->id << endl;
1118 
1119  if ( flag & 1 ) p->histogram_counts(2);
1120 
1121  if ( flag & 2 ) p->fspace_weigh_dose(dose_per_frame, 1);
1122 
1123 // write_img("pw.mrc", p, 0);
1124 
1125  if ( bin.volume() > 1 ) {
1126  p->bin(bin);
1127  mg->pixel_size = p->image->sampling();
1128  }
1129 
1130  Vector3<long> aln_bin(1,1,1);
1131  if ( hi_res > 3*p->image->sampling()[0] ) bin = Vector3<long>(2,2,1);
1132 
1133  JSvalue job = p->align(ref_num, pmask, hi_res, lo_res, shift_limit,
1134  edge_width, gauss_width, aln_bin);
1135 // JSvalue job = p->align_fast(ref_num, pmask, hi_res, lo_res, shift_limit,
1136 // edge_width, gauss_width);
1137 
1138  mg->fom = job["FOM"].real();
1139  double shift(job["shift_average"].real()*mg->pixel_size[0]);
1140  JSvalue sh = job["shifts"];
1141  Bframe* frame = NULL;
1142 
1143  mg->frame = NULL;
1144  mg->dose = 0;
1145  mg->intensity = 0;
1146  for ( long i = 0; i<p->images(); ++i ) {
1147  frame = frame_add(&mg->frame, i+1);
1148  frame->shift[0] = sh[i][0].real();
1149  frame->shift[1] = sh[i][1].real();
1150  frame->fom = sh[i][2].real();
1151  mg->dose += dose_per_frame;
1152  mg->intensity += p->image[i].average();
1153  }
1154 
1155  if ( verbose ) {
1156  cout << "Average shift per frame: " << shift << " A" << endl;
1157  if ( exposure )
1158  cout << "Average shift rate: " <<
1159  (shift/exposure)*p->images() << " A/s" << endl << endl;
1160  cout << job << endl;
1161  }
1162 
1163  Bstring ext = mg->fframe.extension();
1164  if ( ext.contains("dm") ) ext = "mrc";
1165  if ( ext.contains("tif") ) ext = "mrc";
1166 
1167  if ( flag & 4 ) {
1168  mg->fframe = mg->fframe.pre_rev('.') + "_aln." + ext;
1169  if ( verbose )
1170  cout << "Writing aligned frames: " << mg->fframe << endl;
1171  (*p)["dose"] = mg->dose;
1172  write_img(mg->fframe, p, 0);
1173  }
1174 
1175  if ( flag & 8 ) {
1176  Bimage* p1 = img_sum_subset(p, subset, dose_per_frame);
1177  mg->fmg = mg->fframe.pre_rev('.') + "_sum." + ext;
1178  mg->origin = p1->size()/2;
1179  p1->origin(mg->origin);
1180  mg->intensity = p1->average();
1181  mg->dose = (*p1)["dose"].real();
1182  if ( verbose )
1183  cout << "Writing aligned frame sum: " << mg->fmg << endl;
1184  write_img(mg->fmg, p1, 0);
1185  delete p1;
1186  }
1187 
1188  delete p;
1189 
1190  return mg->fom;
1191 }
1192 
1220 double project_align_frames(Bproject* project, int ref_img, Bimage* pgr,
1221  Bimage* pmask, Vector3<double> origin, double hi_res, double lo_res,
1222  double shift_limit, double edge_width, double gauss_width,
1223  Vector3<long> bin, JSvalue& dose_frac, Bstring& subset, int flag)
1224 {
1225  bin[2] = 1;
1226 
1227  Bfield* field = project->field;
1228  Bmicrograph* mg;
1229  long nmg = project_count_micrographs(project);
1230  double d(0);
1231 
1232 // if ( verbose & ( VERB_LABEL | VERB_PROCESS ) ) {
1233  if ( verbose ) {
1234  cout << "Aligning micrograph frames by cross-correlation:" << endl;
1235  cout << "Number of micrographs: " << nmg << endl;
1236  cout << "Reference frame: " << ref_img << endl;
1237  cout << "Resolution limits: " << hi_res << " - " << lo_res << " A" << endl;
1238  cout << "Shift limit: " << shift_limit << endl;
1239  cout << "Edge masking width & smoothing: " << edge_width << " " << gauss_width << endl;
1240  cout << "Binning: " << bin << endl;
1241  if ( pgr )
1242  cout << "Gain reference file: " << pgr->file_name() << endl;
1243  if ( pmask )
1244  cout << "Using mask file: " << pmask->file_name() << endl;
1245  if ( dose_frac.exists("exposure") )
1246  cout << "Exposure time: " << dose_frac["exposure"].real() << " s" << endl;
1247  if ( dose_frac.exists("frame_rate") )
1248  cout << "Frame rate: " << dose_frac["frame_rate"].real() << " frames/s" << endl;
1249  cout << endl;
1250  }
1251 
1252  for ( nmg=0, field = project->field; field; field = field->next ) {
1253  for ( mg = field->mg; mg; mg = mg->next, nmg++ ) {
1254  mg_align_frames(mg, ref_img, pgr, pmask, hi_res, lo_res, shift_limit,
1255  edge_width, gauss_width, bin, dose_frac, subset, flag);
1256  d += mg->fom;
1257  }
1258  }
1259 
1260  d /= nmg;
1261 
1262  if ( verbose & VERB_RESULT )
1263  cout << "Overall average shift per frame: " << d << endl << endl;
1264 
1265  return d;
1266 }
1267 
1268 
1269 double mg_align_series(Bmicrograph* mg, Bmicrograph* mg_ref, Bimage* pref,
1270  Bimage* pgr, Bimage* pmask, double hi_res, double lo_res, double shift_limit,
1271  double edge_width, double gauss_width,
1273 {
1274  if ( mg == mg_ref ) return 0;
1275 
1276  long bv(bin[0]*bin[1]*bin[2]);
1277  double cc(0);
1278  Vector3<long> obin(bin[0], bin[1], bin[2]);
1279  Vector3<double> edge_origin(edge_width, edge_width, 0), shift;
1280  Vector3<long> edge_size = pref->size() - (long) (2*edge_width);
1281  edge_size = edge_size.max(1);
1282 
1283  Bimage* p = read_img(mg->fmg, 1, mg->img_num);
1284 
1285  if ( pgr ) p->multiply(pgr);
1286 
1287  p->calculate_background();
1288 
1289  if ( edge_width > 0 )
1290  p->shape(0, edge_size, edge_origin, gauss_width, FILL_BACKGROUND, 0);
1291 
1292  p->origin(mg_ref->origin);
1293  mg->pixel_size = mg_ref->pixel_size;
1294  p->sampling(pref->sampling(0));
1295 
1296  if ( bv > 1 ) p->bin(bin);
1297 
1298  shift = p->find_shift(pref, pmask, hi_res, lo_res, shift_limit, 0, 1, planf, planb, cc);
1299  if ( bv > 1 ) shift *= obin;
1300 
1301  mg->origin = mg_ref->origin + shift;
1302  mg->fom = cc;
1303 
1304  delete p;
1305 
1306  mg->scale = Vector3<float>(1,1,1);
1307  mg->matrix = Matrix3(1);
1308  mg_apply_transform(mg_ref, mg);
1309 
1310  return mg->fom;
1311 }
1312 
1313 double field_align_series(Bfield* field, int ref_img, Bimage* pgr, Bimage* pmask,
1314  Vector3<double> origin, double hi_res, double lo_res,
1315  double shift_limit, double edge_width, double gauss_width,
1316  Vector3<long> bin, Bstring& subset, int flag)
1317 {
1318  long i, j, nmg, nsel(0);
1319  Bmicrograph* mg, *mg_ref;
1320 
1321  for ( i=0, mg_ref = field->mg; mg_ref && ( i<ref_img ); mg_ref = mg_ref->next, i++ ) ;
1322  if ( !mg_ref ) {
1323  mg_ref = field->mg;
1324  ref_img = 0;
1325  }
1326 
1327  for ( nmg=0, mg = field->mg; mg; mg = mg->next ) nmg++;
1328 // int* numsel = new int[nmg];
1329 // select_numbers(subset, nmg, numsel);
1330  vector<int> numsel = select_numbers(subset, nmg);
1331 
1332  for ( i=nsel=0; i<nmg; i++ ) if ( numsel[i] ) nsel++;
1333 
1334  Bmicrograph** mg_arr = new Bmicrograph*[nsel];
1335 
1336  for ( i=j=0, mg = field->mg; mg; mg = mg->next, i++ )
1337  if ( numsel[i] ) mg_arr[j++] = mg;
1338 
1339  Bimage* pref = read_img(mg_ref->fmg, 1, mg_ref->img_num);
1340  if ( origin.length() < 1 ) origin = pref->size()/2;
1341  pref->origin(origin);
1342  mg_ref->origin = origin;
1343  if ( !mg_ref->pixel_size[0] ) mg_ref->pixel_size = pref->sampling(0);
1344  pref->sampling(mg_ref->pixel_size);
1345 
1346  Vector3<double> edge_origin(edge_width, edge_width, 0);
1347  Vector3<long> edge_size = pref->size() - (long) (2*edge_width);
1348  edge_size = edge_size.max(1);
1349 
1350  pref->calculate_background();
1351 
1352  if ( edge_width > 0 )
1353  pref->edge(0, edge_size, edge_origin, gauss_width, FILL_BACKGROUND);
1354 
1355  if ( bin[0]*bin[1]*bin[2] > 1 ) pref->bin(bin);
1356 
1357  if ( shift_limit < 0 ) shift_limit = pref->sizeX()/10;
1358 
1359  if ( verbose & VERB_RESULT )
1360  cout << "Field " << field->id << endl << "Micrograph\tdx\tdy\tdz\tCC" << endl;
1361 
1362  fft_plan planf = pref->fft_setup(FFTW_FORWARD, 0);
1363  fft_plan planb = pref->fft_setup(FFTW_BACKWARD, 0);
1364 
1365 #ifdef HAVE_GCD
1366  dispatch_apply(nsel, dispatch_get_global_queue(0, 0), ^(size_t i){
1367  mg_align_series(mg_arr[i], mg_ref, pref, pgr, pmask, hi_res, lo_res,
1368  shift_limit, edge_width, gauss_width, bin, planf, planb);
1369  });
1370 #else
1371 #pragma omp parallel for
1372  for ( long i=0; i<nsel; i++ )
1373  mg_align_series(mg_arr[i], mg_ref, pref, pgr, pmask, hi_res, lo_res,
1374  shift_limit, edge_width, gauss_width, bin, planf, planb);
1375 #endif
1376 
1379 
1380  delete[] mg_arr;
1381  delete pref;
1382 
1383  double d, da(0);
1384 
1385  for ( nsel=i=0, mg = field->mg; mg; mg = mg->next, i++ ) if ( numsel[i] ) {
1386  if ( verbose & VERB_RESULT )
1387  cout << mg->id << tab <<
1388  mg->origin - mg_ref->origin << tab <<
1389  mg->fom << endl;
1390  if ( mg != mg_ref ) {
1391  d = mg->origin.distance(mg_ref->origin)/(fabs(i-ref_img));
1392  da += d;
1393  nsel++;
1394  }
1395  }
1396 
1397  if ( nsel ) da /= nsel;
1398 
1399  if ( verbose & VERB_RESULT )
1400  cout << "Average shift per micrograph: " << da << endl;
1401 
1402 // delete[] numsel;
1403 
1404  field->fom = da;
1405 
1406  Bstring ext = mg->fmg.extension();
1407  if ( ext.contains("dm") ) ext = "mrc";
1408  if ( ext.contains("tif") ) ext = "mrc";
1409 
1410  if ( flag & 4 ) {
1411  DataType dt(Float);
1412  Bstring label("Written by bseries");
1413  Bstring favg = field->mg->fmg.pre_rev('.') + "_avg." + ext;
1414  field_write_aligned_average(field, pgr, mg->fmg, dt, subset);
1415  }
1416 
1417  return da;
1418 }
1419 
1446 double project_align_series(Bproject* project, int ref_img, Bimage* pgr,
1447  Bimage* pmask, Vector3<double> origin, double hi_res, double lo_res,
1448  double shift_limit, double edge_width, double gauss_width,
1449  Vector3<long> bin, Bstring& subset, int flag)
1450 {
1451  Bfield* field = project->field;
1452  long nfield(0);
1453  long nmg = project_count_micrographs(project);
1454 
1455  for ( field = project->field; field; field = field->next ) nfield++;
1456 
1457 
1458 // if ( verbose & ( VERB_LABEL | VERB_PROCESS ) ) {
1459  if ( verbose ) {
1460  cout << "Aligning micrographs in series by cross-correlation:" << endl;
1461  cout << "Number of images: " << nmg << endl;
1462  cout << "Resolution limits: " << hi_res << " - " << lo_res << " A" << endl;
1463  cout << "Shift limit: " << shift_limit << endl;
1464  cout << "Edge masking width & smoothing: " << edge_width << " " << gauss_width << endl;
1465  cout << "Binning: " << bin << endl;
1466  if ( pmask )
1467  cout << "Using mask file: " << pmask->file_name() << endl;
1468  if ( subset.length() )
1469  cout << "Subset: " << subset << endl;
1470  cout << endl;
1471  }
1472 
1473  double d(0);
1474  for ( field = project->field; field; field = field->next ) {
1475  field_align_series(field, ref_img, pgr, pmask, origin, hi_res, lo_res,
1476  shift_limit, edge_width, gauss_width, bin, subset, flag);
1477  d += field->fom;
1478  }
1479 
1480  d /= nfield;
1481 
1482  if ( verbose & VERB_RESULT )
1483  cout << "Overall average shift per frame: " << d << endl << endl;
1484 
1485  return d;
1486 }
1487 
1488 Bimage* mg_tomo_reconstruct(Bmicrograph** mgarr, long mg_id, long mg_min, long mg_max,
1489  double hi_res, double scale, Vector3<long> size,
1490  long ft_size, fft_plan planf, fft_plan planb)
1491 {
1492  long i;
1493  Bimage* p = NULL;
1494 
1495  Bmicrograph* mg_res = mgarr[mg_id];
1496  Bmicrograph* mg;
1497 
1498  if ( !mg_res ) {
1499  error_show("Error in mg_tomo_reconstruct", __FILE__, __LINE__);
1500  cerr << "Micrograph number " << mg_id << " not found!" << endl << endl;
1501  return NULL;
1502  }
1503 
1504  if ( !mg_res->select ) {
1505  if ( verbose & VERB_FULL )
1506  cout << "Skipping micrograph number " << mg_id << endl << endl;
1507  return NULL;
1508  }
1509 
1510  if ( mg_max < mg_min || ( mg_max == mg_id && mg_min == mg_id ) ) {
1511  error_show("Error in mg_tomo_reconstruct", __FILE__, __LINE__);
1512  cerr << "Micrograph range is incorrect: " << mg_min << " - " << mg_max << endl << endl;
1513  return NULL;
1514  }
1515 
1516  if ( mg_res->fmg.length() < 0 ) {
1517  error_show("Error in mg_tomo_reconstruct", __FILE__, __LINE__);
1518  cerr << "No micrograph image file name given for micrograph " << mg_res->id << endl;
1519  return NULL;
1520  }
1521 
1522  if ( hi_res < 2*mg_res->pixel_size[0] ) hi_res = 2*mg_res->pixel_size[0];
1523 
1524  if ( verbose & VERB_DEBUG )
1525  cout << "DEBUG mg_tomo_reconstruct: size=" << size << " ft_size=" << ft_size << endl;
1526 
1527  // Header structure for the final reconstruction
1528  Bimage* prec = new Bimage(Float, TComplex, size[0], size[1], 1, 1);
1529  prec->sampling(mg_res->pixel_size);
1530  prec->origin(prec->size()/2);
1531 
1532  prec->next = new Bimage(Float, TSimple, prec->size(), prec->images());
1533 
1534  long data_size = (long) prec->size().volume();
1535 
1536  long nrec(0), nmg(mg_max-mg_min), nover(0);
1537 // long interp_type(0), pad_factor(0);
1538 // double pad_ratio(ft_size*1.0/prec->sizeX());
1539  Vector3<long> translate;
1540 
1541  for ( i=mg_min; i<=mg_max; i++ ) if ( mgarr[i]->select && i != mg_id ) {
1542  mg = mgarr[i];
1543  if ( verbose & VERB_FULL )
1544  cout << "Reading image " << mg->img_num << " (micrograph " << mg->id << ")" << endl;
1545  if ( ( p = read_img(mg->fmg, 1, mg->img_num) ) == NULL ) {
1546  error_show("mg_tomo_reconstruct", __FILE__, __LINE__);
1547  return NULL;
1548  }
1549 
1550  p->change_type(Float);
1551  p->image->origin(mg->origin[0], mg->origin[1], 0);
1552  p->sampling(mg->pixel_size);
1553  p->statistics();
1554 // p->rescale_to_avg_std(0,1);
1555  p->resize(prec->size(), translate, FILL_AVERAGE, 0);
1556 
1557 
1558  p->fft(planf);
1559  p->phase_shift_to_origin();
1560 
1561  nover += prec->fspace_pack_2D_into_central_section(p, ft_size, 1, hi_res, 0, mg_res->matrix, mg->matrix);
1562 
1563  delete p;
1564 
1565  nrec++;
1566 
1567  if ( verbose & ( VERB_TIME | VERB_PROCESS ) )
1568  cout << "Complete: " << nrec*100.0/nmg << "%\r" << flush;
1569 
1570  }
1571 
1572  if ( nrec < 1 ) {
1573  delete prec;
1574  error_show("Error in mg_tomo_reconstruct: No micrographs used in this reconstruction!", __FILE__, __LINE__);
1575  return NULL;
1576  }
1577 
1578  float* fom = (float *) prec->next->data_pointer();
1579 
1580  if ( verbose & VERB_FULL ) {
1581  cout << "Contributions: " << nover << " (" << nover*100.0/data_size << "%)" << endl;
1582  cout << "Weighing reconstruction. " << endl;
1583  }
1584 
1585  for ( i=0; i<data_size; i++ ) {
1586  if ( fom[i] ) prec->set(i, prec->complex(i) / fom[i]);
1587  fom[i] = fom[i]/(fom[i] + 1);
1588  }
1589 
1590  prec->set(0, 0);
1591  prec->origin(0, 0, 0);
1592  prec->phase_shift_to_center();
1593  prec->fft_back(planb);
1594  prec->statistics();
1595 
1596  return prec;
1597 }
1598 
1610  Vector3<long> size, double scale, double hi_res)
1611 {
1612  if ( scale < 0.1 ) scale = 1;
1613 
1614  long i, nmg(0);
1615 
1618 
1619  if ( hi_res < 2*mg0->pixel_size[0] )
1620  hi_res = 4*mg0->pixel_size[0];
1621 
1622  if ( dimg < 1 ) {
1623  for ( i=0; i<nmg; ++i )
1624  if ( fabs(mgarr[i]->tilt_angle) <= 15*M_PI/180.0 )
1625  break;
1626  dimg = abs(mg0->img_num - mgarr[i]->img_num);
1627  }
1628 
1629  Bimage* p = read_img(mg0->fmg, 0, mg0->img_num);
1630  if ( size.volume() < 1 ) size = p->size()/scale;
1631  size[2] = 1;
1632 
1633  long ft_size = p->sizeX();
1634  if ( ft_size < p->sizeY() ) ft_size = p->sizeY();
1635  ft_size = findNextPowerOf(ft_size, 2);
1636 
1637  delete p;
1638 
1639  if ( verbose ) {
1640  cout << "Reconstructing a 2D image:" << endl;
1641  cout << "Fourier transform size: " << ft_size << " x " << ft_size << endl;
1642  cout << "Reconstruction size: " << size << endl;
1643  cout << "Reconstruction scale: " << scale << endl;
1644  cout << "Number of adjacent images: " << dimg << endl;
1645  cout << "Resolution limit: " << hi_res << " A" << endl;
1646  cout << endl;
1647  }
1648 
1649  fft_plan planf = fft_setup_plan(ft_size, ft_size, 1, FFTW_FORWARD, 1);
1650  fft_plan planb = fft_setup_plan(ft_size, ft_size, 1, FFTW_BACKWARD, 1);
1651 
1652  Bimage* prec = mg_tomo_reconstruct(mgarr, mg0->img_num,
1653  mg0->img_num - dimg, mg0->img_num + dimg,
1654  hi_res, scale, size, ft_size, planf, planb);
1655 
1656  delete[] mgarr;
1659 
1660  return prec;
1661 }
1662 
1663 double mg_reconstruct_align(Bmicrograph** mgarr, long nmg,
1664  long mg_id, long dimg, double resolution, double shift_limit,
1665  Vector3<long> size, double edge_width, double gauss_width,
1666  long ft_size, fft_plan planf, fft_plan planb)
1667 {
1668  long imin, imax;
1669  double cc;
1670  Bmicrograph* mg_res = mgarr[mg_id];
1671 
1672  if ( shift_limit < 0 ) shift_limit = size[0]/4;
1673 
1674  for ( imin=(mg_id>dimg)? mg_id-dimg: 0; mgarr[imin]->fom < -0.5 && imin<=mg_id; imin++ ) ;
1675 
1676  for ( imax=(mg_id+dimg<nmg)? mg_id+dimg: nmg-1; mgarr[imax]->fom < -0.5 && imax>=mg_id; imax-- ) ;
1677 
1678 // cout << mg_id << ": " << imin << " - " << imax << endl;
1679 
1680  Bimage* prec = mg_tomo_reconstruct(mgarr, mg_id, imin, imax,
1681  resolution, 1, size, ft_size, planf, planb);
1682 
1683  if ( !prec ) {
1684  cerr << "Error: Reconstruction for " << mg_id << " failed!" << endl;
1685  bexit(-1);
1686  }
1687 
1688 // cout << "reconstruction origin = " << prec->image->origin() << endl;
1689 
1690 // cout << mg_id << ": " << imin << " - " << imax << endl;
1691 
1692 /*
1693  long k(14);
1694  Bstring name(k, "t%d.pif");
1695  if ( mg_id == k ) {
1696  cout << "writing " << name << endl;
1697  write_img(name, prec, 0);
1698  bexit(0);
1699  }
1700 */
1701  Bimage* p = read_img(mg_res->fmg, 1, mg_res->img_num);
1702 
1703  p->image->origin(p->size()/2);
1704  p->sampling(prec->sampling(0));
1705 
1706  Vector3<long> translate;
1707  Vector3<double> edge_origin(edge_width, edge_width, 0);
1708  Vector3<double> edge_size(p->sizeX() - (long)edge_width, p->sizeY() - (long)edge_width, 1);
1709  if ( edge_width > 0 ) {
1710  p->edge(0, edge_size, edge_origin, gauss_width, FILL_AVERAGE, 0);
1711  prec->edge(0, edge_size, edge_origin, gauss_width, FILL_AVERAGE, 0);
1712  }
1713 
1714  p->resize(prec->size(), translate, FILL_AVERAGE, 0);
1715 
1716  Vector3<double> shift = p->find_shift(prec, NULL, resolution, 0, shift_limit, 0, 1, planf, planb, cc);
1717 // cout << "origin = " << p->image->origin() << endl;
1718 // cout << "mg origin = " << mg_res->origin << endl;
1719 
1720  // Change in origin from previous one
1721  Vector3<double> oldori = mg_res->origin;
1722  mg_res->origin = prec->image->origin() + shift;
1723  mg_res->fom = cc;
1724  shift = mg_res->origin - oldori;
1725 
1726  if ( verbose )
1727  cout << mg_id << ": " << imin << " - " << imax << tab <<
1728  mg_res->origin << tab << shift << tab << mg_res->fom << endl;
1729 
1730 // Bstring fn = mg_res->fmg.pre_rev('.') + Bstring(mg_res->img_num, "_%03d.mrc");
1731 // write_img(fn, prec, 0);
1732 
1733  delete p;
1734  delete prec;
1735 
1736  return shift.length();
1737 }
1738 
1739 
1764 long project_tomo_align(Bproject* project, long thickness, long iter, double dchange,
1765  long dimg, double resolution, double shift_limit, double edge_width, double gauss_width)
1766 {
1768 
1769  if ( !mg0->fmg.length() ) {
1770  error_show("Error in project_tomo_align ", __FILE__, __LINE__);
1771  cerr << "No micrograph image or transform file name given for micrograph "
1772  << mg0->id << endl << endl;
1773  return -1;
1774  }
1775 
1776  Bimage* p = read_img(mg0->fmg, 0, mg0->img_num);
1777 
1778  long ft_size = p->sizeX();
1779  if ( ft_size < p->sizeY() ) ft_size = p->sizeY();
1780  ft_size = findNextPowerOf(ft_size, 2);
1781 
1782  if ( thickness < 10 ) thickness = ft_size/5;
1783 
1784  delete p;
1785 
1786  if ( resolution < 2*mg0->pixel_size[0] ) resolution = 4*mg0->pixel_size[0];
1787 
1788  long it, nmg(0), i, j, n, mg_id0(0);
1789  double dori(10);
1790  Vector3<long> size(ft_size,ft_size,thickness);
1791 
1792  if ( shift_limit < 0 ) shift_limit = ft_size/4;
1793 
1795  for ( i=0; i<nmg; i++ ) {
1796  mgarr[i]->fom = -1;
1797  if ( mg0 == mgarr[i] ) mg_id0 = i;
1798  }
1799  mg0->fom = 1;
1800 
1801 // ft_size = part_ft_size(size[0], 1, 2);
1802 
1803  if ( verbose ) {
1804  cout << "Aligning images in a tilt series by cross-correlation:" << endl;
1805  cout << "Maximum number of iterations: " << iter << endl;
1806  cout << "Number of images: " << nmg << endl;
1807  cout << "Fourier transform size: " << ft_size << " x " << ft_size << endl;
1808  cout << "Reconstruction size: " << size << endl;
1809  cout << "Number of adjacent images: " << dimg << endl;
1810  cout << "Resolution limit: " << resolution << " A" << endl;
1811  cout << "Shift limit: " << shift_limit << " pixels" << endl;
1812  cout << "Smoothing edge and width: " << edge_width << " " << gauss_width << " pixels" << endl;
1813  cout << endl;
1814  }
1815 
1816  fft_plan planf = fft_setup_plan(ft_size, ft_size, 1, FFTW_FORWARD, 1);
1817  fft_plan planb = fft_setup_plan(ft_size, ft_size, 1, FFTW_BACKWARD, 1);
1818 
1819  for ( it = 0; it < iter && dori > dchange; it++ ) {
1820  if ( verbose ) {
1821  cout << "Iteration " << it+1 << ":" << endl;
1822  cout << "Micrograph: range" << tab << "Origin" << tab << "Shift" << tab << "FOM" << endl;
1823  }
1824  n = 0;
1825  dori = 0;
1826  for ( i=mg_id0-1, j=mg_id0+1; i>=0 || j<nmg; i--, j++ ) {
1827  if ( i >= 0 ) {
1828  dori += mg_reconstruct_align(mgarr, nmg, i, dimg, resolution,
1829  shift_limit, size, edge_width, gauss_width, ft_size, planf, planb);
1830  n++;
1831  }
1832  if ( j < nmg ) {
1833  dori += mg_reconstruct_align(mgarr, nmg, j, dimg, resolution,
1834  shift_limit, size, edge_width, gauss_width, ft_size, planf, planb);
1835  n++;
1836  }
1837  }
1838  dori /= n;
1839  if ( verbose )
1840  cout << "Iteration:\t" << it+1 << tab << dori << endl;
1841  }
1842 
1843  delete[] mgarr;
1846 
1847  Bmicrograph* mg;
1848  if ( verbose & VERB_RESULT ) {
1849  cout << "\nImage\tdx\tdy\tdz" << endl;
1850  for ( mg = project->field->mg; mg; mg = mg->next )
1851  cout << mg->id << tab << mg->origin[0] << tab << mg->origin[1]
1852  << tab << mg->origin[2] << endl;
1853  cout << endl;
1854  }
1855 
1856  return 0;
1857 }
1858 
1859 
1860 
1861 double field_ssnr(Bfield* field, fft_plan plan)
1862 {
1863  long i;
1864  Bmicrograph* mg;
1865  Vector3<double> origin;
1866  Bimage* p, *ps;
1867  Bimage* pavg = NULL;
1868  Bimage* pstd = NULL;
1869  Vector3<double> scale(1,1,1), nori;
1870  Matrix3 mat(1);
1871  Vector3<long> size;
1872 
1873  for ( i=0, mg = field->mg; mg; mg = mg->next, i++ ) {
1874  p = read_img(mg->fmg, 1, mg->img_num);
1875  p->calculate_background();
1876  origin = p->size()/2;
1877  if ( size.volume() < 1 ) { // Make sure it is square
1878  size = p->size();
1879  if ( size[0] < size[1] ) size[1] = size[0];
1880  else size[0] = size[1];
1881  }
1882  ps = p->transform(size, scale, nori, (origin - mg->origin), mat, FILL_BACKGROUND, 0);
1883  ps->fft(plan);
1884  if ( !pavg ) pavg = ps->copy();
1885  else pavg->add(ps);
1886  ps->complex_to_intensities();
1887  if ( !pstd ) pstd = ps->copy();
1888  else pstd->add(ps);
1889  delete p;
1890  delete ps;
1891  }
1892 
1893  if ( i ) {
1894  pavg->multiply(1.0L/i);
1895  pstd->multiply(1.0L/i);
1896  }
1897 
1898  pavg->complex_to_intensities();
1899  pstd->subtract(pavg);
1900  pstd->truncate_to_min_max(1e-10, pstd->maximum());
1901  pavg->divide(pstd, 1, 0);
1902 
1903  field->fom = pavg->average();
1904 
1905  Bstring imgfile = field->id + "_snr.map";
1906  write_img(imgfile, pavg, 0);
1907 
1908  double rad_step(10), maxrad(size[0]/2);
1909  Bimage* prad = pavg->radial(0, maxrad, rad_step, 1);
1910  imgfile = field->id + "_snr.txt";
1911  write_img(imgfile, prad, 0);
1912 
1913  delete pavg;
1914  delete pstd;
1915  delete prad;
1916 
1917  return 0;
1918 }
1919 
1921 {
1922  Bfield* field = project->field;
1923  long n, nfield(0);
1924 
1925  for ( field = project->field; field; field = field->next ) nfield++;
1926 
1927  Bfield** farr = new Bfield*[nfield];
1928  for ( n=0, field = project->field; field; field = field->next, n++ )
1929  farr[n] = field;
1930 
1931  if ( verbose )
1932  cout << "Calculating the SSNR for each field:" << endl;
1933 
1934  Bimage* p = read_img(project->field->mg->fmg, 0, 0);
1935 
1936  fft_plan plan = p->fft_setup(FFTW_FORWARD, 0);
1937 
1938  delete p;
1939 
1940 //#ifdef HAVE_GCD
1941 // dispatch_apply(nfield, dispatch_get_global_queue(0, 0), ^(size_t i){
1942 // field_ssnr(farr[i], plan);
1943 // });
1944 //#else
1945 //#pragma omp parallel for
1946  for ( long i=0; i<nfield; i++ ) {
1947  field_ssnr(farr[i], plan);
1948  }
1949 //#endif
1950 
1951  fft_destroy_plan(plan);
1952  delete[] farr;
1953 
1954  if ( verbose ) {
1955  cout << "Field\tSNR" << endl;
1956  for ( field = project->field; field; field = field->next )
1957  cout << field->id << tab << field->fom << endl;
1958  }
1959 
1960  return 0;
1961 }
1962 
Bimage::regions
Bimage * regions(double threshold, int sign)
Segments an image into contiguous regions.
Definition: Bimage_segment.cpp:56
Bmicrograph::scale
Vector3< double > scale
Definition: mg_processing.h:224
Bsub_image::average
double average()
Definition: Bimage.h:119
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
Bbadarea::loc
Vector3< double > loc
Definition: mg_processing.h:146
Bmicrograph::id
Bstring id
Definition: mg_processing.h:203
verbose
int verbose
Bmicrograph
Definition: mg_processing.h:201
Bimage::complex_to_intensities
void complex_to_intensities()
The intensities from a complex image is written to a simple image.
Definition: Bimage_complex.cpp:92
ps_marker.h
Header file for postscript tools dealing with Bmarkers.
Bmarker::fom
float fom
Definition: marker.h:28
field_count_micrographs
long field_count_micrographs(Bfield *field)
Counts all the micrographs in the field-of-view structure.
Definition: mg_select.cpp:671
Bmicrograph::filament_width
double filament_width
Definition: mg_processing.h:234
Bimage::sizeZ
void sizeZ(long nz)
Definition: Bimage.h:392
Bframe::shift
Vector3< double > shift
Definition: mg_processing.h:78
field_write_aligned_average
double field_write_aligned_average(Bfield *field, Bimage *pgr, Bstring &imgfile, DataType datatype, Bstring &subset)
Definition: mg_align.cpp:866
Bimage::align
JSvalue align(long ref_num, Bimage *pmask, double hi_res, double lo_res, double shift_limit, double edge_width, double gauss_width, Vector3< long > bin)
Aligns and sums a set of sub-images, first progressively and then iteratively.
Definition: Bimage_align.cpp:203
VERB_DEBUG
#define VERB_DEBUG
Definition: utilities.h:116
project_tomo_align
long project_tomo_align(Bproject *project, long thickness, long iter, double dchange, long dimg, double resolution, double shift_limit, double edge_width, double gauss_width)
Aligns a series of micrographs by cross-correlation sequentially.
Definition: mg_align.cpp:1764
kill_list
long kill_list(char *list, unsigned long size)
Frees all the items in a linked list.
Definition: linked_list.cpp:214
filament_node_count
long filament_node_count(Bfilament *fil)
Counts the number of filament nodes in a linked list of filaments.
Definition: mg_select.cpp:809
Bfilament
Definition: mg_processing.h:129
Bmarker::img_num
int img_num
Definition: marker.h:24
Bimage::set
void set(long j, double v)
Sets a single value at the given index.
Definition: Bimage.cpp:1118
Bstring
Definition: Bstring.h:29
Bimage::next
Bimage * next
Definition: Bimage.h:179
add_item
char * add_item(char **list, unsigned long size)
Adds an item to a linked list.
Definition: linked_list.cpp:26
Bstring::extension
Bstring extension()
Definition: Bstring.cpp:523
micrograph_get_nominal_origin
Vector3< double > micrograph_get_nominal_origin(Bmicrograph *mg)
Gets the nominal origin for a micrograph.
Definition: mg_img_proc.cpp:741
Bparticle
Definition: mg_processing.h:90
Bstring::post_rev
Bstring post_rev(char c)
Definition: Bstring.cpp:436
Bproject::field
Bfield * field
Definition: mg_processing.h:346
project_ssnr
double project_ssnr(Bproject *project)
Definition: mg_align.cpp:1920
micrograph_kill
int micrograph_kill(Bmicrograph *mg)
Frees a whole micrograph parameter structure.
Definition: mg_processing.cpp:493
project_write_aligned_averages
double project_write_aligned_averages(Bproject *project, Bimage *pgr, Bstring &imgfile, DataType datatype, Bstring &subset)
Calculates aligned micrograph images and write them to a file.
Definition: mg_align.cpp:1024
Bimage::copy
Bimage * copy()
Copies the header information and data of an image into a new image structure.
Definition: Bimage.cpp:2702
JSvalue::real
double & real()
Definition: json.h:149
Bmicrograph::bad_radius
double bad_radius
Definition: mg_processing.h:236
Vector3< double >
Bimage::sizeX
void sizeX(long nx)
Definition: Bimage.h:390
bexit
int bexit(int value)
Exit function for cleanup and debugging.
Definition: utilities.cpp:280
Bimage::fspace_weigh_dose
int fspace_weigh_dose(long nn, double dose_per_frame, vector< double > critdose)
Definition: Bimage_fspace.cpp:1460
Bimage::histogram_counts
Bplot * histogram_counts(int flags=0)
Finds the peaks in a quantized image from the histogram.
Definition: Bimage_histogram.cpp:207
filament_add
Bfilament * filament_add(Bfilament **fil, int pid)
Adds a filament parameter structure to a linked list.
Definition: mg_processing.cpp:319
Bfilament::next
Bfilament * next
Definition: mg_processing.h:130
micrograph_count_particles
long micrograph_count_particles(Bmicrograph *mg)
Counts all the particles in the micrograph structure.
Definition: mg_select.cpp:736
Bmicrograph::img_num
int img_num
Definition: mg_processing.h:212
mg_select.h
Header file for micrograph processing.
error_show
int error_show(string message, string file, int line)
Displays the error with file and line reference.
Definition: utilities.cpp:719
Bimage::radial
Bimage * radial(long minrad, long maxrad, double rad_step=1, int wrap=0)
Calculates the radial average of an image.
Definition: Bimage_polar.cpp:33
TComplex
@ TComplex
Definition: Bimage.h:60
Bframe::fom
double fom
Definition: mg_processing.h:79
Bimage::size
Vector3< long > size() const
Definition: Bimage.h:386
project_align_frames
double project_align_frames(Bproject *project, int ref_img, Bimage *pgr, Bimage *pmask, Vector3< double > origin, double hi_res, double lo_res, double shift_limit, double edge_width, double gauss_width, Vector3< long > bin, JSvalue &dose_frac, Bstring &subset, int flag)
Aligns a series of micrographs by cross-correlation.
Definition: mg_align.cpp:1220
Bmicrograph::part
Bparticle * part
Definition: mg_processing.h:242
FILL_AVERAGE
#define FILL_AVERAGE
Definition: utilities.h:177
Bimage::calculate_background
int calculate_background(long nn, int flag)
Calculates the background for one sub-image.
Definition: Bimage_background.cpp:27
Bfield::id
Bstring id
Definition: mg_processing.h:262
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
Bimage::fft_back
int fft_back()
Definition: Bimage.h:831
View
Definition: View.h:26
project_micrograph_array
Bmicrograph ** project_micrograph_array(Bproject *project, long &nmg)
Sets up an array of selected micrograph pointers.
Definition: mg_processing.cpp:1254
Bsub_image::view
void view(double x, double y, double z, double a)
Definition: Bimage.h:157
Bmicrograph::fpart
Bstring fpart
Definition: mg_processing.h:208
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
Bfield
Definition: mg_processing.h:260
Bsub_image::FOM
double FOM()
Definition: Bimage.h:165
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
Bimage::standard_deviation
double standard_deviation()
Definition: Bimage.h:544
Transform::fom
double fom
Definition: Transform.h:32
Bmicrograph::fframe
Bstring fframe
Definition: mg_processing.h:207
mg_tomo_reconstruct2D
Bimage * mg_tomo_reconstruct2D(Bproject *project, long dimg, Vector3< long > size, double scale, double hi_res)
Reconstructs the zero-tilt image of a tilt-series.
Definition: mg_align.cpp:1609
Bbadarea
Definition: mg_processing.h:143
Bmicrograph::frame
Bframe * frame
Definition: mg_processing.h:240
marker.h
Header file for image parameter functions.
planf
fft_plan planf
Definition: bico.cpp:24
Bframe
Definition: mg_processing.h:75
Bmicrograph::dose
double dose
Definition: mg_processing.h:216
Bmarker
Definition: marker.h:21
Bfield::fom
double fom
Definition: mg_processing.h:266
Bmicrograph::fil
Bfilament * fil
Definition: mg_processing.h:243
Vector3::distance
double distance(const Vector3 &v)
Definition: Vector3.h:227
project_align_series
double project_align_series(Bproject *project, int ref_img, Bimage *pgr, Bimage *pmask, Vector3< double > origin, double hi_res, double lo_res, double shift_limit, double edge_width, double gauss_width, Vector3< long > bin, Bstring &subset, int flag)
Aligns a series of micrographs by cross-correlation.
Definition: mg_align.cpp:1446
Bimage::images
long images()
Definition: Bimage.h:504
ps_marker_errors
int ps_marker_errors(Bstring &filename, Bmarker *set1, Bmarker *set2, Transform t, Vector3< long > size, double err_scale)
Output a postscript file that graphs the deviations of points in a Bmarker from their predicted locat...
Definition: ps_marker.cpp:252
project
Bproject * project
Definition: bshow.cpp:33
field_align_series
double field_align_series(Bfield *field, int ref_img, Bimage *pgr, Bimage *pmask, Vector3< double > origin, double hi_res, double lo_res, double shift_limit, double edge_width, double gauss_width, Vector3< long > bin, Bstring &subset, int flag)
Definition: mg_align.cpp:1313
Matrix3
Definition: Matrix3.h:18
read_img
Bimage * read_img(char *filename, int readdata, int img_select)
General driver function to read multiple image formats.
Definition: rwimg.cpp:77
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
Bfilament::id
int id
Definition: mg_processing.h:132
Bmarker::next
Bmarker * next
Definition: marker.h:22
Bimage::add
void add(long j, double v)
Definition: Bimage.h:321
insert
string insert(string &filename, string ins)
Definition: string_util.cpp:48
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::slices_to_images
int slices_to_images()
Changes the slices in a 3D image into a set of 2D images.
Definition: Bimage.cpp:2074
Bimage::fft
int fft()
Definition: Bimage.h:830
JSvalue::exists
bool exists(string tag)
Definition: json.h:221
Bmarker::id
int id
Definition: marker.h:23
Bmicrograph::origin
Vector3< double > origin
Definition: mg_processing.h:223
Bstring::pre_rev
Bstring pre_rev(char c)
Definition: Bstring.cpp:421
Bimage::mask_by_threshold
Bimage * mask_by_threshold(double threshold)
Generates a mask based on an image at a given threshold.
Definition: Bimage_mask.cpp:93
VERB_RESULT
#define VERB_RESULT
Definition: utilities.h:109
Bfilnode::id
int id
Definition: mg_processing.h:118
Bimage::divide
void divide(Bimage *p, double scale=1, double shift=0)
Divides the first image by the second.
Definition: Bimage.cpp:3582
Bimage
General image parameter class.
Definition: Bimage.h:177
mg_reconstruct_align
double mg_reconstruct_align(Bmicrograph **mgarr, long nmg, long mg_id, long dimg, double resolution, double shift_limit, Vector3< long > size, double edge_width, double gauss_width, long ft_size, fft_plan planf, fft_plan planb)
Definition: mg_align.cpp:1663
Bimage::compound_type
CompoundType compound_type()
Definition: Bimage.h:364
Bimage::shape
int shape(int type, Vector3< long > rect, Vector3< double > start, double width, int fill_type=0, double fill=0)
Creates a shape in an image and fills it with a constant value.
Definition: Bimage_edit.cpp:105
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
Bfilament::node
Bfilnode * node
Definition: mg_processing.h:133
Bimage::extract_tiles
Bimage * extract_tiles(long nn, vector< Vector3< long >> &coords, Vector3< long > tile_size)
Extracts a set of tiles at specified positions from an image into a new image.
Definition: Bimage_extract.cpp:331
Bproject
Definition: mg_processing.h:336
Unknown_Type
@ Unknown_Type
Definition: utilities.h:151
Bmarker::err
Vector3< float > err
Definition: marker.h:26
Bbadarea::next
Bbadarea * next
Definition: mg_processing.h:144
JSvalue
Definition: json.h:53
Bimage::replace
int replace(Bimage *img)
Replaces the data with that from the given image.
Definition: Bimage.cpp:2830
mg_align_series
double mg_align_series(Bmicrograph *mg, Bmicrograph *mg_ref, Bimage *pref, Bimage *pgr, Bimage *pmask, double hi_res, double lo_res, double shift_limit, double edge_width, double gauss_width, Vector3< long > bin, fft_plan planf, fft_plan planb)
Definition: mg_align.cpp:1269
mg_img_proc.h
Header file for image processing from micrograph structures.
Transform::scale
Vector3< double > scale
Definition: Transform.h:31
Bimage::complex
Complex< double > complex(long j)
Returns a complex value at the given index.
Definition: Bimage.cpp:1027
VERB_TIME
#define VERB_TIME
Definition: utilities.h:114
Bimage.h
Header file for image class.
Bimage::truncate_to_min_max
int truncate_to_min_max(double minim, double maxim)
Truncates image data to a given minimum and maximum.
Definition: Bimage_rescale.cpp:331
Bmicrograph::mark_radius
double mark_radius
Definition: mg_processing.h:238
Bimage::data_alloc_and_clear
unsigned char * data_alloc_and_clear()
Definition: Bimage.h:272
Bparticle::loc
Vector3< double > loc
Definition: mg_processing.h:100
mg_align_micrographs
int mg_align_micrographs(Bproject *project, int refset, Vector3< long > tile_size, double res_lo, double res_hi, double max_shift, int filter_flag, int refine_flag)
Aligns a focal series of micrographs.
Definition: mg_align.cpp:319
img_sum_subset
Bimage * img_sum_subset(Bimage *p, Bstring &subset, double dose_per_frame)
Definition: mg_align.cpp:251
Bmarker::loc
Vector3< float > loc
Definition: marker.h:25
Bimage::file_name
void file_name(string s)
Definition: Bimage.h:245
Bimage::subtract
void subtract(Bimage *p)
Subtracts another image from an image.
Definition: Bimage.cpp:3406
Bimage::fspace_bandpass
int fspace_bandpass(double res_hi, double res_lo=0, double width=0)
Applies a bandpass filter to an image.
Definition: Bimage_fspace.cpp:496
Bimage::data_type
DataType data_type()
Definition: Bimage.h:362
Bfilnode::next
Bfilnode * next
Definition: mg_processing.h:117
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
markers_map_and_find_transform
Transform * markers_map_and_find_transform(Bmarker **set, int nseries, int refset, Vector3< long > size)
This function finds the transform parameters between sets of coordinates. These sets are expected to ...
Definition: marker.cpp:635
Bmicrograph::box_size
Vector3< long > box_size
Definition: mg_processing.h:233
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
Bmicrograph::matrix
Matrix3 matrix
Definition: mg_processing.h:225
Bimage::origin
void origin(double ox, double oy, double oz)
Definition: Bimage.h:570
Bmicrograph::fmg
Bstring fmg
Definition: mg_processing.h:206
field_find_zero_tilt_mg
Bmicrograph * field_find_zero_tilt_mg(Bfield *field)
Finds the micrograph closest to a zero degree tilt in a series.
Definition: mg_select.cpp:281
Bfield::select
long select
Definition: mg_processing.h:265
Bimage::fspace_pack_2D_into_central_section
long fspace_pack_2D_into_central_section(Bimage *p, long ft_size, double scale, double hi_res, double lo_res, Matrix3 matr, Matrix3 mat)
Packs a 2D Fourier transform into a central section of a 3D reciprocal space volume.
Definition: Bimage_reconstruct.cpp:212
Bimage::change_type
void change_type(char letter)
Get the data type indicated by a single letter code.
Definition: Bimage.cpp:1765
Vector3::volume
double volume()
Definition: Vector3.h:237
Bmicrograph::fom
double fom
Definition: mg_processing.h:239
particle_add
Bparticle * particle_add(Bparticle **part, int pid)
Adds a particle parameter structure to a linked list.
Definition: mg_processing.cpp:221
Transform::trans
Vector3< double > trans
Definition: Transform.h:30
rwimg.h
Header file for 2D and 3D image I/O.
Bmicrograph::ctf
CTFparam * ctf
Definition: mg_processing.h:241
markers_find_rottrans
Transform markers_find_rottrans(Bmarker *set1, Bmarker *set2, double tolerance)
Finds the rotation and shift between two sets of vectors.
Definition: marker.cpp:466
Bfield::next
Bfield * next
Definition: mg_processing.h:261
Bimage::square
void square()
Calculates the square of an image.
Definition: Bimage_rescale.cpp:678
Bimage::copy_header
Bimage * copy_header()
Definition: Bimage.h:658
Bmicrograph::mark
Bmarker * mark
Definition: mg_processing.h:245
Bparticle::ori
Vector3< double > ori
Definition: mg_processing.h:101
mg_processing.h
Header file for micrograph processing.
Bimage::extract
Bimage * extract(long nn)
Extracts one sub-image into new image structure.
Definition: Bimage_extract.cpp:21
Bmicrograph::intensity
double intensity
Definition: mg_processing.h:217
fft_plan
fftwf_plan fft_plan
Definition: fft.h:20
Bmarker::sel
int sel
Definition: marker.h:29
CTFparam::defocus_average
double defocus_average()
Definition: ctf.h:106
Bmicrograph::block
int block
Definition: mg_processing.h:205
project_write_aligned_images
double project_write_aligned_images(Bproject *project, Bimage *pgr, Bstring &imgfile, DataType datatype)
Calculates aligned micrograph images and write them to a file.
Definition: mg_align.cpp:952
Bsub_image::sampling
void sampling(double x, double y, double z)
Definition: Bimage.h:127
Bparticle::next
Bparticle * next
Definition: mg_processing.h:91
Bmicrograph::rot_angle
double rot_angle
Definition: mg_processing.h:222
linked_list.h
Header file for generalized linked list functions.
Bmicrograph::select
long select
Definition: mg_processing.h:204
mg_tomo_reconstruct
Bimage * mg_tomo_reconstruct(Bmicrograph **mgarr, long mg_id, long mg_min, long mg_max, double hi_res, double scale, Vector3< long > size, long ft_size, fft_plan planf, fft_plan planb)
Definition: mg_align.cpp:1488
Bfilnode::loc
Vector3< double > loc
Definition: mg_processing.h:119
VERB_FULL
#define VERB_FULL
Definition: utilities.h:113
Bimage::data_pointer
unsigned char * data_pointer()
Definition: Bimage.h:284
frame_add
Bframe * frame_add(Bframe **frame, int pid)
Adds a movie frame parameter structure to a linked list.
Definition: mg_processing.cpp:189
Bstring::base
Bstring base()
Definition: Bstring.cpp:516
filament_kill
int filament_kill(Bfilament *fil)
Frees a list of filaments.
Definition: mg_processing.cpp:552
FILL_BACKGROUND
#define FILL_BACKGROUND
Definition: utilities.h:178
Vector3::min
Type min()
Definition: Vector3.h:169
Bmicrograph::pixel_size
Vector3< double > pixel_size
Definition: mg_processing.h:215
Transform::axis
Vector3< double > axis
Definition: Transform.h:28
planb
fft_plan planb
Definition: bico.cpp:24
Bimage::sampling
void sampling(long nn, Vector3< double > u)
Definition: Bimage.h:514
Transform::angle
double angle
Definition: Transform.h:29
Bmicrograph::fil_node_radius
double fil_node_radius
Definition: mg_processing.h:235
DataType
DataType
Base data type specifier.
Definition: utilities.h:150
Bimage::phase_shift_to_origin
int phase_shift_to_origin()
Phase shifts a set of reflections to the image origin.
Definition: Bimage_complex.cpp:327
Bfilnode
Definition: mg_processing.h:116
Transform
Definition: Transform.h:24
Bstring::contains
bool contains(const Bstring &s)
Definition: Bstring.cpp:592
mg_merge_focal_series
int mg_merge_focal_series(Bproject *project, int use_old_origins)
Merges corresponding particle images in each focal series.
Definition: mg_align.cpp:766
particle_kill
int particle_kill(Bparticle *part)
Frees a list of particles.
Definition: mg_processing.cpp:528
markers_limit
long markers_limit(int target_num, int sign, Bmarker **set)
This method constricts a marker set to target_num points.
Definition: marker.cpp:959
Vector3::length
double length()
Definition: Vector3.h:222
mg_align_feature_extraction
int mg_align_feature_extraction(Bproject *project, int max_features, double res_low, double res_high, double thresh, int extract_method)
Aligns images by feature extraction.
Definition: mg_align.cpp:545
Bmicrograph::bad
Bbadarea * bad
Definition: mg_processing.h:244
Bimage::edge
int edge(int type, Vector3< long > rect, Vector3< double > start, double width, int fill_type=0, double fill=0)
Smooths the image edge with a soft rectangular function.
Definition: Bimage_edit.cpp:321
filament_node_add
Bfilnode * filament_node_add(Bfilnode **fnode, int pid)
Adds a filament node parameter structure to a linked list.
Definition: mg_processing.cpp:349
mg_align.h
Header file for functions to align micrographs or coordinates from micrographs and apply the resultan...
img_align
Transform img_align(Bimage *p1, Bimage *p2, Vector3< long > tile_size, double res_lo, double res_hi, double max_shift, int filter_flag, int refine_flag)
Definition: mg_align.cpp:108
Float
@ Float
Definition: utilities.h:161
field_ssnr
double field_ssnr(Bfield *field, fft_plan plan)
Definition: mg_align.cpp:1861
VERB_LABEL
#define VERB_LABEL
Definition: utilities.h:110
Bimage::phase_shift_to_center
int phase_shift_to_center()
Phase shifts a set of reflections to the nominal center of the image origin.
Definition: Bimage_complex.cpp:382
Bmicrograph::next
Bmicrograph * next
Definition: mg_processing.h:202
img_extract_features
Bmarker * img_extract_features(Bimage *p, int extract_method, int target_num, double threshold)
Definition: mg_align.cpp:406
Bfield::mg
Bmicrograph * mg
Definition: mg_processing.h:267
select_numbers
int select_numbers(Bstring &string, int n, int *numsel)
Converts a string with a selection specification into an integer array.
Definition: utilities.cpp:335
findNextPowerOf
int findNextPowerOf(int startNumber, int powerOf)
Finds the next greatest number that is a power of a given number.
Definition: utilities.cpp:397
Bparticle::id
int id
Definition: mg_processing.h:93
mg_align_coordinates
int mg_align_coordinates(Bproject *project, int refset)
Aligns the particle coordinates of a series of micrographs.
Definition: mg_align.cpp:39
Transform::next
Transform * next
Definition: Transform.h:26
project_count_micrographs
long project_count_micrographs(Bproject *project)
Counts all the micrographs in the project structure.
Definition: mg_select.cpp:350
mg_align_frames
double mg_align_frames(Bmicrograph *mg, int ref_num, Bimage *pgr, Bimage *pmask, double hi_res, double lo_res, double shift_limit, double edge_width, double gauss_width, Vector3< long > bin, JSvalue &dose_frac, Bstring &subset, int flag)
Definition: mg_align.cpp:1085
Bimage::statistics
long statistics()
Calculates the statistics for an image.
Definition: Bimage_stats.cpp:22
mg_apply_transform
int mg_apply_transform(Bmicrograph *mg_ref, Bmicrograph *mg_apply)
Applies a transformation to particle coordinates in a reference micrograph and writes them into an ap...
Definition: mg_align.cpp:634
Bimage::filter_extremes
int filter_extremes()
Filters the extremes out of a micrograph image.
Definition: Bimage_segment.cpp:620
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
Vector3::max
Type max()
Definition: Vector3.h:175