EMAN2
Static Public Member Functions | List of all members
EMAN::Util Class Reference

Util is a collection of utility functions. More...

#include <util.h>

Static Public Member Functions

static int MUTEX_INIT (MUTEX *mutex)
 For those util function developed by Pawel's group. More...
 
static int MUTEX_LOCK (MUTEX *mutex)
 
static int MUTEX_UNLOCK (MUTEX *mutex)
 
static bool is_nan (const float number)
 tell whether a float value is a NaN More...
 
static void ap2ri (float *data, size_t n)
 convert complex data array from Amplitude/Phase format into Real/Imaginary format. More...
 
static void ap2ri (double *data, size_t n)
 
static void flip_complex_phase (float *data, size_t n)
 flip the phase of a complex data array. More...
 
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 More...
 
static int file_lock_wait (FILE *file)
 lock a file. More...
 
static bool check_file_by_magic (const void *first_block, const char *magic)
 check whether a file starts with certain magic string. More...
 
static bool is_file_exist (const string &filename)
 check whether a file exists or not More...
 
static void flip_image (float *data, size_t nx, size_t ny)
 Vertically flip the data of a 2D real image. More...
 
static vector< EMData * > svdcmp (const vector< EMData * > &data, int nvec)
 Perform singular value decomposition on a set of images. More...
 
static string str_to_lower (const string &s)
 Return a lower case version of the argument string. More...
 
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. More...
 
static bool sstrncmp (const char *s1, const char *s2)
 Safe string compare. More...
 
static string int2str (int n)
 Get a string format of an integer, e.g. More...
 
static string get_line_from_string (char **str)
 Extract a single line from a multi-line string. More...
 
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=1.1"; 'float_var' is "XYZ="; 'p_val' points to float number 1.1. More...
 
static bool get_str_float (const char *str, const char *float_var, float *p_v1, float *p_v2)
 Extract the float values from a variable=value1,value2 string with format like "XYZ=1.1,1.2", where 'str' is "XYZ=1.1,1.2"; 'float_var' is "XYZ="; 'p_v1' points to 1.1; 'p_v2' points to 1.2. More...
 
static bool get_str_float (const char *str, const char *float_var, int *p_nvalues, float *p_v1, float *p_v2)
 Extract number of values and the float values, if any, from a string whose format is either "variable=value1,value2 " or "variable". More...
 
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"; 'int_var' is "XYZ="; 'p_val' points to float number 1. More...
 
static bool get_str_int (const char *str, const char *int_var, int *p_v1, int *p_v2)
 Extract the int value from a variable=value1,value2 string with format like "XYZ=1,2", where 'str' is "XYZ=1,2"; 'int_var' is "XYZ="; 'p_val' points to float number 1. More...
 
static bool get_str_int (const char *str, const char *int_var, int *p_nvalues, int *p_v1, int *p_v2)
 Extract number of values and the int values, if any, from a string whose format is either "variable=value1,value2 " or "variable". More...
 
static string change_filename_ext (const string &old_filename, const string &new_ext)
 Change a file's extension and return the new filename. More...
 
static string remove_filename_ext (const string &filename)
 Remove a filename's extension and return the new filename. More...
 
static string get_filename_ext (const string &filename)
 Get a filename's extension. More...
 
static string sbasename (const string &filename)
 Get a filename's basename. More...
 
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. More...
 
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,b,c vector does not accept error bars on z or return goodness of fit More...
 
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. More...
 
static void save_data (float x0, float dx, const vector< float > &y_array, const string &filename)
 Save x, y data into a file. More...
 
static void save_data (float x0, float dx, float *y_array, size_t array_size, const string &filename)
 Save x, y data into a file. More...
 
static void sort_mat (float *left, float *right, int *leftPerm, int *rightPerm)
 does a sort as in Matlab. More...
 
static unsigned long long get_randnum_seed ()
 Get the seed for Randnum class. More...
 
static void set_randnum_seed (unsigned long long seed)
 Set the seed for Randnum class. More...
 
static int get_irand (int low, int high)
 Get an integer random number between low and high, [low, high]. More...
 
static float get_frand (int low, int high)
 Get a float random number between low and high, [low, high) More...
 
static float get_frand (float low, float high)
 Get a float random number between low and high, [low, high) More...
 
static float get_frand (double low, double high)
 Get a float random number between low and high, [low, high) More...
 
static float get_gauss_rand (float mean, float sigma)
 Get a Gaussian random number. More...
 
static int round (float x)
 Get ceiling round of a float number x. More...
 
static int round (double x)
 Get ceiling round of a float number x. More...
 
static float log_2 (float x)
 Get the log base 2 of a float x. More...
 
static double log_2 (double x)
 Get the log base 2 of a double x. More...
 
static float log_2 (int i)
 Get the log base 2 of an integer i. More...
 
static float linear_interpolate (float p1, float p2, float t)
 Calculate linear interpolation. More...
 
static std::complex< float > linear_interpolate_cmplx (std::complex< float > p1, std::complex< float > p2, float t)
 Calculate linear interpolation. More...
 
static float bilinear_interpolate (float p1, float p2, float p3, float p4, float t, float u)
 Calculate bilinear interpolation. More...
 
static std::complex< float > bilinear_interpolate_cmplx (std::complex< float > p1, std::complex< float > p2, std::complex< float > p3, std::complex< float > p4, float t, float u)
 Calculate bilinear interpolation. More...
 
static std::complex< float > gauss_interpolate_cmplx (std::complex< float > p1, std::complex< float > p2, std::complex< float > p3, std::complex< float > p4, float t, float u)
 Calculate 2x2 Gaussian interpolation. More...
 
static std::complex< float > gauss3_interpolate_cmplx (std::complex< float > *p, float t, float u)
 Calculate 3x3 Gaussian interpolation. More...
 
static float trilinear_interpolate (float p1, float p2, float p3, float p4, float p5, float p6, float p7, float p8, float t, float u, float v)
 Calculate trilinear interpolation. More...
 
static std::complex< float > trilinear_interpolate_complex (std::complex< float > p1, std::complex< float > p2, std::complex< float > p3, std::complex< float > p4, std::complex< float > p5, std::complex< float > p6, std::complex< float > p7, std::complex< float > p8, float t, float u, float v)
 Calculate trilinear interpolation. More...
 
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. More...
 
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. More...
 
static Dict get_stats (const vector< float > &data)
 Get the mean, standard deviation, skewness and kurtosis of the input data. More...
 
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 perform better than get_stats. More...
 
static int calc_best_fft_size (int low)
 Search the best FFT size with good primes. More...
 
static vector< float > nonconvex (const vector< float > &curve, int first=3)
 Returns a non-convex version of a curve. More...
 
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. More...
 
static EMDatacalc_bessel (const int n, const float &x)
 
static double angle3 (double x1, double y1, double z1, double x2, double y2, double z2)
 Given 2 vectors, it will compute the angle between them in radians. More...
 
static float angle3 (float x1, float y1, float z1, float x2, float y2, float z2)
 
static int square (int n)
 Calculate a number's square. More...
 
static float square (float x)
 Calculate a number's square. More...
 
static float square (double x)
 Calculate a number's square. More...
 
static float square_sum (float x, float y)
 Calcuate (x*x + y*y). More...
 
static float hypot2 (float x, float y)
 Euclidean distance function in 2D: f(x,y) = sqrt(x*x + y*y);. More...
 
static int hypot2sq (int x, int y)
 Euclidean distance function squared in 2D: f(x,y) = (x*x + y*y);. More...
 
static float hypot2sq (float x, float y)
 Euclidean distance function squared in 2D: f(x,y) = (x*x + y*y);. More...
 
static int hypot3sq (int x, int y, int z)
 Euclidean distance function squared in 3D: f(x,y,z) = (x*x + y*y + z*z);. More...
 
static float hypot3sq (float x, float y, float z)
 Euclidean distance function squared in 3D: f(x,y,z) = (x*x + y*y + z*z);. More...
 
static float hypot3 (int x, int y, int z)
 Euclidean distance function in 3D: f(x,y,z) = sqrt(x*x + y*y + z*z);. More...
 
static float hypot3 (float x, float y, float z)
 Euclidean distance function in 3D: f(x,y,z) = sqrt(x*x + y*y + z*z);. More...
 
static double hypot3 (double x, double y, double z)
 Euclidean distance function in 3D: f(x,y,z) = sqrt(x*x + y*y + z*z);. More...
 
static float hypot_fast (int x, int y)
 Euclidean distance in 2D for integers computed fast using a cached lookup table. More...
 
static short hypot_fast_int (int x, int y)
 Euclidean distance in 2D for integers computed fast using a cached lookup table. More...
 
static int fast_floor (float x)
 A fast way to calculate a floor, which is largest integral value not greater than argument. More...
 
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. More...
 
static float fast_acos (const float &f)
 Returns an approximate of acos(x) using a cached table and linear interpolation tolerates values very slightly outside the -1 - 1 range (returning 0) More...
 
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 range. More...
 
static float agauss (float a, float dx, float dy, float dz, float d)
 Calculate Gaussian value. More...
 
static int get_min (int f1, int f2)
 Get the minimum of 2 numbers. More...
 
static int get_min (int f1, int f2, int f3)
 Get the minimum of 3 numbers. More...
 
static float get_min (float f1, float f2)
 Get the minimum of 2 numbers. More...
 
static float get_min (float f1, float f2, float f3)
 Get the minimum of 3 numbers. More...
 
static float get_min (float f1, float f2, float f3, float f4)
 Get the minimum of 4 numbers. More...
 
