Xmipp  v3.23.11-Nereus
xmipp_funcs.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  *
3  * Authors: Carlos Oscar S. Sorzano (coss@cnb.csic.es)
4  *
5  * Unidad de Bioinformatica of Centro Nacional de Biotecnologia , CSIC
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
20  * 02111-1307 USA
21  *
22  * All comments concerning this program package may be sent to the
23  * e-mail address 'xmipp@cnb.csic.es'
24  ***************************************************************************/
25 
26 //#include <stdlib.h>
27 //#include <time.h>
28 #include <iostream>
29 #include <fstream>
30 #include <sys/time.h>
31 #include <sys/stat.h>
32 #include <fcntl.h>
33 //#include <string.h>
34 #include "xmipp_funcs.h"
35 #include "numerical_recipes.h"
36 #include "xmipp_filename.h"
37 
38 //#include <typeinfo>
39 //#include "xmipp_error.h"
40 //#include <algorithm>
41 
42 #ifndef __MINGW32__
43  #include <sys/mman.h>
44  #ifdef __MACH__
45  #include <mach/clock.h>
46  #include <mach/mach.h>
47  #endif
48 #endif
49 
50 
51 /* Numerical functions ----------------------------------------------------- */
52 // Kaiser-Bessel constructor
53 KaiserBessel::KaiserBessel(double alpha_, int K_, double r_, double v_,
54  int N_, double vtable_, int ntable_)
55  : alpha(alpha_), v(v_), r(r_), N(N_), K(K_), vtable(vtable_),
56  ntable(ntable_)
57 {
58  // Default values are alpha=1.25, K=6, r=0.5, v = K/2
59  if (0.f == v)
60  v = double(K)/2;
61  if (0.f == vtable)
62  vtable = v;
63  alphar = alpha*r;
64  fac = static_cast<double>(2.*PI)*alphar*v;
65  vadjust = 1.0f*v;
66  facadj = static_cast<double>(2.*PI)*alphar*vadjust;
67  build_I0table();
68 }
69 
70 // Kaiser-Bessel I0 selfWindow function
71 double KaiserBessel::i0win(double x) const
72 {
73  double val0 = double(bessi0(facadj));
74  double absx = fabs(x);
75  if (absx > vadjust)
76  return 0.f;
77  double rt = sqrt(1.f - pow(absx/vadjust, 2));
78  double res = bessi0(facadj*rt)/val0;
79  return res;
80 }
81 
82 // Tabulate I0 selfWindow for speed
84 {
85  i0table.resize(ntable+1); // i0table[0:ntable]
86  int ltab = int(ROUND(double(ntable)/1.25f));
87  fltb = double(ltab)/(K/2);
88  //double val0 = gsl_sf_bessel_I0(facadj);
89  double val0 = bessi0(facadj);
90  for (int i=ltab+1; i <= ntable; i++)
91  i0table[i] = 0.f;
92  for (int i=0; i <= ltab; i++)
93  {
94  double s = double(i)/fltb/N;
95  if (s < vadjust)
96  {
97  double rt = sqrt(1.f - pow(s/vadjust, 2));
98  //i0table[i] = gsl_sf_bessel_I0(facadj*rt)/val0;
99  i0table[i] = bessi0(facadj*rt)/val0;
100  }
101  else
102  {
103  i0table[i] = 0.f;
104  }
105  }
106 }
107 
108 // Compute the maximum error in the table
110 {
111  double maxdiff = 0.f;
112  for (int i = 1; i <= ntable; i++)
113  {
114  double diff = fabs(i0table[i] - i0table[i-1]);
115  if (diff > maxdiff)
116  maxdiff = diff;
117  }
118  return maxdiff;
119 }
120 
121 // Kaiser-Bessel Sinh selfWindow function
122 double KaiserBessel::sinhwin(double x) const
123 {
124  double val0 = sinh(fac)/fac;
125  double absx = fabs(x);
126  if (0.0 == x)
127  {
128  double res = 1.0f;
129  return res;
130  }
131  else if (absx == alphar)
132  {
133  return 1.0f/val0;
134  }
135  else if (absx < alphar)
136  {
137  double rt = sqrt(1.0f - pow((x/alphar), 2));
138  double facrt = fac*rt;
139  double res = (sinh(facrt)/facrt)/val0;
140  return res;
141  }
142  else
143  {
144  double rt = sqrt(pow((x/alphar),2) - 1.f);
145  double facrt = fac*rt;
146  double res = (sin(facrt)/facrt)/val0;
147  return res;
148  }
149 }
150 
151 
152 // Solve second degree equation. ax^2+bx+c=0 -------------------------------
153 int solve_2nd_degree_eq(double a, double b, double c, double &x1, double &x2,
154  double prec)
155 {
156  // Degenerate case?
157  if (fabs(a) < prec)
158  {
159  if (fabs(b) < prec)
160  return -1;
161  else
162  {
163  x1 = -c / b;
164  return 1;
165  }
166  }
167 
168  // Normal case
169  double d = b * b - 4 * a * c;
170  if (d < 0)
171  return 0;
172  else
173  {
174  x1 = (-b + sqrt(d)) / (2 * a);
175  x2 = (-b - sqrt(d)) / (2 * a);
176  return 2;
177  }
178 }
179 
180 /* Gaussian value ---------------------------------------------------------- */
181 double gaussian1D(double x, double sigma, double mu)
182 {
183  x -= mu;
184  return 1 / sqrt(2*PI*sigma*sigma)*exp(-0.5*((x / sigma)*(x / sigma)));
185 }
186 
187 /* t-student value -------------------------------------------------------- */
188 double tstudent1D(double x, double df, double sigma, double mu)
189 {
190  x -= mu;
191  double norm = exp(gammln((df+1.)/2.)) / exp(gammln(df/2.));
192  norm /= sqrt(df*PI*sigma*sigma);
193  return norm * pow((1 + (x/sigma)*(x/sigma)/df),-((df+1.)/2.));
194 
195 }
196 
197 double gaussian2D(double x, double y, double sigmaX, double sigmaY,
198  double ang, double muX, double muY)
199 {
200  // Express x,y in the gaussian internal coordinates
201  x -= muX;
202  y -= muY;
203  double xp = cos(ang) * x + sin(ang) * y;
204  double yp = -sin(ang) * x + cos(ang) * y;
205 
206  // Now evaluate
207  return 1 / sqrt(2*PI*sigmaX*sigmaY)*exp(-0.5*((xp / sigmaX)*(xp / sigmaX) +
208  (yp / sigmaY)*(yp / sigmaY)));
209 }
210 
211 /* ICDF Gaussian ----------------------------------------------------------- */
212 double icdf_gauss(double p)
213 {
214  const double c[] =
215  {
216  2.515517, 0.802853, 0.010328
217  };
218  const double d[] =
219  {
220  1.432788, 0.189269, 0.001308
221  };
222  if (p < 0.5)
223  {
224  // F^-1(p) = - G^-1(p)
225  double t=sqrt(-2.0*log(p));
226  double z=t - ((c[2]*t + c[1])*t + c[0]) /
227  (((d[2]*t + d[1])*t + d[0])*t + 1.0);
228  return -z;
229  }
230  else
231  {
232  // F^-1(p) = G^-1(1-p)
233  double t=sqrt(-2.0*log(1-p));
234  double z=t - ((c[2]*t + c[1])*t + c[0]) /
235  (((d[2]*t + d[1])*t + d[0])*t + 1.0);
236  return z;
237  }
238 }
239 
240 /* CDF Gaussian ------------------------------------------------------------ */
241 double cdf_gauss(double x)
242 {
243  return 0.5 * (1. + erf(x/sqrt(2.)));
244 }
245 
246 /*************************************************************************
247 Student's t distribution
248 
249 Computes the integral from minus infinity to t of the Student
250 t distribution with integer k > 0 degrees of freedom:
251 
252  t
253  -
254  | |
255  - | 2 -(k+1)/2
256  | ( (k+1)/2 ) | ( x )
257  ---------------------- | ( 1 + --- ) dx
258  - | ( k )
259  sqrt( k pi ) | ( k/2 ) |
260  | |
261  -
262  -inf.
263 
264 Relation to incomplete beta integral:
265 
266  1 - stdtr(k,t) = 0.5 * incbet( k/2, 1/2, z )
267 where
268  z = k/(k + t**2).
269 
270 For t < -2, this is the method of computation. For higher t,
271 a direct method is derived from integration by parts.
272 Since the function is symmetric about t=0, the area under the
273 right tail of the density is found by calling the function
274 with -t instead of t.
275 
276 ACCURACY:
277 
278 Tested at random 1 <= k <= 25. The "domain" refers to t.
279  Relative error:
280 arithmetic domain # trials peak rms
281  IEEE -100,-2 50000 5.9e-15 1.4e-15
282  IEEE -2,100 500000 2.7e-15 4.9e-17
283 
284 Cephes Math Library Release 2.8: June, 2000
285 Copyright 1984, 1987, 1995, 2000 by Stephen L. Moshier
286 *************************************************************************/
287 double cdf_tstudent(int k, double t)
288 {
289  double EPS=5E-16;
290  double result;
291  double x;
292  double rk;
293  double z;
294  double f;
295  double tz;
296  double p;
297  double xsqk;
298  int j;
299 
300  if ( t==0 )
301  {
302  result = 0.5;
303  return result;
304  }
305  if ( t<-2.0 )
306  {
307  rk = k;
308  z = rk/(rk+t*t);
309  result = 0.5*betai(0.5*rk, 0.5, z);
310  return result;
311  }
312  if ( t<0 )
313  {
314  x = -t;
315  }
316  else
317  {
318  x = t;
319  }
320  rk = k;
321  z = 1.0+x*x/rk;
322  if ( k%2 != 0 )
323  {
324  xsqk = x/sqrt(rk);
325  p = atan(xsqk);
326  if ( k > 1 )
327  {
328  f = 1.0;
329  tz = 1.0;
330  j = 3;
331  while ( j <= k-2 && tz/f > EPS )
332  {
333  tz = tz*((j-1)/(z*j));
334  f = f+tz;
335  j = j+2;
336  }
337  p = p+f*xsqk/z;
338  }
339  p = p*2.0/PI;
340  }
341  else
342  {
343  f = 1.0;
344  tz = 1.0;
345  j = 2;
346  while ( j<= k-2 && tz/f > EPS)
347  {
348  tz = tz*((j-1)/(z*j));
349  f = f+tz;
350  j = j+2;
351  }
352  p = f*x/sqrt(z*rk);
353  }
354  if ( t<0 )
355  {
356  p = -p;
357  }
358  result = 0.5+0.5*p;
359  return result;
360 }
361 
362 /* Snedecor's F ------------------------------------------------------------ */
363 // http://en.wikipedia.org/wiki/F-distribution
364 double cdf_FSnedecor(int d1, int d2, double x)
365 {
366  return betai(0.5*d1,0.5*d2,(d1*x)/(d1*x+d2));
367 }
368 
369 double icdf_FSnedecor(int d1, int d2, double p)
370 {
371  double xl=0, xr=1e6;
372  double xm, pm;
373  do
374  {
375  xm=(xl+xr)*0.5;
376  pm=cdf_FSnedecor(d1,d2,xm);
377  if (pm>p)
378  {
379  xr=xm;
380  }
381  else
382  {
383  xl=xm;
384  }
385  }
386  while (fabs(pm-p)/p>0.001);
387  return xm;
388 }
389 
390 /* Random functions -------------------------------------------------------- */
391 int idum;
392 
393 // Uniform distribution ....................................................
394 void init_random_generator(int seed)
395 {
396  idum = -1;
397  ran1(&idum);
398  if (seed != -1)
399  {
400  // Prevent seeds larger than 65000
401  seed %=0xffff;
402  for (int i = 0; i < seed; i++)
403  ran1(&idum);
404  }
405 }
406 
408 {
409  static unsigned int seed;
410  int rand_return;
411  struct timespec highresTime;
412 
413 #ifdef __MACH__ // OS X does not have clock_gettime, use clock_get_time
414 
415  clock_serv_t cclock;
416  mach_timespec_t mts;
417  host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
418  clock_get_time(cclock, &mts);
419  mach_port_deallocate(mach_task_self(), cclock);
420  highresTime.tv_sec = mts.tv_sec;
421  highresTime.tv_nsec = mts.tv_nsec;
422 #else
423 
424  clock_gettime(CLOCK_REALTIME, &highresTime);
425 #endif
426 
427  srand(rand()+clock()+time(NULL)+highresTime.tv_nsec);
428  rand_return = rand();
429 
430  time_t t;
431  time(&t);
432  //rand_return = abs(rand_return);
433  idum = (-(int)(t % 10000)
434  - (int)(rand_return % 10000));
435  ran1(&idum);
436  seed = (unsigned int)rand_return;
437  return seed;
438 }
439 
440 double rnd_unif()
441 {
442  return ran1(&idum);
443 }
444 double rnd_unif(double a, double b)
445 {
446  if (a == b)
447  return a;
448  else
449  return a + (b - a)*ran1(&idum);
450 }
451 
452 // t-distribution
453 double rnd_student_t(double nu)
454 {
455  return tdev(nu, &idum);
456 }
457 double rnd_student_t(double nu, double a, double b)
458 {
459  if (b == 0)
460  return a;
461  else
462  return b*tdev(nu, &idum) + a;
463 }
464 
465 // Gaussian distribution ...................................................
466 double rnd_gaus()
467 {
468  return gasdev(&idum);
469 }
470 double rnd_gaus(double a, double b)
471 {
472  if (b == 0)
473  return a;
474  else
475  return b*gasdev(&idum) + a;
476 }
477 double gaus_within_x0(double x0, double mean, double stddev)
478 {
479  double z0 = (x0 - mean) / stddev;
480  return erf(ABS(z0) / sqrt(2.0));
481 }
482 
483 double gaus_outside_x0(double x0, double mean, double stddev)
484 {
485  double z0 = (x0 - mean) / stddev;
486  return erfc(ABS(z0) / sqrt(2.0));
487 }
488 
489 double gaus_up_to_x0(double x0, double mean, double stddev)
490 {
491  if (x0 > mean)
492  return 1.0 -gaus_outside_x0(x0, mean, stddev) / 2;
493  else if (x0 == mean)
494  return 0.5;
495  else
496  return gaus_outside_x0(x0, mean, stddev) / 2;
497 }
498 
499 double gaus_from_x0(double x0, double mean, double stddev)
500 {
501  if (x0 > mean)
502  return gaus_outside_x0(x0, mean, stddev) / 2;
503  else if (x0 == mean)
504  return 0.5;
505  else
506  return 1.0 -gaus_outside_x0(x0, mean, stddev) / 2;
507 }
508 
509 double gaus_outside_probb(double p, double mean, double stddev)
510 {
511  // Make a Bolzano search for the right value
512  double pm, x1, x2, xm;
513  x1 = mean;
514  x2 = mean + 5 * stddev;
515  do
516  {
517  xm = (x1 + x2) / 2;
518  pm = gaus_outside_x0(xm, mean, stddev);
519  if (pm > p)
520  x1 = xm;
521  else
522  x2 = xm;
523  }
524  while (ABS(pm - p) / p > 0.005);
525  return xm;
526 }
527 
528 // See Numerical Recipes, Chap. 6.3
529 double student_within_t0(double t0, double degrees_of_freedom)
530 {
531  return 1 -betai(degrees_of_freedom / 2, 0.5,
532  degrees_of_freedom / (degrees_of_freedom + t0*t0));
533 }
534 
535 double student_outside_t0(double t0, double degrees_of_freedom)
536 {
537  return 1 -student_within_t0(t0, degrees_of_freedom);
538 }
539 
540 double student_up_to_t0(double t0, double degrees_of_freedom)
541 {
542  if (t0 >= 0)
543  return 1.0 -student_outside_t0(t0, degrees_of_freedom) / 2;
544  else
545  return student_outside_t0(t0, degrees_of_freedom) / 2;
546 }
547 
548 double student_from_t0(double t0, double degrees_of_freedom)
549 {
550  return 1 -student_up_to_t0(t0, degrees_of_freedom);
551 }
552 
553 double student_outside_probb(double p, double degrees_of_freedom)
554 {
555  // Make a Bolzano search for the right value
556  double pm, t1, t2, tm;
557  t1 = 0;
558  t2 = 100;
559  do
560  {
561  tm = (t1 + t2) / 2;
562  pm = student_outside_t0(tm, degrees_of_freedom);
563  if (pm > p)
564  t1 = tm;
565  else
566  t2 = tm;
567  }
568  while (fabs(pm - p) / p > 0.005);
569  return tm;
570 }
571 
572 double chi2_up_to_t0(double t0, double degrees_of_freedom)
573 {
574  return gammp(degrees_of_freedom / 2, t0 / 2);
575 }
576 
577 double chi2_from_t0(double t0, double degrees_of_freedom)
578 {
579  return 1 -chi2_up_to_t0(t0, degrees_of_freedom);
580 }
581 
582 // Log uniform distribution ................................................
583 double rnd_log(double a, double b)
584 {
585  if (a == b)
586  return a;
587  else
588  return exp(rnd_unif(log(a), log(b)));
589 }
590 
591 /* Time managing ----------------------------------------------------------- */
592 #ifdef _NO_TIME
593 void time_config()
594 {}
596 {}
598 {}
599 double elapsed_time(ProcessorTimeStamp &time)
600 {}
601 double time_to_go(ProcessorTimeStamp &time, double fraction_done)
602 {}
603 void TimeMessage(const std::string &message)
604 {}
605 void progress_bar(long rlen)
606 {}
607 #else
608 #if defined __MINGW32__ || defined __APPLE__
609 struct tm* localtime_r (const time_t *clock, struct tm *result)
610 {
611  if (!clock || !result)
612  return NULL;
613  memcpy(result,localtime(clock),sizeof(*result));
614  return result;
615 }
616 void sin_cos(double angle, double * sine, double * cosine)
617 {
618  *sine = sin(angle);
619  *cosine = cos(angle);
620 }
621 #endif
622 
623 // A global ................................................................
625 
626 // Time configuration ......................................................
627 // The clock frequency for each machine must be known
629 {
630 #ifndef __MINGW32__
631  XmippTICKS = sysconf(_SC_CLK_TCK);
632 #else
633 
634  XmippTICKS = CLK_TCK;
635 #endif
636 }
637 
638 #if !defined _NO_TIME && !defined __MINGW32__
639 // Annotate actual time ....................................................
641 {
642  times(time);
643 }
644 #endif
645 
647 {
648  struct timeval tv;
649  gettimeofday(&tv, NULL);
650  struct tm tm;
651  localtime_r(&tv.tv_sec,&tm);
652  *time = tm.tm_hour * 3600 * 1000 + tm.tm_min * 60 * 1000 + tm.tm_sec * 1000 +
653  tv.tv_usec / 1000;
654 }
655 
656 #if !defined _NO_TIME && !defined __MINGW32__
657 // Acumulative time
659 {
660  ProcessorTimeStamp now;
661  times(&now);
662  (*dest).tms_utime += (*dest).tms_utime + (now.tms_utime - (*orig).tms_utime);
663  (*dest).tms_stime += (*dest).tms_stime + (now.tms_utime - (*orig).tms_utime);
664 }
665 #endif
666 
667 #if !defined _NO_TIME && !defined __MINGW32__
668 // Show elapsed time since last annotation .................................
669 void print_elapsed_time(ProcessorTimeStamp &time, bool _IN_SECS)
670 {
671  ProcessorTimeStamp now;
672  times(&now);
673  double userTime = now.tms_utime - time.tms_utime;
674  double sysTime = now.tms_stime - time.tms_stime;
675  if (_IN_SECS)
676  {
677  userTime /= XmippTICKS;
678  sysTime /= XmippTICKS;
679  }
680  std::cout << "Elapsed time: User(" << userTime << ") System(" << sysTime
681  << ")\n";
682 }
683 #endif
684 
685 void print_elapsed_time(TimeStamp& time, bool _IN_SECS)
686 {
687  struct timeval tv;
688  gettimeofday(&tv, NULL);
689  struct tm tm;
690  localtime_r(&tv.tv_sec,&tm);
691  TimeStamp now = tm.tm_hour * 3600 * 1000 + tm.tm_min * 60 * 1000 + tm.tm_sec * 1000 +
692  tv.tv_usec / 1000;
693  TimeStamp diff=now-time;
694 
695  std::cout << "Elapsed time: ";
696  if (_IN_SECS)
697  std::cout << diff/1000.0 << " secs." << std::endl;
698  else
699  std::cout << diff << " msecs." << std::endl;
700 }
701 
702 size_t Timer::now()
703 {
704  gettimeofday(&tv, NULL);
705  localtime_r(&tv.tv_sec,&tm);
706  return tm.tm_hour * 3600 * 1000 + tm.tm_min * 60 * 1000 + tm.tm_sec * 1000 +
707  tv.tv_usec / 1000;
708 }
709 
710 size_t Timer::tic()
711 {
712  tic_time = now();
713  return tic_time;
714 }
715 
716 size_t Timer::toc(const char * msg, bool inSecs)
717 {
718  size_t diff = elapsed();
719 
720  if (msg != NULL)
721  std::cout << msg;
722  std::cout << "Elapsed time: ";
723 
724  if (inSecs)
725  std::cout << diff/1000.0 << " secs." << std::endl;
726  else
727  std::cout << diff << " msecs." << std::endl;
728 
729  return diff;
730 }
731 
733 {
734  return now() - tic_time;
735 }
736 
737 
738 // Calculate elapsed time since last annotation .............................
739 double elapsed_time(ProcessorTimeStamp &time, bool _IN_SECS)
740 {
741 #if !defined _NO_TIME && !defined __MINGW32__
742  ProcessorTimeStamp now;
743  times(&now);
744  double userTime = now.tms_utime - time.tms_utime;
745  double sysTime = now.tms_stime - time.tms_stime;
746  if (_IN_SECS)
747  {
748  userTime /= XmippTICKS;
749  sysTime /= XmippTICKS;
750  }
751  return userTime + sysTime;
752 #endif
753 }
754 
755 #if !defined _NO_TIME && !defined __MINGW32__
756 // Compute the predicted time left .........................................
757 double time_to_go(ProcessorTimeStamp &time, double fraction_done)
758 {
759  ProcessorTimeStamp now;
760  times(&now);
761  double totalTime = (now.tms_utime - time.tms_utime +
762  now.tms_stime - time.tms_stime) / XmippTICKS;
763  return totalTime*(1 - fraction_done) / fraction_done;
764 }
765 #endif
766 
767 // Show a message with the time it is produced .............................
768 void TimeMessage(const std::string & message)
769 {
770  struct tm *T;
771  time_t seconds;
772 
773  if (time(&seconds) < 0)
774  seconds = 0;
775  T = localtime(&seconds);
776 
777  printf("%2d:%2d:%2d (day=%2d) =>%s ", T->tm_hour,
778  T->tm_min, T->tm_sec, T->tm_mday, message.c_str());
779 }
780 
781 // Init progress bar
782 void init_progress_bar(long total)
783 {
784  progress_bar(-(total));
785 }
786 
787 // Show a bar with the progress in time ....................................
788 // When the input is negative then we are setting the progress bar, this
789 // will be the total of elements to process. Afterwards the call to this
790 // routine must be in ascending order, ie, 0, 1, 2, ... No. elements
791 void progress_bar(long rlen)
792 {
793  static time_t startt;
794  time_t currt;
795  static long totlen;
796  long t1, t2;
797  int min, i, hour;
798  double h1, h2, m1, m2;
799  bool queue = (getenv("XMIPP_IN_QUEUE") != NULL);
800 
801  if (rlen == 0)
802  return;
803  currt = time(NULL);
804 
805  if (rlen < 0)
806  {
807  totlen = -rlen;
808  startt = currt;
809  fprintf(stdout, "0000/???? sec. ");
810  if (!queue)
811  for (i = 0; i < 10; i++)
812  fprintf(stdout, "------");
813  fflush(stdout);
814  }
815  else if (totlen > 0)
816  {
817  t1 = currt - startt; // Elapsed time
818  t2 = (long)(t1 * (double)totlen / rlen); // Total time
819 
820  hour = 0;
821  min = 0;
822  if (t2 > 60)
823  {
824  m1 = (double)t1 / 60.0;
825  m2 = (double)t2 / 60.0;
826  min = 1;
827  if (m2 > 60)
828  {
829  h1 = (double)m1 / 60.0;
830  h2 = (double)m2 / 60.0;
831  hour = 1;
832  min = 0;
833  }
834  else
835  hour = 0;
836  }
837 
838  if (hour)
839  fprintf(stdout, "\r%3.2f/%3.2f %s ", h1, h2, "hours");
840  else if (min)
841  fprintf(stdout, "\r%3.2f/%3.2f %s ", m1, m2, "min");
842  else
843  fprintf(stdout, "\r%4u/%4u %4s ", (int)t1, (int)t2, "sec.");
844 
845  if (!queue)
846  {
847  i = (int)(60 * (1 - (double)(totlen - rlen) / totlen));
848  while (i--)
849  fprintf(stdout, ".");
850  }
851 
852  if (rlen == totlen)
853  {
854  fprintf(stdout, "\n");
855  totlen = 0;
856  }
857  fflush(stdout);
858  }
859 }
860 
862 {
863  time_t rawtime;
864  time ( &rawtime );
865  char * str = ctime (&rawtime);
866  char * pos = strrchr(str, '\n');
867  pos[0] = '\0'; //Remove \n end character
868  return str;
869 
870 }
871 
872 // Initialize progress bar.
873 
874 void TextualListener::OnInitOperation(unsigned long _est_it)
875 {
876  progress_bar(-static_cast<long>(_est_it));
877 }
878 
879 // Show a bar with the progress in time ....................................
880 // When the input is negative then we are setting the progress bar, this
881 // will be the total of elements to process. Afterwards the call to this
882 // routine must be in ascending order, ie, 0, 1, 2, ... No. elements
883 // Almost identical to previous progress bar function, in fact, we call
884 // those functions inside.
885 
886 void TextualListener::OnProgress(unsigned long _it)
887 {
888  progress_bar(_it);
889 }
890 
891 // Shows a message indicating the operation in progress.
892 void TextualListener::OnReportOperation(const std::string& _rsOp)
893 {
894  fprintf(stderr, "%s", _rsOp.c_str());// std::cout << _rsOp;
895 }
896 
897 
898 #endif
899 
900 /* Little/big endian ------------------------------------------------------- */
901 // Read in reverse/normal order --------------------------------------------
902 size_t xmippFREAD(void *dest, size_t size, size_t nitems, FILE * &fp, bool reverse)
903 {
904  size_t retval;
905  if (!reverse)
906  retval = fread(dest, size, nitems, fp);
907  else
908  {
909  char *ptr = (char *)dest;
910  bool end = false;
911  retval = 0;
912  for (size_t n = 0; n < nitems; n++)
913  {
914  char * ptrp = ptr + size - 1;
915  for (size_t i = 0; i < size; ++i, --ptrp)
916  {
917  if (fread(ptrp, 1, 1, fp) != 1)
918  {
919  end = true;
920  break;
921  }
922  }
923  if (end)
924  break;
925  else
926  retval++;
927  ptr += size;
928  }
929  }
930  if (retval != nitems)
931  REPORT_ERROR(ERR_IO_NOREAD,"XmippFREAD: An error occurred or End of File was reached.");
932 
933  return retval;
934 }
935 
936 // Read in reverse/normal order --------------------------------------------
937 size_t xmippFWRITE(const void *src, size_t size, size_t nitems, FILE * &fp,
938  bool reverse)
939 {
940  size_t retval;
941  if (!reverse)
942  retval = fwrite(src, size, nitems, fp);
943  else
944  {
945  char *ptr = (char *)src;
946  bool end = false;
947  retval = 0;
948  for (size_t n = 0; n < nitems; n++)
949  {
950  char * ptrp = ptr + size - 1;
951  for (size_t i = 0; i < size; ++i, --ptrp)
952  {
953  if (fwrite(ptrp, 1, 1, fp) != 1)
954  {
955  end = true;
956  break;
957  }
958  }
959  if (end)
960  break;
961  else
962  retval++;
963  ptr += size;
964  }
965  }
966  return retval;
967 }
968 
969 /* Map file */
970 void mapFile(const FileName &filename, char*&map, size_t &size, int &fileDescriptor, bool readOnly)
971 {
972  if (size<0)
973  {
974  struct stat file_status;
975  if(stat(filename.c_str(), &file_status) != 0)
976  REPORT_ERROR(ERR_IO_NOPATH,"Cannot get filesize for file "+filename);
977  size = file_status.st_size;
978  }
979 #ifdef XMIPP_MMAP
980  struct stat file_status;
981  if(stat(filename.c_str(), &file_status) != 0)
982  REPORT_ERROR(ERR_IO_NOPATH,(String)"Cannot get filesize for file "+filename);
983  size = file_status.st_size;
984  if(size==0)
985  REPORT_ERROR(ERR_IO_NOPATH,(String)"File size=0, cannot read it ("+filename+")");
986 
987  if (readOnly)
988  fileDescriptor = open(filename.c_str(), O_RDONLY, S_IREAD);
989  else
990  fileDescriptor = open(filename.c_str(), O_RDWR, S_IREAD | S_IWRITE);
991  if (fileDescriptor == -1)
992  REPORT_ERROR(ERR_IO_NOPATH,(String)"Cannot open file named "+filename);
993 
994  if (readOnly)
995  map = (char *) mmap(0, size, PROT_READ, MAP_SHARED, fileDescriptor, 0);
996  else
997  map = (char *) mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileDescriptor, 0);
998  if (map == MAP_FAILED)
999  REPORT_ERROR(ERR_MEM_BADREQUEST,"Write can not map memory ");
1000 #else
1001 
1002  map = new char[size];
1003  fileDescriptor = open(filename.data(), O_RDONLY);
1004  if (fileDescriptor == -1)
1005  REPORT_ERROR(ERR_IO_NOPATH,(String)"Cannot open file named "+filename);
1006  int ok=read(fileDescriptor,map,size);
1007  if (ok==-1)
1008  REPORT_ERROR(ERR_IO_NOREAD,(String)"Cannot read from file named"+filename);
1009 #endif
1010 }
1011 
1012 /* Unmap file*/
1013 void unmapFile(char *&map, size_t &size, int& fileDescriptor)
1014 {
1015 #ifdef XMIPP_MMAP
1016  if (munmap(map, size) == -1)
1017  REPORT_ERROR(ERR_MEM_NOTDEALLOC,"Cannot unmap memory");
1018 #else
1019 
1020  delete []map;
1021  map=NULL;
1022 #endif
1023 
1024  close(fileDescriptor);
1025 }
1026 
1027 /* Conversion little-big endian any size */
1028 void ByteSwap(unsigned char * b, int n)
1029 {
1030  int i = 0;
1031  int j = n - 1;
1032  while (i < j)
1033  {
1034  std::swap(b[i], b[j]);
1035  i++, j--;
1036  }
1037 }
1038 
1039 // Bsoft function
1040 void swapbytes(char* v, unsigned long n)
1041 {
1042  char t, t0, t1, t2, t3;
1043  switch (n)
1044  {
1045  case 4:
1046  t0 = v[0];
1047  t1 = v[1];
1048  v[0]=v[3];
1049  v[1]=v[2];
1050  v[2]=t1;
1051  v[3]=t0;
1052  break;
1053  case 2:
1054  t = v[0];
1055  v[0] = v[1];
1056  v[1] = t;
1057  break;
1058  case 1:
1059  break;
1060  case 8:
1061  t0 = v[0];
1062  t1 = v[1];
1063  t2 = v[2];
1064  t3 = v[4];
1065  v[0]=v[7];
1066  v[1]=v[6];
1067  v[2]=v[5];
1068  v[3]=v[4];
1069  v[4]=t3;
1070  v[5]=t2;
1071  v[6]=t1;
1072  v[7]=t0;
1073  break;
1074  default:
1075  for (size_t i=0; i<n/2; i++ )
1076  {
1077  t = v[i];
1078  v[i] = v[n-1-i];
1079  v[n-1-i] = t;
1080  }
1081  }
1082 }
1083 
1085 bool IsLittleEndian(void)
1086 {
1087  static const unsigned long ul = 0x00000001;
1088  return ((int)(*((unsigned char *) &ul)))!=0;
1089 }
1090 
1092 bool IsBigEndian(void)
1093 {
1094  static const unsigned long ul = 0x01000000;
1095  return ((int)(*((unsigned char *) &ul)))!=0;
1096 }
1097 
1099 //
1100 // process_mem_usage(double &, double &) - takes two doubles by reference,
1101 // attempts to read the system-dependent data for a process' virtual memory
1102 // size and resident set size, and return the results in KB.
1103 //
1104 // On failure, returns 0.0, 0.0
1105 void processMemUsage(double& vm_usage, double& resident_set)
1106 {
1107  using std::ios_base;
1108  using std::ifstream;
1109  using std::string;
1110 
1111  vm_usage = 0.0;
1112  resident_set = 0.0;
1113 
1114  // 'file' stat seems to give the most reliable results
1115  //
1116  ifstream stat_stream("/proc/self/stat",ios_base::in);
1117 
1118  // dummy vars for leading entries in stat that we don't care about
1119  //
1120  string pid, comm, state, ppid, pgrp, session, tty_nr;
1121  string tpgid, flags, minflt, cminflt, majflt, cmajflt;
1122  string utime, stime, cutime, cstime, priority, nice;
1123  string O, itrealvalue, starttime;
1124 
1125  // the two fields we want
1126  //
1127  unsigned long vsize;
1128  long rss;
1129 
1130  stat_stream >> pid >> comm >> state >> ppid >> pgrp >> session >> tty_nr
1131  >> tpgid >> flags >> minflt >> cminflt >> majflt >> cmajflt
1132  >> utime >> stime >> cutime >> cstime >> priority >> nice
1133  >> O >> itrealvalue >> starttime >> vsize >> rss; // don't care about the rest
1134 
1135  stat_stream.close();
1136 
1137  long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to use 2MB pages
1138  vm_usage = vsize / 1024.0;
1139  resident_set = rss * page_size_kb;
1140 }
1141 
1143 {
1144  double virtualMemory, residentMemory;
1145  processMemUsage(virtualMemory, residentMemory);
1146  std::cout << "VM: " << virtualMemory << "kB ; RSS: " << residentMemory << " kB" << std::endl;
1147 }
1148 
1150 size_t divide_equally(size_t N, size_t size, size_t rank, size_t &first, size_t &last)
1151 {
1152  size_t jobs_per_worker = N / size;
1153  size_t jobs_resting = N % size;
1154 
1155  if (rank < jobs_resting)
1156  {
1157  first = rank * (jobs_per_worker + 1);
1158  last = first + jobs_per_worker;
1159  }
1160  else
1161  {
1162  first = rank * jobs_per_worker + jobs_resting;
1163  last = first + jobs_per_worker - 1;
1164  }
1165 
1166  return last - first + 1;
1167 }
1169 size_t divide_equally_group(size_t N, size_t size, size_t myself)
1170 {
1171  size_t first, last;
1172  for (size_t rank = 0; rank < size; rank++)
1173  {
1174  divide_equally(N, size, rank, first, last);
1175  if (myself >= first && myself <= last)
1176  return rank;
1177  }
1178  return -1;
1179 
1180 }
1181 
1183 bool compareTwoFiles(const FileName &fn1, const FileName &fn2, size_t offset)
1184 {
1185  char *map1,*map2;
1186  int fd1, fd2;
1187  size_t size1=-1, size2=-1;
1188  mapFile(fn1,map1,size1,fd1,true);
1189  mapFile(fn2,map2,size2,fd2,true);
1190  int result=memcmp(map1+offset,map2+offset,size1-offset);
1191  unmapFile(map1,size1,fd1);
1192  unmapFile(map2,size2,fd2);
1193  return (result==0);
1194 }
double cdf_gauss(double x)
void init_progress_bar(long total)
void TimeMessage(const std::string &message)
void min(Image< double > &op1, const Image< double > &op2)
size_t now()
double student_outside_probb(double p, double degrees_of_freedom)
size_t tic()
double betai(double a, double b, double x)
double student_within_t0(double t0, double degrees_of_freedom)
double gaus_up_to_x0(double x0, double mean, double stddev)
double cdf_tstudent(int k, double t)
double rnd_student_t(double nu)
bool IsLittleEndian(void)
bool IsBigEndian(void)
#define REPORT_ERROR(nerr, ErrormMsg)
Definition: xmipp_error.h:211
void swapbytes(char *v, unsigned long n)
char * getCurrentTimeString()
double vadjust
Definition: xmipp_funcs.h:161
doublereal * c
int solve_2nd_degree_eq(double a, double b, double c, double &x1, double &x2, double prec)
doublereal * xl
void sqrt(Image< double > &op)
double facadj
Definition: xmipp_funcs.h:162
void annotate_processor_time(ProcessorTimeStamp *time)
double vtable
Definition: xmipp_funcs.h:155
static double * y
double gaus_outside_probb(double p, double mean, double stddev)
size_t divide_equally(size_t N, size_t size, size_t rank, size_t &first, size_t &last)
double sinhwin(double x) const
double icdf_gauss(double p)
void processMemUsage(double &vm_usage, double &resident_set)
double elapsed_time(ProcessorTimeStamp &time, bool _IN_SECS)
#define z0
double time_to_go(ProcessorTimeStamp &time, double fraction_done)
Memory has not been deallocated.
Definition: xmipp_error.h:167
T norm(const std::vector< T > &v)
Definition: vector_ops.h:399
double cdf_FSnedecor(int d1, int d2, double x)
double student_up_to_t0(double t0, double degrees_of_freedom)
void ByteSwap(unsigned char *b, int n)
Bad amount of memory requested.
Definition: xmipp_error.h:165
doublereal * x
#define i
void init_random_generator(int seed)
ql0001_ & k(htemp+1),(cvec+1),(atemp+1),(bj+1),(bl+1),(bu+1),(x+1),(clamda+1), &iout, infoqp, &zero,(w+1), &lenw,(iw+1), &leniw, &glob_grd.epsmac
double chi2_from_t0(double t0, double degrees_of_freedom)
doublereal * d
size_t divide_equally_group(size_t N, size_t size, size_t myself)
double student_from_t0(double t0, double degrees_of_freedom)
int XmippTICKS
void time_config()
double gaussian2D(double x, double y, double sigmaX, double sigmaY, double ang, double muX, double muY)
double rnd_unif()
size_t elapsed()
__device__ float bessi0(float x)
glob_log first
double rnd_log(double a, double b)
doublereal * b
void unmapFile(char *&map, size_t &size, int &fileDescriptor)
void log(Image< double > &op)
#define x0
virtual void OnProgress(unsigned long _it)
int in
double * f
double student_outside_t0(double t0, double degrees_of_freedom)
struct tms ProcessorTimeStamp
Definition: xmipp_funcs.h:822
void progress_bar(long rlen)
bool compareTwoFiles(const FileName &fn1, const FileName &fn2, size_t offset)
binary comparison of two files skipping first "offset" bytes
double chi2_up_to_t0(double t0, double degrees_of_freedom)
double icdf_FSnedecor(int d1, int d2, double p)
#define ABS(x)
Definition: xmipp_macros.h:142
double z
size_t toc(const char *msg=NULL, bool inSecs=true)
#define ROUND(x)
Definition: xmipp_macros.h:210
double gaus_within_x0(double x0, double mean, double stddev)
void print_elapsed_time(ProcessorTimeStamp &time, bool _IN_SECS)
Couldn&#39;t read from file.
Definition: xmipp_error.h:139
double gasdev(int *idum)
double gammp(double a, double x)
double tstudent1D(double x, double df, double sigma, double mu)
#define j
size_t xmippFWRITE(const void *src, size_t size, size_t nitems, FILE *&fp, bool reverse)
size_t xmippFREAD(void *dest, size_t size, size_t nitems, FILE *&fp, bool reverse)
virtual void OnInitOperation(unsigned long _est_it)
void mapFile(const FileName &filename, char *&map, size_t &size, int &fileDescriptor, bool readOnly)
double tdev(double nu, int *idum)
void build_I0table()
Definition: xmipp_funcs.cpp:83
constexpr long double EPS
double alphar
Definition: xmipp_funcs.h:159
double ran1(int *idum)
std::string String
Definition: xmipp_strings.h:34
double rnd_gaus()
double i0win(double x) const
Definition: xmipp_funcs.cpp:71
int mu
KaiserBessel(double alpha_, int K, double r_, double v_, int N_, double vtable_=0., int ntable_=5999)
Definition: xmipp_funcs.cpp:53
fprintf(glob_prnt.io, "\)
virtual void OnReportOperation(const std::string &_rsOp)
Environment PATH cannot be read.
Definition: xmipp_error.h:143
constexpr int K
double I0table_maxerror()
int idum
std::vector< double > i0table
Definition: xmipp_funcs.h:157
void annotate_time(TimeStamp *time)
unsigned int randomize_random_generator()
file read(std::istream &is)
Definition: pdb2cif.cpp:6200
#define PI
Definition: tools.h:43
double gaus_outside_x0(double x0, double mean, double stddev)
double alpha
Definition: xmipp_funcs.h:152
int * n
doublereal * a
void printMemoryUsed()
double gammln(double xx)
size_t TimeStamp
Definition: xmipp_funcs.h:823
void acum_time(ProcessorTimeStamp *orig, ProcessorTimeStamp *dest)
double gaus_from_x0(double x0, double mean, double stddev)
double gaussian1D(double x, double sigma, double mu)