Bsoft  2.1.0
Bernard's software package
Bimage_histogram.cpp
Go to the documentation of this file.
1 
9 #include "Bimage.h"
10 #include "simplex.h"
11 #include "cluster.h"
12 #include "matrix_linear.h"
13 #include "qsort_functions.h"
14 #include "utilities.h"
15 
16 // Declaration of global variables
17 extern int verbose; // Level of output to the screen
18 
32 vector<long> Bimage::histogram(long bins, double& scale, double& offset)
33 {
34  scale = 1;
35  offset = 0;
36 
37  vector<long> histo(bins*c, 0);
38 
39  if ( !data_pointer() ) return histo;
40 
41  long i, j, cc;
42 // for ( i=0; i<bins*c; i++ ) histo[i] = 0;
43 
44  if ( datatype < Float ) {
45  scale = 1/(ceil((max - min + 1)/bins));
46  offset = -scale*min;
47  } else {
48  scale = (bins - 1)*1.0/(max - min);
49  offset = 0.5 - scale*min;
50  }
51 
52  if ( verbose & VERB_DEBUG )
53  cout << "DEBUG Bimage::histogram: range=" << min << "-"
54  << max << " bins=" << bins << " scale=" << scale
55  << " offset=" << offset << endl;
56 
57  for ( i=0; i<n*image_size(); ) {
58  for ( cc=0; cc<c; cc++, i++ ) {
59  j = (long) (scale*(*this)[i] + offset);
60  if ( j >= 0 && j < bins ) histo[cc*bins+j]++;
61  }
62  }
63 
64  return histo;
65 }
66 
80 {
81  long i, j, k, cc, npage, ncol;
82  double Hi, H;
83  double bin_half = (max - min)/(4*bins);
84  double unit_mass = RHO * sampling(0).volume();
85  vector<long> hsum(bins*c, 0);
86 
87  double scale, offset;
88  vector<long> histo = histogram(bins, scale, offset);
89 
90  long hmax(0);
91  for ( i=0; i<bins; i++ ) if ( hmax < histo[i] ) hmax = histo[i];
92 
93  for ( i=0; i<bins*c; i++ ) hsum[i] = histo[i];
94  for ( i=bins-1; i>0; i-- )
95  for ( cc=0; cc<c; cc++ )
96  hsum[cc*bins+i-1] += hsum[cc*bins+i];
97 
98  if ( c > 1 ) {
99  npage = 1;
100  ncol = c + 1;
101  } else {
102  npage = 2;
103  ncol = 3;
104  }
105 
106  if ( verbose & VERB_LABEL ) {
107  cout << "Histogram" << endl;
108  if ( c == 1 )
109  cout << "Bin\tLevel\tNumber\tSum\tVolume\tInformation" << endl;
110  else {
111  cout << "Bin\tLevel";
112  for ( cc=0; cc<c; cc++ ) cout << "\tChannel" << cc+1;
113  cout << endl;
114  }
115  }
116 
117  Bstring title("Histogram");
118  Bplot* plot = new Bplot(npage, bins, ncol);
119  plot->title(title);
120 
121  plot->page(0).title(title);
122  plot->page(0).columns(c+1);
123  for ( i=0; i<=c; i++ ) plot->page(0).column(i).number(i);
124  plot->page(0).column(0).label("Bin");
125  plot->page(0).column(0).axis(1);
126  for ( i=1; i<=c; i++ ) {
127  plot->page(0).column(i).type(1);
128  plot->page(0).column(i).label("Count");
129  plot->page(0).column(i).axis(3);
130  plot->page(0).column(i).element_size(0.5);
131  }
132  if ( c > 1 ) {
133  plot->page(0).column(1).color(1,0,0);
134  plot->page(0).column(2).color(0,1,0);
135  plot->page(0).column(3).color(0,0,1);
136  }
137  plot->page(0).axis(1).min(min - bin_half);
138  plot->page(0).axis(1).max(max + bin_half);
139  plot->page(0).axis(3).min(0);
140  plot->page(0).axis(3).max(hmax);
141 
142  if ( c < 2 ) {
143  title = "Cumulative mass";
144  plot->page(1).title(title);
145  plot->page(1).columns(2);
146  plot->page(1).column(0).number(0);
147  plot->page(1).column(1).number(2);
148  plot->page(1).column(0).label("Bin");
149  plot->page(1).column(0).axis(1);
150  plot->page(1).column(1).type(1);
151  plot->page(1).column(1).label("Mass(MDa)");
152  plot->page(1).column(1).axis(3);
153  plot->page(1).column(1).element_size(0.5);
154  plot->page(1).axis(1).min(min - bin_half);
155  plot->page(1).axis(1).max(max + bin_half);
156  plot->page(1).axis(3).min(0);
157  plot->page(1).axis(3).max(hsum[0] * unit_mass);
158  }
159 
160  for ( i=0; i<bins; i++ ) {
161  (*plot)[i] = min + i/scale;
162  for ( cc=0, j=i, k=bins+i; cc<c; cc++, j+=bins, k+=bins ) (*plot)[k] = histo[j];
163  }
164 
165  if ( c == 1 ) {
166  H = 0;
167  for ( i=0, k=2*bins; i<bins; i++, k++ ) {
168  (*plot)[k] = hsum[i] * unit_mass;
169  Hi = 0;
170  if ( histo[i] )
171  Hi = (-histo[i]*1.0/hsum[0]) * log(histo[i]*1.0/hsum[0]) / log(2.0);
172  H += Hi;
173  cout << i+1 << tab << setw(12) << (*plot)[i] << tab << histo[i] << tab << hsum[i] << tab <<
174  sampling(0).volume()*hsum[i] << tab << Hi << endl;
175  }
176 
177  if ( verbose & VERB_LABEL ) {
178  cout << "Voxels & number in histogram: " << datasize << " "
179  << hsum[0] << " (" << hsum[0]*100.0/datasize << " %)" << endl;
180  cout << "Voxel volume: " << sampling(0).volume() << " A/voxel" << endl;
181  cout << "Informational entropy and rate: " << H << " " << log(1.0*bins)/log(2.0) - H << endl << endl;
182  }
183  } else {
184  for ( i=0; i<bins; i++ ) {
185  cout << i+1 << tab << (*plot)[i];
186  for ( cc=0, j=0; cc<c; cc++, j+=bins ) cout << tab << histo[j];
187  cout << endl;
188  }
189  }
190 
191 
192 // delete[] histo;
193 // delete[] hsum;
194 
195  return plot;
196 }
197 
208 {
209  long i, j, k, bins(1000), imax(0), imax2(0);
210  double scale, offset, hmax(0), hmax2(0);
211 
212  if ( datatype < Float ) bins = max - min + 1;
213 
214  vector<long> h = histogram(bins, scale, offset);
215 
216  // Find highest peak
217  for ( i=0, imax=0; i<bins; ++i ) if ( hmax < h[i] ) {
218  hmax = h[i];
219  imax = i;
220  }
221  hmax2 = hmax/2;
222 
223  if ( imax < 1 ) {
224  cerr << "Warning: First bin in histogram is already the highest!" << endl;
225  return NULL;
226  }
227 
228  // Track to start of peak
229  for ( i=imax; i && h[i] >= hmax2; --i ) ;
230 
231  // Track to end of previous peak
232  for ( ; i && h[i] < hmax2; --i ) ;
233 
234  // Find previous peak
235  for ( ; i && h[i] > hmax/2; --i ) if ( hmax2 < h[i] ) {
236  hmax2 = h[i];
237  imax2 = i;
238  }
239 
240  imax -= imax2;
241 
242  if ( imax < 1 ) {
243  cerr << "Warning: First bin in histogram is already the highest!" << endl;
244  cerr << "scale = " << scale << " offset = " << offset << endl;
245  cerr << "imax = " << imax << " imax2 = " << imax2 << endl;
246  return NULL;
247  }
248 
249  long np(bins/imax+1), ninc(0), thr(datasize/1e4);
250  double stot(0), inc(0), d;
251  double amp[np], s[np], sv[np], sv2[np];
252 
253  for ( j=0; j<np; j++ ) s[j] = sv[j] = sv2[j] = amp[j] = 0;
254 
255  for ( i=0, j=0; i<bins && j<np; i++ ) {
256  j = (i+imax/2)/imax;
257  if ( j < np ) {
258  s[j] += h[i];
259  sv[j] += h[i]*i;
260  sv2[j] += h[i]*i*i;
261  if ( amp[j] < h[i] ) amp[j] = h[i];
262  }
263  }
264 
265  for ( j=0; j<np; j++ ) stot += s[j];
266 
267  if ( verbose )
268  cout << "Peak\t%\tAmp\tAvg\tStDev" << endl;
269  for ( j=k=0; j<np; j++ ) if ( s[j] ) {
270  sv[j] /= s[j];
271  sv2[j] = sv2[j]/s[j] - sv[j]*sv[j];
272  if ( j && amp[j] > thr ) {
273  inc += sv[j]/j;
274  ninc++;
275  }
276  if ( verbose )
277  cout << setprecision(4) << j << tab << 100*s[j]/stot << tab <<
278  amp[j] << tab << sv[j] << tab << sqrt(sv2[j]) << endl;
279  }
280 
281  if ( ninc ) {
282  inc /= ninc;
283  cout << "Counts scale: " << inc << " (" << ninc << ")" << endl;
284  if ( flags & 2 ) {
285  if ( datatype < Float ) scale = inc;
286  else scale /= inc;
287  for ( i=0; i<datasize; i++ ) set(i, floor((*this)[i]/scale + 0.5));
288  statistics();
289  }
290  }
291 
292  long ncol(1+np);
293  Bstring title("Peaks");
294  Bplot* plot = NULL;
295 
296  if ( flags & 1 ) {
297  plot = new Bplot(1, bins, ncol);
298  plot->title(title);
299 
300  plot->page(0).title(title);
301  plot->page(0).columns(ncol);
302  for ( i=0; i<ncol; i++ ) plot->page(0).column(i).number(i);
303  plot->page(0).column(0).label("Bin");
304  plot->page(0).column(0).axis(1);
305  plot->page(0).column(1).type(1);
306  plot->page(0).column(1).label("Count");
307  plot->page(0).column(1).axis(3);
308  plot->page(0).column(1).element_size(0.5);
309  plot->page(0).column(1).color(0.5,0.5,0.5);
310  for ( j=1, i=2; j<np; j++, i++ ) {
311  plot->page(0).column(i).type(2);
312  plot->page(0).column(i).label("Count");
313  plot->page(0).column(i).axis(3);
314  plot->page(0).column(i).element_size(0.5);
315  plot->page(0).column(i).color(1,0,0);
316  }
317 
318  for ( i=0; i<bins; i++ ) {
319  (*plot)[i] = i;
320  (*plot)[i+bins] = h[i];
321  for ( j=1, k=2*bins; j<np; j++, k+=bins )
322  if ( sv2[j] ) {
323  d = sv[j] - i;
324  (*plot)[i+k] = amp[j] * exp(-0.5*d*d/sv2[j]);
325  } else
326  (*plot)[i+k] = 0;
327  }
328  }
329 
330 // delete[] h;
331 
332  return plot;
333 }
334 
345 {
346  long bins(10000), pbins(101);
347  long i, j, hsum;
348  double invsize(100.0/datasize);
349  double scale, offset, fraction, d;
350 
351  vector<long> histo = histogram(bins, scale, offset);
352 
353  vector<double> perc(pbins);
354 
355  perc[0] = min;
356  perc[100] = max;
357 
358  long ncol(3);
359  Bstring title("Percentiles");
360  Bplot* plot = new Bplot(1, pbins, ncol);
361  plot->title(title);
362 
363  plot->page(0).title(title);
364  plot->page(0).columns(ncol);
365  for ( i=0; i<ncol; i++ ) plot->page(0).column(i).number(i);
366  plot->page(0).column(0).label("%");
367  plot->page(0).column(0).axis(1);
368  plot->page(0).column(1).type(1);
369  plot->page(0).column(1).label("Bin");
370  plot->page(0).column(1).axis(3);
371  plot->page(0).column(1).element_size(0.5);
372  plot->page(0).column(2).type(2);
373  plot->page(0).column(2).label("Value");
374  plot->page(0).column(2).axis(3);
375  plot->page(0).column(2).element_size(0.5);
376  plot->page(0).column(2).color(1,0,0);
377 // plot->page(0).axis(1).min(min - bin_half);
378 // plot->page(0).axis(1).max(max + bin_half);
379 // plot->page(0).axis(3).min(prad->minimum());
380 // plot->page(0).axis(3).max(prad->maximum());
381 
382  if ( verbose ) {
383  cout << "%\tBin\tValue" << endl;
384  cout << 0 << tab << 0 << tab << perc[0] << endl;
385  }
386  (*plot)[2*pbins] = perc[0];
387  for ( i=j=1, hsum = histo[0]; i<bins; hsum += histo[i], i++ ) {
388  fraction = hsum*invsize;
389  for ( d = (fraction>j)? 1.0/(fraction - j): 1; fraction > j; j++ ) {
390  perc[j] = min + (i - d*(fraction - j))/scale;
391  if ( verbose )
392  cout << j << tab << i << tab << perc[j] << endl;
393  (*plot)[j] = j;
394  (*plot)[pbins+j] = i;
395  (*plot)[2*pbins+j] = perc[j];
396  }
397  }
398  if ( verbose )
399  cout << 100 << tab << i << tab << perc[100] << endl;
400  (*plot)[100] = 100;
401  (*plot)[pbins+100] = i;
402  (*plot)[2*pbins+100] = perc[100];
403 
404 // delete[] histo;
405 // delete[] perc;
406 
407  return plot;
408 }
409 
421 int Bimage::histogram_thresholds(double& tmin, double& tmax)
422 {
423  if ( max <= min ) statistics();
424 
425  // Calculate the histogram and remove large numbers of white and black pixels
426  long i, j, bins(256);
427  if ( (max - min)/std < 25 ) bins = 10*(max - min)/std;
428  if ( datatype <= SCharacter ) bins = (long) (max - min + 1.1);
429 
430  long ihi, imin, nmin, imax(bins/2), nmax(0), isig(0);
431  double g, sigma(8.0/(bins*bins));
432  double scale, offset;
433 
434  vector<long> hist = histogram(bins, scale, offset);
435 
436  if ( verbose & VERB_PROCESS ) {
437  cout << "Estimating extreme thresholds from the histogram:" << endl;
438  cout << "Bins: " << bins << endl;
439  }
440 
441  imax = (avg - min)*scale;
442  nmax = hist[imax];
443 
444  for ( i=imax/2, j=(bins-imax)/2; i<j; i++ ) {
445  if ( nmax < hist[i] ) { // Find the maximum in the middle part of the histogram
446  nmax = hist[i];
447  imax = i;
448  }
449  }
450 
451  while ( imax+isig < bins - 1 && imax-isig > 0 &&
452  hist[imax] < 2*hist[imax+isig] && hist[imax] < 2*hist[imax-isig] )
453  isig++;
454 
455  if ( verbose & VERB_DEBUG ) {
456  cout << "DEBUG Bimage::histogram_thresholds: Gaussian parameters:" << endl;
457  cout << "DEBUG Bimage::histogram_thresholds: max=" << nmax << " imax=" << imax << " sigma=" << isig << endl;
458  }
459 
460  if ( isig > 0 ) sigma = -0.5/(isig*isig);
461  ihi = 0;
462  for ( i=0; i<imax/2; i++ ) { // Find the highest peak in the first part
463  g = nmax*exp(sigma*(imax - i)*(imax - i));
464  if ( hist[i] > 20*g ) ihi = i;
465  }
466 
467  if ( verbose & VERB_DEBUG )
468  cout << "DEBUG Bimage::histogram_thresholds: highest peak in first quarter = " << ihi << endl;
469 
470  imin = ihi;
471  nmin = x*y*z;
472  for ( i=ihi; i<imax/2; i++ ) { // Find the minimum after the highest peak in the first part
473  if ( nmin > hist[i] ) {
474  nmin = hist[i];
475  imin = i;
476  }
477  }
478 
479  ihi = bins - 1;
480  for ( i=bins-1, j=(bins-imax)/2; i>j; i-- ) { // Find the highest peak in the last part
481  g = nmax*exp(sigma*(imax - i)*(imax - i));
482  if ( hist[i] > 20*g ) ihi = i;
483  }
484 
485  if ( verbose & VERB_DEBUG )
486  cout << "DEBUG Bimage::histogram_thresholds: highest peak in last quarter = " << ihi << endl;
487 
488  imax = ihi;
489  nmin = x*y*z;
490  for ( i=(bins-imax)/2; i<ihi; i++ ) { // Find the minumum before the highest peak in the last part
491  if ( nmin >= hist[i] ) {
492  nmin = hist[i];
493  imax = i;
494  }
495  }
496 
497 // delete[] hist;
498 
499  if ( imin >= imax ) {
500  cerr << "Error in Bimage::histogram_thresholds: extremes not found!" << endl;
501  return -1;
502  }
503 
504  tmin = imin/scale + min;
505  tmax = imax/scale + min;
506 
507  if ( verbose & VERB_DEBUG )
508  cout << "DEBUG Bimage::histogram_thresholds: imin=" << imin << " imax=" << imax << " tmin=" << tmin << " tmax=" << tmax << endl;
509 
510  if ( verbose & VERB_PROCESS )
511  cout << "Thresholds: " << tmin << tab << tmax << endl << endl;
512 
513  return 0;
514 }
515 
523 double Bimage::otsu_threshold(long bins)
524 {
525  double scale, offset;
526  vector<long> h = histogram(bins, scale, offset);
527 
528  long i, total(x*y*z);
529  double sum(0), sumB(0), wB(0), wF(0), mB, mF, mx(0), bt(0), t1(0), t2(0);
530 
531  for ( i = 1; i < bins; ++i )
532  sum += i * h[i];
533 
534  for ( i = 0; i < bins; ++i ) {
535  wB += h[i];
536  if (wB == 0)
537  continue;
538  wF = total - wB;
539  if (wF == 0)
540  break;
541  sumB += i * h[i];
542  mB = sumB / wB;
543  mF = (sum - sumB) / wF;
544  bt = wB * wF * (mB - mF) * (mB - mF);
545  if ( bt >= mx ) {
546  t1 = i;
547  if ( bt > mx ) {
548  t2 = i;
549  }
550  mx = bt;
551  }
552  }
553 
554 // delete[] h;
555 
556  return ( t1 + t2 ) / (2 * scale) + min;
557 }
558 
560 {
561  long i, j, k;
562  double v, df, R(0);
563  vector<double>& f = simp.dependent_values();
564  vector<double>& x = simp.independent_values();
565 
566  for ( i=0; i<simp.points(); i++ ) {
567  for ( j=k=0, df=0; j<simp.constant(0); j++, k+=3 ) {
568  v = (x[i] - simp.parameter(k+1))/simp.parameter(k+2);
569  df += simp.parameter(k)*exp(-0.5*v*v);
570  }
571  df -= f[i];
572  R += df*df;
573  }
574 
575  R = sqrt(R/i);
576 
577  return R;
578 }
579 
590 vector<double> Bimage::histogram_gauss_fit(long bins, long ngauss)
591 {
593 
594  long i, j, nh(bins);
595  long thresh((100*datasize)/bins);
596  double hmax(0), havg[ngauss], hstd[ngauss], w[ngauss];
597 
598  double scale, offset;
599  vector<long> histo = histogram(bins, scale, offset);
600 
601  long* sel = k_means(datasize, (float *)data_pointer(), ngauss);
602 
603  for ( j=0; j<ngauss; j++ ) havg[j] = hstd[j] = w[j] = 0;
604  for ( i=0; i<datasize; i++ ) {
605  havg[sel[i]] += (*this)[i];
606  hstd[sel[i]] += (*this)[i]*(*this)[i];
607  w[sel[i]] += 1;
608  }
609  for ( j=0; j<ngauss; j++ ) {
610  havg[j] /= w[j];
611  hstd[j] /= w[j];
612  hstd[j] -= havg[j]*havg[j];
613  if ( hstd[j] > 0 ) hstd[j] = sqrt(hstd[j]);
614  else hstd[j] = 0;
615  }
616 
617  delete[] sel;
618 
619  sel = new long[bins];
620 
621  // Selection of bins to fit
622  for ( i=nh=0; i<bins; i++ ) {
623  if ( histo[i] < thresh ) {
624  sel[i] = 1;
625  nh++;
626  } else {
627  sel[i] = 0;
628  }
629  }
630 
631  if ( nh < 20 && nh < bins/2 )
632  cerr << "Warning: Too few bins selected for fitting! (" << nh << "/" << bins << ")" << endl;
633 
634  // 3 parameters: amplitude, position, sigma
635  vector<double> xx(bins), fx(nh);
636  for ( i=j=0; i<bins; i++ ) if ( sel[i] ) {
637  xx[j] = min + i/scale;
638  fx[j] = histo[i];
639  if ( hmax < histo[i] ) hmax = histo[i];
640  j++;
641  }
642 
643  delete[] sel;
644 
645  Bsimplex simp(1, 3*ngauss, 1, nh, xx, fx);
646  simp.constant(0, ngauss);
647 
648  for ( i=j=0; j<ngauss; j++, i++ ) {
649  simp.parameter(i, hmax); // Amplitude
650  simp.limits(i, datasize/bins, 5*hmax);
651 // cout << tab << simp.parameter(i);
652  i++;
653  simp.parameter(i, havg[j]); // Position
654  if ( hstd[j] ) {
655  simp.limits(i, havg[j] - 5*hstd[j], havg[j] + 5*hstd[j]);
656  if ( simp.limit_low(i) < min ) simp.limit_low(i, min);
657  if ( simp.limit_high(i) > max ) simp.limit_high(i, max);
658  } else {
659  simp.limits(i, min, max);
660  }
661 // cout << tab << simp.parameter(i);
662  i++;
663  if ( hstd[j] ) {
664  simp.parameter(i, hstd[j]); // Sigma
665  simp.limits(i, hstd[j]/5, 5*hstd[j]);
666  } else {
667  simp.parameter(i, std); // Sigma
668  simp.limits(i, 1/scale, 0.5*(max - min)/n);
669  }
670 // cout << tab << simp.parameter(i) << endl;
671  }
672 
673  double R = simp.run(1000, 0.001, simplex_gauss_R);
674 
675  vector<double> gauss;
676  for ( j=0; j<3*ngauss; j++ ) gauss.push_back(simp.parameter(j));
677 
678  if ( verbose & VERB_PROCESS ) {
679  cout << "Gaussian fit over " << nh << " bins:" << endl;
680  cout << "Amp\tOffset\tSigma\tSIP" << endl;
681  for ( j=0; j<ngauss; j++ )
682  cout << gauss[3*j] << tab << gauss[3*j+1] << tab << gauss[3*j+2] << tab << bins*gauss[3*j]/datasize << endl;
683  cout << "Sampling-independent RMSD: " << bins*R/datasize << endl << endl;
684  }
685 
686 // delete[] histo;
687 
688  image->FOM(R);
689 
690  return gauss;
691 }
692 
702 Bplot* Bimage::histogram_gauss_plot(long bins, long ngauss)
703 {
704  long i, j, k, m, ncol(ngauss+2);
705  double v, bin_half = (max - min)/(4*bins);
706 
707  vector<double> gauss = histogram_gauss_fit(bins, ngauss);
708 
709  double scale, offset;
710  vector<long> histo = histogram(bins, scale, offset);
711 
712  // Set the average and standard deviation to the first gaussian parameters
713  average(gauss[1]);
714  standard_deviation(gauss[2]);
715 
716  Bstring title("Gaussian fit"), txt;
717  Bplot* plot = new Bplot(1, bins, ncol);
718  plot->title(title);
719 
720  plot->page(0).title(title);
721  plot->page(0).columns(ncol);
722  for ( i=0; i<ncol; i++ ) plot->page(0).column(i).number(i);
723  plot->page(0).column(0).label("Bin");
724  plot->page(0).column(0).axis(1);
725  for ( i=1; i<ncol; i++ ) {
726  plot->page(0).column(i).type(2);
727  plot->page(0).column(i).axis(3);
728  plot->page(0).column(i).element_size(0.5);
729  }
730  plot->page(0).column(1).label("Count");
731  for ( i=2; i<ncol; i++ )
732  plot->page(0).column(i).label("Gaussian");
733  plot->page(0).column(1).type(1);
734  plot->page(0).column(1).color(0.5,0.5,0.5);
735  plot->page(0).column(2).color(1,0,0);
736  if ( n > 1 ) plot->page(0).column(3).color(0,1,0);
737  if ( n > 2 ) plot->page(0).column(4).color(0,0,1);
738  plot->page(0).axis(1).min(min - bin_half);
739  plot->page(0).axis(1).max(max + bin_half);
740 
741  for ( j=0; j<ngauss; j++ ){
742  txt = Bstring(j+1, "Gaussian %d:") + Bstring(gauss[3*j], " a=%g") +
743  Bstring(gauss[3*j+1], " u=%g") + Bstring(gauss[3*j+2], " s=%g");
744  plot->page(0).add_text(txt);
745  }
746  txt = Bstring(image->FOM(), "R: %g");
747  plot->page(0).add_text(txt);
748 
749  for ( i=0, j=bins; i<bins; i++, j++ ) {
750  (*plot)[i] = min + i/scale;
751  (*plot)[j] = histo[i];
752  for ( k=0, m=i+2*bins; k<3*ngauss; k+=3, m+=bins ) {
753  v = ((*plot)[i] - gauss[k+1])/gauss[k+2];
754  (*plot)[m] = gauss[k]*exp(-0.5*v*v);
755  }
756  }
757 
758 // delete[] histo;
759 
760  return plot;
761 }
762 /*
763 double simplex_poisson_R(Bsimplex& simp)
764 {
765  long i, j, n;
766  double v, R(0);
767 // double* df = new double[simp.points()];
768  vector<double> df(simp.points());
769 
770  simp.parameter(1, floor(simp.parameter(1)+0.5)); // Enforce integer
771 
772  for ( i=0, n=0; i<simp.points(); i++ ) {
773  if ( simp.fx[i] >= 0 ) {
774  v = simp.x[i] + simp.parameter(1);
775  df[i] = fabs(simp.fx[i] - simp.parameter(0) - v*log(simp.parameter(2)) +
776  simp.parameter(2) + lgamma(v+1.0L));
777  if ( !isfinite(df[i]) ) {
778  error_show("Error in img_fit_poisson_to_his_R", __FILE__, __LINE__);
779  cerr << "i=" << i << "\tfx[i]=" << simp.fx[i] << "\tamp=" <<
780  simp.parameter(0) << "\tpos=" << simp.parameter(1)
781  << "\tlambda=" << simp.parameter(2) << endl;
782  return 1e37;
783  }
784  n++;
785  } else df[i] = -1;
786  }
787 
788 // qsort((void *) df, simp.points(), sizeof(double),
789 // (int (*)(const void *, const void *)) QsortSmallToLargeDouble);
790  sort(df.begin(), df.end());
791 
792 // if ( simp->npoint < 100 ) j = simp->npoint - 3;
793 // else j = (simp->npoint*97)/100;
794  j = simp.points() - 3;
795 
796  for ( i=0, R=0; i<j; i++ ) if ( df[i] > -1 ) {
797  R += df[i]*df[i];
798  n++;
799  }
800 
801  if ( n ) R = sqrt(R/n);
802  else R = 1e37;
803 
804 // delete[] df;
805 
806  return R;
807 }
808 */
810 {
811  long i;
812  double fact(1), pl(1), df, R(0);
813  vector<double>& f = simp.dependent_values();
814  double ep(simp.parameter(0)*exp(-simp.parameter(1)));
815 
816 // simp.parameter(1, floor(simp.parameter(1)+0.5)); // Enforce integer
817 
818  for ( i=0; i<simp.points(); i++ ) {
819  if ( i ) {
820  fact *= i;
821  pl *= simp.parameter(1);
822  }
823  df = f[i] - pl*ep/fact;
824  R += df*df;
825  }
826 
827  if ( i ) R = sqrt(R/i);
828 
829  return R;
830 }
831 
848 /*Bplot* Bimage::histogram_poisson_fit(long bins, int flag)
849 {
850  long i, j, m, nn, ni;
851  double hmax(0), sum(0);
852  double bin_half = (max - min)/(4*bins);
853 
854  double scale, offset;
855  long* histo = histogram(bins, scale, offset);
856 
857  // Count the number of positive bins and readjust the histogram to have only positive bins
858  for ( i=0, j=0, nn=0, ni=0; i<bins; i++ ) {
859  if ( histo[i] > 0 ) {
860  ni += j;
861  nn++;
862  j = 0;
863  }
864  j++;
865  }
866 // if ( verbose & VERB_FULL )
867  cout << "Positive bins = " << nn << " Interval size = " << ni*1.0/nn << endl;
868  delete[] histo;
869 
870  if ( bins < nn ) bins = nn;
871  else bins = (bins*nn)/ni;
872 
873  histo = histogram(bins, scale, offset);
874 
875 // if ( verbose & VERB_FULL )
876  cout << "Bins reset to " << bins << ", scale = " << scale << ", offset = " << offset << endl << endl;
877 
878  // 3 parameters: amplitude, position, sigma
879 // double* x = new double[bins];
880 // double* fx = new double[bins];
881  vector<double> xx(bins), fx(bins);
882  for ( i=0; i<bins; i++ ) xx[i] = min + i/scale;
883  for ( i=1; i<bins-1; i++ ) {
884  if ( histo[i] < 1 ) fx[i] = log(0.5);
885  else fx[i] = log(1.0*histo[i]);
886  sum += fx[i];
887  if ( hmax < fx[i] ) hmax = fx[i];
888  cout << i << tab << xx[i] << tab << histo[i] << tab << fx[i] << endl;
889  }
890  fx[0] = fx[1];
891  fx[bins-1] = log(0.5);
892 
893  Bsimplex simp(1, 3, 0, bins, xx, fx);
894 
895  simp.parameter(0, log(datasize*1.0)); // ln(Amplitude)
896  simp.limits(0, log(datasize/2.0), log(datasize+1.0));
897 
898  simp.parameter(0, 0); // Position in bins
899  simp.limits(1, 0, 0);
900 
901  simp.parameter(2, std*std); // Lambda in bins
902  if ( simp.parameter(2) < 0.001 ) simp.parameter(2, 0.001);
903  simp.limits(2, 0.001, 10*std);
904  if ( simp.hi[2] < 1 ) simp.hi[2] = 10*avg;
905 
906  double R = simp.run(1000, 0.001, simplex_poisson_R);
907  R = exp(R);
908 
909 // delete[] x;
910 // delete[] fx;
911 
912  double* poisson = new double[3];
913  poisson[0] = exp(simp.parameter(0));
914  poisson[1] = simp.parameter(1);
915  poisson[2] = simp.parameter(2);
916 
917  if ( verbose & VERB_PROCESS ) {
918  cout << "Poisson function fit over " << bins << " bins:" << endl;
919  cout << "Lambda: " << poisson[2] << endl;
920 // cout << "Offset: " << poisson[1] << endl;
921  cout << "Included voxels: " << poisson[0] << " (" << 100*poisson[0]/datasize << "%)" << endl;
922  cout << "Sampling-independent RMSD: " << bins*R/datasize << endl << endl;
923  }
924 
925  // Set the average and standard deviation to the poisson parameters
926  average(poisson[2]);
927  standard_deviation(sqrt(poisson[2]));
928  image->FOM(R);
929 
930  long ncol(3);
931  Bstring title("Poisson fit"), txt;
932  Bplot* plot = NULL;
933 
934  if ( flag ) {
935  plot = new Bplot(1, bins, ncol);
936  plot->title(title);
937 
938  plot->page(0).title(title);
939  plot->page(0).columns(ncol);
940  for ( i=0; i<ncol; i++ ) plot->page(0).column(i).number(i);
941  plot->page(0).column(0).label("Bin");
942  plot->page(0).column(0).axis(1);
943  plot->page(0).column(1).type(1);
944  plot->page(0).column(1).label("Count");
945  plot->page(0).column(1).axis(3);
946  plot->page(0).column(1).element_size(0.5);
947  plot->page(0).column(1).color(0.5,0.5,0.5);
948  plot->page(0).column(2).type(2);
949  plot->page(0).column(2).label("Count");
950  plot->page(0).column(2).axis(3);
951  plot->page(0).column(2).element_size(0.5);
952  plot->page(0).column(2).color(1,0,0);
953  plot->page(0).axis(1).min(min - bin_half);
954  plot->page(0).axis(1).max(max + bin_half);
955 // plot->page(0).axis(3).min(prad->minimum());
956 // plot->page(0).axis(3).max(prad->maximum());
957 
958  txt = Bstring(poisson[0], "Poisson: a=%g") + Bstring(poisson[2], " u=%g");
959  plot->page(0).add_text(txt);
960  txt = Bstring(R, "R: %g");
961  plot->page(0).add_text(txt);
962 
963  for ( i=0, j=bins, m=2*bins; i<bins; i++, j++, m++ ) {
964  (*plot)[i] = i;
965  (*plot)[j] = histo[i];
966  (*plot)[m] = poisson[0]*pow(poisson[2],(double)i)*exp(-poisson[2])/factorial(i);
967  if ( !isfinite((*plot)[m]) ) (*plot)[m] = 0;
968  }
969  }
970 
971  delete[] histo;
972  delete[] poisson;
973 
974  return plot;
975 }
976 */
978 {
979  if ( std <= 0 ) statistics();
980 
981  if ( bins > avg + 5*std ) bins = avg + 5*std;
982  if ( bins > 150 ) bins = 150;
983  if ( bins < 5 ) bins = 5;
984 
985  long i, j, m, imax(0);
986  double hmax(0), scale(bins*1.0/(avg+5*std));
987 
988  vector<double> b(bins, 0);
989  vector<double> h(bins, 0);
990 
991  for ( i=0; i<datasize; ++i ) {
992  j = (long) (scale*(*this)[i] + 0.5);
993  if ( j >= 0 && j < bins ) h[j]+=1;
994  }
995 
996  for ( i=0; i<bins; ++i ) {
997  b[i] = i;
998  if ( hmax < h[i] ) {
999  hmax = h[i];
1000  imax = i;
1001  }
1002 // cout << i << tab << b[i] << tab << h[i] << endl;
1003  }
1004  if ( imax < 1 ) imax = 1;
1005 
1006 // bexit(0);
1007 
1008  cout << "scale=" << scale << " imax=" << imax << endl;
1009 
1010  Bsimplex simp(1, 2, 0, bins, b, h);
1011 
1012  simp.parameter(0, hmax); // Amplitude
1013  simp.limits(0, hmax, 20*hmax);
1014 
1015  simp.parameter(1, imax); // Lambda in bins
1016  if ( avg < imax ) simp.parameter(1, avg);
1017 // simp.limits(1, 0.5*imax, 2*imax);
1018  simp.limits(1, avg/2, 2*imax);
1019 
1020  double R = simp.run(1000, 0.001, simplex_poisson_R);
1021 
1022  if ( verbose & VERB_PROCESS ) {
1023  cout << "Poisson function fit over " << bins << " bins:" << endl;
1024  cout << "Amplitude: " << simp.parameter(0) << endl;
1025  cout << "Lambda: " << simp.parameter(1) << endl;
1026  cout << "Sampling-independent RMSD: " << bins*R/datasize << endl << endl;
1027  }
1028 
1029  // Set the average and standard deviation to the poisson parameters
1030  average(simp.parameter(1));
1031  standard_deviation(sqrt(simp.parameter(1)));
1032  image->FOM(R);
1033 
1034  long ncol(3);
1035  Bstring title("Poisson fit"), txt;
1036  Bplot* plot = NULL;
1037 
1038  if ( flag ) {
1039  plot = new Bplot(1, bins, ncol);
1040  plot->title(title);
1041 
1042  plot->page(0).title(title);
1043  plot->page(0).columns(ncol);
1044  for ( i=0; i<ncol; i++ ) plot->page(0).column(i).number(i);
1045  plot->page(0).column(0).label("Bin");
1046  plot->page(0).column(0).axis(1);
1047  plot->page(0).column(1).type(1);
1048  plot->page(0).column(1).label("Count");
1049  plot->page(0).column(1).axis(3);
1050  plot->page(0).column(1).element_size(0.5);
1051  plot->page(0).column(1).color(0.5,0.5,0.5);
1052  plot->page(0).column(2).type(2);
1053  plot->page(0).column(2).label("Count");
1054  plot->page(0).column(2).axis(3);
1055  plot->page(0).column(2).element_size(0.5);
1056  plot->page(0).column(2).color(1,0,0);
1057  plot->page(0).axis(1).min(0);
1058  plot->page(0).axis(1).max(bins);
1059 // plot->page(0).axis(3).min(prad->minimum());
1060 // plot->page(0).axis(3).max(prad->maximum());
1061 
1062  txt = Bstring(simp.parameter(0), "Poisson: a=%g") + Bstring(simp.parameter(1), " u=%g");
1063  plot->page(0).add_text(txt);
1064  txt = Bstring(R, "R: %g");
1065  plot->page(0).add_text(txt);
1066 
1067  for ( i=0, j=bins, m=2*bins; i<bins; i++, j++, m++ ) {
1068  (*plot)[i] = i;
1069  (*plot)[j] = h[i];
1070  (*plot)[m] = simp.parameter(0)*pow(simp.parameter(1),(double)i)*exp(-simp.parameter(1))/factorial(i);
1071  if ( !isfinite((*plot)[m]) ) (*plot)[m] = 0;
1072  }
1073  }
1074 
1075  return plot;
1076 }
1077 
qsort_functions.h
Header file for utility functions for use in qsort calls.
RHO
#define RHO
Definition: utilities.h:95
matrix_linear.h
Header file for matrix functions.
Bimage::histogram_gauss_fit
vector< double > histogram_gauss_fit(long bins, long ngauss=1)
Fits a gaussian function to a histogram of an image.
Definition: Bimage_histogram.cpp:590
verbose
int verbose
cluster.h
Header file for clustering functions.
VERB_DEBUG
#define VERB_DEBUG
Definition: utilities.h:116
Bimage::average
double average()
Definition: Bimage.h:543
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
Bcolumn::color
double * color()
Definition: Bplot.h:76
Bcolumn::element_size
double element_size()
Definition: Bplot.h:74
Bimage::sum
void sum(long m, Bimage **p)
Sums an array of images with their FOM blocks.
Definition: Bimage_combine.cpp:23
Bimage::histogram_counts
Bplot * histogram_counts(int flags=0)
Finds the peaks in a quantized image from the histogram.
Definition: Bimage_histogram.cpp:207
Bsimplex::constant
double constant(long i)
Definition: simplex.h:61
simplex.h
Nelder and Mead downhill simplex method for generalized parameter fitting.
Bplot
Definition: Bplot.h:146
Bcolumn::type
long type()
Definition: Bplot.h:66
Bsimplex::dependent_values
vector< double > & dependent_values()
Definition: simplex.h:85
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
factorial
double factorial(int n)
Calculates the factorial of n.
Definition: math_util.cpp:66
Bsimplex
Structure used in the downhill simplex method.
Definition: simplex.h:44
Bcolumn::axis
long axis()
Definition: Bplot.h:68
Bimage::standard_deviation
double standard_deviation()
Definition: Bimage.h:544
Bpage::axis
Baxis & axis(long id)
Definition: Bplot.h:117
Bpage::title
Bstring & title()
Definition: Bplot.h:100
Bsimplex::independent_values
vector< double > & independent_values()
Definition: simplex.h:84
Bsimplex::points
long points()
Definition: simplex.h:66
Bimage::image_size
long image_size()
Definition: Bimage.h:290
Bimage::histogram_thresholds
int histogram_thresholds(double &tmin, double &tmax)
Calculates minimum and maximum thresholds for truncation.
Definition: Bimage_histogram.cpp:421
Bpage::add_text
void add_text(Bstring &s)
Definition: Bplot.h:122
Bpage::column
Bcolumn & column(long i)
Definition: Bplot.h:110
Bsimplex::run
double run(long maxcycles, double tolerance, double(funk)(Bsimplex &))
Definition: simplex.cpp:76
simplex_poisson_R
double simplex_poisson_R(Bsimplex &simp)
Definition: Bimage_histogram.cpp:809
Bplot::title
Bstring & title()
Definition: Bplot.h:194
Bsimplex::parameter
void parameter(long i, double p)
Definition: simplex.h:71
Baxis::min
double min()
Definition: Bplot.h:30
Bimage.h
Header file for image class.
Bimage::plot
Bplot * plot()
Converts a one-dimensional image into a plot.
Definition: Bimage.cpp:3839
k_means
long * k_means(long n, float *data, long k)
Generate clusters using a K-means algorithm.
Definition: cluster.cpp:28
Bsimplex::limit_low
void limit_low(long i, double v)
Definition: simplex.h:73
Bimage::histogram_poisson_fit
Bplot * histogram_poisson_fit(long bins, int flag=0)
Fits a poisson function to a histogram of an image.
Definition: Bimage_histogram.cpp:977
Bimage::percentiles
Bplot * percentiles()
Calculates the percentiles from the histogram of an image.
Definition: Bimage_histogram.cpp:344
utilities.h
Header file for general utilities.
tab
ostream & tab(ostream &out)
Definition: utilities.cpp:22
isfinite
bool isfinite(complex< T > &value)
Bimage::histogram_gauss_plot
Bplot * histogram_gauss_plot(long bins, long ngauss=1)
Fits a gaussian function to a histogram of an image.
Definition: Bimage_histogram.cpp:702
Bimage::change_type
void change_type(char letter)
Get the data type indicated by a single letter code.
Definition: Bimage.cpp:1765
SCharacter
@ SCharacter
Definition: utilities.h:154
Bimage::data_pointer
unsigned char * data_pointer()
Definition: Bimage.h:284
Bimage::sampling
vector< Vector3< double > > sampling()
Definition: Bimage.h:529
Bcolumn::label
Bstring & label()
Definition: Bplot.h:63
Bplot::page
Bpage & page(long i)
Definition: Bplot.h:216
Bcolumn::number
long number()
Definition: Bplot.h:61
simplex_gauss_R
double simplex_gauss_R(Bsimplex &simp)
Definition: Bimage_histogram.cpp:559
Bsimplex::limits
void limits(long i, double vlo, double vhi)
Definition: simplex.h:77
Float
@ Float
Definition: utilities.h:161
Baxis::max
double max()
Definition: Bplot.h:32
VERB_LABEL
#define VERB_LABEL
Definition: utilities.h:110
Bimage::histogram
vector< long > histogram(long bins, double &scale, double &offset)
Calculates the histogram of an image.
Definition: Bimage_histogram.cpp:32
Bpage::columns
void columns(long ncol)
Definition: Bplot.h:105
Bimage::statistics
long statistics()
Calculates the statistics for an image.
Definition: Bimage_stats.cpp:22
Bsimplex::limit_high
void limit_high(long i, double v)
Definition: simplex.h:75
Bimage::otsu_threshold
double otsu_threshold(long bins)
Calculates the threshold on a histogram according to Otsu.
Definition: Bimage_histogram.cpp:523