static float get_max (float f1, float f2)
 Get the maximum of 2 numbers. More...
 
static float get_max (float f1, float f2, float f3)
 Get the maximum of 3 numbers. More...
 
static float get_max (float f1, float f2, float f3, float f4)
 Get the maximum of 4 numbers. More...
 
static float angle_norm_2pi (float in)
 Normalize an angle in radians so it is in the 0-2pi range. More...
 
static float angle_norm_pi (float in)
 Normalize an angle in radians so it is in the -pi to pi range. More...
 
static float angle_sub_2pi (float x, float y)
 Calculate the difference of 2 angles and makes the equivalent result to be less than Pi. More...
 
static float angle_sub_pi (float x, float y)
 Calculate the difference of 2 angles and makes the equivalent result to be less than Pi/2. More...
 
static float angle_err_ri (float r1, float i1, float r2, float i2)
 Calculate the angular phase difference between two r/i vectors. More...
 
static int goodf (const float *p_f)
 Check whether a number is a good float. More...
 
static int goodf (const double *p_f)
 
static string recv_broadcast (int port)
 
static string get_time_label ()
 Get the current time in a string with format "mm/dd/yyyy hh:mm". More...
 
static void set_log_level (int argc, char *argv[])
 Set program logging level through command line option "-v N", where N is the level. More...
 
static float eman_copysign (float a, float b)
 copy sign of a number. More...
 
static float eman_erfc (float x)
 complementary error function. More...
 
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. More...
 
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, which is a fast way of performing the query. More...
 
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 performing the query Triangle points can be specified in any order. More...
 
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). More...
 
template<class T >
static T sgn (T &val)
 Sign function. More...
 
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)
 
static bool IsPower2 (int x)
 Return true if an integer is positive and is power of 2. More...
 
static void apply_precision (float &value, const float &precision)
 

Detailed Description

Util is a collection of utility functions.

Definition at line 89 of file util.h.

Member Function Documentation

◆ agauss()

static float EMAN::Util::agauss ( float  a,
float  dx,
float  dy,
float  dz,
float  d 
)
inlinestatic

Calculate Gaussian value.

a * exp(-(dx * dx + dy * dy + dz * dz) / d)

Parameters
[in]aamplitude
[in]dxx center
[in]dyy center
[in]dzz center
[in]dwidth of gaussian
Returns
The Gaussian value.

Definition at line 912 of file util.h.

913 {
914 return (a * exp(-(dx * dx + dy * dy + dz * dz) / d));
915 }

Referenced by EMAN::FourierReconstructorSimple2D::insert_slice(), and EMAN::GaussFFTProjector::interp_ft_3d().

◆ angle3() [1/2]

static double EMAN::Util::angle3 ( double  x1,
double  y1,
double  z1,
double  x2,
double  y2,
double  z2 
)
inlinestatic

Given 2 vectors, it will compute the angle between them in radians.

Definition at line 724 of file util.h.

724 {
725 return fast_acos((x1*x2+y1*y2+z1*z2)/(hypot3(x1,y1,z1)*hypot3(x2,y2,z2))); //fast_acos tolerates roundoff error slightly outside -1 to 1 range
726 }
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 float hypot3(int x, int y, int z)
Euclidean distance function in 3D: f(x,y,z) = sqrt(x*x + y*y + z*z);.
Definition: util.h:827

References fast_acos(), and hypot3().

◆ angle3() [2/2]

static float EMAN::Util::angle3 ( float  x1,
float  y1,
float  z1,
float  x2,
float  y2,
float  z2 
)
inlinestatic

Definition at line 728 of file util.h.

728 {
729 return fast_acos((x1*x2+y1*y2+z1*z2)/(hypot3(x1,y1,z1)*hypot3(x2,y2,z2)));
730 }

References fast_acos(), and hypot3().

◆ angle_err_ri()

static float EMAN::Util::angle_err_ri ( float  r1,
float  i1,
float  r2,
float  i2 
)
inlinestatic

Calculate the angular phase difference between two r/i vectors.

Parameters
[in]r1/i1first vector, 2 floats
[in]r2/i2second vector, 2 floats
Returns
angular difference

Definition at line 1099 of file util.h.

1099 {
1100 if ((r1==0 && i1==0) || (r2==0 && i2==0)) return 0;
1101// printf("%f\t%f\t%f\n",r1*r2+i1*i2,hypot(r1,i1),hypot(r2,i2));
1102// return acos((r1*r2+i1*i2)/(hypot(r1,i1)*hypot(r2,i2)));
1103 return fast_acos((r1*r2+i1*i2)/(float)(hypot(r1,i1)*hypot(r2,i2))); // fast_acos also tolerates values very slightly above 1
1104 }

References fast_acos().

Referenced by EMAN::PhaseCmp::cmp().

◆ angle_norm_2pi()

static float EMAN::Util::angle_norm_2pi ( float  in)
inlinestatic

Normalize an angle in radians so it is in the 0-2pi range.

Definition at line 1043 of file util.h.

1044 {
1045 float m = fmod((float)in, (float)(2.0*M_PI));
1046
1047 return m<0?m+2.0*M_PI:m;
1048 }

◆ angle_norm_pi()

static float EMAN::Util::angle_norm_pi ( float  in)
inlinestatic

Normalize an angle in radians so it is in the -pi to pi range.

Definition at line 1051 of file util.h.

1052 {
1053 float m = fmod((float)in, (float)(2.0*M_PI));
1054 if (m<-M_PI) m+=2.0*M_PI;
1055 return m>M_PI?m-2.0*M_PI:m;
1056 }

Referenced by EMAN::MaskAzProcessor::process_inplace().

◆ angle_sub_2pi()

static float EMAN::Util::angle_sub_2pi ( float  x,
float  y 
)
inlinestatic

Calculate the difference of 2 angles and makes the equivalent result to be less than Pi.

Parameters
[in]xThe first angle.
[in]yThe second angle.
Returns
The difference of 2 angles.

Definition at line 1066 of file util.h.

1067 {
1068 float r = fmod(fabs(x - y), (float) (2.0 * M_PI));
1069 if (r<0) r+=2.0*M_PI;
1070 if (r > M_PI) {
1071 r = (float) (2.0 * M_PI - r);
1072 }
1073
1074 return r;
1075 }
#define y(i, j)
Definition: projector.cpp:1516
#define x(i)
Definition: projector.cpp:1517

References x, and y.

Referenced by EMAN::EMData::common_lines(), and EMAN::MaskAzProcessor::process_inplace().

◆ angle_sub_pi()

static float EMAN::Util::angle_sub_pi ( float  x,
float  y 
)
inlinestatic

Calculate the difference of 2 angles and makes the equivalent result to be less than Pi/2.

Parameters
[in]xThe first angle.
[in]yThe second angle.
Returns
The difference of 2 angles.

Definition at line 1084 of file util.h.

1085 {
1086 float r = fmod(fabs(x - y), (float) M_PI);
1087 if (r > M_PI / 2.0) {
1088 r = (float)(M_PI - r);
1089 }
1090 return r;
1091 }

References x, and y.

◆ ap2ri() [1/2]

void Util::ap2ri ( double *  data,
size_t  n 
)
static

Definition at line 112 of file util.cpp.

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}
#define Assert(s)
Define Assert() function that is effective only when -DDEBUG is used.
Definition: emassert.h:42
#define NullPointerException(desc)
Definition: exception.h:241

References Assert, and NullPointerException.

◆ ap2ri() [2/2]

void Util::ap2ri ( float *  data,
size_t  n 
)
static

convert complex data array from Amplitude/Phase format into Real/Imaginary format.

Parameters
datacomplex data array.
narray size.

Definition at line 97 of file util.cpp.

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}

References Assert, and NullPointerException.

◆ apply_precision()

static void EMAN::Util::apply_precision ( float &  value,
const float &  precision 
)
inlinestatic

Definition at line 1309 of file util.h.

1309 {
1310 float c = ceilf(value);
1311 float f = (float)fast_floor(value);
1312 if (fabs(value - c) < precision) value = c;
1313 else if (fabs(value - f) < precision) value = f;
1314 }
static int fast_floor(float x)
A fast way to calculate a floor, which is largest integral value not greater than argument.
Definition: util.h:874

References fast_floor().

Referenced by EMAN::Transform::get_determinant(), EMAN::Transform::get_scale(), EMAN::Transform::get_scale_and_mirror(), EMAN::Transform::get_trans(), EMAN::Transform::is_identity(), EMAN::Transform::is_rot_identity(), and EMAN::Transform::set_scale().

◆ bilinear_interpolate()

static float EMAN::Util::bilinear_interpolate ( float  p1,
float  p2,
float  p3,
float  p4,
float  t,
float  u 
)
inlinestatic

Calculate bilinear interpolation.

Parameters
[in]p1The first number. corresponding to (x0,y0).
[in]p2The second number. corresponding to (x1,y0).
[in]p3The third number. corresponding to (x1,y1).
[in]p4The fourth number. corresponding to (x0,y1).
[in]tt
[in]uu
Returns
The bilinear interpolation value.

Definition at line 543 of file util.h.

545 {
546 return (1-t) * (1-u) * p1 + t * (1-u) * p2 + (1-t) * u * p3 + t * u * p4;
547 }

Referenced by EMAN::EMData::common_lines(), EMAN::EMData::cut_slice(), EMAN::MaxValProjector::project3d(), EMAN::StandardProjector::project3d(), sget_value_at_interp(), EMAN::TransformProcessor::transform(), and EMAN::EMData::unwrap().

