EMAN2
util.cpp
Go to the documentation of this file.
1/*
2 * Author: Steven Ludtke, 04/10/2003 (sludtke@bcm.edu)
3 * Copyright (c) 2000-2006 Baylor College of Medicine
4 *
5 * This software is issued under a joint BSD/GNU license. You may use the
6 * source code in this file under either license. However, note that the
7 * complete EMAN2 and SPARX software packages have some GPL dependencies,
8 * so you are responsible for compliance with the licenses of these packages
9 * if you opt to use BSD licensing. The warranty disclaimer below holds
10 * in either instance.
11 *
12 * This complete copyright notice must be included in any revised version of the
13 * source code. Additional authorship citations may be added, but existing
14 * author citations must be preserved.
15 *
16 * This program is free software; you can redistribute it and/or modify
17 * it under the terms of the GNU General Public License as published by
18 * the Free Software Foundation; either version 2 of the License, or
19 * (at your option) any later version.
20 *
21 * This program is distributed in the hope that it will be useful,
22 * but WITHOUT ANY WARRANTY; without even the implied warranty of
23 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 * GNU General Public License for more details.
25 *
26 * You should have received a copy of the GNU General Public License
27 * along with this program; if not, write to the Free Software
28 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
29 *
30 * */
31
32#include "byteorder.h"
33#include "emassert.h"
34#include "emdata.h"
35#include "util.h"
36#include "randnum.h"
37
38#include <fcntl.h>
39#include <iomanip>
40#include <sstream>
41
42#include <cstring>
43
44#include <ctype.h>
45#include <sys/types.h>
46#include <gsl/gsl_linalg.h>
47#include <algorithm> // using accumulate, inner_product, transform
48
49#ifndef WIN32
50 #include <unistd.h>
51 #include <sys/param.h>
52#else
53 #include <ctime>
54 #include <io.h>
55 #define access _access
56 #define F_OK 00
57#endif //WIN32
58
59using namespace std;
60using namespace boost;
61using namespace EMAN;
62
64int Util::MUTEX_INIT(MUTEX *mutex)
65{
66 #ifdef WIN32
67 *mutex = CreateMutex(0, FALSE, 0);
68 return (*mutex==0);
69 #else
70 return pthread_mutex_init(mutex, NULL);
71 #endif
72 return -1;
73}
74
76{
77 #ifdef WIN32
78 return (WaitForSingleObject(*mutex, INFINITE)==WAIT_FAILED?1:0);
79 #else
80 return pthread_mutex_lock(mutex);
81 #endif
82 return -1;
83}
84
86{
87 #ifdef WIN32
88 return (ReleaseMutex(*mutex)==0);
89 #else
90 return pthread_mutex_unlock(mutex);
91 #endif
92 return -1;
93}
94
95
97void Util::ap2ri(float *data, size_t n)
98{
99 Assert(n > 0);
100
101 if (!data) {
102 throw NullPointerException("pixel data array");
103 }
104
105 for (size_t i = 0; i < n; i += 2) {
106 float f = data[i] * sin(data[i + 1]);
107 data[i] = data[i] * cos(data[i + 1]);
108 data[i + 1] = f;
109 }
110}
111
112void Util::ap2ri(double *data, size_t n)
113{
114 Assert(n > 0);
115
116 if (!data) {
117 throw NullPointerException("pixel data array");
118 }
119
120 for (size_t i = 0; i < n; i += 2) {
121 double f = data[i] * sin(data[i + 1]);
122 data[i] = data[i] * cos(data[i + 1]);
123 data[i + 1] = f;
124 }
125}
126
127void Util::flip_complex_phase(float *data, size_t n)
128{
129 Assert(n > 0);
130
131 if (!data) {
132 throw NullPointerException("pixel data array");
133 }
134
135 for (size_t i = 0; i < n; i += 2) {
136 data[i + 1] *= -1;
137 }
138}
139
140void Util::rotate_phase_origin(float *data, size_t nx, size_t ny, size_t nz)
141{
142 if(ny==1 && nz==1) { //1D, do nothing
143 return;
144 }
145 else if(ny!=1 && nz==1) { //2D, rotate vertically by ny/2
146 size_t i, j, k, l;
147 float re;
148 l=ny/2*nx;
149 for (i=0; i<ny/2; i++) {
150 for (j=0; j<nx; j++) {
151 k=j+i*nx;
152 re=data[k];
153 data[k]=data[k+l];
154 data[k+l]=re;
155 }
156 }
157 }
158 else { //3D, in the y,z plane, swaps quadrants I,III and II,IV, this is the 'rotation' in y and z
159 size_t i, j, k, l, ii, jj;
160 char * t=(char *)malloc(sizeof(float)*nx);
161
162 k=nx*ny*(nz+1)/2;
163 l=nx*ny*(nz-1)/2;
164 jj=nx*sizeof(float);
165 for (j=ii=0; j<nz/2; ++j) {
166 for (i=0; i<ny; ++i,ii+=nx) {
167 memcpy(t,data+ii,jj);
168 if (i<ny/2) {
169 memcpy(data+ii,data+ii+k,jj);
170 memcpy(data+ii+k,t,jj);
171 }
172 else {
173 memcpy(data+ii,data+ii+l,jj);
174 memcpy(data+ii+l,t,jj);
175 }
176 }
177 }
178 free(t);
179 }
180}
181
182int Util::file_lock_wait(FILE * file)
183{
184#ifdef WIN32
185 return 1;
186#else
187
188 if (!file) {
189 throw NullPointerException("Tried to lock NULL file");
190 }
191
192 int fdes = fileno(file);
193
194 struct flock fl;
195 fl.l_type = F_WRLCK;
196 fl.l_whence = SEEK_SET;
197 fl.l_start = 0;
198 fl.l_len = 0;
199#ifdef WIN32
200 fl.l_pid = _getpid();
201#else
202 fl.l_pid = getpid();
203#endif
204
205#if defined __sgi
206 fl.l_sysid = getpid();
207#endif
208
209 int err = 0;
210 if (fcntl(fdes, F_SETLKW, &fl) == -1) {
211 LOGERR("file locking error! NFS problem?");
212
213 int i = 0;
214 for (i = 0; i < 5; i++) {
215 if (fcntl(fdes, F_SETLKW, &fl) != -1) {
216 break;
217 }
218 else {
219#ifdef WIN32
220 Sleep(1000);
221#else
222 sleep(1);
223#endif
224
225 }
226 }
227 if (i == 5) {
228 LOGERR("Fatal file locking error");
229 err = 1;
230 }
231 }
232
233 return err;
234#endif
235}
236
237
238
239bool Util::check_file_by_magic(const void *first_block, const char *magic)
240{
241 if (!first_block || !magic) {
242 throw NullPointerException("first_block/magic");
243 }
244
245 const char *buf = static_cast < const char *>(first_block);
246
247 if (strncmp(buf, magic, strlen(magic)) == 0) {
248 return true;
249 }
250 return false;
251}
252
253bool Util::is_file_exist(const string & filename)
254{
255 return access(filename.c_str(), F_OK) == 0;
256}
257
258
259void Util::flip_image(float *data, size_t nx, size_t ny)
260{
261 if (!data) {
262 throw NullPointerException("image data array");
263 }
264 Assert(nx > 0);
265 Assert(ny > 0);
266
267 float *buf = new float[nx];
268 size_t row_size = nx * sizeof(float);
269
270 for (size_t i = 0; i < ny / 2; i++) {
271 memcpy(buf, &data[i * nx], row_size);
272 memcpy(&data[i * nx], &data[(ny - 1 - i) * nx], row_size);
273 memcpy(&data[(ny - 1 - i) * nx], buf, row_size);
274 }
275
276 if( buf )
277 {
278 delete[]buf;
279 buf = 0;
280 }
281}
282
283string Util::str_to_lower(const string& s) {
284 string ret(s);
285 std::transform(s.begin(), s.end(), ret.begin(), ::tolower);
286 return ret;
287}
288
289void Util::replace_non_ascii(char *str, int max_size, char repl_char)
290{
291 int ic;
292
293 if (str != NULL) {
294 ic = 0;
295
296 while (ic < max_size && str[ic] != 0) {
297 if (! isascii (str[ic])) {
298 str[ic] = repl_char;
299 }
300
301 ic++;
302 }
303 }
304}
305
306bool Util::sstrncmp(const char *s1, const char *s2)
307{
308 if (!s1 || !s2) {
309 throw NullPointerException("Null string");
310 }
311
312 return strncmp(s1, s2, strlen(s2)) == 0;
313}
314
315string Util::int2str(int n)
316{
317 char s[32] = {'\0'};
318 sprintf(s, "%d", n);
319 return string(s);
320}
321
322string Util::get_line_from_string(char **slines)
323{
324 if (!slines || !(*slines)) {
325 throw NullPointerException("Null string");
326 }
327
328 string result = "";
329 char *str = *slines;
330
331 while (*str != '\n' && *str != '\0') {
332 result.push_back(*str);
333 str++;
334 }
335 if (*str != '\0') {
336 str++;
337 }
338 *slines = str;
339
340 return result;
341}
342
343vector<EMData *> Util::svdcmp(const vector<EMData *> &data,int nvec) {
344 int nimg=data.size();
345 if (nvec==0) nvec=nimg;
346 vector<EMData *> ret(nvec);
347 if (nimg==0) return ret;
348 int pixels=data[0]->get_xsize()*data[0]->get_ysize()*data[0]->get_zsize();
349
350 // Allocate the working space
351 gsl_vector *work=gsl_vector_alloc(nimg);
352 gsl_vector *S=gsl_vector_alloc(nimg);
353 gsl_matrix *A=gsl_matrix_alloc(pixels,nimg);
354 gsl_matrix *V=gsl_matrix_alloc(nimg,nimg);
355 gsl_matrix *X=gsl_matrix_alloc(nimg,nimg);
356
357 int im,x,y,z,i;
358 for (im=0; im<nimg; im++) {
359 for (z=0,i=0; z<data[0]->get_zsize(); z++) {
360 for (y=0; y<data[0]->get_ysize(); y++) {
361 for (x=0; x<data[0]->get_xsize(); x++,i++) {
362 gsl_matrix_set(A,i,im,data[im]->get_value_at(x,y,z));
363 }
364 }
365 }
366 }
367
368 // This calculates the SVD
369 gsl_linalg_SV_decomp_mod (A,X, V, S, work);
370
371 for (im=0; im<nvec; im++) {
372 EMData *a=data[0]->copy_head();
373 ret[im]=a;
374 for (z=0,i=0; z<data[0]->get_zsize(); z++) {
375 for (y=0; y<data[0]->get_ysize(); y++) {
376 for (x=0; x<data[0]->get_xsize(); x++,i++) {
377 a->set_value_at(x,y,z,static_cast<float>(gsl_matrix_get(A,i,im)));
378 }
379 }
380 }
381 }
382 return ret;
383}
384
385bool Util::get_str_float(const char *s, const char *float_var, float *p_val)
386{
387 if (!s || !float_var || !p_val) {
388 throw NullPointerException("string float");
389 }
390 size_t n = strlen(float_var);
391 if (strncmp(s, float_var, n) == 0) {
392 *p_val = (float) atof(&s[n]);
393 return true;
394 }
395
396 return false;
397}
398
399bool Util::get_str_float(const char *s, const char *float_var, float *p_v1, float *p_v2)
400{
401 if (!s || !float_var || !p_v1 || !p_v2) {
402 throw NullPointerException("string float");
403 }
404
405 size_t n = strlen(float_var);
406 if (strncmp(s, float_var, n) == 0) {
407 sscanf(&s[n], "%f,%f", p_v1, p_v2);
408 return true;
409 }
410
411 return false;
412}
413
414bool Util::get_str_float(const char *s, const char *float_var,
415 int *p_v0, float *p_v1, float *p_v2)
416{
417 if (!s || !float_var || !p_v0 || !p_v1 || !p_v2) {
418 throw NullPointerException("string float");
419 }
420
421 size_t n = strlen(float_var);
422 *p_v0 = 0;
423 if (strncmp(s, float_var, n) == 0) {
424 if (s[n] == '=') {
425 *p_v0 = 2;
426 sscanf(&s[n + 1], "%f,%f", p_v1, p_v2);
427 }
428 else {
429 *p_v0 = 1;
430 }
431 return true;
432 }
433 return false;
434}
435
436bool Util::get_str_int(const char *s, const char *int_var, int *p_val)
437{
438 if (!s || !int_var || !p_val) {
439 throw NullPointerException("string int");
440 }
441
442 size_t n = strlen(int_var);
443 if (strncmp(s, int_var, n) == 0) {
444 *p_val = atoi(&s[n]);
445 return true;
446 }
447 return false;
448}
449
450bool Util::get_str_int(const char *s, const char *int_var, int *p_v1, int *p_v2)
451{
452 if (!s || !int_var || !p_v1 || !p_v2) {
453 throw NullPointerException("string int");
454 }
455
456 size_t n = strlen(int_var);
457 if (strncmp(s, int_var, n) == 0) {
458 sscanf(&s[n], "%d,%d", p_v1, p_v2);
459 return true;
460 }
461 return false;
462}
463
464bool Util::get_str_int(const char *s, const char *int_var, int *p_v0, int *p_v1, int *p_v2)
465{
466 if (!s || !int_var || !p_v0 || !p_v1 || !p_v2) {
467 throw NullPointerException("string int");
468 }
469
470 size_t n = strlen(int_var);
471 *p_v0 = 0;
472 if (strncmp(s, int_var, n) == 0) {
473 if (s[n] == '=') {
474 *p_v0 = 2;
475 sscanf(&s[n + 1], "%d,%d", p_v1, p_v2);
476 }
477 else {
478 *p_v0 = 1;
479 }
480 return true;
481 }
482 return false;
483}
484
485string Util::change_filename_ext(const string & old_filename,
486 const string & ext)
487{
488 Assert(old_filename != "");
489 if (ext.empty())
490 return old_filename;
491
492 return remove_filename_ext(old_filename) + "." + ext;
493}
494
495string Util::remove_filename_ext(const string& filename)
496{
497 if (filename.empty())
498 return "";
499
500 auto pos = filename.rfind('.');
501
502 return pos!=string::npos ? filename.substr(0, pos) : filename;
503}
504
505string Util::sbasename(const string & filename)
506{
507 if (filename == "") {
508 return "";
509 }
510
511 char s = '/';
512#ifdef _WIN32
513 s = '\\';
514#endif
515 const char * c = strrchr(filename.c_str(), s);
516 if (!c) {
517 return filename;
518 }
519 else {
520 c++;
521 }
522 return string(c);
523}
524
525
526string Util::get_filename_ext(const string& filename)
527{
528 if (filename.empty())
529 return "";
530
531 auto pos = filename.rfind('.');
532 if (pos != string::npos)
533 return filename.substr(pos+1);
534 else
535 return "";
536}
537
538void Util::calc_least_square_fit(size_t nitems, const float *data_x, const float *data_y,
539 float *slope, float *intercept, bool ignore_zero,float absmax)
540{
541 Assert(nitems > 0);
542
543 if (!data_x || !data_y || !slope || !intercept) {
544 throw NullPointerException("null float pointer");
545 }
546 double sum = 0;
547 double sum_x = 0;
548 double sum_y = 0;
549 double sum_xx = 0;
550 double sum_xy = 0;
551
552 for (size_t i = 0; i < nitems; i++) {
553 if ((!ignore_zero || (data_x[i] != 0 && data_y[i] != 0))&&(!absmax ||(data_y[i]<absmax && data_y[i]>-absmax))) {
554 double y = data_y[i];
555 double x = i;
556 if (data_x) {
557 x = data_x[i];
558 }
559
560 sum_x += x;
561 sum_y += y;
562 sum_xx += x * x;
563 sum_xy += x * y;
564 sum++;
565 }
566 }
567
568 double div = sum * sum_xx - sum_x * sum_x;
569 if (div == 0) {
570 div = 0.0000001f;
571 }
572
573 *intercept = (float) ((sum_xx * sum_y - sum_x * sum_xy) / div);
574 *slope = (float) ((sum * sum_xy - sum_x * sum_y) / div);
575}
576
578unsigned int i;
579
580// various sums used in the final solution
581double Sx=0,Sy=0,Sxy=0,Sxx=0,Syy=0,Sz=0,Sxz=0,Syz=0,S=0;
582for (i=0; i<p.size(); i+=3) {
583 Sx+=p[i];
584 Sy+=p[i+1];
585 Sz+=p[i+2];
586 Sxx+=p[i]*p[i];
587 Syy+=p[i+1]*p[i+1];
588 Sxy+=p[i]*p[i+1];
589 S+=1.0;
590 Sxz+=p[i]*p[i+2];
591 Syz+=p[i+1]*p[i+2];
592}
593double d=S*Sxy*Sxy - 2*Sx*Sxy*Sy + Sxx*Sy*Sy + Sx*Sx*Syy - S*Sxx*Syy;
594
595Vec3f ret(0,0,0);
596
597ret[0]=static_cast<float>(-((Sxy*Sxz*Sy - Sx*Sxz*Syy + Sx*Sxy*Syz - Sxx*Sy*Syz - Sxy*Sxy*Sz +Sxx*Syy*Sz)/d));
598ret[1]=static_cast<float>(-((-Sxz*Sy*Sy + S*Sxz*Syy - S*Sxy*Syz + Sx*Sy*Syz + Sxy*Sy*Sz -Sx*Syy*Sz) /d));
599ret[2]=static_cast<float>(-((-S*Sxy*Sxz + Sx*Sxz*Sy - Sx*Sx*Syz + S*Sxx*Syz + Sx*Sxy*Sz -Sxx*Sy*Sz) /d));
600
601return ret;
602}
603
604void Util::save_data(const vector < float >&x_array, const vector < float >&y_array,
605 const string & filename)
606{
607 Assert(x_array.size() > 0);
608 Assert(y_array.size() > 0);
609 Assert(filename != "");
610
611 if (x_array.size() != y_array.size()) {
612 LOGERR("array x and array y have different size: %d != %d\n",
613 x_array.size(), y_array.size());
614 return;
615 }
616
617 FILE *out = fopen(filename.c_str(), "wb");
618 if (!out) {
619 throw FileAccessException(filename);
620 }
621
622 for (size_t i = 0; i < x_array.size(); i++) {
623 fprintf(out, "%g\t%g\n", x_array[i], y_array[i]);
624 }
625 fclose(out);
626}
627
628void Util::save_data(float x0, float dx, const vector < float >&y_array,
629 const string & filename)
630{
631 Assert(dx != 0);
632 Assert(y_array.size() > 0);
633 Assert(filename != "");
634
635 FILE *out = fopen(filename.c_str(), "wb");
636 if (!out) {
637 throw FileAccessException(filename);
638 }
639
640 for (size_t i = 0; i < y_array.size(); i++) {
641 fprintf(out, "%g\t%g\n", x0 + dx * i, y_array[i]);
642 }
643 fclose(out);
644}
645
646
647void Util::save_data(float x0, float dx, float *y_array,
648 size_t array_size, const string & filename)
649{
650 Assert(dx > 0);
651 Assert(array_size > 0);
652 Assert(filename != "");
653
654 if (!y_array) {
655 throw NullPointerException("y array");
656 }
657
658 FILE *out = fopen(filename.c_str(), "wb");
659 if (!out) {
660 throw FileAccessException(filename);
661 }
662
663 for (size_t i = 0; i < array_size; i++) {
664 fprintf(out, "%g\t%g\n", x0 + dx * i, y_array[i]);
665 }
666 fclose(out);
667}
668
669
670void Util::sort_mat(float *left, float *right, int *leftPerm, int *rightPerm)
671// Adapted by PRB from a macro definition posted on SourceForge by evildave
672{
673 float *pivot ; int *pivotPerm;
674
675 {
676 float *pLeft = left; int *pLeftPerm = leftPerm;
677 float *pRight = right; int *pRightPerm = rightPerm;
678 float scratch = *left; int scratchPerm = *leftPerm;
679
680 while (pLeft < pRight) {
681 while ((*pRight > scratch) && (pLeft < pRight)) {
682 pRight--; pRightPerm--;
683 }
684 if (pLeft != pRight) {
685 *pLeft = *pRight; *pLeftPerm = *pRightPerm;
686 pLeft++; pLeftPerm++;
687 }
688 while ((*pLeft < scratch) && (pLeft < pRight)) {
689 pLeft++; pLeftPerm++;
690 }
691 if (pLeft != pRight) {
692 *pRight = *pLeft; *pRightPerm = *pLeftPerm;
693 pRight--; pRightPerm--;
694 }
695 }
696 *pLeft = scratch; *pLeftPerm = scratchPerm;
697 pivot = pLeft; pivotPerm= pLeftPerm;
698 }
699 if (left < pivot) {
700 sort_mat(left, pivot - 1,leftPerm,pivotPerm-1);
701 }
702 if (right > pivot) {
703 sort_mat(pivot + 1, right,pivotPerm+1,rightPerm);
704 }
705}
706
707void Util::set_randnum_seed(unsigned long long seed)
708{
709 Randnum* randnum = Randnum::Instance();
710 randnum->set_seed(seed);
711}
712
713unsigned long long Util::get_randnum_seed()
714{
715 Randnum* randnum = Randnum::Instance();
716 return randnum->get_seed();
717}
718
719int Util::get_irand(int lo, int hi)
720{
721 Randnum* randnum = Randnum::Instance();
722 return randnum->get_irand(lo, hi);
723}
724
725float Util::get_frand(int lo, int hi)
726{
727 return get_frand((float)lo, (float)hi);
728}
729
730float Util::get_frand(float lo, float hi)
731{
732 Randnum* randnum = Randnum::Instance();
733 return randnum->get_frand(lo, hi);
734}
735
736float Util::get_frand(double lo, double hi)
737{
738 Randnum* randnum = Randnum::Instance();
739 return randnum->get_frand(lo, hi);
740}
741
742float Util::hypot_fast(int x, int y)
743{
744static float *mem = (float *)malloc(4*128*128);
745static int dim = 0;
746x=abs(x);
747y=abs(y);
748
749if (x>=dim || y>=dim) {
750 if (x>2048 || y>2048) return (float)hypot((float)x,(float)y); // We won't cache anything bigger than 4096^2
751 dim=x>=dim?x+1:dim;
752 dim=y>=dim?y+1:dim;
753 mem=(float*)realloc(mem,4*dim*dim);
754 for (int y=0; y<dim; y++) {
755 for (int x=0; x<dim; x++) {
756 mem[x+y*dim]=hypot((float)x,(float)y);
757 }
758 }
759}
760
761return mem[x+y*dim];
762}
763
764short Util::hypot_fast_int(int x, int y)
765{
766static short *mem = (short *)malloc(2*128*128);
767static int dim = 0;
768x=abs(x);
769y=abs(y);
770
771if (x>=dim || y>=dim) {
772 if (x>4095 || y>4095) return (short)hypot((float)x,(float)y); // We won't cache anything bigger than 4096^2
773 dim=x>=dim?x+1:dim;
774 dim=y>=dim?y+1:dim;
775 mem=(short*)realloc(mem,2*dim*dim);
776 for (int y=0; y<dim; y++) {
777 for (int x=0; x<dim; x++) {
778 mem[x+y*dim]=(short)Util::round(hypot((float)x,(float)y));
779 }
780 }
781}
782
783return mem[x+y*dim];
784}
785
786// Uses a precached table to return a good approximate to exp(x)
787// if outside the cached range, uses regular exp
788float Util::fast_exp(const float &f) {
789static float *mem = (float *)malloc(sizeof(float)*1000);
790static bool needinit=true;
791
792if (needinit) {
793 needinit=false;
794 for (int i=0; i<1000; i++) mem[i]=(float)exp(-i/50.0);
795}
796if (f>0 || f<-19.98) return exp(f);
797int g=(int)(-f*50.0+0.5);
798
799return mem[g];
800}
801
802// Uses a precached table to return a good approximate to acos(x)
803// tolerates values outside the -1 - 1 domain by clamping to PI,0
804float Util::fast_acos(const float &f) {
805if (f>=1.0) return 0.0;
806if (f<=-1.0) return M_PI;
807
808static float *mem = (float *)malloc(sizeof(float)*2001);
809static bool needinit=true;
810
811
812if (needinit) {
813 needinit=false;
814 for (int i=0; i<=2000; i++) mem[i]=(float)acos(i/1000.0-1.0);
815}
816float f2=f*1000.0f+1000.0f;
817
818int g=(int)(f2+.5);
819
820return mem[g];
821
822// This version interpolates, but is slower
823/*int g=(int)f2;
824f2-=g;
825return mem[g+1]*f2+mem[g]*(1.0-f2);*/
826}
827
828// Uses a precached table to return a good approximate to exp(-2 x^2)
829// if outside the cached range, uses regular function
830float Util::fast_gauss_B2(const float &f) {
831static float *mem = (float *)malloc(sizeof(float)*1000);
832static bool needinit=true;
833
834if (needinit) {
835 needinit=false;
836 for (int i=0; i<1000; i++) mem[i]=(float)exp(-i*i/125000.0f);
837}
838if (f>1.998) return exp(-2.0f*f*f);
839int g=(int)(fabs(f)*500.0f+0.5f);
840
841return mem[g];
842}
843
844
845float Util::get_gauss_rand(float mean, float sigma)
846{
847 Randnum* randnum = Randnum::Instance();
848 return randnum->get_gauss_rand(mean, sigma);
849}
850
851void Util::find_max(const float *data, size_t nitems, float *max_val, int *max_index)
852{
853 Assert(nitems > 0);
854
855 if (!data || !max_val || !max_index) {
856 throw NullPointerException("data/max_val/max_index");
857 }
858 float max = -FLT_MAX;
859 int m = 0;
860
861 for (size_t i = 0; i < nitems; i++) {
862 if (data[i] > max) {
863 max = data[i];
864 m = (int)i;
865 }
866 }
867
868 *max_val = (float)max;
869
870 if (max_index) {
871 *max_index = m;
872 }
873}
874
875void Util::find_min_and_max(const float *data, size_t nitems,
876 float *max_val, float *min_val,
877 int *max_index, int *min_index)
878{
879 Assert(nitems > 0);
880
881 if (!data || !max_val || !min_val || !max_index || !min_index) {
882 throw NullPointerException("data/max_val/min_val/max_index/min_index");
883 }
884 float max = -FLT_MAX;
885 float min = FLT_MAX;
886 int max_i = 0;
887 int min_i = 0;
888
889 for (size_t i = 0; i < nitems; i++) {
890 if (data[i] > max) {
891 max = data[i];
892 max_i = (int)i;
893 }
894 if (data[i] < min) {
895 min = data[i];
896 min_i = (int)i;
897 }
898 }
899
900 *max_val = max;
901 *min_val = min;
902
903 if (min_index) {
904 *min_index = min_i;
905 }
906
907 if (max_index) {
908 *max_index = max_i;
909 }
910
911}
912
913Dict Util::get_stats( const vector<float>& data )
914{
915 // Note that this is a heavy STL approach using generic algorithms - some memory could be saved
916 // using plain c style code, as in get_stats_cstyle below
917
918 if (data.size() == 0) EmptyContainerException("Error, attempting to call get stats on an empty container (vector<double>)");
919
920 double sum = accumulate(data.begin(), data.end(), 0.0);
921
922 double mean = sum / static_cast<double> (data.size());
923
924 double std_dev = 0.0, skewness = 0.0, kurtosis = 0.0;
925
926 if (data.size() > 1)
927 {
928 // read mm is "minus_mean"
929 vector<double> data_mm(data.size());
930 // read ts as "then squared"
931 vector<double> data_mm_sq(data.size());
932
933 // Subtract the mean from the data and store it in data_mm
934 transform(data.begin(), data.end(), data_mm.begin(), std::bind2nd(std::minus<double>(), mean));
935
936 // Get the square of the data minus the mean and store it in data_mm_sq
937 transform(data_mm.begin(), data_mm.end(), data_mm.begin(), data_mm_sq.begin(), std::multiplies<double>());
938
939 // Get the sum of the squares for the calculation of the standard deviation
940 double square_sum = accumulate(data_mm_sq.begin(), data_mm_sq.end(), 0.0);
941
942 //Calculate teh standard deviation
943 std_dev = sqrt(square_sum / static_cast<double>(data.size()-1));
944 double std_dev_sq = std_dev * std_dev;
945
946 // The numerator for the skewness fraction, as defined in http://www.itl.nist.gov/div898/handbook/eda/section3/eda35b.htm
947 double cubic_sum = inner_product(data_mm.begin(), data_mm.end(),data_mm_sq.begin(), 0.0);
948
949 // The numerator for the kurtosis fraction, as defined in http://www.itl.nist.gov/div898/handbook/eda/section3/eda35b.htm
950 double quartic_sum = inner_product(data_mm_sq.begin(), data_mm_sq.end(),data_mm_sq.begin(), 0.0);
951
952 // Finalize the calculation of the skewness and kurtosis, as defined in
953 // http://www.itl.nist.gov/div898/handbook/eda/section3/eda35b.htm
954 skewness = cubic_sum / ((data.size()-1) * std_dev_sq * std_dev );
955 kurtosis = quartic_sum / ((data.size()-1) * std_dev_sq * std_dev_sq );
956
957 }
958
959 Dict parms;
960 parms["mean"] = mean;
961 parms["std_dev"] = std_dev;
962 parms["skewness"] = skewness;
963 parms["kurtosis"] = kurtosis;
964
965 return parms;
966}
967
968
969Dict Util::get_stats_cstyle( const vector<float>& data )
970{
971 if (data.size() == 0) EmptyContainerException("Error, attempting to call get stats on an empty container (vector<double>)");
972
973 double square_sum = 0.0, sum = 0.0, cube_sum = 0.0, quart_sum = 0.0;
974 for( vector<float>::const_iterator it = data.begin(); it != data.end(); ++it )
975 {
976 double val = *it;
977 double square = val*val;
978 quart_sum += square*square;
979 cube_sum += square*val;
981 sum += val;
982 }
983
984 double mean = sum/(double)data.size();
985
986 double std_dev = 0.0, skewness = 0.0, kurtosis = 0.0;
987
988 if (data.size() > 1)
989 {
990 // The standard deviation is calculated here
991 std_dev = sqrt( (square_sum - mean*sum)/(double)(data.size()-1));
992
993 double square_mean = mean*mean;
994 double cube_mean = mean*square_mean;
995
996 double square_std_dev = std_dev*std_dev;
997
998 // This is the numerator of the skewness fraction, if you expand the brackets, as defined in
999 // http://www.itl.nist.gov/div898/handbook/eda/section3/eda35b.htm
1000 double cubic_sum = cube_sum - 3*square_sum*mean + 3*sum*square_mean - cube_mean*data.size();
1001 // Complete the skewness fraction
1002 skewness = cubic_sum/((data.size()-1)*square_std_dev*std_dev);
1003
1004 // This is the numerator of the kurtosis fraction, if you expand the brackets, as defined in
1005 // http://www.itl.nist.gov/div898/handbook/eda/section3/eda35b.htm
1006 double quartic_sum = quart_sum - 4*cube_sum*mean + 6*square_sum*square_mean - 4*sum*cube_mean + square_mean*square_mean*data.size();
1007 // Complete the kurtosis fraction
1008 kurtosis = quartic_sum /( (data.size()-1)*square_std_dev*square_std_dev);
1009 }
1010
1011 Dict parms;
1012 parms["mean"] = mean;
1013 parms["std_dev"] = std_dev;
1014 parms["skewness"] = skewness;
1015 parms["kurtosis"] = kurtosis;
1016
1017 return parms;
1018}
1019
1020
1022{
1023 Assert(low >= 0);
1024 if (low>16384) return 16384; // I suppose we could throw an exception...
1025
1026 int i=0;
1027 while (i<277) {
1028 if (good_fft_sizes[i]>=low) return good_fft_sizes[i];
1029 i++;
1030 }
1031
1032 return 16384;
1033}
1034
1035// This takes a 1-D curve and makes it non-convex, by iteratively constraining each point to be
1036// lower than the mean of the surrounding 2 values
1037vector<float> Util::nonconvex(const vector<float>&curve,int first) {
1038
1039 vector<float> ret(curve);
1040 if (first<1) first=1; // we need one point at each end as an anchor
1041
1042 int cont=1;
1043 while (cont) {
1044 cont=0;
1045 for (int i=first; i<ret.size()-1; i++) {
1046 float q= (ret[i-1]+ret[i+1])/2.0;
1047 if (ret[i]>q) { ret[i]=q; cont=1; }
1048// printf("%1.2f (%1.2f) ",ret[i],q);
1049 }
1050// printf("\n");
1051 }
1052
1053 return ret;
1054}
1055
1056vector<float> Util::windowdot(const vector<float>&curveA,const vector<float>&curveB,int window,int normA) {
1057 if (window<=0) { printf("Warning, %d window in windowdot\n",window); window=1; }
1058
1059 int ws=window*2+1;
1060 vector<float> ret(curveA.size(),0.0f);
1061 vector<float> suba(ws,0.0f);
1062 vector<float> subb(ws,0.0f);
1063
1064
1065 for (int i=window; i<curveA.size()-window; i++) {
1066 double asig=0,bsig=0,amean=0,bmean=0;
1067
1068 // extract subcurves and compute stats
1069 for (int j=0,k=i-window; k<=i+window; j++,k++) {
1070 suba[j]=curveA[k];
1071 subb[j]=curveB[k];
1072 amean+=suba[j];
1073 bmean+=subb[j];
1074 asig +=suba[j]*suba[j];
1075 bsig +=subb[j]*subb[j];
1076 }
1077 amean/=(double)ws;
1078 bmean/=(double)ws;
1079 asig=sqrt(asig/(double)ws-amean*amean);
1080 bsig=sqrt(bsig/(double)ws-bmean*bmean);
1081// printf("%lf %lf %lf %lf\n",amean,asig,bmean,bsig);
1082
1083 double dot=0;
1084 // normalize vector(s) & compute dot
1085 for (int j=0; j<ws; j++) {
1086 subb[j]=(subb[j]-bmean)/bsig;
1087 if (normA) suba[j]=(suba[j]-amean)/asig;
1088
1089 dot+=suba[j]*subb[j];
1090 }
1091 ret[i]=dot/(float)ws;
1092 }
1093 return ret;
1094}
1095
1096
1097#ifndef _WIN32
1098#include <sys/types.h>
1099#include <sys/socket.h>
1100#include "byteorder.h"
1101// This is the structure of a broadcast packet
1102// Transmitter assumes little endian
1103struct BPKT {
1104 char hdr[4];
1105 int uid; // user id on transmitter
1106 int len; // length of total object
1107 int oseq; // object id
1108 int pseq; // packet id within object
1109 unsigned char data[1024]; };
1110
1111string Util::recv_broadcast(int sock) {
1112// struct sockaddr_in sadr = { AF_INET, 9989, INADDR_ANY};
1113// int sock=socket(AF_INET,SOCK_DGRAM,0);
1114// if (bind(sock,&sadr,sizeof(sockaddr_in))) return string();
1115
1117 printf("No cache mirroring on Big endian machines yet\n");
1118 return string(); // FIXME: no support for big endian hosts
1119 }
1120
1121 BPKT pkt;
1122 string ret;
1123 vector<char> fill;
1124 int obj=-1;
1125 unsigned int i=0;
1126// printf ("Listening\n");
1127
1128 while (1) {
1129 int l = recv(sock,&pkt,1044,0);
1130 if (l<=0) {
1131 if (obj!=-1) printf("Timeout with incomplete obj %d %d/%d\n",obj,i,(int)fill.size());
1132 return string(); // probably a timeout
1133 }
1134 if (l<20) {
1135 printf("Bad packet from broadcast");
1136 continue;
1137 }
1138
1139 if (strncmp(pkt.hdr,"EMAN",4)!=0) continue;
1140
1141 // new object coming in
1142 if (obj!=pkt.oseq) {
1143 obj=pkt.oseq;
1144 ret.resize(pkt.len);
1145 fill.resize((pkt.len-1)/1024+1);
1146 for (i=0; i<fill.size(); i++) fill[i]=0;
1147 }
1148 if (obj==-1) printf("Something wierd happened. please report\n");
1149
1150 // copy the packet into the output buffer
1151 fill[pkt.pseq]=1;
1152 ret.replace(pkt.pseq*1024,l-20,(char *)pkt.data,l-20);
1153
1154 // see if we got everything
1155 for (i=0; i<fill.size(); i++) {
1156 if (fill[i]!=1) break;
1157 }
1158// printf("\t\t\tObj %d %d/%d \r",obj,i,(int)fill.size());
1159 fflush(stdout);
1160
1161 if (i==fill.size()) return ret; // Yea ! We got a good packet
1162 }
1163
1164}
1165#endif //_WIN32
1166
1168{
1169 time_t t0 = time(0);
1170 struct tm *t = localtime(&t0);
1171 char label[32];
1172 sprintf(label, "%d/%02d/%04d %d:%02d",
1173 t->tm_mon + 1, t->tm_mday, t->tm_year + 1900, t->tm_hour, t->tm_min);
1174 return string(label);
1175}
1176
1177
1178void Util::set_log_level(int argc, char *argv[])
1179{
1180 if (argc > 1 && strncmp(argv[1], "-v", 2) == 0) {
1181 char level_str[32];
1182 strcpy(level_str, argv[1] + 2);
1183 Log::LogLevel log_level = (Log::LogLevel) atoi(level_str);
1184 Log::logger()->set_level(log_level);
1185 }
1186}
1187
1188void Util::printMatI3D(MIArray3D& mat, const string str, ostream& out) {
1189 // Note: Don't need to check if 3-D because 3D is part of
1190 // the MIArray3D typedef.
1191 out << "Printing 3D Integer data: " << str << std::endl;
1192 const multi_array_types::size_type* sizes = mat.shape();
1193 int nx = sizes[0], ny = sizes[1], nz = sizes[2];
1194 const multi_array_types::index* indices = mat.index_bases();
1195 int bx = indices[0], by = indices[1], bz = indices[2];
1196 for (int iz = bz; iz < nz+bz; iz++) {
1197 cout << "(z = " << iz << " slice)" << endl;
1198 for (int ix = bx; ix < nx+bx; ix++) {
1199 for (int iy = by; iy < ny+by; iy++) {
1200 cout << setiosflags(ios::fixed) << setw(5)
1201 << mat[ix][iy][iz] << " ";
1202 }
1203 cout << endl;
1204 }
1205 }
1206}
1207
1208#include <gsl/gsl_matrix.h>
1209#include <gsl/gsl_vector.h>
1210#include <gsl/gsl_linalg.h>
1211
1212void printmatrix( gsl_matrix* M, const int n, const int m, const string& message = "")
1213{
1214 cout << message << endl;
1215 for(int i = 0; i < n; ++i ){
1216 for (int j = 0; j < m; ++j ){
1217 cout << gsl_matrix_get(M,i,j) << "\t";
1218 }
1219 cout << endl;
1220 }
1221}
1222
1223void printvector( gsl_vector* M, const int n, const string& message = "")
1224{
1225 cout << message << endl;
1226 for(int i = 0; i < n; ++i ){
1227 cout << gsl_vector_get(M,i) << "\t";
1228 }
1229 cout << endl;
1230}
1231
1232float* Util::getBaldwinGridWeights( const int& freq_cutoff, const float& P, const float& r, const float& dfreq, const float& alpha, const float& beta)
1233{
1234 int i = 0;
1235 int discs = (int)(1+2*freq_cutoff/dfreq);
1236
1237 float* W = new float[discs];
1238
1239 int fc = (int)(2*freq_cutoff + 1);
1240 gsl_matrix* M = gsl_matrix_calloc(fc,fc);
1241
1242 gsl_vector* rhs = gsl_vector_calloc(fc);
1243 cout << i++ << endl;
1244 for(int k = -freq_cutoff; k <= freq_cutoff; ++k){
1245 for(int kp = -freq_cutoff; kp <= freq_cutoff; ++kp){
1246 int kdiff =abs( k-kp);
1247 int evenoddfac = ( kdiff % 2 == 0 ? 1 : -1);
1248
1249 if (kdiff !=0){
1250 float val = sin(M_PI*(float)kdiff*r)/(sin(M_PI*(float)kdiff/(float)P))*(alpha+2.0f*beta*evenoddfac);
1251 gsl_matrix_set(M,int(k+freq_cutoff),int(kp+freq_cutoff),val);
1252 }
1253 }
1254 gsl_matrix_set(M,int(k+freq_cutoff),int(k+freq_cutoff),r*P* (alpha+2*beta));
1255 float val = alpha*sin(M_PI*k*r)/(sin(M_PI*(float)k/(float)P));
1256 if (k!=0) {
1257 gsl_vector_set(rhs,int(k+freq_cutoff),val);
1258 }
1259 }
1260 printmatrix(M,fc,fc,"M");
1261
1262 gsl_vector_set(rhs,int(freq_cutoff),alpha*r*P);
1263 gsl_matrix* V = gsl_matrix_calloc(fc,fc);
1264 gsl_vector* S = gsl_vector_calloc(fc);
1265 gsl_vector* soln = gsl_vector_calloc(fc);
1266 gsl_linalg_SV_decomp(M,V,S,soln);
1267
1268 gsl_linalg_SV_solve(M, V, S, rhs, soln); // soln now runs from -freq_cutoff to + freq_cutoff
1269 printvector(soln,fc,"soln");
1270
1271 // we want to solve for W, which ranges from -freq_cutoff to +freq_cutoff in steps of dfreq 2
1272 int Count=0;
1273 for(float q = (float)(-freq_cutoff); q <= (float)(freq_cutoff); q+= dfreq){
1274 float temp=0;
1275 for(int k = -freq_cutoff; k <= freq_cutoff; ++k){
1276 float dtemp;
1277 if (q!=k) {
1278 dtemp=(1/(float) P)* (float)gsl_vector_get(soln,int(k+freq_cutoff)) * sin(M_PI*(q-k))/sin(M_PI*(q-k)/((float) P));
1279 } else{
1280 dtemp = (1/(float) P)* (float)gsl_vector_get(soln,int(k+freq_cutoff)) * P;
1281 }
1282 temp +=dtemp;
1283 }
1284 W[Count]=temp;
1285 cout << W[Count] << " ";
1286 Count+=1;
1287 }
1288 cout << endl;
1289 return W;
1290}
1291
1292
1293void Util::equation_of_plane(const Vec3f& p1, const Vec3f& p2, const Vec3f& p3, float * plane )
1294{
1295 int x=0,y=1,z=2;
1296 plane[0] = p1[y]*(p2[z]-p3[z])+p2[y]*(p3[z]-p1[z])+p3[y]*(p1[z]-p2[z]);
1297 plane[1] = p1[z]*(p2[x]-p3[x])+p2[z]*(p3[x]-p1[x])+p3[z]*(p1[x]-p2[x]);
1298 plane[2] = p1[x]*(p2[y]-p3[y])+p2[x]*(p3[y]-p1[y])+p3[x]*(p1[y]-p2[y]);
1299 plane[3] = p1[x]*(p2[y]*p3[z]-p3[y]*p2[z])+p2[x]*(p3[y]*p1[z]-p1[y]*p3[z])+p3[x]*(p1[y]*p2[z]-p2[y]*p1[z]);
1300 plane[3] = -plane[3];
1301}
1302
1303
1304bool Util::point_is_in_triangle_2d(const Vec2f& p1, const Vec2f& p2, const Vec2f& p3,const Vec2f& point)
1305{
1306
1307 Vec2f u = p2 - p1;
1308 Vec2f v = p3 - p1;
1309 Vec2f w = point - p1;
1310
1311 float udotu = u.dot(u);
1312 float udotv = u.dot(v);
1313 float udotw = u.dot(w);
1314 float vdotv = v.dot(v);
1315 float vdotw = v.dot(w);
1316
1317 float d = 1.0f/(udotv*udotv - udotu*vdotv);
1318 float s = udotv*vdotw - vdotv*udotw;
1319 s *= d;
1320
1321 float t = udotv*udotw - udotu*vdotw;
1322 t *= d;
1323
1324 // We've done a few multiplications, so detect when there are tiny residuals that may throw off the final
1325 // decision
1326 if (fabs(s) < Transform::ERR_LIMIT ) s = 0;
1327 if (fabs(t) < Transform::ERR_LIMIT ) t = 0;
1328
1329 if ( fabs((fabs(s)-1.0)) < Transform::ERR_LIMIT ) s = 1;
1330 if ( fabs((fabs(t)-1.0)) < Transform::ERR_LIMIT ) t = 1;
1331
1332// cout << "s and t are " << s << " " << t << endl;
1333
1334 // The final decision, if this is true then we've hit the jackpot
1335 if ( s >= 0 && t >= 0 && (s+t) <= 1 ) return true;
1336 else return false;
1337}
1338
1339bool Util::point_is_in_convex_polygon_2d(const Vec2f& p1, const Vec2f& p2, const Vec2f& p3, const Vec2f& p4,const Vec2f& actual_point)
1340{
1341
1342 if (point_is_in_triangle_2d(p1,p2,p4,actual_point)) return true;
1343 else return point_is_in_triangle_2d(p3,p2,p4,actual_point);
1344}
1345
1346/*
1347Dict Util::get_isosurface(EMData * image, float surface_palue, bool smooth)
1348{
1349 if (image->get_ndim() != 3) {
1350 throw ImageDimensionException("3D only");
1351 }
1352
1353 MarchingCubes * mc = new MarchingCubes(image, smooth);
1354 mc->set_surface_palue(surface_palue);
1355
1356 Dict d;
1357 if(smooth) {
1358 d.put("points", *(mc->get_points()));
1359 d.put("faces", *(mc->get_faces()));
1360 d.put("normals", *(mc->get_normalsSm()));
1361 }
1362 else {
1363 d.put("points", *(mc->get_points()));
1364 d.put("faces", *(mc->get_faces()));
1365 d.put("normals", *(mc->get_normals()));
1366 }
1367
1368 delete mc;
1369 mc = 0;
1370
1371 return d;
1372}
1373*/
#define V(i, j)
Definition: analyzer.cpp:697
static bool is_host_big_endian()
Definition: byteorder.cpp:40
Dict is a dictionary to store <string, EMObject> pair.
Definition: emobject.h:385
EMData stores an image's data and defines core image processing routines.
Definition: emdata.h:82
void set_level(int level)
Definition: log.cpp:165
static Log * logger()
Definition: log.cpp:80
LogLevel
Definition: log.h:72
The wrapper class for gsl's random number generater.
Definition: randnum.h:86
void set_seed(unsigned long long seed)
Set the seed for the random number generator.
Definition: randnum.cpp:142
static Randnum * Instance()
Definition: randnum.cpp:104
long long get_irand(long long lo, long long hi) const
This function returns a random integer from lo to hi inclusive.
Definition: randnum.cpp:153
unsigned long long get_seed()
Get the current random number seed.
Definition: randnum.cpp:148
float get_gauss_rand(float mean, float sigma) const
Return a Gaussian random number.
Definition: randnum.cpp:168
float get_frand(double lo=0.0, double hi=1.0) const
This function returns a random float from lo inclusive to hi.
Definition: randnum.cpp:158
static const float ERR_LIMIT
Definition: transform.h:78
static float * getBaldwinGridWeights(const int &freq_cutoff, const float &P, const float &r, const float &dfreq=1, const float &alpha=0.5, const float &beta=0.2)
Definition: util.cpp:1232
static float fast_gauss_B2(const float &f)
Returns an approximate of exp(-2x^2) using a cached table uses actual function outside the cached ran...
Definition: util.cpp:830
static void calc_least_square_fit(size_t nitems, const float *data_x, const float *data_y, float *p_slope, float *p_intercept, bool ignore_zero, float absmax=0)
calculate the least square fit value.
Definition: util.cpp:538
static int MUTEX_UNLOCK(MUTEX *mutex)
Definition: util.cpp:85
static string remove_filename_ext(const string &filename)
Remove a filename's extension and return the new filename.
Definition: util.cpp:495
static string recv_broadcast(int port)
Definition: util.cpp:1111
static string str_to_lower(const string &s)
Return a lower case version of the argument string.
Definition: util.cpp:283
static bool get_str_float(const char *str, const char *float_var, float *p_val)
Extract the float value from a variable=value string with format like "XYZ=1.1", where 'str' is "XYZ=...
Definition: util.cpp:385
static void flip_complex_phase(float *data, size_t n)
flip the phase of a complex data array.
Definition: util.cpp:127
static int file_lock_wait(FILE *file)
lock a file.
Definition: util.cpp:182
static short hypot_fast_int(int x, int y)
Euclidean distance in 2D for integers computed fast using a cached lookup table.
Definition: util.cpp:764
static int MUTEX_LOCK(MUTEX *mutex)
Definition: util.cpp:75
static float fast_acos(const float &f)
Returns an approximate of acos(x) using a cached table and linear interpolation tolerates values very...
Definition: util.cpp:804
static vector< EMData * > svdcmp(const vector< EMData * > &data, int nvec)
Perform singular value decomposition on a set of images.
Definition: util.cpp:343
static bool point_is_in_triangle_2d(const Vec2f &p1, const Vec2f &p2, const Vec2f &p3, const Vec2f &actual_point)
Determines if a point is in a 2D triangle using the Barycentric method, which is a fast way of perfor...
Definition: util.cpp:1304
static int square(int n)
Calculate a number's square.
Definition: util.h:736
static Dict get_stats(const vector< float > &data)
Get the mean, standard deviation, skewness and kurtosis of the input data.
Definition: util.cpp:913
static Vec3f calc_bilinear_least_square(const vector< float > &points)
calculate bilinear least-square fit, z = a + b x + c y Takes a set of x,y,z vectors and produces an a...
Definition: util.cpp:577
static void flip_image(float *data, size_t nx, size_t ny)
Vertically flip the data of a 2D real image.
Definition: util.cpp:259
static string get_time_label()
Get the current time in a string with format "mm/dd/yyyy hh:mm".
Definition: util.cpp:1167
static bool sstrncmp(const char *s1, const char *s2)
Safe string compare.
Definition: util.cpp:306
static bool get_str_int(const char *str, const char *int_var, int *p_val)
Extract the int value from a variable=value string with format like "XYZ=1", where 'str' is "XYZ=1"; ...
Definition: util.cpp:436
static void set_log_level(int argc, char *argv[])
Set program logging level through command line option "-v N", where N is the level.
Definition: util.cpp:1178
static void find_max(const float *data, size_t nitems, float *p_max_val, int *p_max_index=0)
Find the maximum value and (optional) its index in an array.
Definition: util.cpp:851
static void set_randnum_seed(unsigned long long seed)
Set the seed for Randnum class.
Definition: util.cpp:707
static float get_frand(int low, int high)
Get a float random number between low and high, [low, high)
Definition: util.cpp:725
static string get_filename_ext(const string &filename)
Get a filename's extension.
Definition: util.cpp:526
static void find_min_and_max(const float *data, size_t nitems, float *p_max_val, float *p_min_val, int *p_max_index=0, int *p_min_index=0)
Find the maximum value and (optional) its index, minimum value and (optional) its index in an array.
Definition: util.cpp:875
static bool is_file_exist(const string &filename)
check whether a file exists or not
Definition: util.cpp:253
static void replace_non_ascii(char *str, int max_size, char repl_char='?')
Replace any non-ASCII characters in a C string with a given character.
Definition: util.cpp:289
static string sbasename(const string &filename)
Get a filename's basename.
Definition: util.cpp:505
static void rotate_phase_origin(float *data, size_t nx, size_t ny, size_t nz)
rotate data vertically by ny/2, to make the mrc phase origin compliance with EMAN1 and TNF reader
Definition: util.cpp:140
static void printMatI3D(MIArray3D &mat, const string str=string(""), ostream &out=std::cout)
Print a 3D integer matrix to a file stream (std out by default).
Definition: util.cpp:1188
static vector< float > nonconvex(const vector< float > &curve, int first=3)
Returns a non-convex version of a curve.
Definition: util.cpp:1037
static int round(float x)
Get ceiling round of a float number x.
Definition: util.h:465
static void ap2ri(float *data, size_t n)
convert complex data array from Amplitude/Phase format into Real/Imaginary format.
Definition: util.cpp:97
static int calc_best_fft_size(int low)
Search the best FFT size with good primes.
Definition: util.cpp:1021
static void save_data(const vector< float > &x_array, const vector< float > &y_array, const string &filename)
Save (x y) data array into a file.
Definition: util.cpp:604
static bool check_file_by_magic(const void *first_block, const char *magic)
check whether a file starts with certain magic string.
Definition: util.cpp:239
static string change_filename_ext(const string &old_filename, const string &new_ext)
Change a file's extension and return the new filename.
Definition: util.cpp:485
static string get_line_from_string(char **str)
Extract a single line from a multi-line string.
Definition: util.cpp:322
static vector< float > windowdot(const vector< float > &curveA, const vector< float > &curveB, int window, int normA)
Computes a windowed dot product between curve A and curve B.
Definition: util.cpp:1056
static float fast_exp(const float &f)
Returns an approximate of exp(x) using a cached table uses actual exp(x) outside the cached range.
Definition: util.cpp:788
static bool point_is_in_convex_polygon_2d(const Vec2f &p1, const Vec2f &p2, const Vec2f &p3, const Vec2f &p4, const Vec2f &actual_point)
Determines if a point is in a 2D convex polygon described by 4 points using the Barycentric method,...
Definition: util.cpp:1339
static string int2str(int n)
Get a string format of an integer, e.g.
Definition: util.cpp:315
static float square_sum(float x, float y)
Calcuate (x*x + y*y).
Definition: util.h:764
static void sort_mat(float *left, float *right, int *leftPerm, int *rightPerm)
does a sort as in Matlab.
Definition: util.cpp:670
static int get_irand(int low, int high)
Get an integer random number between low and high, [low, high].
Definition: util.cpp:719
static Dict get_stats_cstyle(const vector< float > &data)
Performs the same calculations as in get_stats, but uses a single pass, optimized c approach Should p...
Definition: util.cpp:969
static unsigned long long get_randnum_seed()
Get the seed for Randnum class.
Definition: util.cpp:713
static void equation_of_plane(const Vec3f &p1, const Vec3f &p2, const Vec3f &p3, float *plane)
Determine the equation of a plane that intersects 3 points in 3D space.
Definition: util.cpp:1293
static float get_gauss_rand(float mean, float sigma)
Get a Gaussian random number.
Definition: util.cpp:845
static float hypot_fast(int x, int y)
Euclidean distance in 2D for integers computed fast using a cached lookup table.
Definition: util.cpp:742
The Vec2 is precisely the same as Vec3 except it works exclusively in 2D Note there are convenient ty...
Definition: vec3.h:710
Type dot(const Vec2< Type2 > &v) const
Calculate the dot product of 'this' vector with a second vector.
Definition: vec3.h:804
#define Assert(s)
Define Assert() function that is effective only when -DDEBUG is used.
Definition: emassert.h:42
EMData * sqrt() const
return square root of current image
float get_value_at(int x, int y, int z) const
Get the pixel density value at coordinates (x,y,z).
Definition: emdata_core.h:221
void div(float f)
make each pixel value divided by a float number.
#define EmptyContainerException(desc)
Definition: exception.h:374
#define FileAccessException(filename)
Definition: exception.h:187
#define NullPointerException(desc)
Definition: exception.h:241
#define LOGERR
Definition: log.h:51
E2Exception class.
Definition: aligner.h:40
double dot(const Vector3 &w, const Vector3 &v)
Definition: vecmath.h:305
boost::multi_array< int, 3 > MIArray3D
Definition: emdata.h:73
#define y(i, j)
Definition: projector.cpp:1516
#define x(i)
Definition: projector.cpp:1517
Definition: util.cpp:1103
int oseq
Definition: util.cpp:1107
unsigned char data[1024]
Definition: util.cpp:1109
int uid
Definition: util.cpp:1105
char hdr[4]
Definition: util.cpp:1104
int len
Definition: util.cpp:1106
int pseq
Definition: util.cpp:1108
void printvector(gsl_vector *M, const int n, const string &message="")
Definition: util.cpp:1223
void printmatrix(gsl_matrix *M, const int n, const int m, const string &message="")
Definition: util.cpp:1212
#define MUTEX
Definition: util.h:43
const int good_fft_sizes[]
Definition: util.h:64