◆ bilinear_interpolate_cmplx()

static std::complex< float > EMAN::Util::bilinear_interpolate_cmplx ( std::complex< float >  p1,
std::complex< float >  p2,
std::complex< float >  p3,
std::complex< float >  p4,
float  t,
float  u 
)
inlinestatic

Calculate bilinear interpolation.

Parameters
[in]p1The first number. corresponding to (x0,y0).
[in]p2The second number. corresponding to (x1,y0).
[in]p3The third number. corresponding to (x1,y1).
[in]p4The fourth number. corresponding to (x0,y1).
[in]tt
[in]uu
Returns
The bilinear interpolation value.

Definition at line 558 of file util.h.

560 {
561 return (1.0f-t) * (1.0f-u) * p1 + t * (1.0f-u) * p2 + (1.0f-t) * u * p3 + t * u * p4;
562 }

Referenced by get_complex_at_interp().

◆ calc_bessel()

static EMData * EMAN::Util::calc_bessel ( const int  n,
const float &  x 
)
static

◆ calc_best_fft_size()

int Util::calc_best_fft_size ( int  low)
static

Search the best FFT size with good primes.

It supports FFT size up to 4096 now.

Parameters
[in]lowlow size the search starts with.
Returns
The best FFT size.

Definition at line 1021 of file util.cpp.

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}
const int good_fft_sizes[]
Definition: util.h:64

References Assert, and good_fft_sizes.

Referenced by EMAN::HarmonicProcessor::process(), EMAN::BispecSliceProcessor::process(), EMAN::EMData::unwrap(), and EMAN::EMData::unwrap_largerR().

◆ calc_bilinear_least_square()

Vec3f Util::calc_bilinear_least_square ( const vector< float > &  points)
static

calculate bilinear least-square fit, z = a + b x + c y Takes a set of x,y,z vectors and produces an a,b,c vector does not accept error bars on z or return goodness of fit

Parameters
[in]pointsa vector<float> of x,y,z values in (x1,y1,z1,x2,y2,z2...) sequence to fit a plane to
Returns
result as a Vec3f(a,b,c)

Definition at line 577 of file util.cpp.

577 {
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}

Referenced by EMAN::PointArray::align_2d().

◆ calc_least_square_fit()

void Util::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 
)
static

calculate the least square fit value.

Parameters
[in]nitemsNumber of items in array data_x and data_y.
[in]data_xx data array.
[in]data_yy data array. It should have the same number of items to data_x.
[out]p_slopepointer to the result slope.
[out]p_interceptpointer to the result intercept.
[in]ignore_zeroIf true, ignore data where either x or y is 0. If false, includes all 0.
[in]absmaxIgnores values in y more than absmax from zero

Definition at line 538 of file util.cpp.

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}
void div(float f)
make each pixel value divided by a float number.

References Assert, div(), NullPointerException, x, and y.

Referenced by EMAN::OptVarianceCmp::cmp(), EMAN::LowpassAutoBProcessor::create_radial_func(), and EMAN::GradientRemoverProcessor::process_inplace().

◆ change_filename_ext()

string Util::change_filename_ext ( const string &  old_filename,
const string &  new_ext 
)
static

Change a file's extension and return the new filename.

If the given new extension is empty, the old filename is not changed. If the old filename has no extension, add the new extension to it.

Parameters
[in]old_filenameOld filename.
[in]new_extThe new extension. It shouldn't have ".". e.g., for MRC file, it will be "mrc", not ".mrc".
Returns
The new filename with the new extension.

Definition at line 485 of file util.cpp.

487{
488 Assert(old_filename != "");
489 if (ext.empty())
490 return old_filename;
491
492 return remove_filename_ext(old_filename) + "." + ext;
493}
static string remove_filename_ext(const string &filename)
Remove a filename's extension and return the new filename.
Definition: util.cpp:495

References Assert, and remove_filename_ext().

Referenced by EMAN::EMUtil::get_image_type(), EMAN::ImagicIO::ImagicIO(), and EMAN::ImagicIO2::ImagicIO2().

◆ check_file_by_magic()

bool Util::check_file_by_magic ( const void *  first_block,
const char *  magic 
)
static

check whether a file starts with certain magic string.

Parameters
first_blockThe first block of the file.
magicThe magic string to identify a file format.
Returns
True if file matches magic. Otherwise, false.

Definition at line 239 of file util.cpp.

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}

References NullPointerException.

Referenced by EMAN::AmiraIO::is_valid(), EMAN::LstFastIO::is_valid(), EMAN::LstIO::is_valid(), EMAN::PgmIO::is_valid(), EMAN::SalIO::is_valid(), and EMAN::VtkIO::is_valid().

◆ eman_copysign()

static float EMAN::Util::eman_copysign ( float  a,
float  b 
)
inlinestatic

copy sign of a number.

return a value whose absolute value matches that of 'a', but whose sign matches that of 'b'. If 'a' is a NaN, then a NaN with the sign of 'b' is returned.

It is exactly copysign() on non-Windows system.

Parameters
[in]aThe first number.
[in]bThe second number.
Returns
Copy sign of a number.

Definition at line 1159 of file util.h.

1160 {
1161#ifndef WIN32
1162 return copysign(a, b);
1163#else
1164 int flip = -1;
1165 if ((a <= 0 && b <= 0) || (a > 0 && b > 0)) {
1166 flip = 1;
1167 }
1168 return a * flip;
1169#endif
1170 }

◆ eman_erfc()

static float EMAN::Util::eman_erfc ( float  x)
inlinestatic

complementary error function.

It is exactly erfc() on non-Windows system. On Windows, it tries to simulate erfc().

The erf() function returns the error function of x; defined as erf(x) = 2/sqrt(pi)* integral from 0 to x of exp(-t*t) dt

The erfc() function returns the complementary error function of x, that is 1.0 - erf(x).

Parameters
[in]xA float number.
Returns
The complementary error function of x.

Definition at line 1184 of file util.h.

1185 {
1186#ifndef WIN32
1187 return (float)erfc(x);
1188#else
1189 static double a[] = { -1.26551223, 1.00002368,
1190 0.37409196, 0.09678418,
1191 -0.18628806, 0.27886807,
1192 -1.13520398, 1.48851587,
1193 -0.82215223, 0.17087277
1194 };
1195
1196 double result = 1;
1197 double z = fabs(x);
1198 if (z > 0) {
1199 double t = 1 / (1 + 0.5 * z);
1200 double f1 = t * (a[4] + t * (a[5] + t * (a[6] +
1201 t * (a[7] + t * (a[8] + t * a[9])))));
1202 result = t * exp((-z * z) + a[0] + t * (a[1] + t * (a[2] + t * (a[3] + f1))));
1203
1204 if (x < 0) {
1205 result = 2 - result;
1206 }
1207 }
1208 return (float)result;
1209#endif
1210 }

References x.

◆ equation_of_plane()

void Util::equation_of_plane ( const Vec3f p1,
const Vec3f p2,
const Vec3f p3,
float *  plane 
)
static

Determine the equation of a plane that intersects 3 points in 3D space.

Required by Symmetry3D::reduce IMPORTANT - does no error checking, if the float pointer is less than 4 in size will get unknown behavior

Parameters
p1point one
p2point two
p3point three
planea float pointer - should have room for 4 elements which will be A,B,C, and D (in that order) for the equation Ax+By+Cz+D=0
Returns
there is no explicit return - data is implicitly returned in the plane pointer
Author
David Woolford
Date
May 2008

Definition at line 1293 of file util.cpp.

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}

References x, and y.

Referenced by EMAN::Symmetry3D::cache_au_planes().

◆ fast_acos()

float Util::fast_acos ( const float &  f)
static

Returns an approximate of acos(x) using a cached table and linear interpolation tolerates values very slightly outside the -1 - 1 range (returning 0)

Parameters
[in]xargument to acos(x)
Returns
(float)acos(x)

Definition at line 804 of file util.cpp.

804 {
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}

Referenced by angle3(), and angle_err_ri().

◆ fast_exp()

float Util::fast_exp ( const float &  f)
static

Returns an approximate of exp(x) using a cached table uses actual exp(x) outside the cached range.

Parameters
[in]fargument to exp(f)
Returns
(float)exp(x)

Definition at line 788 of file util.cpp.

788 {
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}

Referenced by EMAN::FourierInserter3DMode2::insert_pixel(), EMAN::FourierInserter3DMode3::insert_pixel(), EMAN::FourierInserter3DMode5::insert_pixel(), EMAN::FourierInserter3DMode6::insert_pixel(), EMAN::FourierInserter3DMode8::insert_pixel(), EMAN::FourierIterReconstructor::insert_slice(), and EMAN::WienerFourierReconstructor::pixel_at().

◆ fast_floor()

static int EMAN::Util::fast_floor ( float  x)
inlinestatic

◆ fast_gauss_B2()

float Util::fast_gauss_B2 ( const float &  f)
static

Returns an approximate of exp(-2x^2) using a cached table uses actual function outside the cached range.

Parameters
[in]fargument to exp(f)
Returns
(float)exp(-2 x^2)

Definition at line 830 of file util.cpp.

830 {
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}

Referenced by gauss3_interpolate_cmplx(), and gauss_interpolate_cmplx().

◆ file_lock_wait()

int Util::file_lock_wait ( FILE *  file)
static

lock a file.

If the lock fails, wait for 1 second; then try again. Repleat this wait-try for a maxinum of 5 times unless the lock succeeds.

Parameters
fileThe file to be locked.
Returns
0 if lock succeeds. 1 if fails.

Definition at line 182 of file util.cpp.

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}
#define LOGERR
Definition: log.h:51

References LOGERR, and NullPointerException.

◆ find_max()

void Util::find_max ( const float *  data,
size_t  nitems,
float *  p_max_val,
int *  p_max_index = 0 
)
static

Find the maximum value and (optional) its index in an array.

Parameters
[in]datadata array.
[in]nitemsnumber of items in the data array.
[out]p_max_valpointer to the maximum value.
[out]p_max_indexpointer to index of the maximum value.

Definition at line 851 of file util.cpp.

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}

References Assert, and NullPointerException.

Referenced by EMAN::RotationalAligner::align_180_ambiguous().

◆ find_min_and_max()

void Util::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 
)
static

Find the maximum value and (optional) its index, minimum value and (optional) its index in an array.

Parameters
[in]datadata array.
[in]nitemsnumber of items in the data array.
[out]p_max_valpointer to the maximum value.
[out]p_min_valpointer to the minimum value.
[out]p_max_indexpointer to index of the maximum value.
[out]p_min_indexpointer to index of the minimum value.

Definition at line 875 of file util.cpp.

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}

References Assert, and NullPointerException.

◆ flip_complex_phase()

void Util::flip_complex_phase ( float *  data,
size_t  n 
)
static

flip the phase of a complex data array.

Parameters
datacomplex data array.
narray size.

Definition at line 127 of file util.cpp.

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}

References Assert, and NullPointerException.

◆ flip_image()

void Util::flip_image ( float *  data,
size_t  nx,
size_t  ny 
)
static

Vertically flip the data of a 2D real image.

Parameters
dataData array of the 2D real image.
nxImage Width.
nyImage Height.

Definition at line 259 of file util.cpp.

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}

References Assert, and NullPointerException.

◆ gauss3_interpolate_cmplx()

static std::complex< float > EMAN::Util::gauss3_interpolate_cmplx ( std::complex< float > *  p,
float  t,
float  u 
)
inlinestatic

Calculate 3x3 Gaussian interpolation.

Note that this sort of interpolation has discontinuities

Parameters
[in]p[9]The 9 pixel values [0,0],[1,0],...
[in]tx distance from p[0] sample
[in]uy distance from p[0] sample
Returns
The interpolated value.

Definition at line 589 of file util.h.

590 {
591 std::complex<float> sm=0;
592 float wt=0;
593 for (int y=0,i=0; y<3; y++) {
594 for (int x=0; x<3; x++,i++) {
596 sm+=c*p[i];
597 wt+=c;
598 }
599 }
600 return sm/wt;
601 }
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

References fast_gauss_B2(), x, and y.

Referenced by get_complex_at_3ginterp().

◆ gauss_interpolate_cmplx()

static std::complex< float > EMAN::Util::gauss_interpolate_cmplx ( std::complex< float >  p1,
std::complex< float >  p2,
std::complex< float >  p3,
std::complex< float >  p4,
float  t,
float  u 
)
inlinestatic

Calculate 2x2 Gaussian interpolation.

Note that this sort of interpolation has discontinuities

Parameters
[in]p1The first number. corresponding to (x0,y0).
[in]p2The second number. corresponding to (x1,y0).
[in]p3The third number. corresponding to (x1,y1).
[in]p4The fourth number. corresponding to (x0,y1).
[in]tt
[in]uu
Returns
The interpolated value.

Definition at line 573 of file util.h.

575 {
576 float c4 = Util::fast_gauss_B2(1.0f-t)*Util::fast_gauss_B2(1.0f-u);
577 float c3 = Util::fast_gauss_B2(t)*Util::fast_gauss_B2(1.0f-u);
578 float c2 = Util::fast_gauss_B2(1.0f-t)*Util::fast_gauss_B2(u);
580 return (c1 * p1 + c2 * p2 + c3 * p3 + c4 * p4)/(c1+c2+c3+c4);
581 }

References fast_gauss_B2().

Referenced by get_complex_at_ginterp().

◆ get_filename_ext()

string Util::get_filename_ext ( const string &  filename)
static

Get a filename's extension.

Parameters
[in]filenameA given filename.
Returns
The filename's extension, or empty string if the file has no extension.

Definition at line 526 of file util.cpp.

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}

Referenced by EMAN::EMUtil::fast_get_image_type(), EMAN::EMUtil::get_image_type(), and EMAN::EMUtil::is_valid_filename().

◆ get_frand() [1/3]

float Util::get_frand ( double  low,
double  high 
)
static

Get a float random number between low and high, [low, high)

Parameters
[in]lowThe lower bound of the random number.
[in]highThe upper bound of the random number.
Returns
The random number between low and high.

Definition at line 736 of file util.cpp.

737{
738 Randnum* randnum = Randnum::Instance();
739 return randnum->get_frand(lo, hi);
740}
The wrapper class for gsl's random number generater.
Definition: randnum.h:86
static Randnum * Instance()
Definition: randnum.cpp:104
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

References EMAN::Randnum::get_frand(), and EMAN::Randnum::Instance().

◆ get_frand() [2/3]

float Util::get_frand ( float  low,
float  high 
)
static

Get a float random number between low and high, [low, high)

Parameters
[in]lowThe lower bound of the random number.
[in]highThe upper bound of the random number.
Returns
The random number between low and high.

Definition at line 730 of file util.cpp.

731{
732 Randnum* randnum = Randnum::Instance();
733 return randnum->get_frand(lo, hi);
734}

References EMAN::Randnum::get_frand(), and EMAN::Randnum::Instance().

◆ get_frand() [3/3]

float Util::get_frand ( int  low,
int  high 
)
static

Get a float random number between low and high, [low, high)

Parameters
[in]lowThe lower bound of the random number.
[in]highThe upper bound of the random number.
Returns
The random number between low and high.

Definition at line 725 of file util.cpp.

726{
727 return get_frand((float)lo, (float)hi);
728}
static float get_frand(int low, int high)
Get a float random number between low and high, [low, high)
Definition: util.cpp:725

References get_frand().

Referenced by EMAN::OrientationGenerator::add_orientation(), EMAN::RandomOrientationGenerator::gen_orientations(), get_frand(), EMAN::KmeansSegmentProcessor::process(), EMAN::LowpassRandomPhaseProcessor::process_inplace(), EMAN::TestImageFourierNoiseGaussian::process_inplace(), EMAN::TestImageFourierNoiseProfile::process_inplace(), and EMAN::PointArray::set_from_density_map().

◆ get_gauss_rand()

float Util::get_gauss_rand ( float  mean,
float  sigma 
)
static

Get a Gaussian random number.

Parameters
[in]meanThe gaussian mean
[in]sigmaThe gaussian sigma
Returns
the gaussian random number.

Definition at line 845 of file util.cpp.

846{
847 Randnum* randnum = Randnum::Instance();
848 return randnum->get_gauss_rand(mean, sigma);
849}
float get_gauss_rand(float mean, float sigma) const
Return a Gaussian random number.
Definition: randnum.cpp:168

References EMAN::Randnum::get_gauss_rand(), and EMAN::Randnum::Instance().

Referenced by EMAN::EmanOrientationGenerator::gen_orientations(), and EMAN::MaskNoiseProcessor::process_dist_pixel().

◆ get_irand()

int Util::get_irand ( int  low,
int  high 
)
static

Get an integer random number between low and high, [low, high].

Parameters
[in]lowThe lower bound of the random number.
[in]highThe upper bound of the random number.
Returns
The random number between low and high.

Definition at line 719 of file util.cpp.

720{
721 Randnum* randnum = Randnum::Instance();
722 return randnum->get_irand(lo, hi);
723}
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

References EMAN::Randnum::get_irand(), and EMAN::Randnum::Instance().

Referenced by EMAN::KMeansAnalyzer::analyze(), EMAN::PointArray::calc_transform(), EMAN::KMeansAnalyzer::reseed(), and EMAN::PointArray::sim_minstep_seq().

◆ get_line_from_string()

string Util::get_line_from_string ( char **  str)
static

Extract a single line from a multi-line string.

The line delimiter is '
'. The multi-line string moves forward one line. If it is the last line, move to the end of the string.

Parameters
[in,out]strA multiple-line string.
Returns
A single line.

Definition at line 322 of file util.cpp.

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}

References NullPointerException.

Referenced by EMAN::SitusIO::is_valid(), and EMAN::XplorIO::is_valid().

◆ get_max() [1/3]

static float EMAN::Util::get_max ( float  f1,
float  f2 
)
inlinestatic

Get the maximum of 2 numbers.

Parameters
[in]f1The first number.
[in]f2The second number.
Returns
The maximum of 2 numbers.

Definition at line 998 of file util.h.

999 {
1000 return (f1 < f2 ? f2 : f1);
1001 }

Referenced by EMAN::FourierReconstructor::do_insert_slice_work(), EMAN::nnSSNR_Reconstructor::finish(), EMAN::nnSSNR_ctfReconstructor::finish(), EMAN::EMData::max_3D_pixel_error(), EMAN::PawelProjector::project3d(), EMAN::MaxValProjector::project3d(), and EMAN::EMData::update_stat().

◆ get_max() [2/3]

static float EMAN::Util::get_max ( float  f1,
float  f2,
float  f3 
)
inlinestatic

Get the maximum of 3 numbers.

Parameters
[in]f1The first number.
[in]f2The second number.
[in]f3The third number.
Returns
The maximum of 3 numbers.

Definition at line 1009 of file util.h.

1010 {
1011 if (f1 >= f2 && f1 >= f3) {
1012 return f1;
1013 }
1014 if (f2 >= f1 && f2 >= f3) {
1015 return f2;
1016 }
1017 return f3;
1018 }

◆ get_max() [3/3]

static float EMAN::Util::get_max ( float  f1,
float  f2,
float  f3,
float  f4 
)
inlinestatic

Get the maximum of 4 numbers.

Parameters
[in]f1The first number.
[in]f2The second number.
[in]f3The third number.
[in]f4The fourth number.
Returns
The maximum of 4 numbers.

Definition at line 1027 of file util.h.

1028 {
1029 float m = f1;
1030 if (f2 > m) {
1031 m = f2;
1032 }
1033 if (f3 > m) {
1034 m = f3;
1035 }
1036 if (f4 > m) {
1037 m = f4;
1038 }
1039 return m;
1040 }

◆ get_min() [1/5]

static float EMAN::Util::get_min ( float  f1,
float  f2 
)
inlinestatic

Get the minimum of 2 numbers.

Parameters
[in]f1The first number.
[in]f2The second number.
Returns
The minimum of 2 numbers.

Definition at line 949 of file util.h.

950 {
951 return (f1 < f2 ? f1 : f2);
952 }

◆ get_min() [2/5]

static float EMAN::Util::get_min ( float  f1,
float  f2,
float  f3 
)
inlinestatic

Get the minimum of 3 numbers.

Parameters
[in]f1The first number.
[in]f2The second number.
[in]f3The third number.
Returns
The minimum of 3 numbers.

Definition at line 960 of file util.h.

961 {
962 if (f1 <= f2 && f1 <= f3) {
963 return f1;
964 }
965 if (f2 <= f1 && f2 <= f3) {
966 return f2;
967 }
968 return f3;
969 }

◆ get_min() [3/5]

static float EMAN::Util::get_min ( float  f1,
float  f2,
float  f3,
float  f4 
)
inlinestatic

Get the minimum of 4 numbers.

Parameters
[in]f1The first number.
[in]f2The second number.
[in]f3The third number.
[in]f4The fourth number.
Returns
The minimum of 4 numbers.

Definition at line 978 of file util.h.

979 {
980 float m = f1;
981 if (f2 < m) {
982 m = f2;
983 }
984 if (f3 < m) {
985 m = f3;
986 }
987 if (f4 < m) {
988 m = f4;
989 }
990 return m;
991 }

◆ get_min() [4/5]

static int EMAN::Util::get_min ( int  f1,
int  f2 
)
inlinestatic

◆ get_min() [5/5]

static int EMAN::Util::get_min ( int  f1,
int  f2,
int  f3 
)
inlinestatic

Get the minimum of 3 numbers.

Parameters
[in]f1The first number.
[in]f2The second number.
[in]f3The third number.
Returns
The minimum of 3 numbers.

Definition at line 933 of file util.h.

934 {
935 if (f1 <= f2 && f1 <= f3) {
936 return f1;
937 }
938 if (f2 <= f1 && f2 <= f3) {
939 return f2;
940 }
941 return f3;
942 }

◆ get_randnum_seed()

unsigned long long Util::get_randnum_seed ( )
static

Get the seed for Randnum class.

Returns
the seed for current random number generator

Definition at line 713 of file util.cpp.

714{
715 Randnum* randnum = Randnum::Instance();
716 return randnum->get_seed();
717}
unsigned long long get_seed()
Get the current random number seed.
Definition: randnum.cpp:148

References EMAN::Randnum::get_seed(), and EMAN::Randnum::Instance().

◆ get_stats()

Dict Util::get_stats ( const vector< float > &  data)
static

Get the mean, standard deviation, skewness and kurtosis of the input data.

Parameters
datathe vector of input data
Exceptions
EmptyContainerExceptionwhen the argument vector is empty

Definition at line 913 of file util.cpp.

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}
Dict is a dictionary to store <string, EMObject> pair.
Definition: emobject.h:385
static float square_sum(float x, float y)
Calcuate (x*x + y*y).
Definition: util.h:764
EMData * sqrt() const
return square root of current image
#define EmptyContainerException(desc)
Definition: exception.h:374

References EmptyContainerException, sqrt(), and square_sum().

◆ get_stats_cstyle()

Dict Util::get_stats_cstyle ( const vector< float > &  data)
static

Performs the same calculations as in get_stats, but uses a single pass, optimized c approach Should perform better than get_stats.

Definition at line 969 of file util.cpp.

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}
static int square(int n)
Calculate a number's square.
Definition: util.h:736

References EmptyContainerException, sqrt(), square(), and square_sum().

◆ get_str_float() [1/3]

bool Util::get_str_float ( const char *  str,
const char *  float_var,
float *  p_v1,
float *  p_v2 
)
static

Extract the float values from a variable=value1,value2 string with format like "XYZ=1.1,1.2", where 'str' is "XYZ=1.1,1.2"; 'float_var' is "XYZ="; 'p_v1' points to 1.1; 'p_v2' points to 1.2.

Parameters
[in]strA string like "XYZ=1.1,1.2";
[in]float_varThe variable name "XYZ=".
[out]p_v1The pointer to the first float.
[out]p_v2The pointer to the second float.
Returns
True if the extraction succeeds; False if extraction fails.

Definition at line 399 of file util.cpp.

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}

References NullPointerException.

◆ get_str_float() [2/3]

bool Util::get_str_float ( const char *  str,
const char *  float_var,
float *  p_val 
)
static

Extract the float value from a variable=value string with format like "XYZ=1.1", where 'str' is "XYZ=1.1"; 'float_var' is "XYZ="; 'p_val' points to float number 1.1.

Parameters
[in]strA string like "XYZ=1.1";
[in]float_varThe variable name "XYZ=".
[out]p_valThe pointer to the float number.
Returns
True if the extraction succeeds; False if extraction fails.

Definition at line 385 of file util.cpp.

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}

References NullPointerException.

◆ get_str_float() [3/3]

bool Util::get_str_float ( const char *  str,
const char *  float_var,
int *  p_nvalues,
float *  p_v1,
float *  p_v2 
)
static

Extract number of values and the float values, if any, from a string whose format is either "variable=value1,value2 " or "variable".

for example, if the string is "XYZ=1.1,1.2", then 'str' is "XYZ=1.1,1.2"; 'float_var' is "XYZ"; 'p_nvalues' points to 2. 'p_v1' points to 1.1; 'p_v2' points to 1.2. If the string is "XYZ", then 'str' is "XYZ"; 'float_var' is "XYZ". 'p_nvalues' points to 0. 'p_v1' and 'p_v2' unchanged.

Parameters
[in]strA string like "XYZ=1.1,1.2" or "XYZ".
[in]float_varThe variable name "XYZ".
[out]p_nvaluesNumber of values in the string.
[out]p_v1The pointer to the first float, if any.
[out]p_v2The pointer to the second float, if any.
Returns
True if the extraction succeeds; False if extraction fails.

Definition at line 414 of file util.cpp.

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}

References NullPointerException.

◆ get_str_int() [1/3]

bool Util::get_str_int ( const char *  str,
const char *  int_var,
int *  p_nvalues,
int *  p_v1,
int *  p_v2 
)
static

Extract number of values and the int values, if any, from a string whose format is either "variable=value1,value2 " or "variable".

for example, if the string is "XYZ=1,2", then 'str' is "XYZ=1,2"; 'int_var' is "XYZ"; 'p_nvalues' points to 2. 'p_v1' points to 1; 'p_v2' points to 2. If the string is "XYZ", then 'str' is "XYZ"; 'int_var' is "XYZ". 'p_nvalues' points to 0. 'p_v1' and 'p_v2' unchanged.

Parameters
[in]strA string like "XYZ=1,2" or "XYZ".
[in]int_varThe variable name "XYZ".
[out]p_nvaluesNumber of values in the string.
[out]p_v1The pointer to the first int, if any.
[out]p_v2The pointer to the second int, if any.
Returns
True if the extraction succeeds; False if extraction fails.

Definition at line 464 of file util.cpp.

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}

References NullPointerException.

◆ get_str_int() [2/3]

bool Util::get_str_int ( const char *  str,
const char *  int_var,
int *  p_v1,
int *  p_v2 
)
static

Extract the int value from a variable=value1,value2 string with format like "XYZ=1,2", where 'str' is "XYZ=1,2"; 'int_var' is "XYZ="; 'p_val' points to float number 1.

Parameters
[in]strA string like "XYZ=1";
[in]int_varThe variable name "XYZ=".
[out]p_v1The pointer to the first int.
[out]p_v2The pointer to the second int.
Returns
True if the extraction succeeds; False if extraction fails.

Definition at line 450 of file util.cpp.

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}

References NullPointerException.

◆ get_str_int() [3/3]

bool Util::get_str_int ( const char *  str,
const char *  int_var,
int *  p_val 
)
static

Extract the int value from a variable=value string with format like "XYZ=1", where 'str' is "XYZ=1"; 'int_var' is "XYZ="; 'p_val' points to float number 1.

Parameters
[in]strA string like "XYZ=1";
[in]int_varThe variable name "XYZ=".
[out]p_valThe pointer to the int number.
Returns
True if the extraction succeeds; False if extraction fails.

Definition at line 436 of file util.cpp.

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}

References NullPointerException.

◆ get_time_label()

string Util::get_time_label ( )
static

Get the current time in a string with format "mm/dd/yyyy hh:mm".

Returns
The current time string.

Definition at line 1167 of file util.cpp.

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}

◆ getBaldwinGridWeights()

float * Util::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 
)
static
Parameters
[in]freq_cutoff
[in]P
[in]r
[in]dfreq
[in]alpha
[in]beta
Returns
float*

Definition at line 1232 of file util.cpp.

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}
#define V(i, j)
Definition: analyzer.cpp:697
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

References printmatrix(), printvector(), and V.

◆ goodf() [1/2]

static int EMAN::Util::goodf ( const double *  p_f)
inlinestatic

Definition at line 1122 of file util.h.

1123 {
1124 // The old code used 'fpclassify' which was demonstrably broken on many platforms,
1125 // causing many irritating problems
1126
1127 if (((*((long long *)p_f)>>52)&2047)==2047) return 0;
1128
1129 return 1;
1130 }

◆ goodf() [2/2]

static int EMAN::Util::goodf ( const float *  p_f)
inlinestatic

Check whether a number is a good float.

A number is a good float if it is not abnormal zero, and not inf, -inf or NaN

Parameters
[in]p_fPointer to the given float number.
Returns
1 if it is a good float; 0 if it's not good float.

Definition at line 1112 of file util.h.

1113 {
1114 // The old code used 'fpclassify' which was demonstrably broken on many platforms,
1115 // causing many irritating problems
1116
1117 if (((*((int *)p_f)>>23)&255)==255) return 0;
1118
1119 return 1;
1120 }

Referenced by EMAN::CccCmp::cmp(), EMAN::SqEuclideanCmp::cmp(), EMAN::FRCCmp::cmp(), EMAN::EMObject::EMObject(), EMAN::ByteOrder::is_float_big_endian(), EMAN::NormalizeProcessor::process_inplace(), and EMAN::FiniteProcessor::process_pixel().

◆ hypot2()

static float EMAN::Util::hypot2 ( float  x,
float  y 
)
inlinestatic

Euclidean distance function in 2D: f(x,y) = sqrt(x*x + y*y);.

Parameters
[in]xThe first number.
[in]yThe second number.
Returns
sqrt(x*x + y*y);

Definition at line 774 of file util.h.

775 {
776 return (float) hypot(x, y);
777 }

References x, and y.

Referenced by EMAN::FourierWeightAverager::add_image(), and EMAN::SetIsoPowProcessor::process_inplace().

◆ hypot2sq() [1/2]

static float EMAN::Util::hypot2sq ( float  x,
float  y 
)
inlinestatic

Euclidean distance function squared in 2D: f(x,y) = (x*x + y*y);.

Parameters
[in]xThe first number.
[in]yThe second number.
Returns
(int)(x*x + y*y);

Definition at line 794 of file util.h.

795 {
796 return (float)(x * x + y * y);
797 }

References x, and y.

◆ hypot2sq() [2/2]

static int EMAN::Util::hypot2sq ( int  x,
int  y 
)
inlinestatic

Euclidean distance function squared in 2D: f(x,y) = (x*x + y*y);.

Parameters
[in]xThe first number.
[in]yThe second number.
Returns
(int)(x*x + y*y);

Definition at line 784 of file util.h.

785 {
786 return (x * x + y * y);
787 }

References x, and y.

Referenced by get_attr().

◆ hypot3() [1/3]

static double EMAN::Util::hypot3 ( double  x,
double  y,
double  z 
)
inlinestatic

Euclidean distance function in 3D: f(x,y,z) = sqrt(x*x + y*y + z*z);.

Parameters
[in]xThe first number.
[in]yThe second number.
[in]zThe third number.
Returns
sqrt(x*x + y*y + z*z);

Definition at line 849 of file util.h.

850 {
851 return (double) sqrt(x * x + y * y + z * z);
852 }

References sqrt(), x, and y.

◆ hypot3() [2/3]

static float EMAN::Util::hypot3 ( float  x,
float  y,
float  z 
)
inlinestatic

Euclidean distance function in 3D: f(x,y,z) = sqrt(x*x + y*y + z*z);.

Parameters
[in]xThe first number.
[in]yThe second number.
[in]zThe third number.
Returns
sqrt(x*x + y*y + z*z);

Definition at line 838 of file util.h.

839 {
840 return sqrtf(x * x + y * y + z * z);
841 }

References x, and y.

◆ hypot3() [3/3]

static float EMAN::Util::hypot3 ( int  x,
int  y,
int  z 
)
inlinestatic

◆ hypot3sq() [1/2]

static float EMAN::Util::hypot3sq ( float  x,
float  y,
float  z 
)
inlinestatic

Euclidean distance function squared in 3D: f(x,y,z) = (x*x + y*y + z*z);.

Parameters
[in]xThe first number.
[in]yThe second number.
[in]zThe third number.
Returns
(x*x + y*y + z*z);

Definition at line 816 of file util.h.

817 {
818 return (x * x + y * y + z * z);
819 }

References x, and y.

◆ hypot3sq() [2/2]

static int EMAN::Util::hypot3sq ( int  x,
int  y,
int  z 
)
inlinestatic

◆ hypot_fast()

float Util::hypot_fast ( int  x,
int  y 
)
static

Euclidean distance in 2D for integers computed fast using a cached lookup table.

Parameters
[in]xThe first number
[in]yThe second number
Returns
sqrt(x*x+y*y)

Definition at line 742 of file util.cpp.

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}

References x, and y.

Referenced by EMAN::EMData::calc_az_dist(), EMAN::EMData::calc_radial_dist(), EMAN::EMAN2Ctf::compute_1d_fromimage(), EMAN::EMAN2Ctf::compute_2d_complex(), EMAN::MatchSFProcessor::create_radial_func(), EMAN::FourierReconstructor::do_compare_slice_work(), EMAN::CtfWtFiltAverager::finish(), EMAN::HarmonicProcessor::process(), EMAN::BispecSliceProcessor::process(), EMAN::SubtractOptProcessor::process(), EMAN::GaussZFourierProcessor::process_inplace(), and EMAN::TestImageFourierGaussianBand::process_inplace().

◆ hypot_fast_int()

short Util::hypot_fast_int ( int  x,
int  y 
)
static

Euclidean distance in 2D for integers computed fast using a cached lookup table.

Parameters
[in]xThe first number
[in]yThe second number
Returns
(int)round(sqrt(x*x+y*y))

Definition at line 764 of file util.cpp.

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}
static int round(float x)
Get ceiling round of a float number x.
Definition: util.h:465

References round(), x, and y.

Referenced by EMAN::PhaseCmp::cmp(), EMAN::FourierReconstructor::do_insert_slice_work(), EMAN::FourierIterReconstructor::insert_slice(), EMAN::CtfSimProcessor::process(), and EMAN::FFTPeakProcessor::process_inplace().

◆ int2str()

string Util::int2str ( int  n)
static

Get a string format of an integer, e.g.

123 will be "123".

Parameters
[in]nThe input integer.
Returns
The string format of the given integer.

Definition at line 315 of file util.cpp.

316{
317 char s[32] = {'\0'};
318 sprintf(s, "%d", n);
319 return string(s);
320}

Referenced by EMAN::Log::loc(), EMAN::SerIO::read_dim_arr(), and EMAN::E2Exception::what().

◆ is_file_exist()

bool Util::is_file_exist ( const string &  filename)
static

check whether a file exists or not

Returns
True if the file exists; False if not.

Definition at line 253 of file util.cpp.

254{
255 return access(filename.c_str(), F_OK) == 0;
256}

Referenced by EMAN::LstFastIO::calc_ref_image_index(), EMAN::TestUtil::check_image(), and EMAN::SpiderIO::SpiderIO().

◆ is_nan()

static bool EMAN::Util::is_nan ( const float  number)
inlinestatic

tell whether a float value is a NaN

Parameters
numberfloat value

Definition at line 105 of file util.h.

106 {
107 return std::isnan(number);
108 }

Referenced by EMAN::TomoWedgeCccCmp::cmp(), and EMAN::EMUtil::getRenderMinMax().

◆ IsPower2()

static bool EMAN::Util::IsPower2 ( int  x)
inlinestatic

Return true if an integer is positive and is power of 2.

Parameters
[in]xinteger to be checked
Returns
true if the integer is positive and is power of 2

Definition at line 1304 of file util.h.

1304 {
1305 return ( (x>1) && (x & (x-1))==0 );
1306 }

References x.

Referenced by EMAN::WaveletProcessor::process_inplace().

◆ linear_interpolate()

static float EMAN::Util::linear_interpolate ( float  p1,
float  p2,
float  t 
)
inlinestatic

Calculate linear interpolation.

Parameters
[in]p1The first number (at x1).
[in]p2The second number (at x2).
[in]t(x-x1)/(x2-x1)
Returns
The linearly interpolated value at x.

Definition at line 518 of file util.h.

519 {
520 return (1-t) * p1 + t * p2;
521 }

Referenced by EMAN::EMData::cut_slice(), EMAN::WienerFourierReconstructor::do_insert_slice_work(), EMAN::MaxValProjector::project3d(), and EMAN::StandardProjector::project3d().

◆ linear_interpolate_cmplx()

static std::complex< float > EMAN::Util::linear_interpolate_cmplx ( std::complex< float >  p1,
std::complex< float >  p2,
float  t 
)
inlinestatic

Calculate linear interpolation.

Parameters
[in]p1The first number. corresponding to (x0,y0).
[in]p2The second number. corresponding to (x1,y0).
[in]t(x-x1)/(x2-x1)
Returns
The bilinear interpolation value.

Definition at line 529 of file util.h.

530 {
531 return (1.0f-t) * p1 + t * p2;
532 }

◆ log_2() [1/3]

static double EMAN::Util::log_2 ( double  x)
inlinestatic

Get the log base 2 of a double x.

Parameters
[in]xGiven double.
Returns
log base 2 of x.

Definition at line 498 of file util.h.

499 {
500 return (double) (log(x) / log(2.0));
501 }
EMData * log() const
return natural logarithm image for a image

References log(), and x.

◆ log_2() [2/3]

static float EMAN::Util::log_2 ( float  x)
inlinestatic

Get the log base 2 of a float x.

Parameters
[in]xGiven float number.
Returns
log base 2 of x.

Definition at line 489 of file util.h.

490 {
491 return (float) (log(x) / log(2.0f));
492 }

References log(), and x.

◆ log_2() [3/3]

static float EMAN::Util::log_2 ( int  i)
inlinestatic

Get the log base 2 of an integer i.

Parameters
[in]iGiven integer.
Returns
log base 2 of i.

Definition at line 507 of file util.h.

508 {
509 return (float) (log((float)i) / log(2.0f));
510 }

References log().

◆ MUTEX_INIT()

int Util::MUTEX_INIT ( MUTEX mutex)
static

For those util function developed by Pawel's group.

Definition at line 64 of file util.cpp.

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}

◆ MUTEX_LOCK()

int Util::MUTEX_LOCK ( MUTEX mutex)
static

Definition at line 75 of file util.cpp.

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}

◆ MUTEX_UNLOCK()

int Util::MUTEX_UNLOCK ( MUTEX mutex)
static

Definition at line 85 of file util.cpp.

86{
87 #ifdef WIN32
88 return (ReleaseMutex(*mutex)==0);
89 #else
90 return pthread_mutex_unlock(mutex);
91 #endif
92 return -1;
93}

◆ nonconvex()

vector< float > Util::nonconvex ( const vector< float > &  curve,
int  first = 3 
)
static

Returns a non-convex version of a curve.

This is used for finding a good approximate background curve when evaluating power spectra.

Parameters
[in]curveThe data array (vector<float>)
[in]firstFirst point to consider, default = 3
[out]outcurveReturned data array

Definition at line 1037 of file util.cpp.

1037 {
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}

◆ point_is_in_convex_polygon_2d()

bool Util::point_is_in_convex_polygon_2d ( const Vec2f p1,
const Vec2f p2,
const Vec2f p3,
const Vec2f p4,
const Vec2f actual_point 
)
static

Determines if a point is in a 2D convex polygon described by 4 points using the Barycentric method, which is a fast way of performing the query.

The points must be ordered in the way you would encounter them if you traversed the boundary of the polygon. Direction is irrelevant. Could be generalized for polygons with more points

Parameters
p1point one
p2point two
p3point three
p4point three
actual_pointthe point which might be in the polygon described by p1,p2,p3 and p4
Returns
true if the point is in the polygon, false otherwise
Author
David Woolford
Date
October 2008

Definition at line 1339 of file util.cpp.

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}
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

References point_is_in_triangle_2d().

◆ point_is_in_triangle_2d()

bool Util::point_is_in_triangle_2d ( const Vec2f p1,
const Vec2f p2,
const Vec2f p3,
const Vec2f actual_point 
)
static

Determines if a point is in a 2D triangle using the Barycentric method, which is a fast way of performing the query Triangle points can be specified in any order.

Parameters
p1point one
p2point two
p3point three
actual_pointthe point which might be in the triangle described by p1,p2 and p3
Returns
true if the point is in the triangle, false otherwise
Author
David Woolford
Date
October 2008

Definition at line 1304 of file util.cpp.

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}
static const float ERR_LIMIT
Definition: transform.h:78
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

References EMAN::Vec2< Type >::dot(), and EMAN::Transform::ERR_LIMIT.

Referenced by point_is_in_convex_polygon_2d().

◆ printMatI3D()

void Util::printMatI3D ( MIArray3D mat,
const string  str = string(""),
ostream &  out = std::cout 
)
static

Print a 3D integer matrix to a file stream (std out by default).

Parameters
[in]matinteger 3-d multi_array reference
[in]strMessage string to be printed.
[out]outstream; cout by default.

Definition at line 1188 of file util.cpp.

1188 {
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}

◆ recv_broadcast()

string Util::recv_broadcast ( int  port)
static

Definition at line 1111 of file util.cpp.

1111 {
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}
static bool is_host_big_endian()
Definition: byteorder.cpp:40
Definition: util.cpp:1103
int oseq
Definition: util.cpp:1107
unsigned char data[1024]
Definition: util.cpp:1109
char hdr[4]
Definition: util.cpp:1104
int len
Definition: util.cpp:1106
int pseq
Definition: util.cpp:1108

References BPKT::data, BPKT::hdr, EMAN::ByteOrder::is_host_big_endian(), BPKT::len, BPKT::oseq, and BPKT::pseq.

◆ remove_filename_ext()

string Util::remove_filename_ext ( const string &  filename)
static

Remove a filename's extension and return the new filename.

Parameters
[in]filenameThe old filename whose extension is going to be removed.
Returns
The new filename without extension.

Definition at line 495 of file util.cpp.

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}

Referenced by change_filename_ext().

◆ replace_non_ascii()

void Util::replace_non_ascii ( char *  str,
int  max_size,
char  repl_char = '?' 
)
static

Replace any non-ASCII characters in a C string with a given character.

Parameters
strupdated C string where non-ASCII characters to be replaced
max_sizereplace only in the first max_size characters of str
repl_charcharacter to replace any non-ASCII characters in str

Definition at line 289 of file util.cpp.

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}

◆ rotate_phase_origin()

void Util::rotate_phase_origin ( float *  data,
size_t  nx,
size_t  ny,
size_t  nz 
)
static

rotate data vertically by ny/2, to make the mrc phase origin compliance with EMAN1 and TNF reader

Parameters
datacomplex data array
nxx dimension size
nyy dimension size
nzz dimension size

Definition at line 140 of file util.cpp.

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}

◆ round() [1/2]

static int EMAN::Util::round ( double  x)
inlinestatic

Get ceiling round of a float number x.

Parameters
[in]xGiven float number.
Returns
Ceiling round of x.

Definition at line 477 of file util.h.

478 {
479 if (x < 0) {
480 return (int) (x - 0.5);
481 }
482 return (int) (x + 0.5);
483 }

References x.

◆ round() [2/2]

static int EMAN::Util::round ( float  x)
inlinestatic

Get ceiling round of a float number x.

Parameters
[in]xGiven float number.
Returns
Ceiling round of x.

Definition at line 465 of file util.h.

466 {
467 if (x < 0) {
468 return (int) (x - 0.5f);
469 }
470 return (int) (x + 0.5f);
471 }

References x.

Referenced by EMAN::EMData::calc_hist(), EMAN::PointArray::construct_helix(), EMAN::EMData::cut_slice(), EMAN::nnSSNR_Reconstructor::finish(), EMAN::nnSSNR_ctfReconstructor::finish(), hypot_fast_int(), EMAN::FourierReconstructor::pixel_at(), EMAN::BeamstopProcessor::process_inplace(), EMAN::ApplyPolynomialProfileToHelix::process_inplace(), EMAN::EMData::translate(), and EMAN::EMData::uncut_slice().

◆ save_data() [1/3]

void Util::save_data ( const vector< float > &  x_array,
const vector< float > &  y_array,
const string &  filename 
)
static

Save (x y) data array into a file.

Each line of the file have the format "x1TABy1", where x1, y1 are elements of x array and y array. The x, y arrays must have the same number of items.

Parameters
[in]x_arrayThe x array.
[in]y_arrayThe y array.
[in]filenameThe output filename.

Definition at line 604 of file util.cpp.

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}
#define FileAccessException(filename)
Definition: exception.h:187

References Assert, FileAccessException, and LOGERR.

Referenced by EMAN::LowpassAutoBProcessor::create_radial_func().

◆ save_data() [2/3]

void Util::save_data ( float  x0,
float  dx,
const vector< float > &  y_array,
const string &  filename 
)
static

Save x, y data into a file.

Each line of the file have the format "x1TABy1", where x1 = x0 + dx*i; y1 = y_array[i].

Parameters
[in]x0The starting point of x.
[in]dxdelta x. The increase step of x data.
[in]y_arrayThe y data array.
[in]filenameThe output filename.

Definition at line 628 of file util.cpp.

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}

References Assert, and FileAccessException.

◆ save_data() [3/3]

void Util::save_data ( float  x0,
float  dx,
float *  y_array,
size_t  array_size,
const string &  filename 
)
static

Save x, y data into a file.

Each line of the file have the format "x1TABy1", where x1 = x0 + dx*i; y1 = y_array[i].

Parameters
[in]x0The starting point of x.
[in]dxdelta x. The increase step of x data.
[in]y_arrayThe y data array.
[in]array_sizeThe y data array size.
[in]filenameThe output filename.

Definition at line 647 of file util.cpp.

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}

References Assert, FileAccessException, and NullPointerException.

◆ sbasename()

string Util::sbasename ( const string &  filename)
static

Get a filename's basename.

For example, the basename of "hello.c" is still "hello.c"; The basename of "/tmp/abc/hello.c" is "hello.c".

Parameters
[in]filenameThe given filename, full path or relative path.
Returns
The basename of the filename.

Definition at line 505 of file util.cpp.

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}

Referenced by EMAN::Log::begin(), EMAN::TestUtil::check_image(), EMAN::TestUtil::dump_emdata(), EMAN::Log::loc(), and EMAN::TestUtil::set_progname().

◆ set_log_level()

void Util::set_log_level ( int  argc,
char *  argv[] 
)
static

Set program logging level through command line option "-v N", where N is the level.

Parameters
[in]argcNumber of arguments.
[in]argvArgument arrays.

Definition at line 1178 of file util.cpp.

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}
void set_level(int level)
Definition: log.cpp:165
static Log * logger()
Definition: log.cpp:80
LogLevel
Definition: log.h:72

References EMAN::Log::logger(), and EMAN::Log::set_level().

◆ set_randnum_seed()

void Util::set_randnum_seed ( unsigned long long  seed)
static

Set the seed for Randnum class.

Parameters
[in]seedthe seed for current random number generator

Definition at line 707 of file util.cpp.

708{
709 Randnum* randnum = Randnum::Instance();
710 randnum->set_seed(seed);
711}
void set_seed(unsigned long long seed)
Set the seed for the random number generator.
Definition: randnum.cpp:142

References EMAN::Randnum::Instance(), and EMAN::Randnum::set_seed().

◆ sgn()

template<class T >
static T EMAN::Util::sgn ( T &  val)
inlinestatic

Sign function.

@param[in] val value who's sign is to be checked

@return +1 if the value is positive, -1 if the value is negative.

Definition at line 1269 of file util.h.

1269 {
1270 return (val > 0) ? T(+1) : T(-1);
1271 }

◆ sort_mat()

void Util::sort_mat ( float *  left,
float *  right,
int *  leftPerm,
int *  rightPerm 
)
static

does a sort as in Matlab.

Carries along the Permutation matrix

Parameters
[in]leftThe array [left .. right] is sorted
[in]rightThe array [left .. right] is sorted
[in]leftPermThe array [leftPerm rightPerm] is shuffled due to the sorting
[in]rightPermThe array [leftPerm rightPerm] is shuffled due to the sorting Both arrays are reshuffled.

Definition at line 670 of file util.cpp.

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}
static void sort_mat(float *left, float *right, int *leftPerm, int *rightPerm)
does a sort as in Matlab.
Definition: util.cpp:670

References sort_mat().

Referenced by sort_mat().

◆ square() [1/3]

static float EMAN::Util::square ( double  x)
inlinestatic

Calculate a number's square.

Parameters
[in]xGiven number.
Returns
(x*x).

Definition at line 754 of file util.h.

755 {
756 return (float)(x * x);
757 }

References x.

◆ square() [2/3]

static float EMAN::Util::square ( float  x)
inlinestatic

Calculate a number's square.

Parameters
[in]xGiven number.
Returns
(x*x).

Definition at line 745 of file util.h.

746 {
747 return (x * x);
748 }

References x.

◆ square() [3/3]

static int EMAN::Util::square ( int  n)
inlinestatic

◆ square_sum()

static float EMAN::Util::square_sum ( float  x,
float  y 
)
inlinestatic

Calcuate (x*x + y*y).

Parameters
[in]xThe first number.
[in]yThe second number.
Returns
(x*x + y*y).

Definition at line 764 of file util.h.

765 {
766 return (float)(x * x + y * y);
767 }

References x, and y.

Referenced by EMAN::TomoWedgeCccCmp::cmp(), EMAN::TomoWedgeFscCmp::cmp(), EMAN::EMData::common_lines(), EMAN::EMAN2Ctf::compute_1d_fromimage(), get_stats(), get_stats_cstyle(), EMAN::WedgeFillProcessor::process_inplace(), and EMAN::TransformProcessor::transform().

◆ sstrncmp()

bool Util::sstrncmp ( const char *  s1,
const char *  s2 
)
static

Safe string compare.

It compares 's2' with the first N characters of 's1', where N is the length of 's2'.

Parameters
s1String 1. Its first strlen(s2) characters will be used to do the comparison.
s2String 2. Its whole string will be used to do the comparison.
Returns
True if the comparison is equal. False if not equal.

Definition at line 306 of file util.cpp.

307{
308 if (!s1 || !s2) {
309 throw NullPointerException("Null string");
310 }
311
312 return strncmp(s1, s2, strlen(s2)) == 0;
313}

References NullPointerException.

Referenced by EMAN::TestUtil::dump_emdata().

◆ str_to_lower()

string Util::str_to_lower ( const string &  s)
static

Return a lower case version of the argument string.

Parameters
sthe string you want to convert to lower case
Returns
the lower case converted version s

Definition at line 283 of file util.cpp.

283 {
284 string ret(s);
285 std::transform(s.begin(), s.end(), ret.begin(), ::tolower);
286 return ret;
287}

Referenced by EMAN::Transform::detect_problem_keys(), EMAN::Symmetry3D::gen_orientations(), EMAN::Dict::get_ci(), EMAN::Transform::get_params(), EMAN::Transform::get_params_inverse(), EMAN::Transform::get_rotation(), EMAN::Transform::get_sym_proj(), EMAN::Symmetry3D::get_symmetries(), EMAN::Dict::has_key_ci(), and EMAN::Transform::set_rotation().

◆ svdcmp()

vector< EMData * > Util::svdcmp ( const vector< EMData * > &  data,
int  nvec 
)
static

Perform singular value decomposition on a set of images.

Parameters
dataA List of data objects to be decomposed
nvecNumber of basis vectors to return, 0 returns full decomposition
Returns
A list of images representing basis vectors in the SVD generated subspace

Definition at line 343 of file util.cpp.

343 {
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}
EMData stores an image's data and defines core image processing routines.
Definition: emdata.h:82
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

References get_value_at(), V, x, and y.

◆ trilinear_interpolate()

static float EMAN::Util::trilinear_interpolate ( float  p1,
float  p2,
float  p3,
float  p4,
float  p5,
float  p6,
float  p7,
float  p8,
float  t,
float  u,
float  v 
)
inlinestatic

Calculate trilinear interpolation.

Parameters
[in]p1The first number. corresponding to (x0,y0,z0).
[in]p2The second number. corresponding to (x1,y0,z0).
[in]p3The third number. corresponding to (x0,y1, z0).
[in]p4The fourth number. corresponding to (x1,y1,z0).
[in]p5The fifth number. corresponding to (x0,y0,z1).
[in]p6The sixth number. corresponding to (x1,y0,z1).
[in]p7The seventh number. corresponding to (x0,y1,z1).
[in]p8The eighth number. corresponding to (x1,y1,z1).
[in]tt
[in]uu
[in]vv
Returns
The trilinear interpolation value.

Definition at line 619 of file util.h.

623 {
624 return ((1 - t) * (1 - u) * (1 - v) * p1 + t * (1 - u) * (1 - v) * p2
625 + (1 - t) * u * (1 - v) * p3 + t * u * (1 - v) * p4
626 + (1 - t) * (1 - u) * v * p5 + t * (1 - u) * v * p6
627 + (1 - t) * u * v * p7 + t * u * v * p8);
628 }

Referenced by EMAN::EMData::cut_slice(), EMAN::EMData::extract_box(), EMAN::SymSearchProcessor::process_inplace(), EMAN::MaxValProjector::project3d(), EMAN::StandardProjector::project3d(), sget_value_at_interp(), and EMAN::TransformProcessor::transform().

◆ trilinear_interpolate_complex()

static std::complex< float > EMAN::Util::trilinear_interpolate_complex ( std::complex< float >  p1,
std::complex< float >  p2,
std::complex< float >  p3,
std::complex< float >  p4,
std::complex< float >  p5,
std::complex< float >  p6,
std::complex< float >  p7,
std::complex< float >  p8,
float  t,
float  u,
float  v 
)
inlinestatic

Calculate trilinear interpolation.

Parameters
[in]p1The first number. corresponding to (x0,y0,z0).
[in]p2The second number. corresponding to (x1,y0,z0).
[in]p3The third number. corresponding to (x0,y1, z0).
[in]p4The fourth number. corresponding to (x1,y1,z0).
[in]p5The fifth number. corresponding to (x0,y0,z1).
[in]p6The sixth number. corresponding to (x1,y0,z1).
[in]p7The seventh number. corresponding to (x0,y1,z1).
[in]p8The eighth number. corresponding to (x1,y1,z1).
[in]tt
[in]uu
[in]vv
Returns
The trilinear interpolation value.

Definition at line 645 of file util.h.

649 {
650 return ((1 - t) * (1 - u) * (1 - v) * p1 + t * (1 - u) * (1 - v) * p2
651 + (1 - t) * u * (1 - v) * p3 + t * u * (1 - v) * p4
652 + (1 - t) * (1 - u) * v * p5 + t * (1 - u) * v * p6
653 + (1 - t) * u * v * p7 + t * u * v * p8);
654 }

Referenced by EMAN::FourierIterReconstructor::insert_slice(), and EMAN::TransformProcessor::transform().

◆ windowdot()

vector< float > Util::windowdot ( const vector< float > &  curveA,
const vector< float > &  curveB,
int  window,
int  normA 
)
static

Computes a windowed dot product between curve A and curve B.

Curve B is normalized, curve A can be normalized or not. It thus gives either an absolute or relative indicator of similarity between the two curves.

Parameters
[in]curveAThe data curve to be tested
[in]curveBReference curve being compared to
[in]window1/2 Width of local window function in samples, ie 4 -> 4+1+4 = 9 component vector
[in]normAA flag indicating whether A should be localized or not
[out]outcurveReturned data array

Definition at line 1056 of file util.cpp.

1056 {
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}
double dot(const Vector3 &w, const Vector3 &v)
Definition: vecmath.h:305

References EMAN::dot(), and sqrt().


The documentation for this class was generated from the following files: