EMAN2
Classes | Public Types | Public Member Functions | Static Public Member Functions | Static Public Attributes | Private Types | Private Member Functions | Static Private Member Functions | Private Attributes | Friends
EMAN::EMData Class Reference

EMData stores an image's data and defines core image processing routines. More...

#include <emdata.h>

Collaboration diagram for EMAN::EMData:
Collaboration graph
[legend]

List of all members.

Classes

class  ClipInplaceVariables

Public Types

enum  FFTPLACE { FFT_OUT_OF_PLACE, FFT_IN_PLACE }
enum  WINDOWPLACE { WINDOW_OUT_OF_PLACE, WINDOW_IN_PLACE }

Public Member Functions

void read_image (const string &filename, int img_index=0, bool header_only=false, const Region *region=0, bool is_3d=false)
 For all image I/O.
void read_binedimage (const string &filename, int img_index=0, int binfactor=0, bool fast=false, bool is_3d=false)
 read in a binned image, bin while reading.
void write_image (const string &filename, int img_index=0, EMUtil::ImageType imgtype=EMUtil::IMAGE_UNKNOWN, bool header_only=false, const Region *region=0, EMUtil::EMDataType filestoragetype=EMUtil::EM_FLOAT, bool use_host_endian=true)
 write the header and data out to an image.
void append_image (const string &filename, EMUtil::ImageType imgtype=EMUtil::IMAGE_UNKNOWN, bool header_only=false)
 append to an image file; If the file doesn't exist, create one.
void write_lst (const string &filename, const string &reffile="", int refn=-1, const string &comment="")
 Append data to a LST image file.
void print_image (const string str=string(""), ostream &out=std::cout)
 Print the image data to a file stream (standard out by default).
EMDataget_fft_amplitude ()
 For anything read/set image's information.
EMDataget_fft_amplitude2D ()
 return the amplitudes of the 2D FFT including the left half PRB

Exceptions:
ImageFormatExceptionIf the image is not a complex image.

EMDataget_fft_phase ()
 return the phases of the FFT including the left half
float * get_data () const
 Get the image pixel density data in a 1D float array.
const float * get_const_data () const
 Get the image pixel density data in a 1D float array - const version of get_data.
void set_data (float *data, const int x, const int y, const int z)
 Set the data explicitly data pointer must be allocated using malloc!
void set_data (float *data)
void write_data (string fsp, size_t loc, const Region *const area=0, const int file_nx=0, const int file_ny=0, const int file_nz=0)
 Dump the image pixel data in native byte order to a disk file.
void read_data (string fsp, size_t loc, const Region *area=0, const int file_nx=0, const int file_ny=0, const int file_nz=0)
 Read the image pixel data in native byte order from a disk file.
void update ()
 Mark EMData as changed, statistics, etc will be updated at need.
void clearupdate ()
 turn off updates.
bool has_ctff () const
 check whether the image physical file has the CTF info or not.
float calc_center_density ()
 Calculates the density value at the peak of the image histogram, sort of like the mode of the density.
float calc_sigma_diff ()
 Calculates sigma above and below the mean and returns the difference between them.
IntPoint calc_min_location () const
 Calculates the coordinates of the minimum-value pixel.
IntPoint calc_max_location () const
 Calculates the coordinates of the maximum-value pixel.
IntPoint calc_max_location_wrap (const int maxshiftx=-1, const int maxshifty=-1, const int maxshiftz=-1)
 Calculates the wrapped coordinates of the maximum value This function is useful in the context of Fourier correlation you can call this function to find the correct translational shift when using calc_ccf etc.
vector< float > calc_max_location_wrap_intp (const int maxshiftx=-1, const int maxshifty=-1, const int maxshiftz=-1)
 Calculates the wrapped coordinates of the maximum value, and uses quadration intp to subpixel prec This function is useful in the context of Fourier correlation you can call this function to find the correct translational shift when using calc_ccf etc.
FloatPoint calc_center_of_mass (const float threshold=0)
 Calculate the center of mass with a threshold (Default 0, so only positive values are considered)
size_t calc_min_index () const
 Calculates the index of minimum-value pixel when assuming all pixels are in a 1D array.
size_t calc_max_index () const
 Calculates the index of maximum-value pixel when assuming all pixels are in a 1D array.
vector< Pixelcalc_highest_locations (float threshold) const
 Calculate and return a sorted list of pixels whose values are above a specified threshold.
vector< Pixelcalc_n_highest_locations (int n)
 Calculate and return a sorted list of N highest pixels in the map.
vector< Pixelfind_pixels_with_value (float val)
 Find pixels in the image with exactly the specified values.
float get_edge_mean () const
 Calculates the mean pixel values around the (1 pixel) edge of the image.
float get_circle_mean ()
 Calculates the circular edge mean by applying a circular mask on 'this' image.
Ctfget_ctf () const
 Get ctf parameter of this image.
void set_ctf (Ctf *ctf)
 Set the CTF parameter of this image.
Vec3f get_translation () const
 Get 'this' image's translation vector from the original location.
void set_translation (const Vec3f &t)
 Set 'this' images' translation vector from the original location.
void set_translation (float dx, float dy, float dz)
 Set 'this' images' translation vector from the original location.
Transform get_transform () const
 Get the 3D orientation of 'this' image.
void set_rotation (float az, float alt, float phi)
 Define the 3D orientation of this particle, also used to indicate relative rotations for reconstructions.
void set_rotation (const Transform &t3d)
 Define the 3D orientation of this particle Orientation information is extracted from a Transform object and stored internally in EMAN (az,alt,phi) format.
void set_size (int nx, int ny=1, int nz=1, bool noalloc=false)
 Resize this EMData's main board memory pointer.
void set_complex_size (int nx, int ny=1, int nz=1)
 Resize 'this' complex image.
void set_path (const string &new_path)
 Set the path.
void set_pathnum (int n)
 Set the number of paths.
MArray2D get_2dview () const
 Get image raw pixel data in a 2D multi-array format.
MArray3D get_3dview () const
 Get image raw pixel data in a 3D multi-array format.
MCArray2D get_2dcview () const
 Get complex image raw pixel data in a 2D multi-array format.
MCArray3D get_3dcview () const
 Get complex image raw pixel data in a 3D multi-array format.
MCArray3Dget_3dcviewptr () const
 Get pointer to a complex image raw pixel data in a 3D multi-array format.
MArray2D get_2dview (int x0, int y0) const
 Get image raw pixel data in a 2D multi-array format.
MArray3D get_3dview (int x0, int y0, int z0) const
 Get image raw pixel data in a 3D multi-array format.
MCArray2D get_2dcview (int x0, int y0) const
 Get complex image raw pixel data in a 2D multi-array format.
MCArray3D get_3dcview (int x0, int y0, int z0) const
 Get complex image raw pixel data in a 3D multi-array format.
EMObject get_attr (const string &attr_name) const
 The generic way to get any image header information given a header attribute name.
EMObject get_attr_default (const string &attr_name, const EMObject &em_obj=EMObject()) const
 The generic way to get any image header information given a header attribute name.
void set_attr (const string &key, EMObject val)
 Set a header attribute's value.
void set_attr_python (const string &key, EMObject val)
 Set a header attribute's value from Python.
bool has_attr (const string &key) const
 Ask if the header has a particular attribute.
Dict get_attr_dict () const
 Get the image attribute dictionary containing all the image attribute names and attribute values.
void set_attr_dict (const Dict &new_dict)
 Merge the new values with the existing dictionary.
void del_attr (const string &attr_name)
 Delete the attribute from dictionary.
void del_attr_dict (const vector< string > &del_keys)
 Delete the attributes from the dictionary.
int get_xsize () const
 Get the image x-dimensional size.
int get_ysize () const
 Get the image y-dimensional size.
int get_zsize () const
 Get the image z-dimensional size.
size_t get_size () const
 Get the number of allocated floats in the image (nx*ny*nz)
vector< float > get_data_as_vector () const
 Get the pixel data as a vector.
int get_ndim () const
 Get image dimension.
bool is_shuffled () const
 Has this image been shuffled?
bool is_FH () const
 Is this a FH image?
bool is_complex () const
 Is this a complex image?
bool is_real () const
 Is this a real image?
void set_shuffled (bool is_shuffled)
 Mark this image as a shuffled image.
void set_FH (bool is_FH)
 Mark this complex image as a FH image.
void set_complex (bool is_complex)
 Mark this image as a complex image.
bool is_complex_x () const
 Is this image a 1D FFT image in X direction?
void set_complex_x (bool is_complex_x)
 Marks this image a 1D FFT image in X direction.
bool is_flipped () const
 Is this image flipped?
void set_flipped (bool is_flipped)
 Mark this image as flipped.
bool is_ri () const
 Is this image a real/imaginary format complex image?
void set_ri (bool is_ri)
 Mark this image as a real/imaginary format complex image.
bool is_fftpadded () const
 Is this image already extended along x for ffts?
void set_fftpad (bool is_fftpadded)
 Mark this image as already extended along x for ffts.
bool is_fftodd () const
 Does this image correspond to a (real-space) odd nx?
void set_fftodd (bool is_fftodd)
 Mark this image as having (real-space) odd nx.
void set_nxc (int nxc)
 Set the number of complex elements along x.
int get_flags () const
void set_flags (int f)
int get_changecount () const
void set_changecount (int c)
int get_xoff () const
int get_yoff () const
int get_zoff () const
void set_xyzoff (int x, int y, int z)
void scale_pixel (float scale_factor) const
 Scale the angstrom per pixel of this image by a uniform amount Alters the EMData metadata I had to make this function public for access from the Processors (David Woolford)
string get_path () const
int get_pathnum () const
std::string get_data_pickle () const
void set_data_pickle (std::string vf)
int get_supp_pickle () const
void set_supp_pickle (int i)
vector< Vec3imask_contig_region (const float &val, const Vec3i &seed)
float get_amplitude_thres (float thres)
 return the FFT amplitude which is greater than thres %
void process_inplace (const string &processorname, const Dict &params=Dict())
 For modular class functions, process, align, etc.
void process_inplace (Processor *p)
 Call the process_inplace with an instance od Processor, usually this instancecan be get by (in Python) Processors.get("name", {'k':v, 'k':v})
EMDataprocess (const string &processorname, const Dict &params=Dict()) const
 Apply a processor with its parameters on a copy of this image, return result as a a new image.
EMDataprocess (Processor *p) const
 Call the process with an instance od Processor, usually this instance can be get by (in Python) Processors.get("name", {'k':v, 'k':v})
float cmp (const string &cmpname, EMData *with, const Dict &params=Dict())
 Compare this image with another image.
EMDataalign (const string &aligner_name, EMData *to_img, const Dict &params=Dict(), const string &cmp_name="", const Dict &cmp_params=Dict())
 Align this image with another image and return the result image.
vector< Dictxform_align_nbest (const string &aligner_name, EMData *to_img, const Dict &params=Dict(), const unsigned int nsoln=1, const string &cmp_name="dot", const Dict &cmp_params=Dict())
 Align this image with another image, return the parameters of the "n best" solutions See Aligner::xform_align_nbest for more comments.
EMDataproject (const string &projector_name, const Dict &params=Dict())
 Calculate the projection of this image and return the result.
EMDataproject (const string &projector_name, const Transform &t3d)
 Calculate the projection of this image and return the result.
EMDatabackproject (const string &projector_name, const Dict &params=Dict())
 Calculate the backprojection of this image (stack) and return the result.
EMDatado_fft () const
 For fft, wavelet, insert data.
void do_fft_inplace ()
 Do FFT inplace.
EMDatado_ift ()
 return the inverse fourier transform (IFT) image of the current image.
void do_ift_inplace ()
std::string render_amp8 (int x, int y, int xsize, int ysize, int bpl, float scale, int min_gray, int max_gray, float min_render, float max_render, float gamma, int flags)
 Render the image into an 8-bit image.
std::string render_ap24 (int x, int y, int xsize, int ysize, int bpl, float scale, int min_gray, int max_gray, float min_render, float max_render, float gamma, int flags)
 Render the image into an 8-bit image.
void render_amp24 (int x, int y, int xsize, int ysize, int bpl, float scale, int min_gray, int max_gray, float min_render, float max_render, void *ref, void cmap(void *, int coord, unsigned char *tri))
 Render the image into a 24-bit image.
void ri2ap ()
 convert the complex image from real/imaginary to amplitude/phase
void ap2ri ()
 convert the complex image from amplitude/phase to real/imaginary
void ri2inten ()
 convert the complex image from real/imaginary to Intensity/0.
EMDatabispecRotTransInvN (int N, int NK)
 This computes the rotational and translational bispectral invariants of an image.
EMDatabispecRotTransInvDirect (int type=0)
 This computes the rotational and translational bispectral invariants of an image.
void insert_clip (const EMData *const block, const IntPoint &origin)
 Insert a clip into this image.
void insert_scaled_sum (EMData *block, const FloatPoint &center, float scale=1.0, float mult_factor=1.0)
 Add a scaled image into another image at a specified location.
EMDatacopy () const
 For get/set values, basic math operations, operators.
EMDatacopy_head () const
 Make an image with a copy of the current image's header.
void add (float f, int keepzero=0)
 add a number to each pixel value of the image.
void add (const EMData &image)
 add a same-size image to this image pixel by pixel.
void addsquare (const EMData &image)
 add the squared value of each pixel from a same-size image to this image.
void sub (float f)
 subtract a float number to each pixel value of the image.
void sub (const EMData &image)
 subtract a same-size image from this image pixel by pixel.
void subsquare (const EMData &image)
 subtract the squared value of each pixel from a same-size image to this image.
void mult (int n)
 multiply an integer number to each pixel value of the image.
void mult (float f)
 multiply a float number to each pixel value of the image.
void mult (const EMData &image, bool prevent_complex_multiplication=false)
 multiply each pixel of this image with each pixel of some other same-size image.
void mult_complex_efficient (const EMData &em, const int radius)
void div (float f)
 make each pixel value divided by a float number.
void div (const EMData &image)
 make each pixel value divided by pixel value of another same-size image.
void to_zero ()
 Set all the pixel value = 0.
void to_one ()
 set all the pixel values = 1.
void to_value (const float &value)
 set all the pixel values to a value.
float dot (EMData *with)
 Dot product 2 images.
EMDataget_row (int row_index) const
 Get one row of a 1D/2D image.
void set_row (const EMData *data, int row_index)
 Set one row of a 1D/2D image.
EMDataget_col (int col_index) const
 Get one column of a 2D images.
void set_col (const EMData *data, int col_index)
 Set one column of a 2D image.
float get_value_at (int x, int y, int z) const
 Get the pixel density value at coordinates (x,y,z).
float get_value_at_index (int i)
 Get the pixel density value at index i.
float get_value_at (int x, int y) const
 Get the pixel density value at coordinates (x,y).
float get_value_at (size_t i) const
 Get the pixel density value given an index 'i' assuming the pixles are stored in a 1D array.
std::complex< float > get_complex_at (const int &x, const int &y) const
 Get complex<float> value at x,y.
std::complex< float > get_complex_at (const int &x, const int &y, const int &z) const
 Get complex<float> value at x,y,z.
size_t get_complex_index (const int &x, const int &y, const int &z) const
 Get complex<float> index for coords x,y,z.
size_t get_complex_index (int x, int y, int z, const int &subx0, const int &suby0, const int &subz0, const int &fullnx, const int &fullny, const int &fullnz) const
size_t get_complex_index_fast (const int &x, const int &y, const int &z) const
void set_complex_at (const int &x, const int &y, const std::complex< float > &val)
 Set complex<float> value at x,y.
void set_complex_at (const int &x, const int &y, const int &z, const std::complex< float > &val)
 Set complex<float> value at x,y,z.
size_t add_complex_at (const int &x, const int &y, const int &z, const std::complex< float > &val)
 Add complex<float> value at x,y,z.
size_t add_complex_at_fast (const int &x, const int &y, const int &z, const std::complex< float > &val)
size_t add_complex_at (int x, int y, int z, const int &subx0, const int &suby0, const int &subz0, const int &fullnx, const int &fullny, const int &fullnz, const std::complex< float > &val)
 Add complex<float> value at x,y,z assuming that 'this' is a subvolume from a larger virtual volume.
float get_value_at_wrap (int x, int y, int z) const
 Get the pixel density value at coordinates (x,y,z).
float & get_value_at_wrap (int x, int y, int z)
float get_value_at_wrap (int x, int y) const
 Get the pixel density value at coordinates (x,y).
float & get_value_at_wrap (int x, int y)
float get_value_at_wrap (int x) const
 Get the pixel density value at coordinates (x).
float & get_value_at_wrap (int x)
float sget_value_at (Vec3i v)
 Vec3i version of save routines below.
float sget_value_at (int x, int y, int z) const
 A safer, slower way to get the pixel density value at coordinates (x,y,z).
float sget_value_at (int x, int y) const
 A safer, slower way to get the pixel density value at coordinates (x,y).
float sget_value_at (size_t i) const
 A safer, slower way to get the pixel density value given an index 'i' assuming the pixles are stored in a 1D array.
float sget_value_at_interp (float x, float y) const
 Get pixel density value at interpolation of (x,y).
float sget_value_at_interp (float x, float y, float z) const
 Get the pixel density value at interpolation of (x,y,z).
void set_value_at (Vec3i loc, float val)
 set_value_at with Vec3i
void set_value_at (int x, int y, int z, float v)
 Set the pixel density value at coordinates (x,y,z).
void set_value_at_fast (int x, int y, int z, float v)
 Set the pixel density value at coordinates (x,y,z).
void set_value_at_index (int i, float v)
 Set the pixel density value at index.
void set_value_at (int x, int y, float v)
 Set the pixel density value at coordinates (x,y).
void set_value_at_fast (int x, int y, float v)
 Set the pixel density value at coordinates (x,y).
void set_value_at (int x, float v)
 Set the pixel density value at coordinate (x).
void set_value_at_fast (int x, float v)
 Set the pixel density value at coordinate (x).
void free_memory ()
 Free memory associated with this EMData Called in destructor and in assignment operator.
void free_rdata ()
 Free rdata memory associated with this EMData Called in CUDA.
EMDataoperator+= (float n)
EMDataoperator-= (float n)
EMDataoperator*= (float n)
EMDataoperator/= (float n)
EMDataoperator+= (const EMData &em)
EMDataoperator-= (const EMData &em)
EMDataoperator*= (const EMData &em)
EMDataoperator/= (const EMData &em)
bool operator== (const EMData &that) const
 Change the equality check for memory address check, i.e.
bool equal (const EMData &that) const
 compare the equality of two EMData object based on their pixel values
float & operator() (const int ix, const int iy, const int iz) const
 Overload operator() for array indexing.
float & operator() (const int ix, const int iy) const
float & operator() (const size_t ix) const
void set_array_offsets (const int xoff_=0, const int yoff_=0, const int zoff_=0)
 Set the array offsets.
void set_array_offsets (vector< int > offsets)
vector< int > get_array_offsets ()
std::complex< float > & cmplx (const int ix, const int iy, const int iz)
 Return reference to complex elements.
std::complex< float > & cmplx (const int ix, const int iy)
std::complex< float > & cmplx (const int ix)
EMDatapower (int n) const
 return a image to the power of n
EMDatasqrt () const
 return square root of current image
EMDatalog () const
 return natural logarithm image for a image
EMDatalog10 () const
 return base 10 logarithm image for a image
EMDatareal () const
 return real part of a complex image as a real image format, if this image is a real image, return a copy of this image.
EMDataimag () const
 return imaginary part of a complex image as a real image format.
EMDataabsi () const
 For a real image, it returns a same size image with abs() of each pixel.
EMDataamplitude () const
 return amplitude part of a complex image as a real image format
EMDataphase () const
 return phase part of a complex image as a real image format
EMDatareal2complex (float img=0.0f) const
 create a complex image from a real image, this complex image is in real/imaginary format
EMDatareal2FH (float OverSamplekB)
 This is the header of EMData stay in sparx directory.
EMDatacopy_empty_head () const
 copy header but not set size for the image
EMDataFH2F (int Size, float OverSamplekB, int IntensityFlag=0)
 returns the fourier version of the image from the FH version.
EMDataFH2Real (int Size, float OverSamplekB, int IntensityFlag=0)
 returns the real version of the image from the FH version.
EMDatarotavg ()
 Create a (1-D) rotationally averaged image.
EMDatarotavg_i ()
 Create a 2-D or 3-D rotationally averaged image.
EMDatamult_radial (EMData *radial)
 Multiply radially a 2-D or 3-D image by a 1-D image.
vector< float > cog ()
 Calculates the Center of Gravity and the Radius of Gyration of the image.
vector< float > calc_fourier_shell_correlation (EMData *with, float w=1.0f)
 Calculate CCF in Fourier space as a function of spatial frequency between a pair of 2-3D images (corners not included).
vector< float > scale_factors (EMData *with, int beg, int end)
 Calculate normalization factors in Fourier space as a function of spatial frequency between a pair of 2-3D images (corners not included).
EMDataaverage_circ_sub () const
 Subtract average outside of a circle.
void onelinenn (int j, int n, int n2, EMData *wptr, EMData *bi, const Transform &tf)
 Helper function for method nn.
void onelinenn_mult (int j, int n, int n2, EMData *wptr, EMData *bi, const Transform &tf, float mult)
void nn (EMData *wptr, EMData *myfft, const Transform &tf, float mult=1)
 Nearest Neighbor interpolation.
void insert_rect_slice (EMData *w, EMData *myfft, const Transform &trans, int sizeofprojection, float xratio, float yratio, float zratio, int npad, float mult)
void nn_SSNR (EMData *wptr, EMData *wptr2, EMData *myfft, const Transform &tf, float mult=1)
 Nearest Neighbor interpolation, meanwhile return necessary data such as Kn, sum_k(F_k^n) ans sum_k(|F_k^n|^2) Modifies the current object.
void nn_SSNR_ctf (EMData *wptr, EMData *wptr2, EMData *wptr3, EMData *myfft, const Transform &tf, float mult=1)
 Nearest Neighbor interpolation, meanwhile return necessary data such as Kn, sum_k(F_k^n) ans sum_k(|F_k^n|^2) Modifies the current object.
void symplane0 (EMData *norm)
 Calculate Spectrum signal noise ratio (SSNR) accounting CTF correction a.
void symplane1 (EMData *norm, EMData *norm2)
 Symmetrize plane 0 Modifies the current object.
void symplane2 (EMData *norm, EMData *norm2, EMData *norm3)
 Symmetrize plane 0 Modifies the current object.
void onelinenn_ctf (int j, int n, int n2, EMData *w, EMData *bi, const Transform &tf, float mult)
 Helper function for method nn4_ctf.
void onelinenn_ctfw (int j, int n, int n2, EMData *w, EMData *bi, EMData *sigmasq2, const Transform &tf, float weight)
 Helper function for method nn4_ctfw.
void nn_ctf (EMData *w, EMData *myfft, const Transform &tf, float mult)
 Nearest Neighbor interpolation.
void insert_rect_slice_ctf (EMData *w, EMData *myfft, const Transform &trans, int sizeofprojection, float xratio, float yratio, float zratio, int npad, float mult)
 helper function to insert rectangualr slice for ctf rect case
void insert_rect_slice_ctf_applied (EMData *w, EMData *myfft, const Transform &trans, int sizeofprojection, float xratio, float yratio, float zratio, int npad, float mult)
void onelinenn_ctf_applied (int j, int n, int n2, EMData *w, EMData *bi, const Transform &tf, float mult)
 Helper function for method nn4_ctf.
void nn_ctf_applied (EMData *w, EMData *myfft, const Transform &tf, float mult)
 Nearest Neighbor interpolation.
void symplane0_ctf (EMData *w)
 Symmetrize plane 0 Modifies the current object.
void symplane0_rect (EMData *w)
void nn_ctfw (EMData *w, EMData *myfft, EMData *sigmasq2, const Transform &tf, float weight)
 Helper functions for method nn4_ctf.
EMDatasymvol (string symmetry)
 Symmetrize volume in real space.
EMDatarot_scale_trans2D (float ang, float delx=0.0f, float dely=0.0f, float scale=1.0f)
 Rotate-Shift-Scale-Circulantly image.
EMDatarot_scale_trans2D_background (float ang, float delx=0.0f, float dely=0.0f, float scale=1.0f)
 Rotate-Shift-Scale image.
EMDatarot_scale_trans (const Transform &RA)
 Rotate-Shift-Scale-Circulantly image.
EMDatarot_scale_trans_background (const Transform &RA)
 Rotate-Shift-Scale image.
float cm_euc (EMData *sinoj, int n1, int n2)
 euclidean distance between two line
EMDatarot_scale_conv (float ang, float delx, float dely, Util::KaiserBessel &kb, float scale=1.0)
 Rotate-Shift-Scale-Circulantly image using convolution.
EMDatadownsample (Util::sincBlackman &kb, float scale=1.0)
EMDatarot_scale_conv7 (float ang, float delx, float dely, Util::KaiserBessel &kb, float scale_input)
EMDatarot_scale_conv_new (float ang, float delx, float dely, Util::KaiserBessel &kb, float scale=1.0)
EMDatarot_scale_conv_new_background (float ang, float delx, float dely, Util::KaiserBessel &kb, float scale=1.0)
EMDatarot_scale_conv_new_3D (float phi, float theta, float psi, float delx, float dely, float delz, Util::KaiserBessel &kb, float scale=1.0, bool wrap=false)
EMDatarot_scale_conv_new_background_3D (float phi, float theta, float psi, float delx, float dely, float delz, Util::KaiserBessel &kb, float scale=1.0, bool wrap=false)
float get_pixel_conv (float delx, float dely, float delz, Util::KaiserBessel &kb)
 Get pixel value image using convolution.
float get_pixel_filtered (float delx, float dely, float delz, Util::sincBlackman &kb)
float get_pixel_conv7 (float delx, float dely, float delz, Util::KaiserBessel &kb)
float getconvpt2d_kbi0 (float x, float y, Util::KaiserBessel::kbi0_win win, int size=7)
 Value of 2-D analytic masking (or 2-D convolution) at off-grid point.
void fft_shuffle ()
 2-D rotation using gridding convolution.
void pad_corner (float *pad_image)
void shuffle_pad_corner (float *pad_image)
std::complex< float > extractpoint (float xin, float yin, Util::KaiserBessel &kb)
 extractpoint -- Gridding convolution
EMDataextract_plane (const Transform &tf, Util::KaiserBessel &kb)
 extractplane -- Gridding convolution in 3D along a plane
EMDataextract_plane_rect (const Transform &tf, Util::KaiserBessel &kbx, Util::KaiserBessel &kby, Util::KaiserBessel &kbz)
EMDataextract_plane_rect_fast (const Transform &tf, Util::KaiserBessel &kbx, Util::KaiserBessel &kby, Util::KaiserBessel &kbz)
EMDatafouriergridrot2d (float ang, float scale, Util::KaiserBessel &kb)
EMDatafouriergridrot_shift2d (float ang, float sx, float sy, Util::KaiserBessel &kb)
void divkbsinh (const Util::KaiserBessel &kb)
 divkbsinh -- Divide image by a Kaiser-Bessel sinh window.
void divkbsinh_rect (const Util::KaiserBessel &kbx, const Util::KaiserBessel &kby, const Util::KaiserBessel &kbz)
vector< float > peak_search (int ml, float invert)
 masked_stats -- Compute image statistics under a mask
vector< float > phase_cog ()
 Calculate the Phase approximation to center of gravity This operations works for 1-2-3-d images.
float find_3d_threshold (float mass, float pixel_size)
vector< float > peak_ccf (float hf_p)
 Peak (with a radius of hf_p) search for particle picking:
EMDataget_pow (float n_pow)
EMDataconjg ()
EMDataextractline (Util::KaiserBessel &kb, float nuxnew, float nuynew)
EMDatadelete_disconnected_regions (int ix=0, int iy=0, int iz=0)
 Delete disconnected regions in a binary image.
EMDatahelicise (float pixel_size, float dp, float dphi, float section_use=1.0f, float radius=-1.0f, float minrad=-1.0f)
 Apply helical symmetry.
EMDatahelicise_grid (float pixel_size, float dp, float dphi, Util::KaiserBessel &kb, float section_use=1.0f, float radius=-1.0f, float minrad=-1.0f)
void depad ()
 De-pad, and and remove Fourier extension convenience function.
void depad_corner ()
 De-pad, and and remove Fourier extension convenience function.
EMDatanorm_pad (bool do_norm, int npad=1, int valtype=0)
 Normalize, pad, and Fourier extend convenience function.
void center_origin ()
void center_origin_yz ()
void center_origin_fft ()
 Multiply a Fourier image by (-1)**(ix+iy+iz) to center it.
EMDataFourInterpol (int nxni, int nyni=0, int nzni=0, bool RetReal=true)
EMDataFourTruncate (int nxni, int nyni=0, int nzni=0, bool RetReal=true)
 Truncate Fourier transform of an image, it will reduce its size.
EMDataFour_ds (int nxni, int nyni=0, int nzni=0, bool RetReal=true)
EMDataFour_shuf_ds_cen_us (int nxni, int nyni=0, int nzni=0, bool RetReal=true)
EMDatafilter_by_image (EMData *image, bool RetReal=true)
EMDatareplace_amplitudes (EMData *image, bool RetReal=true)
 EMData ()
 Construct an empty EMData instance.
 ~EMData ()
 EMData (const string &filename, int image_index=0)
 Construct from an image file.
 EMData (int nx, int ny, int nz=1, bool is_real=true)
 # makes an image of the specified size, either real or complex.
 EMData (float *data, const int nx, const int ny, const int nz, const Dict &attr_dict=Dict())
 Construction from a data pointer, dimensions must be supplied.
 EMData (float *data, float *cudadata, const int nx, const int ny, const int nz, const Dict &attr_dict=Dict())
 Construction from a data pointer for usage in cuda, dimensions must be supplied.
 EMData (const EMData &that)
 Construct from an EMData (copy constructor).
EMDataoperator= (const EMData &that)
 EMData assignment operator Performs a deep copy.
EMDataget_clip (const Region &area, const float fill=0) const
 Get an inclusive clip.
void clip_inplace (const Region &area, const float &fill_value=0)
 Clip the image inplace - clipping region must be smaller than the current region internally memory is reallocated

Exceptions:
ImageDimensionExceptionif any of the dimensions of the argument region are negative.

EMDataget_top_half () const
 Get the top half of this 3D image.
EMDataget_rotated_clip (const Transform &xform, const IntSize &size, float scale=1.0)
 This will extract an arbitrarily oriented and sized region from the image.
EMDatawindow_center (int l)
 Window the center of an image.
float * setup4slice (bool redo=true)
 Set up for fftslice operations.
void scale (float scale_factor)
 scale the image by a factor.
void translate (float dx, float dy, float dz)
 Translate this image.
void translate (const Vec3f &translation)
 Translate this image.
void translate (int dx, int dy, int dz)
 Translate this image.
void translate (const Vec3i &translation)
 Translate this image.
void rotate (const Transform &t)
 Rotate this image.
float max_3D_pixel_error (const Transform &t1, const Transform &t2, float r)
void rotate (float az, float alt, float phi)
 Rotate this image.
void transform (const Transform &t)
 Rotate then translate the image.
void rotate_translate (const Transform &t)
 Apply a transformation to the image.
void rotate_translate (float az, float alt, float phi, float dx, float dy, float dz)
 Rotate then translate the image.
void rotate_translate (float az, float alt, float phi, float dx, float dy, float dz, float pdx, float pdy, float pdz)
 Rotate then translate the image.
void rotate_x (int dx)
 This performs a translation of each line along x with wraparound.
void rotate_180 ()
 Fast rotation by 180 degrees.
double dot_rotate_translate (EMData *with, float dx, float dy, float da, const bool mirror=false)
 dot product of 2 images.
EMDatalittle_big_dot (EMData *little_img, bool do_sigma=false)
 This does a normalized dot product of a little image with a big image using real-space methods.
EMDatado_radon ()
 Radon Transform: an algorithm that transforms an original image into a series of equiangular projections.
EMDatacalc_ccf (EMData *with=0, fp_flag fpflag=CIRCULANT, bool center=false)
 Calculate Cross-Correlation Function (CCF).
void zero_corner_circulant (const int radius=0)
 Zero the pixels in the bottom left corner of the image If radius is greater than 1, than circulant zeroing occurs assuming that the center of operation starts in the bottom left corner and proceed outwards to the NE and backwards in a circulant fashion towards the SW.
EMDatacalc_ccfx (EMData *const with, int y0=0, int y1=-1, bool nosum=false, bool flip=false, bool usez=false)
 Calculate Cross-Correlation Function (CCF) in the x-direction and adds them up, result in 1D.
EMDatamake_rotational_footprint (bool unwrap=true)
 Makes a 'rotational footprint', which is an 'unwound' autocorrelation function.
EMDatamake_rotational_footprint_e1 (bool unwrap=true)
EMDatamake_rotational_footprint_cmc (bool unwrap=true)
EMDatamake_footprint (int type=0)
 Makes a 'footprint' for the current image.
EMDatacalc_mutual_correlation (EMData *with, bool tocorner=false, EMData *filter=0)
 Calculates mutual correlation function (MCF) between 2 images.
EMDataunwrap (int r1=-1, int r2=-1, int xs=-1, int dx=0, int dy=0, bool do360=false, bool weight_radial=true) const
 Maps to polar coordinates from Cartesian coordinates.
EMDataunwrap_largerR (int r1, int r2, int xs, float rmax_f)
EMDataoneDfftPolar (int size, float rmax, float MAXR)
void apply_radial_func (float x0, float dx, vector< float >array, bool interp=true)
 multiplies by a radial function in fourier space.
vector< float > calc_radial_dist (int n, float x0, float dx, bool inten)
 calculates radial distribution.
vector< float > calc_radial_dist (int n, float x0, float dx, int nwedge, float offset, bool inten)
 calculates radial distribution subdivided by angle.
void cconj ()
 Replace the image its complex conjugate.
void add_incoherent (EMData *obj)
 Adds 'obj' to 'this' incoherently.
vector< float > calc_hist (int hist_size=128, float hist_min=0, float hist_max=0, const float &brt=0.0f, const float &cont=1.0f)
 Calculates the histogram of 'this' image.
vector< float > calc_az_dist (int n, float a0, float da, float rmin, float rmax)
 Caculates the azimuthal distributions.
float calc_dist (EMData *second_img, int y_index=0) const
 Calculates the distance between 2 vectors.
EMDatacalc_flcf (EMData *with)
 Calculates the cross correlation with local normalization between 2 images.
EMDatacalc_fast_sigma_image (EMData *mask)
 Calculates the local standard deviation (sigma) image using the given mask image.
EMDataconvolute (EMData *with)
 Convolutes 2 data sets.
void common_lines (EMData *image1, EMData *image2, int mode=0, int steps=180, bool horizontal=false)
 Finds common lines between 2 complex images.
void common_lines_real (EMData *image1, EMData *image2, int steps=180, bool horizontal=false)
 Finds common lines between 2 real images.
void cut_slice (const EMData *const map, const Transform &tr, bool interpolate=true)
 cut a 2D slice out of a real 3D map.
void uncut_slice (EMData *const map, const Transform &tr) const
 Opposite of the cut_slice().
EMDataextract_box (const Transform &cs, const Region &r)
 Extract a box from EMData in an abritrary orrientation.
int getResolution () const
 function for MarchingCubes, for 3D image display
void debug_print_parms ()
 Printing EMData params for debugging purpose.
void set_xyz_origin (float origin_x, float origin_y, float origin_z)
 Set the x,y,z origin of the image.
EMDatacompute_missingwedge (float wedgeangle, float start=0.05, float stop=0.5)
 Find the mean and variance of voxels in the missing wedge.

Static Public Member Functions

static vector
< boost::shared_ptr< EMData > > 
read_images (const string &filename, vector< int >img_indices=vector< int >(), bool header_only=false)
 Read a set of images from file specified by 'filename'.
static vector
< boost::shared_ptr< EMData > > 
read_images_ext (const string &filename, int img_index_start, int img_index_end, bool header_only=false, const string &ext="")
 Read a set of images from file specified by 'filename'.
static float restrict1 (float x, int nx)
static float restrict2 (float x, int nx)

Static Public Attributes

static int totalalloc = 0

Private Types

enum  EMDataFlags {
  EMDATA_BUSY = 1 << 3, EMDATA_HASCTFF = 1 << 4, EMDATA_NEEDUPD = 1 << 5, EMDATA_FLIP = 1 << 7,
  EMDATA_PAD = 1 << 8, EMDATA_FFTODD = 1 << 9, EMDATA_SHUFFLE = 1 << 10, EMDATA_FH = 1 << 11,
  EMDATA_CPU_NEEDS_UPDATE = 1 << 12, EMDATA_GPU_NEEDS_UPDATE = 1 << 13, EMDATA_GPU_RO_NEEDS_UPDATE = 1 << 14
}
 This EMDataFlags is deprecated. More...

Private Member Functions

void set_attr_dict_explicit (const Dict &new_dict)
 Make the attributes of this EMData exactly equal to the argument dictionary Originally introduced because set_attr_dict does automatic resizing, which is undersirable in some circumstances.
void update_stat () const
void save_byteorder_to_dict (ImageIO *imageio)

Static Private Member Functions

static bool peakcmp (const Pixel &p1, const Pixel &p2)

Private Attributes

Dict attr_dict
 to store all image header info
float * rdata
 image real data
float * supp
 supplementary data array
int flags
 CTF data All CTF data become attribute ctf(vector<float>) in attr_dict --Grant Tang.
int changecount
int nx
 image size
int ny
int nz
int nxy
size_t nxyz
int xoff
 array index offsets
int yoff
int zoff
Vec3f all_translation
 translation from the original location
string path
int pathnum
EMDatarot_fp
 This is a cached rotational footprint, can save much time.

Friends

class GLUtil

Detailed Description

EMData stores an image's data and defines core image processing routines.

The image is 1D, 2D or 3D, in real space or fourier space (complex image).

Data are ordered with x increasing fastest, then y, then z.

Definition at line 88 of file emdata.h.


Member Enumeration Documentation

enum EMAN::EMData::EMDataFlags [private]

This EMDataFlags is deprecated.

For anything which is currently handled by setting a bit in 'flags', instead, set or read an appropriately named attribute in the attributes dictionary. While there is a small overhead in the string lookup, none of these things should be called in the innermost loop anywhere, so it should be fine. --Grant

Enumerator:
EMDATA_BUSY 
EMDATA_HASCTFF 
EMDATA_NEEDUPD 
EMDATA_FLIP 
EMDATA_PAD 
EMDATA_FFTODD 
EMDATA_SHUFFLE 
EMDATA_FH 
EMDATA_CPU_NEEDS_UPDATE 
EMDATA_GPU_NEEDS_UPDATE 
EMDATA_GPU_RO_NEEDS_UPDATE 

Definition at line 806 of file emdata.h.

                                 {
//                      EMDATA_COMPLEX = 1 << 1,
//                      EMDATA_RI = 1 << 2,            // real/imaginary or amp/phase
                        EMDATA_BUSY = 1 << 3,      // someone is modifying data, NO LONGER USED
                        EMDATA_HASCTFF = 1 << 4,   // has CTF info in the image file
                        EMDATA_NEEDUPD = 1 << 5,   // needs a real update
//                      EMDATA_COMPLEXX = 1 << 6,  // 1D fft's in X
                        EMDATA_FLIP = 1 << 7,      // is the image flipped
                        EMDATA_PAD = 1 << 8,       // is the image fft padded
                        EMDATA_FFTODD = 1 << 9,    // is the (real-space) nx odd
                        EMDATA_SHUFFLE = 1 << 10,  // fft been shuffled? (so O is centered) PRB
                        EMDATA_FH = 1 << 11,        // is the complex image a FH image
                        EMDATA_CPU_NEEDS_UPDATE = 1 << 12, // CUDA related: is the CPU version of the image out out data
                        EMDATA_GPU_NEEDS_UPDATE = 1 << 13, // CUDA related: is the GPU version of the image out out data
                        EMDATA_GPU_RO_NEEDS_UPDATE = 1 << 14 // // CUDA related: is the GPU RO version of the image out out data
                };
Enumerator:
FFT_OUT_OF_PLACE 
FFT_IN_PLACE 

Definition at line 115 of file emdata.h.

Enumerator:
WINDOW_OUT_OF_PLACE 
WINDOW_IN_PLACE 

Definition at line 116 of file emdata.h.


Constructor & Destructor Documentation

EMData::EMData ( )

Construct an empty EMData instance.

It has no image data.

Definition at line 74 of file emdata.cpp.

References attr_dict, EMAN::EMUtil::EM_FLOAT, ENTERFUNC, EXITFUNC, and totalalloc.

Referenced by absi(), amplitude(), calc_ccfx(), calc_fast_sigma_image(), calc_flcf(), compute_missingwedge(), copy(), copy_head(), do_radon(), EMData(), extract_box(), get_circle_mean(), get_clip(), get_col(), get_rotated_clip(), get_row(), get_top_half(), imag(), make_footprint(), make_rotational_footprint(), make_rotational_footprint_cmc(), make_rotational_footprint_e1(), oneDfftPolar(), operator=(), phase(), read_binedimage(), read_images(), read_images_ext(), real(), real2complex(), unwrap(), and unwrap_largerR().

               :
#ifdef EMAN2_USING_CUDA
                cudarwdata(0), cudarodata(0), num_bytes(0), nextlistitem(0), prevlistitem(0), roneedsupdate(0), cudadirtybit(0),
#endif //EMAN2_USING_CUDA
#ifdef FFT_CACHING
        fftcache(0),
#endif //FFT_CACHING
                attr_dict(), rdata(0), supp(0), flags(0), changecount(0), nx(0), ny(0), nz(0), nxy(0), nxyz(0), xoff(0), yoff(0),
                zoff(0), all_translation(),     path(""), pathnum(0), rot_fp(0)

{
        ENTERFUNC;

        attr_dict["apix_x"] = 1.0f;
        attr_dict["apix_y"] = 1.0f;
        attr_dict["apix_z"] = 1.0f;

        attr_dict["is_complex"] = int(0);
        attr_dict["is_complex_x"] = int(0);
        attr_dict["is_complex_ri"] = int(1);

        attr_dict["datatype"] = (int)EMUtil::EM_FLOAT;

        EMData::totalalloc++;
#ifdef MEMDEBUG2
        printf("EMDATA+  %4d    %p\n",EMData::totalalloc,this);
#endif
        
        EXITFUNC;
}
EMData::~EMData ( )

Definition at line 335 of file emdata.cpp.

References ENTERFUNC, EXITFUNC, free_memory(), and totalalloc.

{
        ENTERFUNC;
#ifdef FFT_CACHING
        if (fftcache!=0) { delete fftcache; fftcache=0;}
#endif //FFT_CACHING
        free_memory();

#ifdef EMAN2_USING_CUDA
        if(cudarwdata){rw_free();}
        if(cudarodata){ro_free();}
#endif // EMAN2_USING_CUDA
        EMData::totalalloc--;
#ifdef MEMDEBUG2
        printf("EMDATA-  %4d    %p\n",EMData::totalalloc,this);
#endif
        EXITFUNC;
}
EMData::EMData ( const string &  filename,
int  image_index = 0 
) [explicit]

Construct from an image file.

Parameters:
filenamethe image file name
image_indexthe image index for stack image file, default 0

Definition at line 105 of file emdata.cpp.

References attr_dict, EMAN::EMUtil::EM_FLOAT, ENTERFUNC, EXITFUNC, read_image(), totalalloc, and update().

                                                      :
#ifdef EMAN2_USING_CUDA
                cudarwdata(0), cudarodata(0), num_bytes(0), nextlistitem(0), prevlistitem(0), roneedsupdate(0), cudadirtybit(0),
#endif //EMAN2_USING_CUDA
#ifdef FFT_CACHING
        fftcache(0),
#endif //FFT_CACHING
                attr_dict(), rdata(0), supp(0), flags(0), changecount(0), nx(0), ny(0), nz(0), nxy(0), nxyz(0), xoff(0), yoff(0), zoff(0),
                all_translation(),      path(filename), pathnum(image_index), rot_fp(0)
{
        ENTERFUNC;

        attr_dict["apix_x"] = 1.0f;
        attr_dict["apix_y"] = 1.0f;
        attr_dict["apix_z"] = 1.0f;

        attr_dict["is_complex"] = int(0);
        attr_dict["is_complex_x"] = int(0);
        attr_dict["is_complex_ri"] = int(1);

        attr_dict["datatype"] = (int)EMUtil::EM_FLOAT;

        this->read_image(filename, image_index);

        update();
        EMData::totalalloc++;
#ifdef MEMDEBUG2
        printf("EMDATA+  %4d    %p\n",EMData::totalalloc,this);
#endif

        EXITFUNC;
}
EMData::EMData ( float *  data,
const int  nx,
const int  ny,
const int  nz,
const Dict attr_dict = Dict() 
)

Construction from a data pointer, dimensions must be supplied.

Takes possession of the pointer. data pointer must be allocated using malloc!

Parameters:
dataa pointer to the pixel data which is stored in memory. Takes possession
nxthe number of pixels in the x direction
nythe number of pixels in the y direction
nzthe number of pixels in the z direction
attr_dictattribute dictionary for this image

Definition at line 280 of file emdata.cpp.

References ENTERFUNC, EXITFUNC, totalalloc, and update().

                                                                                        :
#ifdef EMAN2_USING_CUDA
                cudarwdata(0), cudarodata(0), num_bytes(0), nextlistitem(0), prevlistitem(0), roneedsupdate(0), cudadirtybit(0),
#endif //EMAN2_USING_CUDA
#ifdef FFT_CACHING
        fftcache(0),
#endif //FFT_CACHING
                attr_dict(attr_dict), rdata(data), supp(0), flags(0), changecount(0), nx(x), ny(y), nz(z), nxy(x*y), nxyz((size_t)x*y*z), xoff(0),
                yoff(0), zoff(0), all_translation(), path(""), pathnum(0), rot_fp(0)
{
        ENTERFUNC;
        // used to replace cube 'pixel'
        attr_dict["apix_x"] = 1.0f;
        attr_dict["apix_y"] = 1.0f;
        attr_dict["apix_z"] = 1.0f;

        EMData::totalalloc++;
#ifdef MEMDEBUG2
        printf("EMDATA+  %4d    %p\n",EMData::totalalloc,this);
#endif

        update();
        EXITFUNC;
}

Member Function Documentation

EMData * EMData::absi ( ) const

For a real image, it returns a same size image with abs() of each pixel.

For a complex image, it returns a image in size (nx/2,ny,nz), the pixel value output[i]=sqrt(input[i]*input[i]+input[i+1]*input[i+1])

Exceptions:
InvalidCallExceptionthis function call require a complex image in real/imaginary format.

Definition at line 1143 of file emdata_core.cpp.

References abs, copy(), data, EMData(), ENTERFUNC, EXITFUNC, get_data(), get_xsize(), get_ysize(), get_zsize(), InvalidCallException, is_real(), is_ri(), nx, ny, nz, set_complex(), set_complex_x(), set_size(), sqrt(), and update().

{
        ENTERFUNC;

        EMData * e = new EMData();

        if( is_real() ) // a real image
        {
                e = this->copy();
                int nx = get_xsize();
                int ny = get_ysize();
                int nz = get_zsize();
                float *edata = e->get_data();
                float * data = get_data();
                size_t idx;
                for( int i=0; i<nx; ++i ) {
                        for( int j=0; j<ny; ++j ) {
                                for( int k=0; k<nz; ++k ) {
                                        idx = i+j*nx+k*nx*ny;
                                        edata[idx] = std::abs(data[idx]);
                                }
                        }
                }
        }
        else //for a complex image
        {
                if( !is_ri() )
                {
                        throw InvalidCallException("This image is in amplitude/phase format, this function call require a complex image in real/imaginary format.");
                }
                int nx = get_xsize();
                int ny = get_ysize();
                int nz = get_zsize();
                e->set_size(nx/2, ny, nz);
                float * edata = e->get_data();
                float * data = get_data();
                size_t idx1, idx2;
                for( int i=0; i<nx; ++i )
                {
                        for( int j=0; j<ny; ++j )
                        {
                                for( int k=0; k<nz; ++k )
                                {
                                        if( i%2 == 0 )
                                        {
                                                idx1 = i/2+j*(nx/2)+k*(nx/2)*ny;
                                                idx2 = i+j*nx+k*nx*ny;
                                                //complex data in format [real, complex, real, complex...]
                                                edata[idx1] =
                                                std::sqrt(data[idx2]*data[idx2]+data[idx2+1]*data[idx2+1]);
                                        }
                                }
                        }
                }
        }

        e->set_complex(false);
        if(e->get_ysize()==1 && e->get_zsize()==1) {
                e->set_complex_x(false);
        }
        e->update();
        return e;

        EXITFUNC;
}
void EMData::add ( const EMData image)

add a same-size image to this image pixel by pixel.

Parameters:
imageThe image added to 'this' image.
Exceptions:
ImageFormatExceptionIf the 2 images are not same size.

Definition at line 326 of file emdata_core.cpp.

References data, ENTERFUNC, EXITFUNC, get_data(), get_xsize(), get_ysize(), get_zsize(), ImageFormatException, is_real(), nx, nxyz, ny, nz, and update().

{
        ENTERFUNC;
        if (nx != image.get_xsize() || ny != image.get_ysize() || nz != image.get_zsize()) {
                throw ImageFormatException( "images not same sizes");
        }
        else if( (is_real()^image.is_real()) == true )
        {
                throw ImageFormatException( "not support add between real image and complex image");
        }
        else {

                const float *src_data = image.get_data();
                size_t size = nxyz;
                float* data = get_data();

                for (size_t i = 0; i < size; i++) {
                        data[i] += src_data[i];
                }
                update();
        }
        EXITFUNC;
}
void EMData::add ( float  f,
int  keepzero = 0 
)

add a number to each pixel value of the image.

Image may be real or complex.

Parameters:
fThe number added to 'this' image.
keepzeroIf set will not modify pixels that are exactly zero

Definition at line 271 of file emdata_core.cpp.

References data, ENTERFUNC, EXITFUNC, get_data(), ImageFormatException, is_complex(), is_real(), nx, nxyz, ny, nz, and update().

Referenced by EMAN::CtfCAutoAverager::add_image(), EMAN::CtfCWautoAverager::add_image(), EMAN::BackProjectionReconstructor::finish(), EMAN::BackProjectionReconstructor::insert_slice(), EMAN::operator+(), operator+=(), EMAN::operator-(), EMAN::CtfSimProcessor::process(), EMAN::NormalizeRampNormVar::process_inplace(), and EMAN::SNREvalProcessor::process_inplace().

{
        ENTERFUNC;

        float * data = get_data();
        if( is_real() )
        {
                if (f != 0) {

                        size_t size = nxyz;
                        if (keepzero) {
                                for (size_t i = 0; i < size; i++) {
                                        if (data[i]) data[i] += f;
                                }
                        }
                        else {
                                for (size_t i = 0; i < size; i++) {
                                        data[i] += f;
                                }
                        }
                        update();
                }
        }
        else if( is_complex() )
        {
                if( f!=0 )
                {
                        update();
                        size_t size = (size_t)nx*ny*nz; //size of data
                        if( keepzero )
                        {
                                for(size_t i=0; i<size; i+=2)
                                {
                                        if (data[i]) data[i] += f;
                                }
                        }
                        else
                        {
                                for(size_t i=0; i<size; i+=2)
                                {
                                        data[i] += f;
                                }
                        }
                }
        }
        else
        {
                throw ImageFormatException("This image is neither a real nor a complex image.");
        }
        update();
        EXITFUNC;
}
size_t EMData::add_complex_at ( const int &  x,
const int &  y,
const int &  z,
const std::complex< float > &  val 
)

Add complex<float> value at x,y,z.

This assumes the image is a standard real/imaginary image with the complex origin in the first memory location. If you take the fft of a real nx x ny x nz image, a nx+2 x ny x nz image will be produced, and values using this function can go from -nx/2 to nx/2 and -ny/2 to ny/2. It will automatically deal with wraparound and complex conjugate issues for -x. It will return the index into the float array at which the complex began, or nx*ny*nz if out of range

Parameters:
xx coordinate
yy coordinate
zz coordinate
valcomplex<float> value to set
Returns:
The complex pixel at x,y

Definition at line 211 of file emdata_core.cpp.

References nx, nxy, nxyz, ny, nz, rdata, and y.

Referenced by EMAN::FourierInserter3DMode7::insert_pixel(), EMAN::FourierInserter3DMode6::insert_pixel(), EMAN::FourierInserter3DMode2::insert_pixel(), and EMAN::FourierInserter3DMode1::insert_pixel().

                                                                                                 {
//if (abs(x)>=nx/2 || abs(y)>ny/2 || abs(z)>nz/2) return nxyz;
if (x>=nx/2 || y>ny/2 || z>nz/2 || x<=-nx/2 || y<-ny/2 || z<-nz/2) return nxyz;

// for x=0, we need to insert the value in 2 places
// complex conjugate insertion. Removed due to ambiguity with returned index
/*if (x==0 && (y!=0 || z!=0)) {
        size_t idx=(y<=0?-y:ny-y)*nx+(z<=0?-z:nz-z)*nx*ny;
        rdata[idx]+=(float)val.real();
        rdata[idx+1]-=(float)val.imag();
}*/

size_t idx;
if (x<0) {
        idx=-x*2+(y<=0?-y:ny-y)*(size_t)nx+(z<=0?-z:nz-z)*(size_t)nxy;
        rdata[idx]+=(float)val.real();
        rdata[idx+1]-=(float)val.imag();
        return idx;
}

idx=x*2+(y<0?ny+y:y)*(size_t)nx+(z<0?nz+z:z)*(size_t)nxy;
rdata[idx]+=(float)val.real();
rdata[idx+1]+=(float)val.imag();

return idx;
}
size_t EMData::add_complex_at ( int  x,
int  y,
int  z,
const int &  subx0,
const int &  suby0,
const int &  subz0,
const int &  fullnx,
const int &  fullny,
const int &  fullnz,
const std::complex< float > &  val 
)

Add complex<float> value at x,y,z assuming that 'this' is a subvolume from a larger virtual volume.

Requires that parameters often stored in the header as: subvolume_x0,y0,z0 and subvolume_full_nx,ny,nz be passed in as parameters. Otherwise similar to add_complex_at. It will return the index into the subvolume float array at which the complex began, or nx*ny*nz if out of range

Parameters:
xx coordinate
yy coordinate
zz coordinate
valcomplex<float> value to set
Returns:
The complex pixel at x,y

Definition at line 238 of file emdata_core.cpp.

References abs, nx, nxyz, ny, nz, rdata, and y.

                                                                                                                                                                                     {
if (abs(x)>=fullnx/2 || abs(y)>fullny/2 || abs(z)>fullnz/2) return nxyz;
//if (x==0 && (y!=0 || z!=0)) add_complex_at(0,-y,-z,subx0,suby0,subz0,fullnx,fullny,fullnz,conj(val));
// complex conjugate insertion. Removed due to ambiguity with returned index
/*if (x==0&& (y!=0 || z!=0)) {
        int yy=y<=0?-y:fullny-y;
        int zz=z<=0?-z:fullnz-z;

        if (yy<suby0||zz<subz0||yy>=suby0+ny||zz>=subz0+nz) return nx*ny*nz;

        size_t idx=(yy-suby0)*nx+(zz-subz0)*nx*ny;
        rdata[idx]+=(float)val.real();
        rdata[idx+1]+=(float)-val.imag();
}*/
float cc=1.0;
if (x<0) {
        x*=-1;
        y*=-1;
        z*=-1;
        cc=-1.0;
}
if (y<0) y=fullny+y;
if (z<0) z=fullnz+z;

if (x<subx0||y<suby0||z<subz0||x>=subx0+nx||y>=suby0+ny||z>=subz0+nz) return nxyz;

size_t idx=(x-subx0)*2+(y-suby0)*(size_t)nx+(z-subz0)*(size_t)nx*ny;
rdata[idx]+=(float)val.real();
rdata[idx+1]+=cc*(float)val.imag();
return idx;
}
size_t EMAN::EMData::add_complex_at_fast ( const int &  x,
const int &  y,
const int &  z,
const std::complex< float > &  val 
) [inline]
void EMData::add_incoherent ( EMData obj)

Adds 'obj' to 'this' incoherently.

'obj' and 'this' should be same size. Both images should be complex images.

Parameters:
objThe image added to 'this' image.
Exceptions:
ImageFormatExceptionIf the 2 images are not same size; or if the 2 images are not complex images.

Definition at line 3210 of file emdata.cpp.

References ENTERFUNC, EXITFUNC, get_data(), ImageFormatException, is_complex(), EMAN::EMUtil::is_same_size(), LOGERR, NullPointerException, nx, ny, nz, ri2ap(), and update().

{
        ENTERFUNC;

        if (!obj) {
                LOGERR("NULL image");
                throw NullPointerException("NULL image");
        }

        if (!obj->is_complex() || !is_complex()) {
                throw ImageFormatException("complex images only");
        }

        if (!EMUtil::is_same_size(this, obj)) {
                throw ImageFormatException("images not same size");
        }

        ri2ap();
        obj->ri2ap();

        float *dest = get_data();
        float *src = obj->get_data();
        size_t size = (size_t)nx * ny * nz;
        for (size_t j = 0; j < size; j += 2) {
#ifdef  _WIN32
                dest[j] = (float) _hypot(src[j], dest[j]);
#else
                dest[j] = (float) hypot(src[j], dest[j]);
#endif  //_WIN32
                dest[j + 1] = 0;
        }

        obj->update();
        update();
        EXITFUNC;
}
void EMData::addsquare ( const EMData image)

add the squared value of each pixel from a same-size image to this image.

Parameters:
imageThe image whose square is added to 'this' image.
Exceptions:
ImageFormatExceptionIf the 2 images are not same size.

Definition at line 351 of file emdata_core.cpp.

References data, ENTERFUNC, EXITFUNC, get_data(), get_xsize(), get_ysize(), get_zsize(), ImageFormatException, is_complex(), nx, nxyz, ny, nz, and update().

{
        ENTERFUNC;
        if (nx != image.get_xsize() || ny != image.get_ysize() || nz != image.get_zsize()) {
                throw ImageFormatException( "images not same sizes");
        }
        else if( this->is_complex() || image.is_complex() )
        {
                throw ImageFormatException( "Cannot addsquare() with complex images");
        }
        else {

                const float *src_data = image.get_data();
                size_t size = nxyz;
                float* data = get_data();

                for (size_t i = 0; i < size; i++) {
                        data[i] += src_data[i]*src_data[i];
                }
                update();
        }
        EXITFUNC;
}
EMData * EMData::align ( const string &  aligner_name,
EMData to_img,
const Dict params = Dict(),
const string &  cmp_name = "",
const Dict cmp_params = Dict() 
)

Align this image with another image and return the result image.

Parameters:
aligner_nameAlignment algorithm name.
to_imgThe image 'this' image aligns to.
paramsAlignment algorithm parameters in a keyed dictionary.
cmp_nameComparison algorithm used in alignment.
cmp_paramsParameter dictionary for comparison algorithm.
Exceptions:
NotExistingObjectErrorIf the alignment algorithm doesn't exist.
Returns:
The result image.

Definition at line 116 of file emdata_modular.cpp.

References EMAN::Aligner::align(), ENTERFUNC, and EXITFUNC.

Referenced by EMAN::RotateFlipAlignerIterative::align(), EMAN::RotateFlipAligner::align(), EMAN::RotateTranslateFlipAlignerIterative::align(), EMAN::RotateTranslateFlipAligner::align(), EMAN::RotateTranslateAligner::align(), EMAN::RotateTranslateAlignerIterative::align(), EMAN::ScaleAlignerABS::align_using_base(), main(), and EMAN::ACFCenterProcessor::process_inplace().

{
        ENTERFUNC;
        EMData *result = 0;
        Aligner *a = Factory < Aligner >::get(aligner_name, params);
        if (a) {
                if (cmp_name == "") {
                        result = a->align(this, to_img);
                }
                else {
                        result = a->align(this, to_img, cmp_name, cmp_params);
                }
                if( a )
                {
                        delete a;
                        a = 0;
                }
        }

        EXITFUNC;
        return result;
}
EMData * EMData::amplitude ( ) const

return amplitude part of a complex image as a real image format

Returns:
EMData * a real image which is the amplitude part of this image
Exceptions:
InvalidCallExceptionif this image is a real image or is in real/imaginary format

Definition at line 1210 of file emdata_core.cpp.

References data, EMData(), ENTERFUNC, EXITFUNC, get_data(), get_xsize(), get_ysize(), get_zsize(), InvalidCallException, is_real(), is_ri(), nx, ny, nz, set_complex(), set_complex_x(), set_size(), and update().

{
        ENTERFUNC;

        EMData * e = new EMData();

        if( is_real() ) {
                throw InvalidCallException("No imaginary part for a real image, this function call require a complex image.");
        }
        else {
                if(is_ri()) {
                        throw InvalidCallException("This image is in real/imaginary format, this function call require a complex image in amplitude/phase format.");
                }

                int nx = get_xsize();
                int ny = get_ysize();
                int nz = get_zsize();
                e->set_size(nx/2, ny, nz);
                float * edata = e->get_data();
                float * data = get_data();
                size_t idx1, idx2;
                for( int i=0; i<nx; ++i )
                {
                        for( int j=0; j<ny; ++j )
                        {
                                for( int k=0; k<nz; ++k )
                                {
                                        if( i%2 == 0 )
                                        {
                                                idx1 = i/2+j*(nx/2)+k*(nx/2)*ny;
                                                idx2 = i+j*nx+k*nx*ny;
                                                //complex data in format [amp, phase, amp, phase...]
                                                edata[idx1] = data[idx2];
                                        }
                                }
                        }
                }
        }

        e->set_complex(false);
        if(e->get_ysize()==1 && e->get_zsize()==1) {
                e->set_complex_x(false);
        }
        e->update();
        return e;

        EXITFUNC;
}
void EMData::ap2ri ( )
void EMData::append_image ( const string &  filename,
EMUtil::ImageType  imgtype = EMUtil::IMAGE_UNKNOWN,
bool  header_only = false 
)

append to an image file; If the file doesn't exist, create one.

Parameters:
filenameThe image file name.
imgtypeWrite to the given image format type. if not specified, use the 'filename' extension to decide.
header_onlyTo write only the header or both header and data.

Definition at line 363 of file emdata_io.cpp.

References ENTERFUNC, EXITFUNC, and write_image().

Referenced by EMAN::IterationAverager::finish(), and main().

{
        ENTERFUNC;
        write_image(filename, -1, imgtype, header_only, 0);
        EXITFUNC;
}
void EMData::apply_radial_func ( float  x0,
float  dx,
vector< float >  array,
bool  interp = true 
)

multiplies by a radial function in fourier space.

Parameters:
x0starting point x coordinate.
dxstep of x.
arrayradial function data array.
interpDo the interpolation or not.

Definition at line 2615 of file emdata.cpp.

References ap2ri(), data, ENTERFUNC, EXITFUNC, get_data(), get_ndim(), ImageFormatException, is_complex(), nx, ny, nz, sqrt(), and update().

Referenced by EMAN::OptVarianceCmp::cmp(), main(), EMAN::FSCFourierProcessor::process(), EMAN::CtfSimProcessor::process(), EMAN::FileFourierProcessor::process_inplace(), EMAN::SNRProcessor::process_inplace(), EMAN::FourierAnlProcessor::process_inplace(), and EMAN::FourierProcessor::process_inplace().

{
        ENTERFUNC;

        if (!is_complex()) throw ImageFormatException("apply_radial_func requires a complex image");

        int n = static_cast < int >(array.size());

        if (n*step>2.0) printf("Warning, apply_radial_func takes x0 and step with respect to Nyquist (0.5)\n");

//      printf("%f %f %f\n",array[0],array[25],array[50]);

        ap2ri();

        size_t ndims = get_ndim();
        float * data = get_data();
        if (ndims == 2) {
                int k = 0;
                for (int j = 0; j < ny; j++) {
                        for (int i = 0; i < nx; i += 2, k += 2) {
                                float r;
#ifdef  _WIN32
                                if (j<ny/2) r = (float)_hypot(i/(float)(nx*2), j/(float)ny);
                                else r = (float)_hypot(i/(float)(nx*2), (ny-j)/(float)ny);
#else
                                if (j<ny/2) r = (float)hypot(i/(float)(nx*2), j/(float)ny);
                                else r = (float)hypot(i/(float)(nx*2), (ny-j)/(float)ny);
#endif  //_WIN32
                                r = (r - x0) / step;

                                int l = 0;
                                if (interp) {
                                        l = (int) floor(r);
                                }
                                else {
                                        l = (int) floor(r + 1);
                                }


                                float f = 0;
                                if (l >= n - 2) {
                                        f = array[n - 1];
                                }
                                else {
                                        if (interp) {
                                                r -= l;
                                                f = (array[l] * (1.0f - r) + array[l + 1] * r);
                                        }
                                        else {
                                                f = array[l];
                                        }
                                }

                                data[k] *= f;
                                data[k + 1] *= f;
                        }
                }
        }
        else if (ndims == 3) {
                int k = 0;
                for (int m = 0; m < nz; m++) {
                        float mnz;
                        if (m<nz/2) mnz=m*m/(float)(nz*nz);
                        else { mnz=(nz-m)/(float)nz; mnz*=mnz; }

                        for (int j = 0; j < ny; j++) {
                                float jny;
                                if (j<ny/2) jny= j*j/(float)(ny*ny);
                                else { jny=(ny-j)/(float)ny; jny*=jny; }

                                for (int i = 0; i < nx; i += 2, k += 2) {
                                        float r = std::sqrt((i * i / (nx*nx*4.0f)) + jny + mnz);
                                        r = (r - x0) / step;

                                        int l = 0;
                                        if (interp) {
                                                l = (int) floor(r);
                                        }
                                        else {
                                                l = (int) floor(r + 1);
                                        }

                                        float f = 0;
                                        if (l >= n - 2) {
                                                f = array[n - 1];
                                        }
                                        else {
                                                if (interp) {
                                                        r -= l;
                                                        f = (array[l] * (1.0f - r) + array[l + 1] * r);
                                                }
                                                else {
                                                        f = array[l];
                                                }
                                        }

//if (k%5000==0) printf("%d %d %d   %f\n",i,j,m,f);
                                        data[k] *= f;
                                        data[k + 1] *= f;
                                }
                        }
                }

        }

        update();
        EXITFUNC;
}
EMData * EMData::average_circ_sub ( ) const

Subtract average outside of a circle.

Returns:
image with sbtracted average outside of a circle.

Definition at line 1161 of file emdata_sparx.cpp.

References copy_head(), ENTERFUNC, EXITFUNC, get_data(), nx, ny, pnewimg, proj, and update().

Referenced by EMAN::padfft_slice().

{
//  this is written as though dimensions could be different, but in fact they should be all equal nx=ny=nz,
//                                                           no check of this
        ENTERFUNC;
        const EMData* const image = this;
        EMData* newimg = copy_head();
        float *proj = image->get_data();
        float *pnewimg = newimg->get_data();
        //  Calculate average outside of a circle
        float r2 = static_cast<float>( (nx/2)*(nx/2) );
        float qs=0.0f;
        int m=0;
        int ncz = nz/2 + 1;
        int ncy = ny/2 + 1;
        int ncx = nx/2 + 1;
        for (int iz = 1; iz <= nz; iz++) {
                float yy = static_cast<float>( (iz-ncz)*(iz-ncz) );
                for (int iy = 1; iy <=ny; iy++) { float xx = yy + (iy-ncy)*(iy-ncy);
                        for (int ix = 1; ix <= nx; ix++) {
                                if ( xx+float((ix-ncx)*(ix-ncx)) > r2 ) {
                                        qs += proj(ix,iy,iz);
                                        m++;
                                }
                        }
                }
        }


        if( m > 0 ) qs /= m;

        for (int iz = 1; iz <= nz; iz++)
                for (int iy = 1; iy <= ny; iy++)
                        for (int ix = 1; ix <= nx; ix++)
                                        pnewimg(ix,iy,iz) = proj(ix,iy,iz) - qs;
        newimg->update();
        return newimg;
        EXITFUNC;
}
EMData * EMData::backproject ( const string &  projector_name,
const Dict params = Dict() 
)

Calculate the backprojection of this image (stack) and return the result.

Parameters:
projector_nameProjection algorithm name. (Only "pawel" and "chao" have been implemented now).
paramsProjection Algorithm parameters.
Exceptions:
NotExistingObjectErrorIf the projection algorithm doesn't exist.
Returns:
The result image.

Definition at line 193 of file emdata_modular.cpp.

References EMAN::Projector::backproject3d(), ENTERFUNC, and EXITFUNC.

{
        ENTERFUNC;
        EMData *result = 0;
        Projector *p = Factory < Projector >::get(projector_name, params);
        if (p) {
                result = p->backproject3d(this);
                if( p )
                {
                        delete p;
                        p = 0;
                }
        }

        EXITFUNC;
        return result;
}
EMData * EMData::bispecRotTransInvDirect ( int  type = 0)

This computes the rotational and translational bispectral invariants of an image.

the output is a single 3d Volume whose x,y labels are lengths, corresponding to the two lengths of sides of a triangle the z label is for the angle

Definition at line 1337 of file emdata_transform.cpp.

References do_fft(), get_value_at(), get_xsize(), process_inplace(), set_value_at(), sqrt(), write_image(), and x.

{

        int EndP = this -> get_xsize(); // length(fTrueVec);
        int Mid  = (int) ((1+EndP)/2);
        int End = 2*Mid-1;

        int CountxyMax = End*End;

//      int   *SortfkInds       = new    int[CountxyMax];
        int   *kVecX            = new    int[CountxyMax];
        int   *kVecY            = new    int[CountxyMax];
        float *fkVecR           = new  float[CountxyMax];
        float *fkVecI           = new  float[CountxyMax];
        float *absD1fkVec       = new  float[CountxyMax];
//      float *absD1fkVecSorted = new  float[CountxyMax];


        float *jxjyatan2         = new  float[End*End];


        EMData * ThisCopy = new EMData(End,End);

        for (int jx=0; jx <End ; jx++) {  // create jxjyatan2
                for (int jy=0; jy <End ; jy++) {
                        float ValNow = this -> get_value_at(jx,jy);
                        ThisCopy -> set_value_at(jx,jy,ValNow);
                        jxjyatan2[jy*End + jx]  = atan2((float)(jy+1-Mid) , (float)(jx +1 -Mid));
//              cout<< " jxM= " << jx+1<<" jyM= " << jy+1<< "ValNow" << ValNow << endl; //    Works
        }}


        EMData* fk = ThisCopy -> do_fft();
        fk          ->process_inplace("xform.fourierorigin.tocenter");

//      Create kVecX , kVecy etc

        for (int kEx= 0; kEx<2*Mid; kEx=kEx+2) { // kEx twice the value of the Fourier
                                                // x variable: EMAN index for real, imag
                int kx    = kEx/2;              // kx  is  the value of the Fourier variable
                int kIx   = kx+Mid-1; // This is the value of the index for a matlab image (-1)
                int kCx   = -kx ;
                int kCIx  = kCx+ Mid-1 ;
                for (int kEy= 0 ; kEy<End; kEy++) { // This is the value of the EMAN index
                        int kIy              =  kEy       ; //  This is the value of the index for a matlab image (-1)
                        int ky               =  kEy+1-Mid; // (kEy+ Mid-1)%End - Mid+1 ;  // This is the actual value of the Fourier variable
                        float realVal        =  fk -> get_value_at(kEx  ,kEy) ;
                        float imagVal        =  fk -> get_value_at(kEx+1,kEy) ;
                        float absVal         =  ::sqrt(realVal*realVal+imagVal*imagVal);
                        float fkAng          =  atan2(imagVal,realVal);

                        float NewRealVal   ;
                        float NewImagVal   ;
                        float AngMatlab    ;

                        if (kIx==Mid-1) {
//                              AngMatlab = -fkAng - 2.*M_PI*(kIy+ 1-Mid)*(Mid)/End;
                        }

                        if (kIx>Mid-1){
//                      cout<< "i= " << i << " kIx= " << kIx << " kIy=" << kIy << " fkVecR[i] =" << fkVecR[i]<< " fkVecI[i]="  << fkVecI[i] <<"  angle[i]= "  << AngMatlab << endl;
                        }

                        AngMatlab = fkAng - 2.0f*M_PI*(kx +ky)*(Mid)/End;
                        NewRealVal  =   absVal*cos(AngMatlab);
                        NewImagVal  =   absVal*sin(AngMatlab);


                        fkVecR[ kIy +kIx *End] =  NewRealVal ;
                        fkVecR[(End-1-kIy)+kCIx*End] =  NewRealVal ;
                        fkVecI[ kIy +kIx *End] =  NewImagVal ;
                        fkVecI[(End-1-kIy)+kCIx*End] = -NewImagVal ;
                        absD1fkVec[(End-1-kIy) + kIx  *End] = absVal;
                        absD1fkVec[(End-1-kIy) + kCIx *End] = absVal;
                        kVecX[kIy+kIx  *End] =  kx      ;
                        kVecX[kIy+kCIx *End] =  kCx    ;
                        kVecY[kIy+kIx  *End] =  ky     ;
                        kVecY[kIy+kCIx *End] =  ky     ;

 //                     cout << " kIxM= " << kIx+1 << " kIy=" << kIy+1 << " fkVecR[i] =" << NewRealVal << " fkVecI[i]="  << NewImagVal <<"  angle[i]= "  << AngMatlab << " Total Index" << kIy+kIx *End << endl;

//                      printf("kx=%d,ky=%d,tempVal =%f+ i %4.2f \n",kx,ky,realVal,imagVal );
//                      cout << "kx = " << kx << "; ky = "<< ky << "; val is" << realVal<<"+ i "<<imagVal<< endl;

//                      cout << "kIMx = "<< kIx+1 << "; kIMy = "<< kIy+1 <<"; fkAng*9/ 2pi is " << fkAng*9/2/M_PI<<  endl;
//                      cout << "kIMx = "<< kIx+1 << "; kIMy = "<< kIy+1 <<"; absval is " << absVal<<  "; realval is " << NewRealVal<< "; imagval is " << NewImagVal<< endl;
                }
        }


//      for (int TotalInd = 0 ;  TotalInd < CountxyMax ; TotalInd++){
//              int kx     = kVecX[TotalInd]; // This is the value of the index for a matlab image (-1)
//              int kIx    = kx+Mid-1; // This is the value of the index for a matlab image (-1)
//              int ky     = kVecY[TotalInd];
//              int kIy    = ky+Mid-1; // This is the value of the index for a matlab image (-1)
                //float fkR  = fkVecR[kIy+kIx *End]  ;
                //float fkI  = fkVecI[kIy+kIx *End]  ;
//      }

        float frR= 3.0/4.0;
        frR= 1;
        int LradRange= (int) (1+floor(Mid/frR -.1)) ;

        float *radRange = new float[LradRange]; //= 0:.75:(Mid-1);
        for (int irad=0; irad < LradRange; irad++){
                        radRange[irad] =  frR*irad;
//                      cout << " irad = " << irad << " radRange[irad]= " <<  radRange[irad] <<  " LradRange= " << LradRange << endl;
        }

        cout << "Starting the calculation of invariants" << endl;


        if (type==0) {
                int LthetaRange  = 59;
                float ftR        = (2.0f*M_PI/LthetaRange );
                float *thetaRange = new float[LthetaRange]; //= 0:.75:(Mid-1);

                for (int ith=0; ith < LthetaRange; ith++){
                                thetaRange[ith] =  ftR*ith; }

                int TotalVol = LradRange*LradRange*LthetaRange;

                float *RotTransInv   = new  float[TotalVol];
                float *WeightInv     = new  float[TotalVol];

                for (int jW=0; jW<TotalVol; jW++) {
                        RotTransInv[jW] = 0;
                        WeightInv[jW]   = 0;
                }

                for (int jW=0; jW<TotalVol; jW++) {
                        RotTransInv[jW] = 0;
                        WeightInv[jW]   = 0;
                }
        //      float  *RotTransInv       = new float[LradRange*LradRange ] ;
        //      float  *RotTransInvN      = new float[LradRange*LradRange*(NMax+1) ] ;

                for (int Countkxy =0; Countkxy<CountxyMax; Countkxy++){  // Main Section for type 0
                        int kx = kVecX[Countkxy] ;
                        int ky = kVecY[Countkxy] ;
                        float k2 = ::sqrt((float)(kx*kx+ky*ky));
                        float phiK =0;
                        if (k2>0)    phiK = jxjyatan2[ (ky+Mid-1)*End + kx+Mid-1]; //  phiK=atan2(ky,kx);
                        float fkR     = fkVecR[(ky+Mid-1) + (kx+Mid-1) *End] ;
                        float fkI     = fkVecI[(ky+Mid-1) + (kx+Mid-1) *End]  ;
        //              printf("Countkxy=%d,\t kx=%d, ky=%d, fkR=%3.2f,fkI=%3.2f \n", Countkxy, kx, ky, fkR, fkI);

                        if ((k2==0)|| (k2>Mid) ) { continue;}

                        for (int Countqxy =0; Countqxy<CountxyMax; Countqxy++){   // This is the innermost loop
                                int qx   = kVecX[Countqxy] ;
                                int qy   = kVecY[Countqxy] ;
                                float q2   = ::sqrt((float)(qx*qx+qy*qy));
                                if ((q2==0)|| (q2>Mid) ) {continue;}
                                float phiQ =0;
                                if (q2>0)   phiQ = jxjyatan2[ (qy+Mid-1)*End + qx+Mid-1]; // phiQ=atan2(qy,qx);
                                float fqR     = fkVecR[(qy+Mid-1) + (qx+Mid-1) *End] ;
                                float fqI     = fkVecI[(qy+Mid-1) + (qx+Mid-1) *End]  ;
                                int kCx  = (-kx-qx);
                                int kCy  = (-ky-qy);
                                int kCIx = ((kCx+Mid+2*End)%End);// labels of the image in C
                                int kCIy = ((kCy+Mid+2*End)%End);
                                kCx  = ((kCIx+End-1)%End)+1-Mid; // correct
                                kCy  = ((kCIy+End-1)%End)+1-Mid ; // correct

//                              float C2   = ::sqrt((float)(kCx*kCx+ kCy*kCy));
                                int CountCxy  = (kCx+Mid-1)*End+(kCy+Mid-1);
                                float fCR     = fkVecR[CountCxy];
                                float fCI     = fkVecI[CountCxy];
        /*                      if (Countkxy==1) {
                                        printf(" Countqxy=%d, absD1fkVec(Countqxy)=%f,qx=%d, qy=%d \n", Countqxy, absD1fkVec[Countqxy],qx, qy);
                                        printf(" CountCxy=%d, absD1fkVec[CountCxy]=%f,kCx=%d,kCy=%d \n",CountCxy, absD1fkVec[CountCxy], kCx, kCy );
                                }*/
//                              float   phiC = jxjyatan2[ (kCy+Mid-1)*End + kCx+Mid-1];
                                float   phiQK = (4*M_PI+phiQ-phiK);
                                while (phiQK> (2*M_PI)) phiQK -= (2*M_PI);



                                float bispectemp  = (fkR*(fqR*fCR -fqI*fCI) -fkI*(fqI*fCR  +fqR*fCI));

                                if  ((q2<k2) )  continue;
//                              if  ((q2<k2) || (C2<k2) || (C2<q2))  continue;

        //                              printf(" CountCxy=%d, absD1fkVec[CountCxy]=%f,kCx=%d,kCy=%d \n",CountCxy, absD1fkVec[CountCxy], kCx, kCy );

        //                      up to here, matched perfectly with Matlab

                                int k2IndLo  = 0; while ((k2>=radRange[k2IndLo+1]) && (k2IndLo+1 < LradRange ) ) k2IndLo +=1;
                                int k2IndHi = k2IndLo;
                                float k2Lo= radRange[k2IndLo];
                                if (k2IndLo+1< LradRange) {
                                        k2IndHi   = k2IndLo+1;
                                }
//                              float k2Hi= radRange[k2IndHi];

                                float kCof =k2-k2Lo;

                                int q2IndLo  = 0; while ((q2>=radRange[q2IndLo+1]) && (q2IndLo+1 < LradRange ) ) q2IndLo +=1;
                                int q2IndHi=q2IndLo;
                                float q2Lo= radRange[q2IndLo];
                                if (q2IndLo+1 < LradRange)  {
                                        q2IndHi   = q2IndLo+1 ;
                                }
                                float qCof = q2-q2Lo;

                                if ((qCof<0) || (qCof >1) ) {
                                        cout<< "Weird! qCof="<< qCof <<  " q2="<< q2 << " q2IndLo="<< q2IndLo << endl ;
                                        int x    ;
                                        cin >> x ;
                                }

                                int thetaIndLo = 0; while ((phiQK>=thetaRange[thetaIndLo+1])&& (thetaIndLo+1<LthetaRange)) thetaIndLo +=1;
                                int thetaIndHi = thetaIndLo;

                                float thetaLo  = thetaRange[thetaIndLo];
                                float thetaHi = thetaLo;
                                float thetaCof = 0;

                                if (thetaIndLo+1< LthetaRange) {
                                        thetaIndHi = thetaIndLo +1;
                                }else{
                                        thetaIndHi=0;
                                }

                                thetaHi    = thetaRange[thetaIndHi];

                                if (thetaHi==thetaLo) {
                                        thetaCof =0 ;
                                } else {
                                        thetaCof   = (phiQK-thetaLo)/(thetaHi-thetaLo);
                                }

                                if ((thetaCof>2*M_PI)  ) {
                                        cout<< "Weird! thetaCof="<< thetaCof <<endl ;
                                        thetaCof=0;
                                }


        //                      if ((thetaIndLo>=58) || (k2IndLo >= LradRange-1) || (q2IndLo >= LradRange-1) ) {


                                for (int jk =1; jk<=2; jk++){
                                for (int jq =1; jq<=2; jq++){
                                for (int jtheta =1; jtheta<=2; jtheta++){

                                        float Weight = (kCof+(1-2*kCof)*(jk==1))*(qCof+(1-2*qCof)*(jq==1))
                                                        * (thetaCof+(1-2*thetaCof)*(jtheta==1));


                                        int k2Ind      =  k2IndLo*(jk==1)      +   k2IndHi*(jk==2);
                                        int q2Ind      =  q2IndLo*(jq==1)      +   q2IndHi*(jq==2);
                                        int thetaInd   =  thetaIndLo*(jtheta==1)  + thetaIndHi*(jtheta ==2);
                                        int TotalInd   = thetaInd*LradRange*LradRange+q2Ind*LradRange+k2Ind;
        /*                              if (TotalInd+1 >=  LthetaRange*LradRange*LradRange) {
                                                cout << "Weird!!! TotalInd="<< TotalInd << " IndMax" << LthetaRange*LradRange*LradRange << " LradRange=" << LradRange << endl;
                                                cout << "k2Ind= "<< k2Ind  << " q2Ind="<< q2Ind  << " thetaInd="<< thetaInd  << " q2IndLo="<< q2IndLo  << " q2IndHi="<< q2IndHi  <<  endl;
                                                cout << "k2=" << k2 << "q2=" << q2 << " phiQK=" << phiQK*180.0/M_PI<< endl;
                                        }*/

                                        RotTransInv[TotalInd] += Weight*bispectemp;
                                        WeightInv[TotalInd]   +=  Weight;
        //                              cout << "k2Ind= "<< k2Ind  << " q2Ind="<< q2Ind  << "Weight=" << Weight << endl;
                                }}}
                        } // Countqxy
                } // Countkxy

                cout << "Finished Main Section " << endl;

        /*              RotTransInvN[jr1 + LradRange*jr2+LradRange*LradRange*N] = RotTransInvTemp  ;*/

                cout << " LradRange " <<LradRange <<" LthetaRange " << LthetaRange << endl;
                EMData *RotTransInvF  = new  EMData(LradRange,LradRange,LthetaRange);
                EMData *WeightImage   = new  EMData(LradRange,LradRange,LthetaRange);

        //      cout << "FFFFFFF" << endl;
        //
        //      RotTransInvF -> set_size(LradRange,LradRange,LthetaRange);
        //
        //      cout << "GGGG" << endl;

                for (int jtheta =0; jtheta < LthetaRange; jtheta++){    // write out to RotTransInvF
                for (int jq =0; jq<LradRange; jq++){ // LradRange
                for (int jk =0; jk<LradRange ; jk++){// LradRange
        //              cout << "Hi There" << endl;
                        int TotalInd   = jtheta*LradRange*LradRange+jq*LradRange+jk;
                        float Weight = WeightInv[TotalInd];
                        WeightImage    -> set_value_at(jk,jq,jtheta,Weight);
                        RotTransInvF   -> set_value_at(jk,jq,jtheta,0);
                        if (Weight <= 0) continue;
                        RotTransInvF -> set_value_at(jk,jq,jtheta,RotTransInv[TotalInd] / Weight);//  include /Weight
                        int newjtheta = (LthetaRange- jtheta)%LthetaRange;
                        RotTransInvF -> set_value_at(jq,jk,newjtheta,RotTransInv[TotalInd]/Weight );//  include /Weight
                                }
                        }
                }

                cout << " Almost Done " << endl;
#ifdef  _WIN32
                _unlink("WeightImage.???");
#else
                system("rm -f WeightImage.???");
#endif  //_WIN32
                WeightImage  -> write_image("WeightImage.img");

                return  RotTransInvF ;
        } // Finish type 0

        if (type==1) {
                int TotalVol = LradRange*LradRange;

                float *RotTransInv   = new  float[TotalVol];
                float *WeightInv     = new  float[TotalVol];

                for (int jW=0; jW<TotalVol; jW++) {
                        RotTransInv[jW] = 0;
                        WeightInv[jW]   = 0;
                }


                for (int Countkxy =0; Countkxy<CountxyMax; Countkxy++){
                        int kx = kVecX[Countkxy] ;
                        int ky = kVecY[Countkxy] ;
                        float k2 = ::sqrt((float)(kx*kx+ky*ky));
                        float fkR     = fkVecR[(ky+Mid-1) + (kx+Mid-1) *End] ;
                        float fkI     = fkVecI[(ky+Mid-1) + (kx+Mid-1) *End]  ;
        //              printf("Countkxy=%d,\t kx=%d, ky=%d, fkR=%3.2f,fkI=%3.2f \n", Countkxy, kx, ky, fkR, fkI);

                        if ((k2==0)|| (k2>Mid) ) { continue;}

                        for (int Countqxy =0; Countqxy<CountxyMax; Countqxy++){   // This is the innermost loop

//                      up to here, matched perfectly with Matlab
                                int qx   = kVecX[Countqxy] ;
                                int qy   = kVecY[Countqxy] ;
                                float q2   = ::sqrt((float)(qx*qx+qy*qy));
                                if ((q2==0)|| (q2>Mid) ) {continue;}
                                if  ((q2<k2) )   continue;

                                float fqR     = fkVecR[(qy+Mid-1) + (qx+Mid-1) *End] ;
                                float fqI     = fkVecI[(qy+Mid-1) + (qx+Mid-1) *End]  ;

                                int kCx  = (-kx-qx);
                                int kCy  = (-ky-qy);
                                int kCIx = ((kCx+Mid+2*End)%End);// labels of the image in C
                                int kCIy = ((kCy+Mid+2*End)%End);
                                kCx  = ((kCIx+End-1)%End)+1-Mid; // correct
                                kCy  = ((kCIy+End-1)%End)+1-Mid ; // correct

//                              float C2   = ::sqrt((float)(kCx*kCx+ kCy*kCy));
                                int CountCxy  = (kCx+Mid-1)*End+(kCy+Mid-1);
                                float fCR     = fkVecR[CountCxy];
                                float fCI     = fkVecI[CountCxy];


                                float bispectemp  = (fkR*(fqR*fCR -fqI*fCI) -fkI*(fqI*fCR  +fqR*fCI));


                                int k2IndLo  = 0; while ((k2>=radRange[k2IndLo+1]) && (k2IndLo+1 < LradRange ) ) k2IndLo +=1;
                                int k2IndHi = k2IndLo;
                                float k2Lo= radRange[k2IndLo];
                                if (k2IndLo+1< LradRange) {
                                        k2IndHi   = k2IndLo+1;
                                }
//                              float k2Hi= radRange[k2IndHi];

                                float kCof =k2-k2Lo;

                                int q2IndLo  = 0; while ((q2>=radRange[q2IndLo+1]) && (q2IndLo+1 < LradRange ) ) q2IndLo +=1;
                                int q2IndHi=q2IndLo;
                                float q2Lo= radRange[q2IndLo];
                                if (q2IndLo+1 < LradRange)  {
                                        q2IndHi   = q2IndLo+1 ;
                                }
                                float qCof = q2-q2Lo;


                                for (int jk =1; jk<=2; jk++){
                                for (int jq =1; jq<=2; jq++){

                                        float Weight = (kCof+(1-2*kCof)*(jk==1))*(qCof+(1-2*qCof)*(jq==1));

                                        int k2Ind      =  k2IndLo*(jk==1)      +   k2IndHi*(jk==2);
                                        int q2Ind      =  q2IndLo*(jq==1)      +   q2IndHi*(jq==2);
                                        int TotalInd   = q2Ind*LradRange+k2Ind;
                                        RotTransInv[TotalInd] += Weight*bispectemp;
                                        WeightInv[TotalInd]   +=  Weight;
        //                              cout << "k2Ind= "<< k2Ind  << " q2Ind="<< q2Ind  << "Weight=" << Weight << endl;
                                }}
                        } // Countqxy
                } // Countkxy

//              cout << "Finished Main Section " << endl;
//              cout << " LradRange " <<LradRange <<  endl;


                EMData *RotTransInvF  = new  EMData(LradRange,LradRange);
                EMData *WeightImage   = new  EMData(LradRange,LradRange);

                for (int jk =0; jk<LradRange ; jk++){// LradRange
                for (int jq =jk; jq<LradRange; jq++){ // LradRange
                        int TotalInd      = jq*LradRange+jk;
                        int TotalIndBar   = jq*LradRange+jk;
                        float Weight = WeightInv[TotalInd] + WeightInv[TotalIndBar];
                        if (Weight <=0) continue;
                        WeightImage    -> set_value_at(jk,jq,Weight);
                        WeightImage    -> set_value_at(jq,jk,Weight);
#ifdef _WIN32
                        float ValNow  = pow( (RotTransInv[TotalInd] + RotTransInv[TotalIndBar]) / Weight, 1.0f/3.0f )  ;
#else
                        float ValNow  = cbrt( (RotTransInv[TotalInd] + RotTransInv[TotalIndBar]) / Weight )  ;
#endif  //_WIN32
                        RotTransInvF -> set_value_at(jk,jq,ValNow);//  include /Weight
                        RotTransInvF -> set_value_at(jq,jk,ValNow );//  include /Weight
                }}

#ifdef  _WIN32
                _unlink("WeightImage.???");
#else
                system("rm -f WeightImage.???");
#endif  //_WIN32
                WeightImage  -> write_image("WeightImage.img");

                return  RotTransInvF ;
        }
        return 0;
}
EMData * EMData::bispecRotTransInvN ( int  N,
int  NK 
)

This computes the rotational and translational bispectral invariants of an image.

The invariants are labelled by the Fourier Harmonic label given by N. fVec is the real input image NK is the number of Fourier components one wishes to use in calculating this bispectrum the output is a single 2D image whose x,y labels are lengths, corresponding to the two lengths of sides of a triangle

Definition at line 1040 of file emdata_transform.cpp.

References calc_bessel(), do_fft(), get_value_at(), get_xsize(), process_inplace(), set_size(), set_value_at(), sqrt(), and write_image().

{

        int EndP = this -> get_xsize(); // length(fTrueVec);
        int Mid  = (int) ((1+EndP)/2);
        int End = 2*Mid-1;

        int CountxyMax = End*End;

        int   *SortfkInds       = new    int[CountxyMax];
        int   *kVecX            = new    int[CountxyMax];
        int   *kVecY            = new    int[CountxyMax];
        float *fkVecR           = new  float[CountxyMax];
        float *fkVecI           = new  float[CountxyMax];
        float *absD1fkVec       = new  float[CountxyMax];
        float *absD1fkVecSorted = new  float[CountxyMax];

        float *jxjyatan2         = new  float[End*End]; //  jxjyatan2[jy*End + jx]  = atan2(jy+1-Mid , jx +1 -Mid);

        EMData * ThisCopy = new EMData(End,End);

        for (int jx=0; jx <End ; jx++) {
                for (int jy=0; jy <End ; jy++) {
                        float ValNow = this -> get_value_at(jx,jy);
                        ThisCopy -> set_value_at(jx,jy,ValNow);
//              cout<< " jxM= " << jx+1<<" jyM= " << jy+1<< "ValNow" << ValNow << endl; //    Works
        }}


        EMData* fk = ThisCopy -> do_fft();
        fk          ->process_inplace("xform.fourierorigin.tocenter");

//      EMData* fk
        EMData* fkRCopy = new EMData(End,End);
        EMData* fkICopy = new EMData(End,End);
        EMData* fkCopy  = new EMData(End,End);


        for  (int jCount= 0; jCount<End*End; jCount++) {
//              jCount = jy*End + jx;
                int jx             = jCount%End ;
                int jy             = (jCount-jx)/End ;
                jxjyatan2[jCount]  = atan2((float)(jy+1-Mid) , (float)(jx +1-Mid));
        }


        for (int kEx= 0; kEx<2*Mid; kEx=kEx+2) { // kEx twice the value of the Fourier
                                                // x variable: EMAN index for real, imag
                int kx    = kEx/2;              // kx  is  the value of the Fourier variable
                int kIx   = kx+Mid-1; // This is the value of the index for a matlab image (-1)
                int kCx   =  -kx ;
                int kCIx  = kCx+ Mid-1 ;
                for (int kEy= 0 ; kEy<End; kEy++) { // This is the value of the EMAN index
                        int kIy              =  kEy       ; //  This is the value of the index for a matlab image (-1)
                        int ky               =  kEy+1-Mid; // (kEy+ Mid-1)%End - Mid+1 ;  // This is the actual value of the Fourier variable
                        float realVal        =  fk -> get_value_at(kEx  ,kEy) ;
                        float imagVal        =  fk -> get_value_at(kEx+1,kEy) ;
                        float absVal         =  ::sqrt(realVal*realVal+imagVal*imagVal);
                        float fkAng          =  atan2(imagVal,realVal);

                        float NewRealVal   ;
                        float NewImagVal   ;
                        float AngMatlab    ;

                        if (kIx==Mid-1) {
//                              AngMatlab = -fkAng - 2.*M_PI*(kIy+ 1-Mid)*(Mid)/End;
//                      cout<< "i= " << i << " kIx= " << kIx << " kIy=" << kIy << " fkVecR[i] =" << fkVecR[i]<< " fkVecI[i]="  << fkVecI[i] <<"  angle[i]= "  << AngMatlab << endl;
                        }

                        if (kIx>Mid-1){
//                      cout<< "i= " << i << " kIx= " << kIx << " kIy=" << kIy << " fkVecR[i] =" << fkVecR[i]<< " fkVecI[i]="  << fkVecI[i] <<"  angle[i]= "  << AngMatlab << endl;
                        }

                        AngMatlab = fkAng - 2.0f*M_PI*(kx +ky)*(Mid)/End;
                        NewRealVal  =   absVal*cos(AngMatlab);
                        NewImagVal  =   absVal*sin(AngMatlab);


                        fkVecR[kIy+kIx *End] =  NewRealVal ;
                        fkVecR[kIy+kCIx*End] =  NewRealVal ;
                        fkVecI[kIy+kIx *End] =  NewImagVal ;
                        fkVecI[kIy+kCIx*End] = -NewImagVal ;
                        absD1fkVec[kIy + kIx  *End] = absVal;
                        absD1fkVec[kIy + kCIx *End] = absVal;
                        kVecX[kIy+kIx  *End] =  kx      ;
                        kVecX[kIy+kCIx *End] =  kCx    ;
                        kVecY[kIy+kIx  *End] =  ky     ;
                        kVecY[kIy+kCIx *End] =  ky     ;
//                      printf("kx=%d,ky=%d,tempVal =%f+ i %4.2f \n",kx,ky,realVal,imagVal );
//                      cout << "kx = " << kx << "; ky = "<< ky << "; val is" << realVal<<"+ i "<<imagVal<< endl;

//                      cout << "kIMx = "<< kIx+1 << "; kIMy = "<< kIy+1 <<"; fkAng*9/ 2pi is " << fkAng*9/2/M_PI<<  endl;
//                      cout << "kIMx = "<< kIx+1 << "; kIMy = "<< kIy+1 <<"; absval is " << absVal<<  "; realval is " << NewRealVal<< "; imagval is " << NewImagVal<< endl;
                        fkCopy  -> set_value_at(kIx ,kIy, absVal);
                        fkCopy  -> set_value_at(kCIx,kIy, absVal);
                        fkRCopy -> set_value_at(kIx, kIy, NewRealVal);
                        fkRCopy -> set_value_at(kCIx,kIy, NewRealVal);
                        fkICopy -> set_value_at(kIx, kIy, NewImagVal);
                        fkICopy -> set_value_at(kCIx,kIy,-NewImagVal);

                }
        }
#ifdef _WIN32
        _unlink("fkCopy.???");
        _unlink("fk?Copy.???");
#else
        system("rm -f fkCopy.???");
        system("rm -f fk?Copy.???");
#endif  //_WIN32
        fkCopy  -> write_image("fkCopy.img");
        fkRCopy -> write_image("fkRCopy.img");
        fkICopy -> write_image("fkICopy.img");

        cout << "Starting the sort "<< endl;

        vector< pair<float, int> > absInds;
        for(int i  = 0; i < CountxyMax; ++i ) {
                pair<float,int> p;
                p = make_pair(absD1fkVec[i],i); // p = make_pair(rand(),i);
                absInds.push_back( p);
        }

        std::sort(absInds.begin(),absInds.end());

        for(int i  = 0; i < CountxyMax; ++i ) {
                pair<float,int> p   ;
                p = absInds[i]         ;
                absD1fkVecSorted[CountxyMax-1-i] =  p.first ;
                SortfkInds[CountxyMax-1-i]       =  p.second ;
        }

        cout << "Ending the sort "<< endl;

// float AngsMat[] ={2.8448, -0.3677,-0.2801,-1.0494,-1.7836,-2.5179, 2.9959, 3.0835,-0.1290,-0.8876,2.1829, 2.2705,1.5011,0.7669,0.0327,-0.7366,-0.6489,2.4215,-1.6029,1.4676,1.5552,0.7859,0.0517,-0.6825,-1.4518,-1.3642,1.7063,-1.7845,1.2859,1.3736,0.6043,-0.1299,-0.8642,-1.6335,-1.5459,1.5247,-1.6546,1.4159,1.5036,0.7342,0,-0.7342,-1.5036,-1.4159,1.6546,-1.5247,1.5459,1.6335,0.8642,0.1299,-0.6043,-1.3736,-1.286,1.7846,-1.7063,1.3642,1.4519,0.6825,-0.0517,-0.7859,-1.5553,-1.4676,1.6029,-2.4216,0.649,0.7366,-0.0327,-0.767,-1.5012,-2.2705,-2.1829,0.8877,0.1291,-3.0836,-2.9959,2.5179,1.7837,1.0495,0.2801,0.3677,-2.8449};


        for(int i  = 0; i < CountxyMax; ++i ) {  // creates a new fkVec
                int Si  = SortfkInds[i];
                int kIx = (int)  Si/End;  kIx = (int)  i/End; // i = kIx*End+kIy
//              int kIy = Si  - kIx*End;  kIy = i  - kIx*End;
//              int iC = (End-1-kIx)*End + (End-1-kIy);
//              if (i<30) { cout<< "i= " << i << " kIx= " << kIx << " kIy=" << kIy << " valAft=" << absD1fkVecSorted[i]<< " valBef="  <<     absD1fkVec[Si] << "  SortfkInds = " << Si <<endl; }// This worked
//              cout<< "i= " << i << " kIx= " << kIx << " kIy=" << kIy << " fkVecR[i] =" << fkVecR[i]<< " fkVecI[i]="  << fkVecI[i] <<"  angle[i]= "  << fkAng << endl;
        }
        cout<< "Ratio of Last Amplitude to First Amplitude= " << absD1fkVecSorted[NK] /absD1fkVecSorted[0]  << endl;

//      pause;

//      for(int i  = 0; i < NK; ++i ) { // Prints out the new fkVec ,  CountxyMax
//              int Si= SortfkInds[i];
//              int kIx = (int)  Si/End; // i = kIx*End+kIy
//              int kIy = Si  - kIx*End;
//              cout << " kIxM= " << kIx+1 << " kIyM=" << kIy+1 << " fkVecAbs=" << ::sqrt(fkVecR[Si]*fkVecR[Si] +  fkVecI[Si]* fkVecI[Si]) << " fkVecAbs=" << absD1fkVecSorted[i] << " kx= " << kVecX[Si] <<  " ky=" << kVecY[Si] <<  endl;
//      }

//       angEMAN+angMat+angDiff    =0  mod 2 pi

//      angDiff=  2*pi*((-4):4)*(Mid)/End; angEMAN+angMat+angDiff= integer*2 *pi
//              [  absD1fkVecSorted, SortfkInds] =sort( absD1fkVec,'descend') ;
//      Util::sort_mat(&absD1fkVec[0],&absD1fkVec[Countxy],&SortfkInds[0],&SortfkInds[Countxy]);


//      Let radial sampling be 0:0.5:(Mid-1)

 //     int NK=  min(12,CountxyMax) ;



        cout << "NK = " << NK << endl;
        float frR= 3.0/4.0;
        int LradRange= (int) (floor(Mid/frR)) ;

        float *radRange = new float[LradRange]; //= 0:.75:(Mid-1);
        radRange[0]=0;
        for (int irad=1; irad < LradRange; irad++){
                        radRange[irad] = radRange[irad-1] + frR; }



         // should equal to (2*Mid-1)
        cout << "Starting the calculation of invariants for N= " << N << endl;

/*      int NMax=5;            */

        EMData* RotTransInv = new EMData();
        RotTransInv -> set_size(LradRange,LradRange);


//      float  *RotTransInv       = new float[LradRange*LradRange ] ;
//      float  *RotTransInvN      = new float[LradRange*LradRange*(NMax+1) ] ;

//      for (int N=0 ; N<NMax; N++) {

        for (int jr1=0; jr1 < LradRange ; jr1++ ) { // LradRange
                float r1= radRange[jr1];
//              cout << "Pre jr2 "<< endl;
                for (int jr2=0;  jr2<LradRange;  jr2++ ) { //LradRange
                        float r2= radRange[jr2];
                        float RotTransInvTemp=0;
                        for (int jCountkxy =0; jCountkxy<NK; jCountkxy++){
                                int Countkxy =SortfkInds[jCountkxy] ;   // 1: CountxyMax
                                int kx = kVecX[Countkxy] ;
                                int ky = kVecY[Countkxy] ;
                                float k2 = (float)(kx*kx+ky*ky);
                                if (k2==0) { continue;}
                                float phiK =0;
                                if (k2>0) phiK= jxjyatan2[ (ky+Mid-1)*End + kx+Mid-1];  phiK= atan2((float)ky,(float)kx);

                                float fkR     = fkVecR[Countkxy] ;
                                float fkI     = fkVecI[Countkxy]  ;
/*                              printf("jCountkxy=%d, Countkxy=%d,absD1fkVec(Countkxy)=%f,\t\t kx=%d, ky=%d \n", jCountkxy, Countkxy, absD1fkVec[Countkxy], kx, ky);*/

                                for (int jCountqxy =0; jCountqxy<NK; jCountqxy++){
                                        int Countqxy =SortfkInds[jCountqxy] ;   // Countqxy is the index for absD1fkVec
                                        int qx   = kVecX[Countqxy] ;
                                        int qy   = kVecY[Countqxy] ;
                                        int q2   = qx*qx+qy*qy;
                                        if (q2==0) {continue;}
                                        float phiQ =0;
                                        if (q2>0) phiQ = jxjyatan2[ (qy+Mid-1)*End + qx+Mid-1];   phiQ=atan2((float)qy,(float)qx);
                                        float fqR     = fkVecR[Countqxy]  ;
                                        float fqI     = fkVecI[Countqxy]  ;
                                        int kCx  = (-kx-qx);
                                        int kCy  = (-ky-qy);
                                        int kCIx = ((kCx+Mid+2*End)%End);// labels of the image in C
                                        int kCIy = ((kCy+Mid+2*End)%End);
                                        kCx  = kCIx-Mid; // correct
                                        kCy  = kCIy-Mid; // correct
                                        int CountCxy = kCIx*End+kCIy;
                                        float fCR     = fkVecR[CountCxy];
                                        float fCI     = fkVecI[CountCxy];
                                        if (jr1+jr2==-1) {
                                        printf("jCountqxy=%d , Countqxy=%d, absD1fkVec(Countqxy)=%f,qx=%d, qy=%d \n", jCountqxy, Countqxy, absD1fkVec[Countqxy],qx, qy);
                                        printf(" CountCxy=%d,absD1fkVec[CountCxy]=%f,  kCx=%d,     kCy=%d \n",CountCxy, absD1fkVec[CountCxy], kCx, kCy );
                                        }
                                        for (int p=0; p<NK; p++){
//                                              printf("p=%d, SortfkInds[p]=%d, CountCxy =%d \n", p,SortfkInds[p], CountCxy);
                                                if (SortfkInds[p]==CountCxy){
                                                        float Arg1 = 2.0f*M_PI*r1*::sqrt((float) q2)/End;
                                                        float Arg2 = 2.0f*M_PI*r2*::sqrt((float) k2)/End;
//                                                      printf("Arg1=%4.2f, Arg2=%4.2f,  \n",Arg1, Arg2 );
//                                                      if (Arg1+ Arg2<15) {
                                                                float bispectemp  = (fkR*(fqR*fCR -fqI*fCI) -fkI*(fqI*fCR  +fqR*fCI))
                                                                * cos(N*(phiK-phiQ+M_PI));
                                                                bispectemp  -= (fkR*(fqR*fCI + fqI*fCR) +fkI*(fqR*fCR - fqI*fCI))
                                                                * sin(N*(phiK-phiQ+M_PI));
                                                                float bess1 = calc_bessel(N, Arg1 );
                                                                float bess2 = calc_bessel(N, Arg2 );
//                      printf("fkr=%4.2f, fqr=%4.2f, bess1=%4.2f,bess2=%4.2f \n",fkR, fqR, bess1, bess2);
/*                      printf("p =%d, SortfkInds[p]=%d, CountCxy=%d, Arg1 =%4.2f, bess1=%4.2f,  \n",
                                p, SortfkInds[p],CountCxy, Arg1, bess1);*/
                                                                RotTransInvTemp   = RotTransInvTemp  + bispectemp  * bess1*bess2 ;
//                                                      }
                                                }
                                        }
                                } // jCountqxy
                        } // jCountkxy
                        RotTransInv -> set_value_at(jr1,jr2, RotTransInvTemp)   ;
/*              RotTransInvN[jr1 + LradRange*jr2+LradRange*LradRange*N] = RotTransInvTemp  ;*/
                } //jr2
        } //jr1
// }//N

        return  RotTransInv ;


}
vector< float > EMData::calc_az_dist ( int  n,
float  a0,
float  da,
float  rmin,
float  rmax 
)

Caculates the azimuthal distributions.

works for real or complex images, 2D only.

Parameters:
nNumber of elements.
a0Starting angle.
daAngle step.
rminMinimum radius.
rmaxMaximum radius.
Exceptions:
ImageDimensionExceptionIf image is 3D.
Returns:
Float array to store the data.

Definition at line 2399 of file emdata.cpp.

References data, ENTERFUNC, EXITFUNC, get_data(), get_ndim(), EMAN::Util::hypot_fast(), ImageDimensionException, is_complex(), is_ri(), nx, ny, x, and y.

{
        ENTERFUNC;

        a0=a0*M_PI/180.0f;
        da=da*M_PI/180.0f;

        if (get_ndim() > 2) {
                throw ImageDimensionException("no 3D image");
        }

        float *yc = new float[n];

        vector<float>   vd(n);
        for (int i = 0; i < n; i++) {
                yc[i] = 0.00001f;
        }

        float * data = get_data();
        if (is_complex()) {
                int c = 0;
                for (int y = 0; y < ny; y++) {
                        for (int x = 0; x < nx; x += 2, c += 2) {
                                int x1 = x / 2;
                                int y1 = y<ny/2?y:y-ny;
                                float r = (float)Util::hypot_fast(x1,y1);

                                if (r >= rmin && r <= rmax) {
                                        float a = 0;

                                        if (y != ny / 2 || x != 0) {
                                                a = (atan2((float)y1, (float)x1) - a0) / da;
                                        }

                                        int i = (int)(floor(a));
                                        a -= i;

                                        if (i == 0) {
                                                vd[0] += data[c] * (1.0f - a);
                                                yc[0] += (1.0f - a);
                                        }
                                        else if (i == n - 1) {
                                                vd[n - 1] += data[c] * a;
                                                yc[n - 1] += a;
                                        }
                                        else if (i > 0 && i < (n - 1)) {
                                                float h = 0;
                                                if (is_ri()) {
#ifdef  _WIN32
                                                        h = (float)_hypot(data[c], data[c + 1]);
#else
                                                        h = (float)hypot(data[c], data[c + 1]);
#endif  //_WIN32
                                                }
                                                else {
                                                        h = data[c];
                                                }

                                                vd[i] += h * (1.0f - a);
                                                yc[i] += (1.0f - a);
                                                vd[i + 1] += h * a;
                                                yc[i + 1] += a;
                                        }
                                }
                        }
                }
        }
        else {
                int c = 0;
                float half_nx = (nx - 1) / 2.0f;
                float half_ny = (ny - 1) / 2.0f;

                for (int y = 0; y < ny; y++) {
                        for (int x = 0; x < nx; x++, c++) {
                                float y1 = y - half_ny;
                                float x1 = x - half_nx;
#ifdef  _WIN32
                                float r = (float)_hypot(x1, y1);
#else
                                float r = (float)hypot(x1, y1);
#endif

                                if (r >= rmin && r <= rmax) {
                                        float a = 0;
                                        if (x1 != 0 || y1 != 0) {
                                                a = atan2(y1, x1);
                                                if (a < 0) {
                                                        a += M_PI * 2;
                                                }
                                        }

                                        a = (a - a0) / da;
                                        int i = static_cast < int >(floor(a));
                                        a -= i;

                                        if (i == 0) {
                                                vd[0] += data[c] * (1.0f - a);
                                                yc[0] += (1.0f - a);
                                        }
                                        else if (i == n - 1) {
                                                vd[n - 1] += data[c] * a;
                                                yc[n - 1] += (a);
                                        }
                                        else if (i > 0 && i < (n - 1)) {
                                                vd[i] += data[c] * (1.0f - a);
                                                yc[i] += (1.0f - a);
                                                vd[i + 1] += data[c] * a;
                                                yc[i + 1] += a;
                                        }
                                }
                        }
                }
        }


        for (int i = 0; i < n; i++) {
                vd[i] /= yc[i];
        }

        if( yc )
        {
                delete[]yc;
                yc = 0;
        }

        return vd;

        EXITFUNC;
}
float EMData::calc_center_density ( )

Calculates the density value at the peak of the image histogram, sort of like the mode of the density.

Returns:
The density value at the peak of the image histogram.

Definition at line 255 of file emdata_metadata.cpp.

References ENTERFUNC, EXITFUNC, get_attr(), get_data(), mean(), norm(), nx, ny, and nz.

{
        ENTERFUNC;

        float center = get_attr("mean");
        float sigma = get_attr("sigma");
        float ds = sigma / 2;
        size_t size = (size_t)nx * ny * nz;
        float *d = get_data();
        float sigma1 = sigma / 20;
        float sigma2 = sigma / 1000;

        while (ds > sigma1) {
                double sum = 0;
                int norm = 0;

                for (size_t i = 0; i < size; ++i) {
                        if (fabs(d[i] - center) < ds) {
                                sum += d[i];
                                norm++;
                        }
                }
                if (!norm) {
                        break;
                }
                float mean = (float)(sum / norm);
                if (fabs(mean - center) < sigma2) {
                        ds *= 0.5f;
                }
                center = mean;
        }
        EXITFUNC;

        return center;
}
FloatPoint EMData::calc_center_of_mass ( const float  threshold = 0)

Calculate the center of mass with a threshold (Default 0, so only positive values are considered)

Author:
Steve Ludtke
Date:
Fri Jun 6th 2008

Definition at line 568 of file emdata_metadata.cpp.

References data, get_data(), nx, nxy, ny, and nz.

Referenced by EMAN::FRM2DAligner::align(), and EMAN::ToMassCenterProcessor::process_inplace().

{
        float *data = get_data();

        //float sigma = get_attr("sigma");
        //float mean = get_attr("mean");
        float m = 0.0;

        FloatPoint com(0,0,0);
        for (int i = 0; i < nx; ++i) {
                for (int j = 0; j < ny; ++j) {
                        int j2 = nx * j;
                        for (int k = 0; k < nz; ++k) {
                                size_t l = i + j2 + (size_t)k * nxy;
                                if (data[l] >= threshold) {             // threshold out noise (and negative density)
                                        com[0] += i * data[l];
                                        com[1] += j * data[l];
                                        com[2] += k * data[l];
                                        m += data[l];
                                }
                        }
                }
        }

        com[0] /= m;
        com[1] /= m;
        com[2] /= m;

        return com;
}
float EMData::calc_dist ( EMData second_img,
int  y_index = 0 
) const

Calculates the distance between 2 vectors.

'this' image is 1D, which contains a vector; 'second_img' may be nD. One of its row is used as the second vector. 'second_img' and 'this' must have the same x size.

Parameters:
second_imgThe image used to caculate the distance.
y_indexSpecifies which row in 'second_img' is used to do the caculation.
Exceptions:
ImageDimensionExceptionIf 'this' image is not 1D.
ImageFormatExceptionIf the 2 images don't have same xsize.
Returns:
The distance between 2 vectors.

Definition at line 3248 of file emdata.cpp.

References ENTERFUNC, EXITFUNC, get_data(), get_ndim(), get_xsize(), get_ysize(), ImageDimensionException, ImageFormatException, nx, ny, sqrt(), and square.

{
        ENTERFUNC;

        if (get_ndim() != 1) {
                throw ImageDimensionException("'this' image is 1D only");
        }

        if (second_img->get_xsize() != nx || ny != 1) {
                throw ImageFormatException("image xsize not same");
        }

        if (y_index > second_img->get_ysize() || y_index < 0) {
                return -1;
        }

        float ret = 0;
        float *d1 = get_data();
        float *d2 = second_img->get_data() + second_img->get_xsize() * y_index;

        for (int i = 0; i < nx; i++) {
                ret += Util::square(d1[i] - d2[i]);
        }
        EXITFUNC;
        return std::sqrt(ret);
}
EMData * EMData::calc_fast_sigma_image ( EMData mask)

Calculates the local standard deviation (sigma) image using the given mask image.

The mask image is typically much smaller than this image, and consists of ones, or is a small circle consisting of ones. The extent of the non zero neighborhood explicitly defines the range over which the local standard deviation is determined. Fourier convolution is used to do the math, ala Roseman (2003, Ultramicroscopy) However, Roseman was just working on methods Van Heel had presented earlier. The normalize flag causes the mask image to be processed so that it has a unit sum. Works in 1,2 and 3D

Parameters:
maskthe image that will be used to define the neighborhood for determine the local standard deviation
Returns:
the sigma image, the phase origin is at the corner (not the center)
Exceptions:
ImageDimensionExceptionif the dimensions of with do not match those of this
ImageDimensionExceptionif any of the dimensions sizes of with exceed of this image's.
Author:
David Woolford
Date:
April 2008

Definition at line 3276 of file emdata.cpp.

References clip_inplace(), convolute(), copy(), EMData(), ENTERFUNC, EXITFUNC, get_clip(), get_edge_mean(), get_ndim(), get_size(), get_value_at(), get_xsize(), get_ysize(), get_zsize(), ImageDimensionException, mult(), nx, ny, nz, process_inplace(), and sub().

Referenced by calc_flcf().

{
        ENTERFUNC;

        bool maskflag = false;
        if (mask == 0) {
                mask = new EMData(nx,ny,nz);
                mask->process_inplace("testimage.circlesphere");
                maskflag = true;
        }

        if (get_ndim() != mask->get_ndim() ) throw ImageDimensionException("The dimensions do not match");

        int mnx = mask->get_xsize(); int mny = mask->get_ysize(); int mnz = mask->get_zsize();

        if ( mnx > nx || mny > ny || mnz > nz)
                throw ImageDimensionException("Can not calculate variance map using an image that is larger than this image");

        size_t P = 0;
        for(size_t i = 0; i < mask->get_size(); ++i){
                if (mask->get_value_at(i) != 0){
                        ++P;
                }
        }
        float normfac = 1.0f/(float)P;

//      bool undoclip = false;

        int nxc = nx+mnx; int nyc = ny+mny; int nzc = nz+mnz;
//      if ( mnx < nx || mny < ny || mnz < nz) {
        Region r;
        if (ny == 1) r = Region((mnx-nxc)/2,nxc);
        else if (nz == 1) r = Region((mnx-nxc)/2, (mny-nyc)/2,nxc,nyc);
        else r = Region((mnx-nxc)/2, (mny-nyc)/2,(mnz-nzc)/2,nxc,nyc,nzc);
        mask->clip_inplace(r,0.0);
        //Region r((mnx-nxc)/2, (mny-nyc)/2,(mnz-nzc)/2,nxc,nyc,nzc);
        //mask->clip_inplace(r);
        //undoclip = true;
        //}

        // Here we generate the local average of the squares
        Region r2;
        if (ny == 1) r2 = Region((nx-nxc)/2,nxc);
        else if (nz == 1) r2 = Region((nx-nxc)/2, (ny-nyc)/2,nxc,nyc);
        else r2 = Region((nx-nxc)/2, (ny-nyc)/2,(nz-nzc)/2,nxc,nyc,nzc);
        EMData* squared = get_clip(r2,get_edge_mean());

        EMData* tmp = squared->copy();
        Dict pow;
        pow["pow"] = 2.0f;
        squared->process_inplace("math.pow",pow);
        EMData* s = mask->convolute(squared);//ming, mask squared exchange
        squared->mult(normfac);

        EMData* m = mask->convolute(tmp);//ming, tmp mask exchange
        m->mult(normfac);
        m->process_inplace("math.pow",pow);
        delete tmp; tmp = 0;
        s->sub(*m);
        // Here we finally generate the standard deviation image
        s->process_inplace("math.sqrt");

//      if ( undoclip ) {
//              Region r((nx-mnx)/2, (ny-mny)/2, (nz-mnz)/2,mnx,mny,mnz);
//              mask->clip_inplace(r);
//      }

        if (maskflag) {
                delete mask;
                mask = 0;
        } else {
                Region r;
                if (ny == 1) r = Region((nxc-mnx)/2,mnx);
                else if (nz == 1) r = Region((nxc-mnx)/2, (nyc-mny)/2,mnx,mny);
                else r = Region((nxc-mnx)/2, (nyc-mny)/2,(nzc-mnz)/2,mnx,mny,mnz);
                mask->clip_inplace(r);
        }

        delete squared;
        delete m;

        s->process_inplace("xform.phaseorigin.tocenter");
        Region r3;
        if (ny == 1) r3 = Region((nxc-nx)/2,nx);
        else if (nz == 1) r3 = Region((nxc-nx)/2, (nyc-ny)/2,nx,ny);
        else r3 = Region((nxc-nx)/2, (nyc-ny)/2,(nzc-nz)/2,nx,ny,nz);
        s->clip_inplace(r3);
        EXITFUNC;
        return s;
}
EMData * EMData::calc_flcf ( EMData with)

Calculates the cross correlation with local normalization between 2 images.

This is a faster version of local correlation that make use of Fourier convolution and correlation. With is the template - the thing that you wish to find in the this image. It should not be unecessarily padded. The function uses the size of with to determine the extent of the local neighborhood used in the local normalization (for technical details, see calc_fast_sigma_image). Note that this function circularly masks the template at its radius so the calling function need not do this beforehand. Works in 1,2 and 3D.

Parameters:
withThe image used to calculate cross correlation (the template)
Returns:
the local normalized cross correlation image - the phase origin is at the corner of the image
Author:
David Woolford
Date:
April 2008

Definition at line 3369 of file emdata.cpp.

References calc_ccf(), calc_fast_sigma_image(), clip_inplace(), copy(), div(), EMData(), ENTERFUNC, EXITFUNC, get_xsize(), get_ysize(), get_zsize(), mult(), nx, ny, nz, and process_inplace().

Referenced by EMAN::TranslationalAligner::align().

{
        ENTERFUNC;
        EMData *this_copy=this;
        this_copy=copy();

        int mnx = with->get_xsize(); int mny = with->get_ysize(); int mnz = with->get_zsize();
        int nxc = nx+mnx; int nyc = ny+mny; int nzc = nz+mnz;

        // Ones is a circular/spherical mask, consisting of 1s.
        EMData* ones = new EMData(mnx,mny,mnz);
        ones->process_inplace("testimage.circlesphere");

        // Get a copy of with, we will eventually resize it
        EMData* with_resized = with->copy();
        with_resized->process_inplace("normalize");
        with_resized->mult(*ones);

        EMData* s = calc_fast_sigma_image(ones);// Get the local sigma image

        Region r1;
        if (ny == 1) r1 = Region((mnx-nxc)/2,nxc);
        else if (nz == 1) r1 = Region((mnx-nxc)/2, (mny-nyc)/2,nxc,nyc);
        else r1 = Region((mnx-nxc)/2, (mny-nyc)/2,(mnz-nzc)/2,nxc,nyc,nzc);
        with_resized->clip_inplace(r1,0.0);

        Region r2;
        if (ny == 1) r2 = Region((nx-nxc)/2,nxc);
        else if (nz == 1) r2 = Region((nx-nxc)/2, (ny-nyc)/2,nxc,nyc);
        else r2 = Region((nx-nxc)/2, (ny-nyc)/2,(nz-nzc)/2,nxc,nyc,nzc);
        this_copy->clip_inplace(r2,0.0);

        EMData* corr = this_copy->calc_ccf(with_resized); // the ccf results should have same size as sigma

        corr->process_inplace("xform.phaseorigin.tocenter");
        Region r3;
        if (ny == 1) r3 = Region((nxc-nx)/2,nx);
        else if (nz == 1) r3 = Region((nxc-nx)/2, (nyc-ny)/2,nx,ny);
        else r3 = Region((nxc-nx)/2, (nyc-ny)/2,(nzc-nz)/2,nx,ny,nz);
        corr->clip_inplace(r3);

        corr->div(*s);

        delete with_resized; delete ones; delete this_copy; delete s;
        EXITFUNC;
        return corr;
}
vector< float > EMData::calc_fourier_shell_correlation ( EMData with,
float  w = 1.0f 
)

Calculate CCF in Fourier space as a function of spatial frequency between a pair of 2-3D images (corners not included).

The input image 'with' must have the same size to 'this' image. Input images can be either real or Fourier in arbitrary combination.

Parameters:
[in]withThe image used to caculate the fourier shell
[in]wRing/shell width in Fourier space.
Exceptions:
ImageFormatExceptionIf the 2 images are not same size.
NullPointerExceptionif the input image is null
Cannotcalculate FSC for 1D images
Returns:
Vector of 3*k FSC results (frequencies, FSC values, error) k - length of FSC curve, depends on dimensions of the image and ring width 1 column - normalized frequency [0,0.5] 2 column - FSC, 3 column - error of the FSC = 1/sqrt(n), where n is the number of Fourier coefficients within given shell.

Definition at line 859 of file emdata_sparx.cpp.

References do_fft_inplace(), ENTERFUNC, EXITFUNC, get_data(), get_xsize(), get_ysize(), get_zsize(), ImageFormatException, is_complex(), is_fftodd(), max, norm_pad(), NullPointerException, nx, ny, EMAN::Util::round(), and sqrt().

Referenced by ali3d_d(), and EMAN::FRCCmp::cmp().

{
        ENTERFUNC;

/*
 ******************************************************
 *DISCLAIMER
 * 08/16/05 P.A.Penczek
 * The University of Texas
 * Pawel.A.Penczek@uth.tmc.edu
 * Please do not modify the content of calc_fourier_shell_correlation
 ******************************************************/
/*
Fourier Ring/Shell Correlation
Purpose: Calculate CCF in Fourier space as a function of spatial frequency
         between a pair of 2-3D images.
Method: Calculate FFT (if needed), calculate FSC.
Input:  f - real or complex 2-3D image
        g - real or complex 2-3D image
        w - float ring width
Output: 2D 3xk real image.
        k - length of FSC curve, depends on dimensions of the image and ring width
        1 column - FSC,
        2 column - normalized frequency [0,0.5]
        3 column - currently n /error of the FSC = 1/sqrt(n),
                     where n is the number of Fourier coefficients within given shell
*/
        int needfree=0, kz, ky, ii;
        float  argx, argy, argz;

        if (!with) {
                throw NullPointerException("NULL input image");
        }


        EMData *f = this;
        EMData *g = with;

        int nx  = f->get_xsize();
        int ny  = f->get_ysize();
        int nz  = f->get_zsize();

        if (ny==0 && nz==0) {
                throw ImageFormatException( "Cannot calculate FSC for 1D images");
        }

        if (f->is_complex()) nx = (nx - 2 + f->is_fftodd()); // nx is the real-space size of the input image
        int lsd2 = (nx + 2 - nx%2) ; // Extended x-dimension of the complex image

//  Process f if real
        EMData* fpimage = NULL;
        if (f->is_complex()) fpimage = f;
        else {
                fpimage= f->norm_pad(false, 1); 
                fpimage->do_fft_inplace();
                needfree|=1; // Extend and do the FFT if f is real
        } 

//  Process g if real
        EMData* gpimage = NULL;
        if (g->is_complex()) gpimage = g;
        else {
                gpimage= g->norm_pad(false, 1);
                gpimage->do_fft_inplace();
                needfree|=2;  // Extend and do the FFT if g is real
        }

        float *d1 = fpimage->get_data();
        float *d2 = gpimage->get_data();

        int nx2 = nx/2;
        int ny2 = ny/2;
        int nz2 = nz/2;

        float dx2 = 1.0f/float(nx2)/float(nx2);
        float dy2 = 1.0f/float(ny2)/float(ny2);

#ifdef _WIN32
        float dz2 = 1.0f / _cpp_max(float(nz2),1.0f)/_cpp_max(float(nz2),1.0f);
        int inc = Util::round(float( _cpp_max( _cpp_max(nx2,ny2),nz2) )/w );
#else
        float dz2 = 1.0f/std::max(float(nz2),1.0f)/std::max(float(nz2),1.0f);
        int inc = Util::round(float(std::max(std::max(nx2,ny2),nz2))/w);
#endif  //_WIN32

        double* ret = new double[inc+1];
        double* n1 = new double[inc+1];
        double* n2 = new double[inc+1];
        float*  lr = new float[inc+1];
        for (int i = 0; i <= inc; i++) {
                ret[i] = 0.0f; n1[i] = 0.0f; n2[i] = 0.0f; lr[i]=0.0f;
        }

        for (int iz = 0; iz <= nz-1; iz++) {
                if(iz>nz2) kz=iz-nz; else kz=iz; argz = float(kz*kz)*dz2;
                for (int iy = 0; iy <= ny-1; iy++) {
                        if(iy>ny2) ky=iy-ny; else ky=iy; argy = argz + float(ky*ky)*dy2;
                        for (int ix = 0; ix <= lsd2-1; ix+=2) {
                        // Skip Friedel related values
                                if (ix>0 || (kz>=0 && (ky>=0 || kz!=0))) {
                                        argx = 0.5f*std::sqrt(argy + float(ix*ix)*0.25f*dx2);
                                        int r = Util::round(inc*2*argx);
                                        if(r <= inc) {
                                                ii = ix + (iy  + iz * ny)* lsd2;
                                                ret[r] += d1[ii] * double(d2[ii]) + d1[ii + 1] * double(d2[ii + 1]);
                                                n1[r]  += d1[ii] * double(d1[ii]) + d1[ii + 1] * double(d1[ii + 1]);
                                                n2[r]  += d2[ii] * double(d2[ii]) + d2[ii + 1] * double(d2[ii + 1]);
                                                lr[r]  += 2.0f;
                                        }
                                }
                        }
                }
        }

        int  linc = 0;
        for (int i = 0; i <= inc; i++) if(lr[i]>0) linc++;

        vector<float> result(linc*3);

        ii = -1;
        for (int i = 0; i <= inc; i++) {
                if(lr[i]>0) {
                        ii++;
                        result[ii]        = float(i)/float(2*inc);
                        result[ii+linc]   = float(ret[i] / (std::sqrt(n1[i] * n2[i])));
                        result[ii+2*linc] = lr[i]  /*1.0f/sqrt(float(lr[i]))*/;
                }
                /*else {
                        result[i]           = 0.0f;
                        result[i+inc+1]     = 0.0f;
                        result[i+2*(inc+1)] = 0.0f;}*/
        }

        if (needfree&1) {
                if (fpimage) {
                        delete fpimage;
                        fpimage = 0;
                }
        }
        if (needfree&2) {
                if (gpimage) {
                        delete gpimage;
                        gpimage = 0;
                }
        }
        delete[] ret; delete[]  n1; delete[]  n2; delete[]  lr;

        EXITFUNC;
        return result;
}
vector< Pixel > EMData::calc_highest_locations ( float  threshold) const

Calculate and return a sorted list of pixels whose values are above a specified threshold.

The pixels are sorted from high to low.

Parameters:
thresholdThe specified pixel value. Returned pixels should have higher values than it.
Returns:
A sorted list of pixels with their values, and locations. Their values are higher than threshold.

Definition at line 616 of file emdata_metadata.cpp.

References data, ENTERFUNC, EXITFUNC, get_data(), is_complex(), is_ri(), nx, nxy, ny, nz, and v.

Referenced by EMAN::DistanceSegmentProcessor::process().

{
        ENTERFUNC;

        vector<Pixel> result;

        int di = 1;
        if (is_complex() && !is_ri()) {
                di = 2;
        }

        int nxy = nx * ny;
        float * data = get_data();

        for (int j = 0; j < nz; ++j) {
                size_t cur_z = (size_t)j * nxy;

                for (int k = 0; k < ny; ++k) {
                        size_t cur_y = k * nx + cur_z;

                        for (int l = 0; l < nx; l += di) {
                                float v =data[l + cur_y];
                                if (v > threshold) {
                                        result.push_back(Pixel(l, k, j, v));
                                }
                        }
                }
        }

        std::sort(result.begin(), result.end());

        EXITFUNC;
        return result;
}
vector< float > EMData::calc_hist ( int  hist_size = 128,
float  hist_min = 0,
float  hist_max = 0,
const float &  brt = 0.0f,
const float &  cont = 1.0f 
)

Calculates the histogram of 'this' image.

The result is stored in float array 'hist'. If hist_min = hist_max, use image data min as hist_min; use image data max as hist_max.

Parameters:
hist_sizeHistogram array's size.
hist_minMinimum histogram value.
hist_maxMaximum histogram value.
brt
cont
Returns:
histogram array of this image.

Definition at line 2319 of file emdata.cpp.

References data, ENTERFUNC, EXITFUNC, get_attr(), get_data(), is_complex(), nx, ny, nz, and EMAN::Util::round().

{
        ENTERFUNC;

        static size_t prime[] = { 1, 3, 7, 11, 17, 23, 37, 59, 127, 253, 511 };

        if (histmin == histmax) {
                histmin = get_attr("minimum");
                histmax = get_attr("maximum");
        }

        vector <float> hist(hist_size, 0.0);

        int p0 = 0;
        int p1 = 0;
        size_t size = (size_t)nx * ny * nz;
        if (size < 300000) {
                p0 = 0;
                p1 = 0;
        }
        else if (size < 2000000) {
                p0 = 2;
                p1 = 3;
        }
        else if (size < 8000000) {
                p0 = 4;
                p1 = 6;
        }
        else {
                p0 = 7;
                p1 = 9;
        }

        if (is_complex() && p0 > 0) {
                p0++;
                p1++;
        }

        size_t di = 0;
//      float norm = 0;
        size_t n = hist.size();

        float * data = get_data();
        for (int k = p0; k <= p1; ++k) {
                if (is_complex()) {
                        di = prime[k] * 2;
                }
                else {
                        di = prime[k];
                }

//              norm += (float)size / (float) di;
                float w = (float)n / (histmax - histmin);

                for(size_t i=0; i<=size-di; i += di) {
                        float val;
                        if (cont != 1.0f || brt != 0)val = cont*(data[i]+brt);
                        else val = data[i];
                        int j = Util::round((val - histmin) * w);
                        if (j >= 0 && j < (int) n) {
                                hist[j] += 1;
                        }
                }
        }
/*
        for (size_t i = 0; i < hist.size(); ++i) {
                if (norm != 0) {
                        hist[i] = hist[i] / norm;
                }
        }
*/
        return hist;

        EXITFUNC;
}
size_t EMData::calc_max_index ( ) const

Calculates the index of maximum-value pixel when assuming all pixels are in a 1D array.

Returns:
Index of the maximum-value pixel.

Definition at line 608 of file emdata_metadata.cpp.

References calc_max_location(), nx, and ny.

Referenced by EMAN::RTFExhaustiveAligner::align().

{
        IntPoint max_location = calc_max_location();
        size_t i = max_location[0] + max_location[1] * nx + (size_t)max_location[2] * nx * ny;
        return i;
}
IntPoint EMData::calc_max_location ( ) const

Calculates the coordinates of the maximum-value pixel.

Returns:
The coordinates of the maximum-value pixel.

Definition at line 367 of file emdata_metadata.cpp.

References data, ENTERFUNC, EXITFUNC, get_data(), is_complex(), is_ri(), max, nx, nxy, ny, nz, and t.

Referenced by calc_max_index().

{
        ENTERFUNC;

        int di = 1;
        if (is_complex() && !is_ri()) {
                di = 2;
        }

        float max = -FLT_MAX;
        int max_x = 0;
        int max_y = 0;
        int max_z = 0;
        int nxy = nx * ny;
        float * data = get_data();

        for (int j = 0; j < nz; ++j) {
                size_t cur_z = (size_t)j * nxy;

                for (int k = 0; k < ny; ++k) {
                        size_t cur_y = k * nx + cur_z;

                        for (int l = 0; l < nx; l += di) {
                                float t = data[l + cur_y];
                                if (t > max) {
                                        max_x = l;
                                        max_y = k;
                                        max_z = j;
                                        max = t;
                                }
                        }
                }
        }

        EXITFUNC;
        return IntPoint(max_x, max_y, max_z);
}
IntPoint EMData::calc_max_location_wrap ( const int  maxshiftx = -1,
const int  maxshifty = -1,
const int  maxshiftz = -1 
)

Calculates the wrapped coordinates of the maximum value This function is useful in the context of Fourier correlation you can call this function to find the correct translational shift when using calc_ccf etc.

Returns:
the wrapped coordinates of the maximum
Author:
David Woolford
Date:
Fri Jun 6th 2008

Definition at line 406 of file emdata_metadata.cpp.

References calc_max_location_wrap_cuda(), get_value_at_wrap(), get_xsize(), get_ysize(), get_zsize(), nx, ny, nz, CudaPeakInfo::px, CudaPeakInfo::py, and CudaPeakInfo::pz.

Referenced by EMAN::Refine3DAlignerGrid::align(), EMAN::TranslationalAligner::align(), EMAN::RT3DSphereAligner::xform_align_nbest(), and EMAN::RT3DGridAligner::xform_align_nbest().

{
        int maxshiftx = maxdx, maxshifty = maxdy, maxshiftz = maxdz;
        if (maxdx == -1) maxshiftx = get_xsize()/4;
        if (maxdy == -1) maxshifty = get_ysize()/4;
        if (maxdz == -1) maxshiftz = get_zsize()/4;

        float max_value = -FLT_MAX;

        IntPoint peak(0,0,0);
        
#ifdef EMAN2_USING_CUDA //CUDA
        if(EMData::usecuda == 1 && cudarwdata){
        
                CudaPeakInfo* soln = calc_max_location_wrap_cuda(cudarwdata, nx, ny, nz, maxdx, maxdy, maxdz);
                
                peak[0] = soln->px;
                peak[1] = soln->py;
                peak[2] = soln->pz;
                free(soln);
                
//              cout << "x " << peak[0] << " y " << peak[1] << " z " << peak[2] << endl;
                return peak;
        }
#endif
        for (int k = -maxshiftz; k <= maxshiftz; k++) {
                for (int j = -maxshifty; j <= maxshifty; j++) {
                        for (int i = -maxshiftx; i <= maxshiftx; i++) {

                                float value = get_value_at_wrap(i,j,k);

                                if (value > max_value) {
                                        max_value = value;
                                        peak[0] = i;
                                        peak[1] = j;
                                        peak[2] = k;
                                }
                        }
                }
        }

        return peak;
}
vector< float > EMData::calc_max_location_wrap_intp ( const int  maxshiftx = -1,
const int  maxshifty = -1,
const int  maxshiftz = -1 
)

Calculates the wrapped coordinates of the maximum value, and uses quadration intp to subpixel prec This function is useful in the context of Fourier correlation you can call this function to find the correct translational shift when using calc_ccf etc.

Returns:
the wrapped coordinates of the maximum
Author:
John Flanagan
Date:
Mon Mar 7th 2011

#ifdef EMAN2_USING_CUDA //CUDA if(cudarwdata){

CudaPeakInfo* soln = calc_max_location_wrap_cuda(cudarwdata, nx, ny, nz, maxdx, maxdy, maxdz);

peak[0] = soln->px; peak[1] = soln->py; peak[2] = soln->pz; free(soln);

cout << "x " << peak[0] << " y " << peak[1] << " z " << peak[2] << endl; return peak; } #endif

I guess I could use GSL, but this is faster.... float x1 = float(peak[0]) - 1.0f; float x2 = float(peak[0]); float x3 = float(peak[0]) + 1.0f; float y1 = float(peak[1]) - 1.0f; float y2 = float(peak[1]); float y3 = float(peak[1]) + 1.0f; float z1 = float(peak[2]) - 1.0f; float z2 = float(peak[2]); float z3 = float(peak[2]) + 1.0f;

float yx1 = get_value_at_wrap(x1,y2,z2); float yx2 = get_value_at_wrap(x2,y2,z2); float yx3 = get_value_at_wrap(x3,y2,z2); float yy1 = get_value_at_wrap(x2,y1,z2); float yy2 = get_value_at_wrap(x2,y2,z2); float yy3 = get_value_at_wrap(x2,y3,z2); float yz1 = get_value_at_wrap(x2,y2,z1); float yz2 = get_value_at_wrap(x2,y2,z2); float yz3 = get_value_at_wrap(x2,y2,z3);

Fit peak in X to y = ax^2 + bx +c float bx = ((yx1 - yx2)*(x2*x2 - x3*x3)/(x1*x1 - x2*x2) - (yx2-yx3))/(-(x2 - x3) + (x1 - x2)*(x2*x2 - x3*x3)/(x1*x1 - x2*x2)); float ax = ((yx1 - yx2) - bx*(x1 - x2))/(x1*x1 - x2*x2); Find minima float xintp = -bx/(2*ax);

Fit peak in X to y = ax^2 + bx +c float by = ((yy1 - yy2)*(x2*x2 - x3*x3)/(x1*x1 - x2*x2) - (yy2-yy3))/(-(x2 - x3) + (x1 - x2)*(x2*x2 - x3*x3)/(x1*x1 - x2*x2)); float ay = ((yy1 - yy2) - by*(x1 - x2))/(x1*x1 - x2*x2); Find minima float yintp = -by/(2*ay);

Fit peak in X to y = ax^2 + bx +c float bz = ((yz1 - yz2)*(x2*x2 - x3*x3)/(x1*x1 - x2*x2) - (yz2-yz3))/(-(x2 - x3) + (x1 - x2)*(x2*x2 - x3*x3)/(x1*x1 - x2*x2)); float az = ((yz1 - yz2) - bz*(x1 - x2))/(x1*x1 - x2*x2); Find minima float zintp = -bz/(2*az);

vector<float> mydata; mydata.push_back(xintp); mydata.push_back(yintp); mydata.push_back(zintp); mydata.push_back(max_value);

Definition at line 450 of file emdata_metadata.cpp.

References get_value_at_wrap(), get_xsize(), get_ysize(), get_zsize(), x, and y.

{
        int maxshiftx = maxdx, maxshifty = maxdy, maxshiftz = maxdz;
        if (maxdx == -1) maxshiftx = get_xsize()/4;
        if (maxdy == -1) maxshifty = get_ysize()/4;
        if (maxdz == -1) maxshiftz = get_zsize()/4;

        float max_value = -FLT_MAX;

        IntPoint peak(0,0,0);

// NOT yet working......
        for (int k = -maxshiftz; k <= maxshiftz; k++) {
                for (int j = -maxshifty; j <= maxshifty; j++) {
                        for (int i = -maxshiftx; i <= maxshiftx; i++) {

                                float value = get_value_at_wrap(i,j,k);

                                if (value > max_value) {
                                        max_value = value;
                                        peak[0] = i;
                                        peak[1] = j;
                                        peak[2] = k;
                                }
                        }
                }
        }
        
        // compute the center of mass
        float cmx = 0.0; float cmy = 0.0f; float cmz = 0.0f;
        float sval = 0.0f;
        for (float x = float(peak[0])-2.0f; x <= float(peak[0])+2.0f; x++) {
                for (float y = float(peak[1])-2.0f; y <= float(peak[1])+2.0f; y++) {
                        for (float z = float(peak[2])-2.0f; z <= float(peak[2])+2.0f; z++) {
                                //Compute center of mass
                                float val = get_value_at_wrap(x,y,z);
                                cmx += x*val;
                                cmy += y*val;
                                cmz += z*val;
                                sval += val;
                        }
                }
        }
        cmx /= sval;
        cmy /= sval;
        cmz /= sval;

        vector<float> mydata;
        mydata.push_back(cmx);
        mydata.push_back(cmy);
        mydata.push_back(cmz);
        mydata.push_back(max_value);

        return mydata;
}
size_t EMData::calc_min_index ( ) const

Calculates the index of minimum-value pixel when assuming all pixels are in a 1D array.

Returns:
Index of the minimum-value pixel.

Definition at line 600 of file emdata_metadata.cpp.

References calc_min_location(), nx, and ny.

{
        IntPoint min_location = calc_min_location();
        size_t i = min_location[0] + min_location[1] * nx + (size_t)min_location[2] * nx * ny;
        return i;
}
IntPoint EMData::calc_min_location ( ) const

Calculates the coordinates of the minimum-value pixel.

Returns:
The coordinates of the minimum-value pixel.

Definition at line 329 of file emdata_metadata.cpp.

References data, ENTERFUNC, get_data(), is_complex(), is_ri(), min, nx, nxy, ny, nz, and t.

Referenced by calc_min_index().

{
        ENTERFUNC;

        int di = 1;
        if (is_complex() && !is_ri()) {
                di = 2;
        }

        float min = FLT_MAX;
        int min_x = 0;
        int min_y = 0;
        int min_z = 0;
        int nxy = nx * ny;
        float * data = get_data();

        for (int j = 0; j < nz; ++j) {
                size_t cur_z = (size_t)j * nxy;

                for (int k = 0; k < ny; ++k) {
                        size_t cur_y = k * nx + cur_z;

                        for (int l = 0; l < nx; l += di) {
                                float t = data[l + cur_y];
                                if (t < min) {
                                        min_x = l;
                                        min_y = k;
                                        min_z = j;
                                        min = t;
                                }
                        }
                }
        }

        return IntPoint(min_x, min_y, min_z);
}
EMData * EMData::calc_mutual_correlation ( EMData with,
bool  tocorner = false,
EMData filter = 0 
)

Calculates mutual correlation function (MCF) between 2 images.

If 'with' is NULL, this does mirror ACF.

Parameters:
withThe image used to calculate MCF.
tocornerSet whether to translate the result image to the corner.
filterThe filter image used in calculating MCF.
Exceptions:
ImageFormatExceptionIf 'with' is not NULL and it doesn't have the same size to 'this' image.
NullPointerExceptionIf FFT returns NULL image.
Returns:
Mutual correlation function image.

Definition at line 2163 of file emdata.cpp.

References ap2ri(), copy(), do_fft(), do_ift(), ENTERFUNC, EXITFUNC, get_data(), get_xsize(), get_ysize(), get_zsize(), ImageFormatException, EMAN::EMUtil::is_same_size(), LOGERR, mcf_cuda(), mult(), mult_complex_efficient(), mult_complex_efficient_cuda(), NullPointerException, process_inplace(), set_attr(), set_path(), sqrt(), square, t, and update().

Referenced by make_rotational_footprint_cmc(), and make_rotational_footprint_e1().

{
        ENTERFUNC;

        if (with && !EMUtil::is_same_size(this, with)) {
                LOGERR("images not same size");
                throw ImageFormatException( "images not same size");
        }

#ifdef EMAN2_USING_CUDA
        if(EMData::usecuda == 1 && cudarwdata && with->cudarwdata)
        {       

                EMData* this_fft = do_fft_cuda();

                EMData *cf = 0;
                if (with && with != this) {
                        cf = with->do_fft_cuda();
                }else{
                        cf = this_fft->copy();
                }
                
                if (filter) {
                        if (!EMUtil::is_same_size(filter, cf)) {
                                LOGERR("improperly sized filter");
                                throw ImageFormatException("improperly sized filter");
                        }
                        mult_complex_efficient_cuda(cf->cudarwdata, filter->cudarwdata, cf->get_xsize(), cf->get_ysize(), cf->get_zsize(), 1);
                        mult_complex_efficient_cuda(this_fft->cudarwdata, filter->cudarwdata, this_fft->get_xsize(), this_fft->get_ysize(), this_fft->get_zsize(), 1);
                }
                
                mcf_cuda(this_fft->cudarwdata, cf->cudarwdata, this_fft->get_xsize(), this_fft->get_ysize(), this_fft->get_zsize());
                
                EMData *f2 = cf->do_ift_cuda();

                if (tocenter) {
                        f2->process_inplace("xform.phaseorigin.tocenter");
                }

                if( cf )
                {
                        delete cf;
                        cf = 0;
                }

                if( this_fft )
                {
                        delete this_fft;
                        this_fft = 0;
                }

                f2->set_attr("label", "MCF");
                f2->set_path("/tmp/eman.mcf");
                f2->update();

                EXITFUNC;
                return f2;
        }
#endif

        EMData *this_fft = 0;
        this_fft = do_fft();

        if (!this_fft) {

                LOGERR("FFT returns NULL image");
                throw NullPointerException("FFT returns NULL image");
        }

        this_fft->ap2ri(); //this is not needed!
        EMData *cf = 0;

        if (with && with != this) {
                cf = with->do_fft();
                if (!cf) {
                        LOGERR("FFT returns NULL image");
                        throw NullPointerException("FFT returns NULL image");
                }
                cf->ap2ri(); //nor is this!
        }
        else {
                cf = this_fft->copy();
        }
        
        if (filter) {
                if (!EMUtil::is_same_size(filter, cf)) {
                        LOGERR("improperly sized filter");
                        throw ImageFormatException("improperly sized filter");
                }
                
                cf->mult_complex_efficient(*filter,true); //insanely this is required....
                this_fft->mult(*filter,true);
                //cf->mult_complex_efficient(*filter,7); // takes advantage of the fact that the filter is 1 everywhere but near the origin
                //this_fft->mult_complex_efficient(*filter,7);
                /*cf->mult_complex_efficient(*filter,5);
                this_fft->mult_complex_efficient(*filter,5);*/
        }

        float *rdata1 = this_fft->get_data();
        float *rdata2 = cf->get_data();
        size_t this_fft_size = (size_t)this_fft->get_xsize() * this_fft->get_ysize() * this_fft->get_zsize();

        if (with == this) {
                for (size_t i = 0; i < this_fft_size; i += 2) {
                        rdata2[i] = std::sqrt(rdata1[i] * rdata2[i] + rdata1[i + 1] * rdata2[i + 1]);
                        rdata2[i + 1] = 0;
                }

                this_fft->update();
                cf->update();
        }
        else {
                for (size_t i = 0; i < this_fft_size; i += 2) {
                        rdata2[i] = (rdata1[i] * rdata2[i] + rdata1[i + 1] * rdata2[i + 1]);
                        rdata2[i + 1] = (rdata1[i + 1] * rdata2[i] - rdata1[i] * rdata2[i + 1]);
                }
                
                //This seems like a bug, but it probably is never used....
                for (size_t i = 0; i < this_fft_size; i += 2) {
                        float t = Util::square(rdata2[i]) + Util::square(rdata2[i + 1]);
                        if (t != 0) {
                                t = pow(t, 0.25f);
                                rdata2[i] /= t;
                                rdata2[i + 1] /= t;
                        }
                }
                this_fft->update();
                cf->update();
        }

        EMData *f2 = cf->do_ift();

        if (tocenter) {
                f2->process_inplace("xform.phaseorigin.tocenter");
        }

        if( cf )
        {
                delete cf;
                cf = 0;
        }

        if( this_fft )
        {
                delete this_fft;
                this_fft = 0;
        }

        f2->set_attr("label", "MCF");
        f2->set_path("/tmp/eman.mcf");

        EXITFUNC;
        return f2;
}
vector< Pixel > EMData::calc_n_highest_locations ( int  n)

Calculate and return a sorted list of N highest pixels in the map.

Parameters:
nThe number of highest value pixels should be returned.
Returns:
A sorted list of N pixels with their values, and locations.

Definition at line 651 of file emdata_metadata.cpp.

References data, ENTERFUNC, EXITFUNC, get_data(), is_complex(), is_ri(), nx, nxy, ny, nz, and v.

Referenced by EMAN::AutoMask3D2Processor::process_inplace(), and EMAN::AutoMask2DProcessor::process_inplace().

{
        ENTERFUNC;

        vector<Pixel> result;

        int di = 1;
        if (is_complex() && !is_ri()) {
                di = 2;
        }

        // initialize with n elements
        float * data = get_data();
        for ( int i=0; i<n; i++) result.push_back(Pixel(0,0,0,data[0]));

        int nxy = nx * ny;

        for (int j = 0; j < nz; ++j) {
                size_t cur_z = (size_t)j * nxy;

                for (int k = 0; k < ny; ++k) {
                        size_t cur_y = k * nx + cur_z;

                        for (int l = 0; l < nx; l += di) {
                                float v =data[l + cur_y];
                                if (v<result[n-1].value) continue;
                                for (vector<Pixel>::iterator i=result.begin(); i<result.end(); i++) {
                                        if (v>(*i).value) { result.insert(i,Pixel(l, k, j, v)); result.pop_back(); break; }
                                }
                        }
                }
        }

        EXITFUNC;
        return result;
}
vector< float > EMData::calc_radial_dist ( int  n,
float  x0,
float  dx,
int  nwedge,
float  offset,
bool  inten 
)

calculates radial distribution subdivided by angle.

works for real and imaginary images. 2-D only. The first returns a single vector of n*nwedge points, with radius varying first. That is, the first n points represent the radial profile in the first wedge.

Parameters:
nnumber of points.
x0starting x coordinate.
dxstep of x.
nwedgeint number of wedges to divide the circle into
nwedgefloat angular offset in radians for start of first bin
intenreturns intensity (amp^2) rather than amplitude if set
Exceptions:
ImageDimensionExceptionIf 'this' image is not 2D.
Returns:
nwedge radial distributions packed into a single vector<float>

Definition at line 2832 of file emdata.cpp.

References data, ENTERFUNC, EXITFUNC, get_attr_default(), get_data(), ImageDimensionException, InvalidParameterException, is_complex(), is_ri(), LOGERR, norm(), nx, ny, nz, v, x, and y.

{
        ENTERFUNC;

        if (nz > 1) {
                LOGERR("2D images only.");
                throw ImageDimensionException("2D images only");
        }
        int isinten=get_attr_default("is_intensity",0);

        if (isinten&&!inten) { throw InvalidParameterException("Must set inten for calc_radial_dist with intensity image"); }


        vector<float>ret(n*nwedge);
        vector<float>norm(n*nwedge);

        int x,y,i;
        int step=is_complex()?2:1;
        float astep=static_cast<float>(M_PI*2.0/nwedge);
        if (is_complex()) astep/=2;                                                     // Since we only have the right 1/2 of Fourier space
        float* data = get_data();
        for (i=0; i<n*nwedge; i++) ret[i]=norm[i]=0.0;

        // We do 2D separately to avoid the hypot3 call
        for (y=i=0; y<ny; y++) {
                for (x=0; x<nx; x+=step,i+=step) {
                        float r,v,a;
                        int bin;
                        if (is_complex()) {
#ifdef  _WIN32
                                r=static_cast<float>(_hypot(x/2.0,y<ny/2?y:ny-y));              // origin at 0,0; periodic
#else
                                r=static_cast<float>(hypot(x/2.0,y<ny/2?y:ny-y));               // origin at 0,0; periodic
#endif
                                a=atan2(float(y<ny/2?y:y-ny),x/2.0f);
                                if (!inten) {
#ifdef  _WIN32
                                        if (is_ri()) v=static_cast<float>(_hypot(data[i],data[i+1]));   // real/imag, compute amplitude
#else
                                        if (is_ri()) v=static_cast<float>(hypot(data[i],data[i+1]));    // real/imag, compute amplitude
#endif  //_WIN32
                                        else v=data[i];                                                 // amp/phase, just get amp
                                } else {
                                        if (isinten) v=data[i];
                                        else if (is_ri()) v=data[i]*data[i]+data[i+1]*data[i+1];
                                        else v=data[i]*data[i];
                                }
                                bin=n*int(floor((a+M_PI/2.0f+offset)/astep));
                        }
                        else {
#ifdef  _WIN32
                                r=static_cast<float>(_hypot(x-nx/2,y-ny/2));
#else
                                r=static_cast<float>(hypot(x-nx/2,y-ny/2));
#endif  //_WIN32
                                a=atan2(float(y-ny/2),float(x-nx/2));
                                if (inten) v=data[i]*data[i];
                                else v=data[i];
                                bin=n*int(floor((a+M_PI+offset)/astep));
                        }
                        if (bin>=nwedge*n) bin-=nwedge*n;
                        if (bin<0) bin+=nwedge*n;
                        r=(r-x0)/dx;
                        int f=int(r);   // safe truncation, so floor isn't needed
                        r-=float(f);    // r is now the fractional spacing between bins
//                      printf("%d %d %d %d %1.3f %1.3f\n",x,y,bin,f,r,a);
                        if (f>=0 && f<n) {
                                ret[f+bin]+=v*(1.0f-r);
                                norm[f+bin]+=(1.0f-r);
                                if (f<n-1) {
                                        ret[f+1+bin]+=v*r;
                                        norm[f+1+bin]+=r;
                                }
                        }
                }
        }

        for (i=0; i<n*nwedge; i++) ret[i]/=norm[i]?norm[i]:1.0f;        // Normalize
        EXITFUNC;

        return ret;
}
vector< float > EMData::calc_radial_dist ( int  n,
float  x0,
float  dx,
bool  inten 
)

calculates radial distribution.

works for real and imaginary images. Returns mean radial amplitude, or intensity if inten is set. Note that the complex origin is at (0,0), with periodic boundaries. Note that the inten option is NOT equivalent to returning amplitude and squaring the result.

Parameters:
nnumber of points.
x0starting point x coordinate.
dxstep of x.
intenreturns intensity (amp^2) rather than amplitude if set
Returns:
The radial distribution in an array.

Definition at line 2724 of file emdata.cpp.

References data, ENTERFUNC, EXITFUNC, get_attr_default(), get_data(), EMAN::Util::hypot3(), EMAN::Util::hypot_fast(), InvalidParameterException, is_complex(), is_ri(), norm(), nx, ny, nz, v, x, and y.

Referenced by EMAN::FRCCmp::cmp(), EMAN::OptVarianceCmp::cmp(), EMAN::MatchSFProcessor::create_radial_func(), EMAN::CtfCAutoAverager::finish(), EMAN::CtfCWautoAverager::finish(), main(), EMAN::CTFSNRWeightProcessor::process_inplace(), EMAN::RotationalSubstractProcessor::process_inplace(), EMAN::RotationalAverageProcessor::process_inplace(), EMAN::NonConvexProcessor::process_inplace(), and EMAN::FourierAnlProcessor::process_inplace().

{
        ENTERFUNC;

        vector<float>ret(n);
        vector<float>norm(n);

        int x,y,z,i;
        int step=is_complex()?2:1;
        int isinten=get_attr_default("is_intensity",0);

        if (isinten&&!inten) { throw InvalidParameterException("Must set inten for calc_radial_dist with intensity image"); }

        for (i=0; i<n; i++) ret[i]=norm[i]=0.0;
        float * data = get_data();

        // We do 2D separately to avoid the hypot3 call
        if (nz==1) {
                for (y=i=0; y<ny; y++) {
                        for (x=0; x<nx; x+=step,i+=step) {
                                float r,v;
                                if (step==2) {          //complex
                                        if (x==0 && y>ny/2) continue;
                                        r=(float)(Util::hypot_fast(x/2,y<ny/2?y:ny-y));         // origin at 0,0; periodic
                                        if (!inten) {
#ifdef  _WIN32
                                                if (is_ri()) v=static_cast<float>(_hypot(data[i],data[i+1]));   // real/imag, compute amplitude
#else
                                                if (is_ri()) v=static_cast<float>(hypot(data[i],data[i+1]));    // real/imag, compute amplitude
#endif
                                                else v=data[i];                                                 // amp/phase, just get amp
                                        } else {
                                                if (isinten) v=data[i];
                                                else if (is_ri()) v=data[i]*data[i]+data[i+1]*data[i+1];
                                                else v=data[i]*data[i];
                                        }
                                }
                                else {
                                        r=(float)(Util::hypot_fast(x-nx/2,y-ny/2));
                                        if (inten) v=data[i]*data[i];
                                        else v=data[i];
                                }
                                r=(r-x0)/dx;
                                int f=int(r);   // safe truncation, so floor isn't needed
                                r-=float(f);    // r is now the fractional spacing between bins
//                              printf("%d\t%d\t%d\t%1.3f\t%d\t%1.3f\t%1.4g\n",x,y,f,r,step,Util::hypot_fast(x/2,y<ny/2?y:ny-y),v);
                                if (f>=0 && f<n) {
                                        ret[f]+=v*(1.0f-r);
                                        norm[f]+=(1.0f-r);
                                        if (f<n-1) {
                                                ret[f+1]+=v*r;
                                                norm[f+1]+=r;
                                        }
                                }
                        }
                }
        }
        else {
                size_t i;       //3D file may have >2G size
                for (z=i=0; z<nz; ++z) {
                        for (y=0; y<ny; ++y) {
                                for (x=0; x<nx; x+=step,i+=step) {
                                        float r,v;
                                        if (step==2) {  //complex
                                                if (x==0 && z<nz/2) continue;
                                                if (x==0 && z==nz/2 && y<ny/2) continue;
                                                r=Util::hypot3(x/2,y<ny/2?y:ny-y,z<nz/2?z:nz-z);        // origin at 0,0; periodic
                                                if (!inten) {
#ifdef  _WIN32
                                                        if (is_ri()) v=static_cast<float>(_hypot(data[i],data[i+1]));   // real/imag, compute amplitude
#else
                                                        if (is_ri()) v=static_cast<float>(hypot(data[i],data[i+1]));    // real/imag, compute amplitude
#endif  //_WIN32
                                                        else v=data[i];                                                 // amp/phase, just get amp
                                                } else {
                                                        if (isinten) v=data[i];
                                                        else if (is_ri()) v=data[i]*data[i]+data[i+1]*data[i+1];
                                                        else v=data[i]*data[i];
                                                }
                                        }
                                        else {
                                                r=Util::hypot3(x-nx/2,y-ny/2,z-nz/2);
                                                if (inten) v=data[i]*data[i];
                                                else v=data[i];
                                        }
                                        r=(r-x0)/dx;
                                        int f=int(r);   // safe truncation, so floor isn't needed
                                        r-=float(f);    // r is now the fractional spacing between bins
                                        if (f>=0 && f<n) {
                                                ret[f]+=v*(1.0f-r);
                                                norm[f]+=(1.0f-r);
                                                if (f<n-1) {
                                                        ret[f+1]+=v*r;
                                                        norm[f+1]+=r;
                                                }
                                        }
                                }
                        }
                }
        }

        for (i=0; i<n; i++) ret[i]/=norm[i]?norm[i]:1.0f;       // Normalize

        EXITFUNC;

        return ret;
}
float EMData::calc_sigma_diff ( )

Calculates sigma above and below the mean and returns the difference between them.

Returns:
The difference between sigma above and below the mean.

Definition at line 292 of file emdata_metadata.cpp.

References ENTERFUNC, EXITFUNC, get_attr(), get_data(), mean(), nx, ny, nz, sqrt(), and square.

{
        ENTERFUNC;

        float *d = get_data();
        float mean = get_attr("mean");
        float sigma = get_attr("sigma");

        double sum_up = 0;
        double sum_down = 0;
        int nup = 0;
        int ndown = 0;

        size_t size = (size_t)nx * ny * nz;

        for (size_t i = 0; i < size; ++i) {
                if (d[i] > mean) {
                        sum_up += Util::square(d[i] - mean);
                        nup++;
                }
                else {
                        sum_down += Util::square(mean - d[i]);
                        ndown++;
                }
        }

        float sigup = std::sqrt((float)sum_up / nup);
        float sigdown = std::sqrt((float)sum_down / ndown);
        float sig_diff = fabs(sigup - sigdown) / sigma;


        EXITFUNC;
        return sig_diff;

}
void EMData::cconj ( )

Replace the image its complex conjugate.

Exceptions:
ImageFormatExceptionImage must be complex (and RI)

Definition at line 2915 of file emdata.cpp.

References cmplx(), ENTERFUNC, EXITFUNC, ImageFormatException, is_complex(), is_fftodd(), is_ri(), nx, ny, and nz.

                   {
        ENTERFUNC;
        if (!is_complex() || !is_ri())
                throw ImageFormatException("EMData::conj requires a complex, ri image");
        int nxreal = nx -2 + int(is_fftodd());
        int nxhalf = nxreal/2;
        for (int iz = 0; iz < nz; iz++)
                for (int iy = 0; iy < ny; iy++)
                        for (int ix = 0; ix <= nxhalf; ix++)
                                cmplx(ix,iy,iz) = conj(cmplx(ix,iy,iz));
        EXITFUNC;
}
void EMData::center_origin ( )

Definition at line 6914 of file emdata_sparx.cpp.

References ENTERFUNC, EXITFUNC, ImageFormatException, is_complex(), LOGERR, nx, ny, and update().

{
        ENTERFUNC;
        if (is_complex()) {
                LOGERR("Real image expected. Input image is complex.");
                throw ImageFormatException("Real image expected. Input image is complex.");
        }
        for (int iz = 0; iz < nz; iz++) {
                for (int iy = 0; iy < ny; iy++) {
                        for (int ix = 0; ix < nx; ix++) {
                                // next line multiplies by +/- 1
                                (*this)(ix,iy,iz) *= -2*((ix+iy+iz)%2) + 1;
                        }
                }
        }
        update();
        EXITFUNC;
}
void EMData::center_origin_fft ( )

Multiply a Fourier image by (-1)**(ix+iy+iz) to center it.

Definition at line 6951 of file emdata_sparx.cpp.

References cmplx(), ENTERFUNC, EXITFUNC, get_array_offsets(), ImageFormatException, is_complex(), is_fftodd(), is_ri(), LOGERR, LOGWARN, nx, ny, set_array_offsets(), and update().

Referenced by EMAN::padfft_slice(), EMAN::FourierGriddingProjector::project3d(), and EMAN::Util::twoD_to_3D_ali().

{
        ENTERFUNC;
        if (!is_complex()) {
                LOGERR("complex image expected. Input image is real image.");
                throw ImageFormatException("complex image expected. Input image is real image.");
        }

        if (!is_ri()) {
                LOGWARN("Only RI should be used. ");
        }
        vector<int> saved_offsets = get_array_offsets();
        // iz in [1,nz], iy in [1,ny], ix in [0,nx/2], but nx comes in as extended and is the same for odd
        //                                                 and even, so we can ignore the difference...
        //                         in short, as nx is extended, it should be  ix in [0,(nx-2)/2],  corrected PAP 05/20
        set_array_offsets(0,1,1);
        int nxc = nx/2;

        if (is_fftodd()) {
                for (int iz = 1; iz <= nz; iz++) {
                        for (int iy = 1; iy <= ny; iy++) {
                                for (int ix = 0; ix < nxc; ix++) {
                                        cmplx(ix,iy,iz) *= float(-2*((ix+iy+iz)%2) + 1);
                                        float temp = float(iz-1+iy-1+ix)/float(ny)*M_PI;
                                        complex<float> temp2 = complex<float>(cos(temp), -sin(temp));
                                        cmplx(ix,iy,iz) *= temp2;
                                }
                        }
                }
        } else {
                for (int iz = 1; iz <= nz; iz++) {
                        for (int iy = 1; iy <= ny; iy++) {
                                for (int ix = 0; ix < nxc; ix++) {
                                        // next line multiplies by +/- 1
                                        cmplx(ix,iy,iz) *= float(-2*((ix+iy+iz)%2) + 1);
                                }
                        }
                }
        }
        set_array_offsets(saved_offsets);
        update();
        EXITFUNC;
}
void EMData::center_origin_yz ( )

Definition at line 6933 of file emdata_sparx.cpp.

References ENTERFUNC, EXITFUNC, ImageFormatException, is_complex(), LOGERR, nx, ny, and update().

{
        ENTERFUNC;
        if (is_complex()) {
                LOGERR("Real image expected. Input image is complex.");
                throw ImageFormatException("Real image expected. Input image is complex.");
        }
        for (int iz = 0; iz < nz; iz++) {
                for (int iy = (iz+1)%2; iy < ny; iy+=2) {
                        for (int ix = 0; ix < nx; ix++) {
                                (*this)(ix,iy,iz) *= -1;
                        }
                }
        }
        update();
        EXITFUNC;
}
void EMAN::EMData::clearupdate ( ) [inline]

turn off updates.

Useful to avoid wasteful recacling stats

Definition at line 154 of file emdata.h.

                                                          {
void EMData::clip_inplace ( const Region area,
const float &  fill_value = 0 
)

Clip the image inplace - clipping region must be smaller than the current region internally memory is reallocated

Exceptions:
ImageDimensionExceptionif any of the dimensions of the argument region are negative.

Parameters:
areaThe clip area, can be 2D/3D.
fill_valuethe value that new region

Definition at line 354 of file emdata.cpp.

References Assert, attr_dict, EMAN::EMUtil::em_memcpy(), EMAN::EMUtil::em_memset(), ENTERFUNC, EXITFUNC, get_data(), EMAN::Dict::has_key(), ImageDimensionException, nx, ny, nz, EMAN::Region::origin, rdata, set_size(), set_xyz_origin(), EMAN::Region::size, and update().

Referenced by calc_ccf(), calc_fast_sigma_image(), calc_flcf(), EMAN::FFTResampleProcessor::fft_resample(), EMAN::ScaleTransformProcessor::process(), EMAN::ZGradientProcessor::process_inplace(), EMAN::YGradientProcessor::process_inplace(), EMAN::XGradientProcessor::process_inplace(), EMAN::ScaleTransformProcessor::process_inplace(), EMAN::IntTranslateProcessor::process_inplace(), and EMAN::FlattenBackgroundProcessor::process_inplace().

{
        // Added by d.woolford
        ENTERFUNC;

//      printf("cip %d %d %d %d %d %d %f %d %d %d\n",area.origin[0],area.origin[1],area.origin[2],area.size[0],area.size[1],area.size[2],fill_value,nx,ny,nz);
        // Store the current dimension values
        int prev_nx = nx, prev_ny = ny, prev_nz = nz;
        size_t prev_size = (size_t)nx*ny*nz;

        // Get the zsize, ysize and xsize of the final area, these are the new dimension sizes of the pixel data
        int new_nz = ( area.size[2]==0 ? 1 : (int)area.size[2]);
        int new_ny = ( area.size[1]==0 ? 1 : (int)area.size[1]);
        int new_nx = (int)area.size[0];

        if ( new_nz < 0 || new_ny < 0 || new_nx < 0 )
        {
                // Negative image dimensions were never tested nor considered when creating this implementation
                throw ImageDimensionException("New image dimensions are negative - this is not supported in the clip_inplace operation");
        }

        size_t new_size = (size_t)new_nz*new_ny*new_nx;

        // Get the translation values, they are used to construct the ClipInplaceVariables object
        int x0 = (int) area.origin[0];
        int y0 = (int) area.origin[1];
        int z0 = (int) area.origin[2];

        // Get a object that calculates all the interesting variables associated with the clip inplace operation
        ClipInplaceVariables civ(prev_nx, prev_ny, prev_nz, new_nx, new_ny, new_nz, x0, y0, z0);

        get_data(); // Do this here to make sure rdata is up to date, applicable if GPU stuff is occuring
        // Double check to see if any memory shifting even has to occur
        if ( x0 > prev_nx || y0 > prev_ny || z0 > prev_nz || civ.x_iter == 0 || civ.y_iter == 0 || civ.z_iter == 0)
        {
                // In this case the volume has been shifted beyond the location of the pixel rdata and
                // the client should expect to see a volume with nothing in it.

                // Set size calls realloc,
                set_size(new_nx, new_ny, new_nz);

                // Set pixel memory to zero - the client should expect to see nothing
                EMUtil::em_memset(rdata, 0, (size_t)new_nx*new_ny*new_nz);

                return;
        }

        // Resize the volume before memory shifting occurs if the new volume is larger than the previous volume
        // All of the pixel rdata is guaranteed to be at the start of the new volume because realloc (called in set size)
        // guarantees this.
        if ( new_size > prev_size )
                set_size(new_nx, new_ny, new_nz);

        // Store the clipped row size.
        size_t clipped_row_size = (civ.x_iter) * sizeof(float);

        // Get the new sector sizes to save multiplication later.
        size_t new_sec_size = new_nx * new_ny;
        size_t prev_sec_size = prev_nx * prev_ny;

        // Determine the memory locations of the source and destination pixels - at the point nearest
        // to the beginning of the volume (rdata)
        size_t src_it_begin = civ.prv_z_bottom*prev_sec_size + civ.prv_y_front*prev_nx + civ.prv_x_left;
        size_t dst_it_begin = civ.new_z_bottom*new_sec_size + civ.new_y_front*new_nx + civ.new_x_left;

        // This loop is in the forward direction (starting at points nearest to the beginning of the volume)
        // it copies memory only when the destination pointer is less the source pointer - therefore
        // ensuring that no memory "copied to" is yet to be "copied from"
        for (int i = 0; i < civ.z_iter; ++i) {
                for (int j = 0; j < civ.y_iter; ++j) {

                        // Determine the memory increments as dependent on i and j
                        // This could be optimized so that not so many multiplications are occurring...
                        size_t dst_inc = dst_it_begin + j*new_nx + i*new_sec_size;
                        size_t src_inc = src_it_begin + j*prev_nx + i*prev_sec_size;
                        float* local_dst = rdata + dst_inc;
                        float* local_src = rdata + src_inc;

                        if ( dst_inc >= src_inc )
                        {
                                // this is fine, it will happen now and then and it will be necessary to continue.
                                // the tempatation is to break, but you can't do that (because the point where memory intersects
                                // could be in this slice - and yes, this aspect could be optimized).
                                continue;
                        }

                        // Asserts are compiled only in debug mode
                        // This situation not encountered in testing thus far
                        Assert( dst_inc < new_size && src_inc < prev_size && dst_inc >= 0 && src_inc >= 0 );

                        // Finally copy the memory
                        EMUtil::em_memcpy(local_dst, local_src, clipped_row_size);
                }
        }

        // Determine the memory locations of the source and destination pixels - at the point nearest
        // to the end of the volume (rdata+new_size)
        size_t src_it_end = prev_size - civ.prv_z_top*prev_sec_size - civ.prv_y_back*prev_nx - prev_nx + civ.prv_x_left;
        size_t dst_it_end = new_size - civ.new_z_top*new_sec_size - civ.new_y_back*new_nx - new_nx + civ.new_x_left;

        // This loop is in the reverse direction (starting at points nearest to the end of the volume).
        // It copies memory only when the destination pointer is greater than  the source pointer therefore
        // ensuring that no memory "copied to" is yet to be "copied from"
        for (int i = 0; i < civ.z_iter; ++i) {
                for (int j = 0; j < civ.y_iter; ++j) {

                        // Determine the memory increments as dependent on i and j
                        size_t dst_inc = dst_it_end - j*new_nx - i*new_sec_size;
                        size_t src_inc = src_it_end - j*prev_nx - i*prev_sec_size;
                        float* local_dst = rdata + dst_inc;
                        float* local_src = rdata + src_inc;

                        if (dst_inc <= (src_inc + civ.x_iter ))
                        {
                                // Overlap
                                if ( dst_inc > src_inc )
                                {
                                        // Because the memcpy operation is the forward direction, and this "reverse
                                        // direction" loop is proceeding in a backwards direction, it is possible
                                        // that memory copied to is yet to be copied from (because memcpy goes forward).
                                        // In this scenario pixel memory "copied to" is yet to be "copied from"
                                        // i.e. there is overlap

                                        // memmove handles overlapping cases.
                                        // memmove could use a temporary buffer, or could go just go backwards
                                        // the specification doesn't say how the function behaves...
                                        // If memmove creates a temporary buffer is clip_inplace no longer inplace?
                                        memmove(local_dst, local_src, clipped_row_size);
                                }
                                continue;
                        }

                        // This situation not encountered in testing thus far
                        Assert( dst_inc < new_size && src_inc < prev_size && dst_inc >= 0 && src_inc >= 0 );

                        // Perform the memory copy
                        EMUtil::em_memcpy(local_dst, local_src, clipped_row_size);
                }
        }

        // Resize the volume after memory shifting occurs if the new volume is smaller than the previous volume
        // set_size calls realloc, guaranteeing that the pixel rdata is in the right location.
        if ( new_size < prev_size )
                set_size(new_nx, new_ny, new_nz);

        // Now set all the edges to zero

        // Set the extra bottom z slices to the fill_value
        if (  z0 < 0 )
        {
                //EMUtil::em_memset(rdata, 0, (-z0)*new_sec_size*sizeof(float));
                size_t inc = (-z0)*new_sec_size;
                std::fill(rdata,rdata+inc,fill_value);
        }

        // Set the extra top z slices to the fill_value
        if (  civ.new_z_top > 0 )
        {
                float* begin_pointer = rdata + (new_nz-civ.new_z_top)*new_sec_size;
                //EMUtil::em_memset(begin_pointer, 0, (civ.new_z_top)*new_sec_size*sizeof(float));
                float* end_pointer = begin_pointer+(civ.new_z_top)*new_sec_size;
                std::fill(begin_pointer,end_pointer,fill_value);
        }

        // Next deal with x and y edges by iterating through each slice
        for ( int i = civ.new_z_bottom; i < civ.new_z_bottom + civ.z_iter; ++i )
        {
                // Set the extra front y components to the fill_value
                if ( y0 < 0 )
                {
                        float* begin_pointer = rdata + i*new_sec_size;
                        //EMUtil::em_memset(begin_pointer, 0, (-y0)*new_nx*sizeof(float));
                        float* end_pointer = begin_pointer+(-y0)*new_nx;
                        std::fill(begin_pointer,end_pointer,fill_value);
                }

                // Set the extra back y components to the fill_value
                if ( civ.new_y_back > 0 )
                {
                        float* begin_pointer = rdata + i*new_sec_size + (new_ny-civ.new_y_back)*new_nx;
                        //EMUtil::em_memset(begin_pointer, 0, (civ.new_y_back)*new_nx*sizeof(float));
                        float* end_pointer = begin_pointer+(civ.new_y_back)*new_nx;
                        std::fill(begin_pointer,end_pointer,fill_value);
                }

                // Iterate through the y to set each correct x component to the fill_value
                for (int j = civ.new_y_front; j <civ.new_y_front + civ.y_iter; ++j)
                {
                        // Set the extra left x components to the fill_value
                        if ( x0 < 0 )
                        {
                                float* begin_pointer = rdata + i*new_sec_size + j*new_nx;
                                //EMUtil::em_memset(begin_pointer, 0, (-x0)*sizeof(float));
                                float* end_pointer = begin_pointer+(-x0);
                                std::fill(begin_pointer,end_pointer,fill_value);
                        }

                        // Set the extra right x components to the fill_value
                        if ( civ.new_x_right > 0 )
                        {
                                float* begin_pointer = rdata + i*new_sec_size + j*new_nx + (new_nx - civ.new_x_right);
                                //EMUtil::em_memset(begin_pointer, 0, (civ.new_x_right)*sizeof(float));
                                float* end_pointer = begin_pointer+(civ.new_x_right);
                                std::fill(begin_pointer,end_pointer,fill_value);
                        }

                }
        }

// These couts may be useful
//      cout << "start starts " << civ.prv_x_left << " " << civ.prv_y_front << " " << civ.prv_z_bottom << endl;
//      cout << "start ends " << civ.prv_x_right << " " << civ.prv_y_back << " " << civ.prv_z_top << endl;
//      cout << "dst starts " << civ.new_x_left << " " << civ.new_y_front << " " << civ.new_z_bottom << endl;
//      cout << "dst ends " << civ.new_x_right << " " << civ.new_y_back << " " << civ.new_z_top << endl;
//      cout << "total iter z - " << civ.z_iter << " y - " << civ.y_iter << " x - " << civ.x_iter << endl;
//      cout << "=====" << endl;
//      cout << "dst_end is " << dst_it_end << " src end is " << src_it_end << endl;
//      cout << "dst_begin is " << dst_it_begin << " src begin is " << src_it_begin << endl;

        // Update appropriate attributes (Copied and pasted from get_clip)
        if( attr_dict.has_key("origin_x") && attr_dict.has_key("origin_y") &&
        attr_dict.has_key("origin_z") )
        {
                float xorigin = attr_dict["origin_x"];
                float yorigin = attr_dict["origin_y"];
                float zorigin = attr_dict["origin_z"];

                float apix_x = attr_dict["apix_x"];
                float apix_y = attr_dict["apix_y"];
                float apix_z = attr_dict["apix_z"];

                set_xyz_origin(xorigin + apix_x * area.origin[0],
                        yorigin + apix_y * area.origin[1],
                        zorigin + apix_z * area.origin[2]);
        }

        // Set the update flag because the size of the image has changed and stats should probably be recalculated if requested.
        update();

        EXITFUNC;
}
float EMData::cm_euc ( EMData sinoj,
int  n1,
int  n2 
)

euclidean distance between two line

Parameters:
sinoj
n1
n2

Definition at line 525 of file emdata_sparx.cpp.

References dist(), get_data(), get_data(), and get_xsize().

{
    int lnlen = get_xsize();
    float* line_1 = get_data() + n1 * lnlen;
    float* line_2 = sinoj->get_data() + n2 * lnlen;
    return dist(lnlen, line_1, line_2);
}
float EMData::cmp ( const string &  cmpname,
EMData with,
const Dict params = Dict() 
)

Compare this image with another image.

Parameters:
cmpnameComparison algorithm name.
withThe image you want to compare to.
paramsComparison parameters in a keyed dictionary.
Exceptions:
NotExistingObjectErrorIf the comparison algorithm doesn't exist.
Returns:
comparison score. The bigger, the better.

Definition at line 97 of file emdata_modular.cpp.

References EMAN::Cmp::cmp(), ENTERFUNC, and EXITFUNC.

Referenced by EMAN::Refine3DAlignerQuaternion::align(), EMAN::SymAlignProcessorQuat::align(), EMAN::RTFSlowExhaustiveAligner::align(), EMAN::RTFExhaustiveAligner::align(), EMAN::RotateFlipAlignerIterative::align(), EMAN::RotateFlipAligner::align(), EMAN::RotateTranslateFlipAlignerIterative::align(), EMAN::RotateTranslateFlipAligner::align(), EMAN::RotateTranslateAligner::align(), EMAN::RotationalAligner::align(), EMAN::ScaleAligner::align(), EMAN::ScaleAlignerABS::align_using_base(), EMAN::Util::ccc_images(), EMAN::Util::ccc_images_G(), main(), EMAN::Util::twoD_fine_ali(), EMAN::Util::twoD_fine_ali_G(), and EMAN::Util::twoD_to_3D_ali().

{
        ENTERFUNC;
        float result = 0;
        Cmp *c = Factory < Cmp >::get(cmpname, params);
        if (c) {
                result = c->cmp(this, with);
                if( c )
                {
                        delete c;
                        c = 0;
                }
        }

        EXITFUNC;
        return result;
}
std::complex<float>& EMAN::EMData::cmplx ( const int  ix,
const int  iy,
const int  iz 
) [inline]
std::complex<float>& EMAN::EMData::cmplx ( const int  ix,
const int  iy 
) [inline]

Definition at line 691 of file emdata.h.

                                          {
std::complex<float>& EMAN::EMData::cmplx ( const int  ix) [inline]

Definition at line 702 of file emdata.h.

                                          {
vector< float > EMData::cog ( )

Calculates the Center of Gravity and the Radius of Gyration of the image.

Returns:
the mass and the radius as vectors.

Definition at line 749 of file emdata_sparx.cpp.

References get_ndim(), nx, ny, rdata, EMAN::Util::round(), sqrt(), and square.

                          {

        vector<float> cntog;
        int ndim = get_ndim();
        int i=1,j=1,k=1;
        float val,sum1=0.f,MX=0.f,RG=0.f,MY=0.f,MZ=0.f,r=0.f;

        if (ndim == 1) {
                for ( i = 1;i <= nx; i++) {
                        val   = rdata(i,j,k);
                        sum1 += val;
                        MX   += ((i-1)*val);
                }
                MX=(MX/sum1);
                for ( i = 1;i <= nx; i++) {
                        val   = rdata(i,j,k);
                        sum1 += val;
                        RG   += val*(square(MX - (i-1)));
                }
                RG=std::sqrt(RG/sum1);
                MX=MX-(nx/2);
                cntog.push_back(MX);
                cntog.push_back(RG);
#ifdef _WIN32
                cntog.push_back((float)Util::round(MX));
#else
                cntog.push_back(round(MX));
#endif  //_WIN32
        } else if (ndim == 2) {
                for (j=1;j<=ny;j++) {
                        for (i=1;i<=nx;i++) {
                                val = rdata(i,j,k);
                                sum1 += val;
                                MX   += ((i-1)*val);
                                MY   += ((j-1)*val);
                        }
                }
                MX=(MX/sum1);
                MY=(MY/sum1);
                sum1=0.f;
                RG=0.f;
                for (j=1;j<=ny;j++) {
                        r = (square(MY-(j-1)));
                        for (i=1;i<=nx;i++) {
                                val = rdata(i,j,k);
                                sum1 += val;
                                RG   += val*(square(MX - (i-1)) + r);
                        }
                }
                RG = std::sqrt(RG/sum1);
                MX = MX - nx/2;
                MY = MY - ny/2;
                cntog.push_back(MX);
                cntog.push_back(MY);
                cntog.push_back(RG);
#ifdef _WIN32
                cntog.push_back((float)Util::round(MX));cntog.push_back((float)Util::round(MY));
#else
                cntog.push_back(round(MX));cntog.push_back(round(MY));
#endif  //_WIN32
        } else {
                for (k = 1;k <= nz;k++) {
                        for (j=1;j<=ny;j++) {
                                for (i=1;i<=nx;i++) {
                                        val = rdata(i,j,k);
                                        sum1 += val;
                                        MX += ((i-1)*val);
                                        MY += ((j-1)*val);
                                        MZ += ((k-1)*val);
                                }
                        }
                }
                MX = MX/sum1;
                MY = MY/sum1;
                MZ = MZ/sum1;
                sum1=0.f;
                RG=0.f;
                for (k = 1;k <= nz;k++) {
                        for (j=1;j<=ny;j++) {
                                float r = (square(MY-(j-1)) + square(MZ - (k-1)));
                                for (i=1;i<=nx;i++) {
                                        val = rdata(i,j,k);
                                        sum1 += val;
                                        RG   += val*(square(MX - (i-1)) + r);
                                }
                        }
                }
                RG = std::sqrt(RG/sum1);
                MX = MX - nx/2;
                MY = MY - ny/2;
                MZ = MZ - nz/2;
                cntog.push_back(MX);
                cntog.push_back(MY);
                cntog.push_back(MZ);
                cntog.push_back(RG);
#ifdef _WIN32
                cntog.push_back((float)Util::round(MX));cntog.push_back((float)Util::round(MY));cntog.push_back((float)Util::round(MZ));
#else
                cntog.push_back(round(MX));cntog.push_back(round(MY));cntog.push_back(round(MZ));
#endif  //_WIN32
        }
        return cntog;
}
EMData * EMData::compute_missingwedge ( float  wedgeangle,
float  start = 0.05,
float  stop = 0.5 
)

Find the mean and variance of voxels in the missing wedge.

Parameters:
wedgeanglethe angle of the missing wedge
influncethe region of influnce in fourier space. This is a fudge factor between 0 and 0.5
wedgedirectionthe direction of the wedge, so far only a wedge along Z is supported (set wedgedirection to 0)

Definition at line 4224 of file emdata.cpp.

References EMData(), get_value_at_wrap(), mean(), nx, ny, nz, set_attr(), set_size(), set_value_at(), sqrt(), sqrt(), and v.

{               
        EMData* test = new EMData();
        test->set_size(nx,ny,nz);
        
        float ratio = tan((90.0f-wedgeangle)*M_PI/180.0f);
        
        int offset_i = 2*int(start*nz/2);
        int offset_f = int(stop*nz/2);
        
        int step = 0;
        float sum = 0.0;
        double square_sum = 0.0;
        for (int j = 0; j < offset_f; j++){
                for (int k = offset_i; k < offset_f; k++) {
                        for (int i = 0; i < nx; i+=2) {
                                if (i < int(k*ratio)) {
                                        test->set_value_at(i, j, k, 1.0);
                                        float v = std::sqrt(pow(get_value_at_wrap(i, j, k),2) + pow(get_value_at_wrap(i+1, j, k),2));
                                        sum += v;
                                        square_sum += v * (double)(v);
                                        step++;
                                }
                        }
                }
        }
        
        float mean = sum / step;
        
        #ifdef _WIN32
        float sigma = (float)std::sqrt( _cpp_max(0.0,(square_sum - sum*mean)/(step-1)));
        #else
        float sigma = (float)std::sqrt(std::max<double>(0.0,(square_sum - sum*mean)/(step-1)));
        #endif  //_WIN32
        
        cout << "Mean sqr wedge amp " << mean << " Sigma Squ wedge Amp " << sigma << endl;
        set_attr("spt_wedge_mean", mean);
        set_attr("spt_wedge_sigma", sigma);
        
        return test;
}
EMData * EMData::conjg ( )

Definition at line 6368 of file emdata_sparx.cpp.

References copy_head(), get_data(), get_data(), ImageFormatException, in, is_complex(), nx, and ny.

{
        if(this->is_complex()) {
                EMData* buf_new = this->copy_head();
                float *in  = this->get_data();
                float *out = buf_new->get_data();
                for(size_t i=0; i<(size_t)nx*ny*nz; i+=2) {out[i] = in[i]; out[i+1] = -in[i+1];}
                return buf_new;
        } else throw ImageFormatException("image has to be complex");
}
EMData * EMData::convolute ( EMData with)

Convolutes 2 data sets.

The 2 images must be of the same size.

Parameters:
withOne data set. 'this' image is the other data set.
Exceptions:
NullPointerExceptionIf FFT resturns NULL image.
Returns:
The result image.

Definition at line 3417 of file emdata.cpp.

References ap2ri(), copy(), do_fft(), do_ift(), ENTERFUNC, EXITFUNC, get_data(), get_xsize(), get_ysize(), get_zsize(), ImageFormatException, EMAN::EMUtil::is_same_size(), LOGERR, NullPointerException, and update().

Referenced by calc_fast_sigma_image(), and EMAN::FlattenBackgroundProcessor::process_inplace().

{
        ENTERFUNC;

        EMData *f1 = do_fft();
        if (!f1) {
                LOGERR("FFT returns NULL image");
                throw NullPointerException("FFT returns NULL image");
        }

        f1->ap2ri();

        EMData *cf = 0;
        if (with) {
                cf = with->do_fft();
                if (!cf) {
                        LOGERR("FFT returns NULL image");
                        throw NullPointerException("FFT returns NULL image");
                }
                cf->ap2ri();
        }
        else {
                cf = f1->copy();
        }
        //printf("cf_x=%d, f1y=%d, thisx=%d, withx=%d\n",cf->get_xsize(),f1->get_ysize(),this->get_xsize(),with->get_xsize());
        if (with && !EMUtil::is_same_size(f1, cf)) {
                LOGERR("images not same size");
                throw ImageFormatException("images not same size");
        }

        float *rdata1 = f1->get_data();
        float *rdata2 = cf->get_data();
        size_t cf_size = (size_t)cf->get_xsize() * cf->get_ysize() * cf->get_zsize();

        float re,im;

        for (size_t i = 0; i < cf_size; i += 2) {
                re = rdata1[i] * rdata2[i] - rdata1[i + 1] * rdata2[i + 1];
                im = rdata1[i + 1] * rdata2[i] + rdata1[i] * rdata2[i + 1];
                rdata2[i]=re;
                rdata2[i+1]=im;
        }
        cf->update();
        EMData *f2 = cf->do_ift();//ming change cf to cf_temp
        //printf("cf_x=%d, f2x=%d, thisx=%d, withx=%d\n",cf->get_xsize(),f2->get_xsize(),this->get_xsize(),with->get_xsize());
        if( cf )
        {
                delete cf;
                cf = 0;
        }

        if( f1 )
        {
                delete f1;
                f1=0;
        }

        EXITFUNC;
        return f2;
}
EMData * EMData::copy ( ) const

For get/set values, basic math operations, operators.

$Id$ This file is a part of "emdata.h", to use functions in this file, you should "#include "emdata.h", NEVER directly include this file. Make a copy of this image including both data and header.

Returns:
A copy of this image including both data and header.

Definition at line 93 of file emdata_core.cpp.

References EMData(), ENTERFUNC, and EXITFUNC.

Referenced by absi(), EMAN::AbsMaxMinAverager::add_image(), EMAN::MinMaxAverager::add_image(), EMAN::FRM2DAligner::align(), EMAN::RTFExhaustiveAligner::align(), calc_fast_sigma_image(), calc_flcf(), calc_mutual_correlation(), EMAN::FRCCmp::cmp(), EMAN::PhaseCmp::cmp(), common_lines_real(), convolute(), EMAN::WienerFourierReconstructor::determine_slice_agreement(), EMAN::FourierReconstructor::determine_slice_agreement(), do_fft(), do_radon(), EMAN::Processor::EMFourierFilterFunc(), FH2F(), EMAN::fourierproduct(), get_attr(), EMAN::WienerFourierReconstructor::insert_slice(), EMAN::FourierReconstructor::insert_slice(), log(), log10(), main(), EMAN::operator*(), EMAN::operator+(), EMAN::operator-(), EMAN::operator/(), EMAN::periodogram(), power(), EMAN::Reconstructor::preprocess_slice(), EMAN::FourierReconstructor::preprocess_slice(), EMAN::ScaleTransformProcessor::process(), EMAN::CtfSimProcessor::process(), EMAN::SubtractOptProcessor::process(), EMAN::BooleanShrinkProcessor::process(), EMAN::FFTResampleProcessor::process(), EMAN::KmeansSegmentProcessor::process(), EMAN::DistanceSegmentProcessor::process(), EMAN::Processor::process(), EMAN::CTFSNRWeightProcessor::process_inplace(), EMAN::SymSearchProcessor::process_inplace(), EMAN::LocalNormProcessor::process_inplace(), EMAN::IterMultiMaskProcessor::process_inplace(), EMAN::NonConvexProcessor::process_inplace(), EMAN::MeanShrinkProcessor::process_inplace(), EMAN::MedianShrinkProcessor::process_inplace(), EMAN::SNREvalProcessor::process_inplace(), EMAN::FourierGriddingProjector::project3d(), real(), set_attr_python(), EMAN::PointArray::set_from_density_map(), and sqrt().

{
        ENTERFUNC;

        EMData *ret = new EMData(*this);

        EXITFUNC;
        return ret;
}
EMData * EMData::copy_empty_head ( ) const

copy header but not set size for the image

Definition at line 222 of file emdata_sparx.cpp.

References all_translation, attr_dict, ENTERFUNC, EXITFUNC, flags, path, pathnum, and update().

Referenced by EMAN::Util::window().

{
        ENTERFUNC;
        EMData *ret = new EMData();
        ret->attr_dict = attr_dict;
        ret->flags = flags;
        ret->all_translation = all_translation;
        ret->path = path;
        ret->pathnum = pathnum;

// should these be here? d.woolford I did not comment them out, merely place them here (commented out) to draw attention
//      ret->xoff = xoff;
//      ret->yoff = yoff;
//      ret->zoff = zoff;
//      ret->changecount = changecount;

        ret->update();

        EXITFUNC;
        return ret;
}
EMData * EMData::copy_head ( ) const

Make an image with a copy of the current image's header.

Returns:
An image with a copy of the current image's header.

Definition at line 104 of file emdata_core.cpp.

References all_translation, attr_dict, EMData(), ENTERFUNC, EXITFUNC, flags, nx, ny, nz, path, pathnum, set_size(), and update().

Referenced by EMAN::CtfCAutoAverager::add_image(), EMAN::CtfCWautoAverager::add_image(), EMAN::IterationAverager::add_image(), EMAN::ImageAverager::add_image(), EMAN::TomoAverager::add_image(), EMAN::Util::addn_img(), EMAN::Util::divn_filter(), EMAN::Util::divn_img(), get_fft_amplitude(), get_fft_amplitude2D(), get_fft_phase(), little_big_dot(), EMAN::Util::madn_scalar(), EMAN::Util::muln_img(), EMAN::Util::mult_scalar(), EMAN::Util::pad(), EMAN::SubtractOptProcessor::process(), EMAN::MeanShrinkProcessor::process(), EMAN::MedianShrinkProcessor::process(), EMAN::Wiener2DFourierProcessor::process(), EMAN::Util::squaren_img(), EMAN::Util::subn_img(), and EMAN::Util::svdcmp().

{
        ENTERFUNC;
        EMData *ret = new EMData();
        ret->attr_dict = attr_dict;

        ret->set_size(nx, ny, nz);
        ret->flags = flags;

        ret->all_translation = all_translation;

        ret->path = path;
        ret->pathnum = pathnum;

// should these be here? d.woolford I did not comment them out, merely place them here (commented out) to draw attention
//      ret->xoff = xoff;
//      ret->yoff = yoff;
//      ret->zoff = zoff;
//      ret->changecount = changecount;

        ret->update();

        EXITFUNC;
        return ret;
}
void EMData::cut_slice ( const EMData *const  map,
const Transform tr,
bool  interpolate = true 
)

cut a 2D slice out of a real 3D map.

Put slice into 'this' image.

Parameters:
mapThe real 3D map.
trorientation of the slice as encapsulated in a Transform object.
interpolateDo interpolation or not.
Exceptions:
NullPointerExceptionIf map is NULL.
ImageDimensionExceptionIf this image is not 2D.
ImageDimensionExceptionIf map image is not 3D.
ImageFormatExceptionIf this image is complex
ImageFormatExceptionIf map is complex
Author:
David Woolford (adapted from an original version by Steve Ludtke)
Date:
Feb 2008

Definition at line 3873 of file emdata.cpp.

References EMAN::Util::bilinear_interpolate(), ENTERFUNC, EXITFUNC, EMAN::Util::fast_floor(), get_data(), get_ndim(), get_xsize(), get_ysize(), get_zsize(), ImageDimensionException, ImageFormatException, is_complex(), EMAN::Util::linear_interpolate(), NullPointerException, nx, ny, EMAN::Util::round(), t, EMAN::Util::trilinear_interpolate(), update(), v, x, and y.

{
        ENTERFUNC;

        if (!map) throw NullPointerException("NULL image");
        // These restrictions should be ultimately restricted so that all that matters is get_ndim() = (map->get_ndim() -1)
        if ( get_ndim() != 2 ) throw ImageDimensionException("Can not call cut slice on an image that is not 2D");
        if ( map->get_ndim() != 3 ) throw ImageDimensionException("Can not cut slice from an image that is not 3D");
        // Now check for complex images - this is really just being thorough
        if ( is_complex() ) throw ImageFormatException("Can not call cut slice on an image that is complex");
        if ( map->is_complex() ) throw ImageFormatException("Can not cut slice from a complex image");


        float *sdata = map->get_data();
        float *ddata = get_data();

        int map_nx = map->get_xsize();
        int map_ny = map->get_ysize();
        int map_nz = map->get_zsize();
        int map_nxy = map_nx * map_ny;

        int ymax = ny/2;
        if ( ny % 2 == 1 ) ymax += 1;
        int xmax = nx/2;
        if ( nx % 2 == 1 ) xmax += 1;
        for (int y = -ny/2; y < ymax; y++) {
                for (int x = -nx/2; x < xmax; x++) {
                        Vec3f coord(x,y,0);
                        Vec3f soln = transform*coord;

//                      float xx = (x+pretrans[0]) * (*ort)[0][0] +  (y+pretrans[1]) * (*ort)[0][1] + pretrans[2] * (*ort)[0][2] + posttrans[0];
//                      float yy = (x+pretrans[0]) * (*ort)[1][0] +  (y+pretrans[1]) * (*ort)[1][1] + pretrans[2] * (*ort)[1][2] + posttrans[1];
//                      float zz = (x+pretrans[0]) * (*ort)[2][0] +  (y+pretrans[1]) * (*ort)[2][1] + pretrans[2] * (*ort)[2][2] + posttrans[2];


//                      xx += map_nx/2;
//                      yy += map_ny/2;
//                      zz += map_nz/2;

                        float xx = soln[0]+map_nx/2;
                        float yy = soln[1]+map_ny/2;
                        float zz = soln[2]+map_nz/2;

                        int l = (x+nx/2) + (y+ny/2) * nx;

                        float t = xx - floor(xx);
                        float u = yy - floor(yy);
                        float v = zz - floor(zz);

                        if (xx < 0 || yy < 0 || zz < 0 ) {
                                ddata[l] = 0;
                                continue;
                        }
                        if (interpolate) {
                                if ( xx > map_nx - 1 || yy > map_ny - 1 || zz > map_nz - 1) {
                                        ddata[l] = 0;
                                        continue;
                                }
                                int k = (int) (Util::fast_floor(xx) + Util::fast_floor(yy) * map_nx + Util::fast_floor(zz) * map_nxy);


                                if (xx < (map_nx - 1) && yy < (map_ny - 1) && zz < (map_nz - 1)) {
                                        ddata[l] = Util::trilinear_interpolate(sdata[k],
                                                                sdata[k + 1], sdata[k + map_nx],sdata[k + map_nx + 1],
                                                                sdata[k + map_nxy], sdata[k + map_nxy + 1], sdata[k + map_nx + map_nxy],
                                                                sdata[k + map_nx + map_nxy + 1],t, u, v);
                                }
                                else if ( xx == (map_nx - 1) && yy == (map_ny - 1) && zz == (map_nz - 1) ) {
                                        ddata[l] += sdata[k];
                                }
                                else if ( xx == (map_nx - 1) && yy == (map_ny - 1) ) {
                                        ddata[l] +=     Util::linear_interpolate(sdata[k], sdata[k + map_nxy],v);
                                }
                                else if ( xx == (map_nx - 1) && zz == (map_nz - 1) ) {
                                        ddata[l] += Util::linear_interpolate(sdata[k], sdata[k + map_nx],u);
                                }
                                else if ( yy == (map_ny - 1) && zz == (map_nz - 1) ) {
                                        ddata[l] += Util::linear_interpolate(sdata[k], sdata[k + 1],t);
                                }
                                else if ( xx == (map_nx - 1) ) {
                                        ddata[l] += Util::bilinear_interpolate(sdata[k], sdata[k + map_nx], sdata[k + map_nxy], sdata[k + map_nxy + map_nx],u,v);
                                }
                                else if ( yy == (map_ny - 1) ) {
                                        ddata[l] += Util::bilinear_interpolate(sdata[k], sdata[k + 1], sdata[k + map_nxy], sdata[k + map_nxy + 1],t,v);
                                }
                                else if ( zz == (map_nz - 1) ) {
                                        ddata[l] += Util::bilinear_interpolate(sdata[k], sdata[k + 1], sdata[k + map_nx], sdata[k + map_nx + 1],t,u);
                                }

//                              if (k >= map->get_size()) {
//                                      cout << xx << " " << yy << " " <<  zz << " " << endl;
//                                      cout << k << " " << get_size() << endl;
//                                      cout << get_xsize() << " " << get_ysize() << " " << get_zsize() << endl;
//                                      throw;
//                                      }
//
//                              ddata[l] = Util::trilinear_interpolate(sdata[k],
//                                              sdata[k + 1], sdata[k + map_nx],sdata[k + map_nx + 1],
//                                              sdata[k + map_nxy], sdata[k + map_nxy + 1], sdata[k + map_nx + map_nxy],
//                                              sdata[k + map_nx + map_nxy + 1],t, u, v);
                        }
                        else {
                                if ( xx > map_nx - 1 || yy > map_ny - 1 || zz > map_nz - 1) {
                                        ddata[l] = 0;
                                        continue;
                                }
                                size_t k = Util::round(xx) + Util::round(yy) * map_nx + Util::round(zz) * (size_t)map_nxy;
                                ddata[l] = sdata[k];
                        }

                }
        }

        update();

        EXITFUNC;
}
void EMAN::EMData::debug_print_parms ( ) [inline]

Printing EMData params for debugging purpose.

Definition at line 774 of file emdata.h.

References attr_dict, EMAN::Dict::begin(), and EMAN::Dict::end().

                {
                        std::cout << "Printing EMData params" << std::endl;
                        for ( Dict::const_iterator it = attr_dict.begin(); it != attr_dict.end(); ++it )
                        {
                                std::cout << (it->first) << " " << (it->second).to_str() << std::endl;
                        }
                        std::cout << "Done printing EMData params" << std::endl;
                }
void EMData::del_attr ( const string &  attr_name)

Delete the attribute from dictionary.

Parameters:
attr_namethe attribute name to be removed

Definition at line 1204 of file emdata_metadata.cpp.

References attr_dict, and EMAN::Dict::erase().

Referenced by del_attr_dict().

{
        attr_dict.erase(attr_name);
}
void EMData::del_attr_dict ( const vector< string > &  del_keys)

Delete the attributes from the dictionary.

Parameters:
del_keysthe attrutes' names to be removed

Definition at line 1209 of file emdata_metadata.cpp.

References del_attr().

{
        vector<string>::const_iterator it;
        for(it=del_keys.begin(); it!=del_keys.end(); ++it) {
                this->del_attr(*it);
        }
}
EMData * EMData::delete_disconnected_regions ( int  ix = 0,
int  iy = 0,
int  iz = 0 
)

Delete disconnected regions in a binary image.

Works only for a volume.

Parameters:
[in]ix,:x coordinate (with respect to the center) from which the search of the compact region begins.
[in]iy,:y coordinate (with respect to the center) from which the search of the compact region begins.
[in]iz,:z coordinate (with respect to the center) from which the search of the compact region begins.
Returns:
New binary image

Definition at line 6379 of file emdata_sparx.cpp.

References copy_head(), get_ndim(), ImageDimensionException, ImageFormatException, is_complex(), nx, ny, to_zero(), and update().

                                                                  {
        if (3 != get_ndim())
                throw ImageDimensionException("delete_disconnected_regions needs a 3-D image.");
        if (is_complex())
                throw ImageFormatException("delete_disconnected_regions requires a real image");
        if ((*this)(ix+nx/2,iy+ny/2,iz+nz/2) == 0)
                throw ImageDimensionException("delete_disconnected_regions starting point is zero.");

        EMData* result = this->copy_head();
        result->to_zero();
        (*result)(ix+nx/2,iy+ny/2,iz+nz/2) = (*this)(ix+nx/2,iy+ny/2,iz+nz/2);
        bool kpt = true;
        //cout << "  delete   "<<(*result)(ix+nx/2,iy+ny/2,iz+nz/2)<<endl;
        while(kpt) {
                kpt = false;
                for (int cz = 1; cz < nz-1; cz++) {
                        for (int cy = 1; cy < ny-1; cy++) {
                                for (int cx = 1; cx < nx-1; cx++) {
                                        if((*result)(cx,cy,cz) == 1) {
                                                for (int lz = -1; lz <= 1; lz++) {
                                                        for (int ly = -1; ly <= 1; ly++) {
                                                                for (int lx = -1; lx <= 1; lx++) {
                                                                        if(((*this)(cx+lx,cy+ly,cz+lz) == 1) && ((*result)(cx+lx,cy+ly,cz+lz) == 0))  {
                                                                                (*result)(cx+lx,cy+ly,cz+lz) = 1;
                                                                                kpt = true;
                                                                        }
                                                                }
                                                        }
                                                }
                                        }
                                }
                        }
                }
        }
        result->update();
        return result;
}
void EMData::depad ( )

De-pad, and and remove Fourier extension convenience function.

Purpose: De-pad, and and remove Fourier extension from a real image.
Method: Remove padding and extension along x for fft,
and return the new image.
Returns:
depadded input image.

Definition at line 6678 of file emdata_sparx.cpp.

References EXITFUNC, get_array_offsets(), get_data(), ImageFormatException, is_complex(), is_fftodd(), nx, ny, set_array_offsets(), set_attr(), set_complex(), set_complex_x(), set_fftodd(), set_fftpad(), set_size(), and update().

Referenced by EMAN::Util::BPCQ(), EMAN::Processor::EMFourierFilterFunc(), filter_by_image(), EMAN::nn4_ctf_rectReconstructor::finish(), EMAN::nn4_ctfwReconstructor::finish(), EMAN::nn4_ctfReconstructor::finish(), EMAN::nn4_rectReconstructor::finish(), EMAN::nn4Reconstructor::finish(), EMAN::WienerFourierReconstructor::finish(), EMAN::FourierReconstructor::finish(), EMAN::FourierReconstructorSimple2D::finish(), Four_ds(), Four_shuf_ds_cen_us(), EMAN::fourierproduct(), FourInterpol(), FourTruncate(), EMAN::TestImageFourierNoiseProfile::process_inplace(), EMAN::CTFSNRWeightProcessor::process_inplace(), EMAN::TestImageFourierNoiseGaussian::process_inplace(), EMAN::LowpassRandomPhaseProcessor::process_inplace(), replace_amplitudes(), EMAN::Util::WTF(), and EMAN::Util::WTM().

                   {
        if (is_complex())
                throw ImageFormatException("Depadding of complex images not supported");
        vector<int> saved_offsets = get_array_offsets();
        set_array_offsets(0,0,0);
        int npad = attr_dict["npad"];
        if (0 == npad) npad = 1;
        int offset = is_fftodd() ? 1 : 2;
        int nxold = (nx - offset)/npad;
#ifdef _WIN32
        int nyold = _cpp_max(ny/npad, 1);
        int nzold = _cpp_max(nz/npad, 1);
#else
        int nyold = std::max<int>(ny/npad, 1);
        int nzold = std::max<int>(nz/npad, 1);
#endif  //_WIN32
        int xstart = 0, ystart = 0, zstart = 0;
        if( npad > 1) {
                xstart = (nx - offset - nxold)/2 + nxold%2;
                if(ny > 1) {
                        ystart = (ny - nyold)/2 + nyold%2;
                        if(nz > 1) {
                                zstart = (nz - nzold)/2 + nzold%2;
                        }
                }
        }
        int bytes = nxold*sizeof(float);
        float* dest = get_data();
        for (int iz=0; iz < nzold; iz++) {
                for (int iy = 0; iy < nyold; iy++) {
                        memmove(dest, &(*this)(xstart,iy+ystart,iz+zstart), bytes);
                        dest += nxold;
                }
        }
        set_size(nxold, nyold, nzold);
        set_attr("npad", 1);
        set_fftpad(false);
        set_fftodd(false);
        set_complex(false);
        if(ny==1 && nz==1) set_complex_x(false);
        set_array_offsets(saved_offsets);
        update();
        EXITFUNC;
}
void EMData::depad_corner ( )

De-pad, and and remove Fourier extension convenience function.

Purpose: De-pad, and and remove Fourier extension from a real image.
Method: Remove padding and extension along x for fft,
and return the new image.
Returns:
depadded input image.

Definition at line 6730 of file emdata_sparx.cpp.

References EXITFUNC, get_array_offsets(), get_data(), ImageFormatException, is_complex(), is_fftodd(), nx, ny, set_array_offsets(), set_attr(), set_complex(), set_complex_x(), set_fftodd(), set_fftpad(), set_size(), and update().

Referenced by EMAN::FFTResampleProcessor::fft_resample(), and EMAN::fourierproduct().

                          {
        if(is_complex())
                throw ImageFormatException("Depadding of complex images not allowed");
        vector<int> saved_offsets = get_array_offsets();
        set_array_offsets(0,0,0);
        int npad = attr_dict["npad"];
        if(0 == npad) npad = 1;
        int offset = is_fftodd() ? 1 : 2;
        int nxold = (nx - offset)/npad;
#ifdef _WIN32
        int nyold = _cpp_max(ny/npad, 1);
        int nzold = _cpp_max(nz/npad, 1);
#else
        int nyold = std::max<int>(ny/npad, 1);
        int nzold = std::max<int>(nz/npad, 1);
#endif  //_WIN32
        size_t bytes = nxold*sizeof(float);
        float* dest = get_data();
        for (int iz=0; iz < nzold; iz++) {
                for (int iy = 0; iy < nyold; iy++) {
                        memmove(dest, &(*this)(0,iy,iz), bytes);
                        dest += nxold;
                }
        }
        set_size(nxold, nyold, nzold);
        set_attr("npad", 1);
        set_fftpad(false);
        set_fftodd(false);
        set_complex(false);
        if(ny==1 && nz==1) set_complex_x(false);
        set_array_offsets(saved_offsets);
        update();
        EXITFUNC;
}
void EMData::div ( float  f)

make each pixel value divided by a float number.

Parameters:
fThe float number 'this' image divided by.

Definition at line 589 of file emdata_core.cpp.

References ENTERFUNC, EXITFUNC, InvalidValueException, and mult().

Referenced by calc_flcf(), EMAN::fourierproduct(), EMAN::operator/(), operator/=(), and EMAN::LocalNormProcessor::process_inplace().

{
        ENTERFUNC;
        if ( f == 0 ) {
                throw InvalidValueException(f,"Can not divide by zero");
        }
        mult(1.0f/f);
        EXITFUNC;
}
void EMData::div ( const EMData image)

make each pixel value divided by pixel value of another same-size image.

Parameters:
imageThe image 'this' image divided by.
Exceptions:
ImageFormatExceptionIf the 2 images are not same size.

Definition at line 600 of file emdata_core.cpp.

References data, ENTERFUNC, EXITFUNC, get_data(), get_xsize(), get_ysize(), get_zsize(), ImageFormatException, InvalidValueException, is_real(), nx, nxyz, ny, nz, and update().

{
        ENTERFUNC;

        if (nx != em.get_xsize() || ny != em.get_ysize() || nz != em.get_zsize()) {
                throw ImageFormatException( "images not same sizes");
        }
        else if( (is_real()^em.is_real()) == true )
        {
                throw ImageFormatException( "not support division between real image and complex image");
        }
        else {
                const float *src_data = em.get_data();
                size_t size = nxyz;
                float* data = get_data();

                if( is_real() )
                {
                        for (size_t i = 0; i < size; i++) {
                                if(src_data[i] != 0) {
                                        data[i] /= src_data[i];
                                }
                                else {
                                        if (data[i]==0) continue;
                                        throw InvalidValueException(src_data[i], "divide by zero");
                                }
                        }
                }
                else
                {
                        typedef std::complex<float> comp;
                        for( size_t i = 0; i < size; i+=2 )
                        {
                                comp c_src( src_data[i], src_data[i+1] );
                                comp c_rdat( data[i], data[i+1] );
                                comp c_result = c_rdat / c_src;
                                data[i] = c_result.real();
                                data[i+1] = c_result.imag();
                        }
                }
                update();
        }

        EXITFUNC;
}
void EMData::divkbsinh ( const Util::KaiserBessel kb)

divkbsinh -- Divide image by a Kaiser-Bessel sinh window.

Parameters:
[in]kbKaiser-Bessel window object

Note: Ideally this method really should be a "processor" instead, but at the moment a KaiserBessel object cannot be passed as part of a Dict, making the usual EMData::project() interface rather awkward here.

Definition at line 4371 of file emdata_sparx.cpp.

References get_array_offsets(), ImageFormatException, is_complex(), nx, ny, set_array_offsets(), and EMAN::Util::KaiserBessel::sinhwin().

Referenced by EMAN::FourierGriddingProjector::project3d().

                                                 {
        
        if (is_complex())
                throw ImageFormatException("divkbsinh requires a real image.");
        vector<int> saved_offsets = get_array_offsets();
        set_array_offsets(0,0,0);
        // Note that the following loops will work for 1-, 2-, and 3-D
        // images, since the "extra" weights will be 1.0.  (For example,
        // for a 2-d image iz=0, nz=1, so iz-nz/2 = 0 - 1/2 = 0, since
        // the division is an integer division.)
        for (int iz=0; iz < nz; iz++) {
                float wz = kb.sinhwin(static_cast<float>(iz-nz/2));
                for (int iy=0; iy < ny; iy++) {
                        float wy = kb.sinhwin(static_cast<float>(iy-ny/2));
                        for (int ix=0; ix < nx; ix++) {
                                float wx = kb.sinhwin(static_cast<float>(ix-nx/2));
                                float w = wx*wy*wz;
                                (*this)(ix,iy,iz) /= w;
                        }
                }
        }
        set_array_offsets(saved_offsets);
}
void EMData::divkbsinh_rect ( const Util::KaiserBessel kbx,
const Util::KaiserBessel kby,
const Util::KaiserBessel kbz 
)

Definition at line 4395 of file emdata_sparx.cpp.

References get_array_offsets(), ImageFormatException, is_complex(), nx, ny, set_array_offsets(), and EMAN::Util::KaiserBessel::sinhwin().

                                                                                                                 {

        if (is_complex())
                throw ImageFormatException("divkbsinh requires a real image.");
        vector<int> saved_offsets = get_array_offsets();
        set_array_offsets(0,0,0);
        // Note that the following loops will work for 1-, 2-, and 3-D
        // images, since the "extra" weights will be 1.0.  (For example,
        // for a 2-d image iz=0, nz=1, so iz-nz/2 = 0 - 1/2 = 0, since
        // the division is an integer division.)
        for (int iz=0; iz < nz; iz++) {
                float wz = kbz.sinhwin(static_cast<float>(iz-nz/2));
                for (int iy=0; iy < ny; iy++) {
                        float wy = kby.sinhwin(static_cast<float>(iy-ny/2));
                        for (int ix=0; ix < nx; ix++) {
                                float wx = kbx.sinhwin(static_cast<float>(ix-nx/2));
                                float w = wx*wy*wz;
                                (*this)(ix,iy,iz) /= w;
                        }
                }
        }
        
        set_array_offsets(saved_offsets);
}
EMData * EMData::do_fft ( ) const

For fft, wavelet, insert data.

$Id$ This file is a part of "emdata.h", to use functions in this file, you should "#include "emdata.h", NEVER directly include this file. return the fast fourier transform (FFT) image of the current image. the current image is not changed. The result is in real/imaginary format.

Returns:
The FFT of the current image in real/imaginary format.

Definition at line 59 of file emdata_transform.cpp.

References copy(), copy(), copy_head(), ENTERFUNC, EXITFUNC, get_data(), get_data(), get_ysize(), get_zsize(), ImageFormatException, is_complex(), is_fftodd(), is_fftpadded(), LOGERR, nx, ny, set_complex(), set_complex_x(), set_fftodd(), set_fftpad(), set_ri(), set_size(), and update().

Referenced by EMAN::CtfCAutoAverager::add_image(), EMAN::CtfCWautoAverager::add_image(), EMAN::FourierWeightAverager::add_image(), EMAN::TomoAverager::add_image(), EMAN::FRM2DAligner::align(), EMAN::Refine3DAlignerGrid::align(), calc_mutual_correlation(), EMAN::FRCCmp::cmp(), EMAN::PhaseCmp::cmp(), EMAN::OptVarianceCmp::cmp(), EMAN::TomoFscCmp::cmp(), common_lines(), convolute(), EMAN::MatchSFProcessor::create_radial_func(), main(), make_footprint(), EMAN::TestUtil::make_image_file_by_mode(), EMAN::FSCFourierProcessor::process(), EMAN::CtfSimProcessor::process(), EMAN::SubtractOptProcessor::process(), EMAN::FFTResampleProcessor::process(), EMAN::Wiener2DFourierProcessor::process(), EMAN::FileFourierProcessor::process_inplace(), EMAN::SNRProcessor::process_inplace(), EMAN::RealToFFTProcessor::process_inplace(), EMAN::CutoffBlockProcessor::process_inplace(), EMAN::AmpweightFourierProcessor::process_inplace(), EMAN::Axis0FourierProcessor::process_inplace(), EMAN::FourierAnlProcessor::process_inplace(), EMAN::FourierProcessor::process_inplace(), EMAN::ImageProcessor::process_inplace(), EMAN::GaussFFTProjector::project3d(), EMAN::RT3DSphereAligner::xform_align_nbest(), and EMAN::RT3DGridAligner::xform_align_nbest().

{
        ENTERFUNC;
#ifdef FFT_CACHING
        if (fftcache!=0) {
                return fftcache->copy();
        }
#endif //FFT_CACHING

        if (is_complex() ) { // ming add 08/17/2010
#ifdef NATIVE_FFT
                LOGERR(" NATIVE_FFT does not support complex to complex.");  // PAP
                throw ImageFormatException("real image expected. Input image is complex image.");
#else
                EMData *temp_in=copy();
                EMData *dat= copy_head();
                int offset;
                if(is_fftpadded()) {
                        offset = is_fftodd() ? 1 : 2;
                }
                else offset=0;
                //printf("offset=%d\n",offset);
                EMfft::complex_to_complex_nd(temp_in->get_data(),dat->get_data(),nx-offset,ny,nz);

                if(dat->get_ysize()==1 && dat->get_zsize()==1) dat->set_complex_x(true);

                dat->update();
                delete temp_in;
                EXITFUNC;
                return dat;
#endif // NATIVE_FFT
        } else {
                int nxreal = nx;
                int offset = 2 - nx%2;
                int nx2 = nx + offset;
                EMData* dat = copy_head();
                dat->set_size(nx2, ny, nz);
                //dat->to_zero();  // do not need it, real_to_complex will do it right anyway
                if (offset == 1) dat->set_fftodd(true);
                else             dat->set_fftodd(false);

                float *d = dat->get_data();
                //std::cout<<" do_fft "<<rdata[5]<<"  "<<d[5]<<std::endl;
                EMfft::real_to_complex_nd(get_data(), d, nxreal, ny, nz);

                dat->update();
                dat->set_fftpad(true);
                dat->set_complex(true);
                if(dat->get_ysize()==1 && dat->get_zsize()==1) dat->set_complex_x(true);
                dat->set_ri(true);

                EXITFUNC;
#ifdef FFT_CACHING
//              printf("%p %d\n",this,nxyz);
                if (nxyz<80000000) {
                        fftcache=dat->copy();
                }
#endif //FFT_CACHING
                return dat;
        }
}
void EMData::do_fft_inplace ( )

Do FFT inplace.

And return the FFT image.

Returns:
The FFT of the current image in real/imaginary format.

Definition at line 121 of file emdata_transform.cpp.

References ENTERFUNC, EXITFUNC, get_data(), ImageFormatException, is_complex(), is_fftodd(), is_fftpadded(), LOGERR, nx, ny, rdata, set_complex(), set_complex_x(), set_fftodd(), set_fftpad(), set_ri(), set_size(), and update().

Referenced by calc_fourier_shell_correlation(), EMAN::FRCCmp::cmp(), EMAN::PhaseCmp::cmp(), EMAN::Processor::EMFourierFilterFunc(), EMAN::FFTResampleProcessor::fft_resample(), filter_by_image(), EMAN::fourierproduct(), EMAN::FourierReconstructorSimple2D::insert_slice(), oneDfftPolar(), EMAN::padfft_slice(), EMAN::periodogram(), EMAN::FourierReconstructor::preprocess_slice(), EMAN::CtfSimProcessor::process(), EMAN::FFTProcessor::process_inplace(), EMAN::CTFSNRWeightProcessor::process_inplace(), EMAN::LowpassRandomPhaseProcessor::process_inplace(), EMAN::FourierGriddingProjector::project3d(), replace_amplitudes(), scale_factors(), EMAN::Util::WTF(), and EMAN::Util::WTM().

{
        ENTERFUNC;

        if ( is_complex() ) {
                LOGERR("real image expected. Input image is complex image.");
                throw ImageFormatException("real image expected. Input image is complex image.");
        }

        size_t offset;
        int nxreal;
        get_data(); // Required call if GPU caching is being used. Otherwise harmless
        if (!is_fftpadded()) {
                // need to extend the matrix along x
                // meaning nx is the un-fftpadded size
                nxreal = nx;
                offset = 2 - nx%2;
                if (1 == offset) set_fftodd(true);
                else             set_fftodd(false);
                int nxnew = nx + offset;
                set_size(nxnew, ny, nz);
                for (int iz = nz-1; iz >= 0; iz--) {
                        for (int iy = ny-1; iy >= 0; iy--) {
                                for (int ix = nxreal-1; ix >= 0; ix--) {
                                        size_t oldxpos = ix + (iy + iz*ny)*(size_t)nxreal;
                                        size_t newxpos = ix + (iy + iz*ny)*(size_t)nxnew;
                                        (*this)(newxpos) = (*this)(oldxpos);
                                }
                        }
                }
                set_fftpad(true);
        } else {
                offset = is_fftodd() ? 1 : 2;
                nxreal = nx - offset;
        }
        EMfft::real_to_complex_nd(rdata, rdata, nxreal, ny, nz);

        set_complex(true);
        if(ny==1 && nz==1)  set_complex_x(true);
        set_ri(true);

        update();

        EXITFUNC;
        //return this;
}
EMData * EMData::do_ift ( )

return the inverse fourier transform (IFT) image of the current image.

the current image may be changed if it is in amplitude/phase format as opposed to real/imaginary format - if this change is performed it is not undone.

Exceptions:
ImageFormatExceptionIf the image is not a complex image.
Returns:
The current image's inverse fourier transform image.

Definition at line 333 of file emdata_transform.cpp.

References ap2ri(), copy_head(), ENTERFUNC, EXITFUNC, get_data(), get_data(), get_ndim(), get_ysize(), get_zsize(), ImageFormatException, is_complex(), is_fftodd(), is_ri(), LOGERR, LOGWARN, mult(), nx, ny, rdata, set_complex(), set_complex_x(), set_fftodd(), set_fftpad(), set_ri(), set_size(), and update().

Referenced by calc_mutual_correlation(), EMAN::OptVarianceCmp::cmp(), convolute(), FH2Real(), EMAN::CtfCAutoAverager::finish(), EMAN::CtfCWautoAverager::finish(), EMAN::FourierWeightAverager::finish(), EMAN::TomoAverager::finish(), main(), make_footprint(), EMAN::PointArray::pdb2mrc_by_nfft(), EMAN::FSCFourierProcessor::process(), EMAN::CtfSimProcessor::process(), EMAN::SubtractOptProcessor::process(), EMAN::Wiener2DFourierProcessor::process(), EMAN::FileFourierProcessor::process_inplace(), EMAN::SNRProcessor::process_inplace(), EMAN::AmpweightFourierProcessor::process_inplace(), EMAN::Axis0FourierProcessor::process_inplace(), EMAN::FourierAnlProcessor::process_inplace(), EMAN::FourierProcessor::process_inplace(), EMAN::ImageProcessor::process_inplace(), and EMAN::GaussFFTProjector::project3d().

{
        ENTERFUNC;

        if (!is_complex()) {
                LOGERR("complex image expected. Input image is real image.");
                throw ImageFormatException("complex image expected. Input image is real image.");
        }

        if (!is_ri()) {
                LOGWARN("run IFT on AP data, only RI should be used. Converting.");
        }

        get_data(); // Required call if GPU caching is being used. Otherwise harmless
        EMData* dat = copy_head();
        dat->set_size(nx, ny, nz);
        ap2ri();

        float *d = dat->get_data();
        int ndim = get_ndim();

        /* Do inplace IFT on a image copy, because the complex to real transform of
         * nd will destroy its input array even for out-of-place transforms.
         */
        memcpy((char *) d, (char *) rdata, (size_t)nx * ny * nz * sizeof(float));

        int offset = is_fftodd() ? 1 : 2;
        //cout << "Sending offset " << offset << " " << nx-offset << endl;
        if (ndim == 1) {
                EMfft::complex_to_real_nd(d, d, nx - offset, ny, nz);
        } else {
                EMfft::complex_to_real_nd(d, d, nx - offset, ny, nz);

                size_t row_size = (nx - offset) * sizeof(float);
                for (size_t i = 1; i < (size_t)ny * nz; i++) {
                        memmove((char *) &d[i * (nx - offset)], (char *) &d[i * nx], row_size);
                }
        }

        dat->set_size(nx - offset, ny, nz);     //remove the padding
#if defined     FFTW2 || defined FFTW3 //native fft and ACML already done normalization
        // SCALE the inverse FFT
        float scale = 1.0f / ((nx - offset) * ny * nz);
        dat->mult(scale);
#endif  //FFTW2 || FFTW3
        dat->set_fftodd(false);
        dat->set_fftpad(false);
        dat->set_complex(false);
        if(dat->get_ysize()==1 && dat->get_zsize()==1)  dat->set_complex_x(false);
        dat->set_ri(false);
        dat->update();


        EXITFUNC;
        return dat;
}
void EMData::do_ift_inplace ( )

Definition at line 394 of file emdata_transform.cpp.

References ap2ri(), data, ENTERFUNC, EXITFUNC, get_data(), ImageFormatException, is_complex(), is_fftodd(), is_ri(), LOGERR, LOGWARN, mult(), nx, ny, set_complex(), set_complex_x(), set_fftpad(), set_ri(), and update().

Referenced by EMAN::Util::BPCQ(), EMAN::PhaseCmp::cmp(), EMAN::Processor::EMFourierFilterFunc(), EMAN::FFTResampleProcessor::fft_resample(), filter_by_image(), EMAN::nn4_ctf_rectReconstructor::finish(), EMAN::nn4_ctfwReconstructor::finish(), EMAN::nn4_ctfReconstructor::finish(), EMAN::nn4_rectReconstructor::finish(), EMAN::nn4Reconstructor::finish(), EMAN::WienerFourierReconstructor::finish(), EMAN::FourierReconstructor::finish(), EMAN::FourierReconstructorSimple2D::finish(), Four_ds(), Four_shuf_ds_cen_us(), EMAN::fourierproduct(), FourInterpol(), FourTruncate(), EMAN::FFTProcessor::process_inplace(), EMAN::TestImageFourierNoiseProfile::process_inplace(), EMAN::CTFSNRWeightProcessor::process_inplace(), EMAN::TestImageFourierNoiseGaussian::process_inplace(), EMAN::LowpassRandomPhaseProcessor::process_inplace(), EMAN::FourierGriddingProjector::project3d(), replace_amplitudes(), EMAN::Util::twoD_to_3D_ali(), EMAN::Util::WTF(), and EMAN::Util::WTM().

{
        ENTERFUNC;

        if (!is_complex()) {
                LOGERR("complex image expected. Input image is real image.");
                throw ImageFormatException("complex image expected. Input image is real image.");
        }

        if (!is_ri()) {
                LOGWARN("run IFT on AP data, only RI should be used. ");
        }
        ap2ri();

        int offset = is_fftodd() ? 1 : 2;
        float* data = get_data();
        EMfft::complex_to_real_nd(data, data, nx - offset, ny, nz);

#if defined     FFTW2 || defined FFTW3  //native fft and ACML already done normalization
        // SCALE the inverse FFT
        int nxo = nx - offset;
        float scale = 1.0f / ((size_t)nxo * ny * nz);
        mult(scale);
#endif //FFTW2 || FFTW3

        set_fftpad(true);
        set_complex(false);
        if(ny==1 && nz==1) set_complex_x(false);
        set_ri(false);
        update();

        EXITFUNC;
//      return this;
}
EMData * EMData::do_radon ( )

Radon Transform: an algorithm that transforms an original image into a series of equiangular projections.

When applied to a 2D object, the output of the Radon transform is a series of 1D lines.

Do radon transformation on this image. This image must be 2D square.

Exceptions:
ImageFormatExceptionIf the image is not square.
ImageDimensionExceptionIf the image is not 2D.
Returns:
Radon transform image in square.

Definition at line 1403 of file emdata.cpp.

References copy(), EMData(), ENTERFUNC, EXITFUNC, get_data(), get_ndim(), ImageDimensionException, ImageFormatException, nx, ny, set_size(), EMAN::Util::square(), t, to_zero(), transform(), update(), x, and y.

Referenced by main().

{
        ENTERFUNC;

        if (get_ndim() != 2) {
                throw ImageDimensionException("2D only");
        }

        if (nx != ny) {
                throw ImageFormatException("square image only");
        }

        EMData *result = new EMData();
        result->set_size(nx, ny, 1);
        result->to_zero();
        float *result_data = result->get_data();

        EMData *this_copy = this;
        this_copy = copy();

        for (int i = 0; i < nx; i++) {
                Transform t(Dict("type","2d","alpha",(float) M_PI * 2.0f * i / nx));
                this_copy->transform(t);

                float *copy_data = this_copy->get_data();

                for (int y = 0; y < nx; y++) {
                        for (int x = 0; x < nx; x++) {
                                if (Util::square(x - nx / 2) + Util::square(y - nx / 2) <= nx * nx / 4) {
                                        result_data[i + y * nx] += copy_data[x + y * nx];
                                }
                        }
                }

                this_copy->update();
        }

        result->update();

        if( this_copy )
        {
                delete this_copy;
                this_copy = 0;
        }

        EXITFUNC;
        return result;
}
float EMData::dot ( EMData with)

Dot product 2 images.

The 2 images must be of same size. If 'evenonly' is true, only calculates pixels with even positions assuming all pixels are in a single array. If 'evenonly' is false, calculates all pixels. Shortcut for cmp("dot")

Parameters:
withThe image to do dot product with.
Exceptions:
NullPointerExceptionif with is a NULL image.
Returns:
The dot product result.

Definition at line 648 of file emdata_core.cpp.

References EMAN::DotCmp::cmp(), ENTERFUNC, EXITFUNC, and NullPointerException.

Referenced by little_big_dot(), main(), and make_footprint().

{
        ENTERFUNC;
        if (!with) {
                throw NullPointerException("Null EMData Image");
        }
        DotCmp dot_cmp;
        float r = -dot_cmp.cmp(this, with);
        EXITFUNC;
        return r;
}
double EMData::dot_rotate_translate ( EMData with,
float  dx,
float  dy,
float  da,
const bool  mirror = false 
)

dot product of 2 images.

Then 'this' image is rotated/translated. It is much faster than Rotate/Translate then dot product. 2D images only.

Parameters:
withThe image used to do the dot product.
dxTranslation distance in x direction.
dyTranslation distance in y direction.
daRotation euler angle in degrees
mirror
Exceptions:
ImageFormatExceptionIf the 2 images are not the same size.
ImageDimensionExceptionIf the image is 3D.
Returns:

Definition at line 1229 of file emdata.cpp.

References ENTERFUNC, EXITFUNC, EMAN::Util::fast_floor(), get_data(), get_ndim(), ImageDimensionException, ImageFormatException, EMAN::EMUtil::is_same_size(), LOGERR, nx, ny, t, and y.

Referenced by refalifnfast().

{
        ENTERFUNC;

        if (!EMUtil::is_same_size(this, with)) {
                LOGERR("images not same size");
                throw ImageFormatException("images not same size");
        }

        if (get_ndim() == 3) {
                LOGERR("1D/2D Images only");
                throw ImageDimensionException("1D/2D only");
        }

        float *this_data = 0;

        this_data = get_data();

        float da_rad = da*(float)M_PI/180.0f;

        float *with_data = with->get_data();
        float mx0 = cos(da_rad);
        float mx1 = sin(da_rad);
        float y = -ny / 2.0f;
        float my0 = mx0 * (-nx / 2.0f - 1.0f) + nx / 2.0f - dx;
        float my1 = -mx1 * (-nx / 2.0f - 1.0f) + ny / 2.0f - dy;
        double result = 0;

        for (int j = 0; j < ny; j++) {
                float x2 = my0 + mx1 * y;
                float y2 = my1 + mx0 * y;

                int ii = Util::fast_floor(x2);
                int jj = Util::fast_floor(y2);
                float t = x2 - ii;
                float u = y2 - jj;

                for (int i = 0; i < nx; i++) {
                        t += mx0;
                        u -= mx1;

                        if (t >= 1.0f) {
                                ii++;
                                t -= 1.0f;
                        }

                        if (u >= 1.0f) {
                                jj++;
                                u -= 1.0f;
                        }

                        if (t < 0) {
                                ii--;
                                t += 1.0f;
                        }

                        if (u < 0) {
                                jj--;
                                u += 1.0f;
                        }

                        if (ii >= 0 && ii <= nx - 2 && jj >= 0 && jj <= ny - 2) {
                                int k0 = ii + jj * nx;
                                int k1 = k0 + 1;
                                int k2 = k0 + nx + 1;
                                int k3 = k0 + nx;

                                float tt = 1 - t;
                                float uu = 1 - u;
                                int idx = i + j * nx;
                                if (mirror) idx = nx-1-i+j*nx; // mirroring of Transforms is always about the y axis
                                result += (this_data[k0] * tt * uu + this_data[k1] * t * uu +
                                                   this_data[k2] * t * u + this_data[k3] * tt * u) * with_data[idx];
                        }
                }
                y += 1.0f;
        }

        EXITFUNC;
        return result;
}
EMData * EMData::downsample ( Util::sincBlackman kb,
float  scale = 1.0 
)

Definition at line 3383 of file emdata_sparx.cpp.

References copy_head(), get_array_offsets(), get_pixel_filtered(), max, nx, ny, set_array_offsets(), set_size(), to_zero(), x, and y.

                                                            {

        /*int M = kb.get_sB_size();
        int kbmin = -M/2;
        int kbmax = -kbmin;*/

        int nxn, nyn, nzn;
        nxn = (int)(nx*scale); nyn = (int)(ny*scale); nzn = (int)(nz*scale);

        vector<int> saved_offsets = get_array_offsets();
        set_array_offsets(0,0,0);
        EMData* ret = this->copy_head();
#ifdef _WIN32
        ret->set_size(nxn, _cpp_max(nyn,1), _cpp_max(nzn,1));
#else
        ret->set_size(nxn, std::max(nyn,1), std::max(nzn,1));
#endif  //_WIN32
        ret->to_zero();  //we will leave margins zeroed.

        // scan new, find pixels in old
        if(nz == 1)
        {
                for (int iy =0; iy < nyn; iy++) {
                        float y = float(iy)/scale;
                        for (int ix = 0; ix < nxn; ix++) {
                                float x = float(ix)/scale;
                                (*ret)(ix,iy) = this->get_pixel_filtered(x, y, 1.0f, kb);
                        }
                }
        }
        else{
                
                for (int iz =0; iz < nzn; iz++) {
                        float z = float(iz)/scale;
                        for (int iy =0; iy < nyn; iy++) {
                                float y = float(iy)/scale;
                                for (int ix = 0; ix < nxn; ix++) {
                                        float x = float(ix)/scale;
                                        (*ret)(ix,iy,iz) = this->get_pixel_filtered(x, y, z, kb);
                                }
                        }
                }
        
        }
        set_array_offsets(saved_offsets);
        return ret;
}
bool EMData::equal ( const EMData that) const

compare the equality of two EMData object based on their pixel values

Definition at line 3016 of file emdata.cpp.

References get_const_data(), get_data(), get_size(), get_xsize(), get_ysize(), get_zsize(), nx, ny, and nz.

                                           {
        if (that.get_xsize() != nx || that.get_ysize() != ny || that.get_zsize() != nz ) return false;

        const float*  d1 = that.get_const_data();
        float* d2 = get_data();

        for(size_t i =0; i < get_size(); ++i,++d1,++d2) {
                if ((*d1) != (*d2)) return false;
        }

//      if(attr_dict != that.attr_dict) {
//              return false;
//      }

        return true;
}
EMData * EMData::extract_box ( const Transform cs,
const Region r 
)

Extract a box from EMData in an abritrary orrientation.

Used for extracting helix boxes from tomograms

EMData extract_box(const Transform& cs, const int ix, const int fx, const int iy, const int yf, const int zi, const int zf);

Parameters:
csTransform describing the coordinate system of the box realative to the standard coord system
rRegion describe the volume to extract, in the local coordinate system
Author:
John Flanagan
Date:
Aug 2011

Definition at line 4156 of file emdata.cpp.

References EMData(), EMAN::Util::fast_floor(), get_data(), EMAN::Region::get_depth(), EMAN::Region::get_height(), EMAN::Transform::get_matrix(), EMAN::Region::get_width(), get_xsize(), get_ysize(), nx, nxy, ny, nz, set_size(), t, EMAN::Util::trilinear_interpolate(), v, x, EMAN::Region::x_origin(), y, EMAN::Region::y_origin(), and EMAN::Region::z_origin().

{
        vector<float> cs_matrix = cs.get_matrix();
        
        EMData* box = new EMData();
        box->set_size((r.get_width()-r.x_origin()), (r.get_height()-r.y_origin()), (r.get_depth()-r.z_origin()));
        int box_nx = box->get_xsize();
        int box_ny = box->get_ysize();
        int box_nxy = box_nx*box_ny;
        float* bdata = box->get_data();
        float* ddata = get_data();
        
        for (int x = r.x_origin(); x < r.get_width(); x++) {
                for (int y = r.y_origin(); y < r.get_height(); y++) {
                        for (int z = r.z_origin(); z < r.get_depth(); z++) {
                                //float xb = cs_matrix[0]*x + cs_matrix[1]*y + cs_matrix[2]*z + cs_matrix[3];
                                //float yb = cs_matrix[4]*x + cs_matrix[5]*y + cs_matrix[6]*z + cs_matrix[7];
                                //float zb = cs_matrix[8]*x + cs_matrix[9]*y + cs_matrix[10]*z + cs_matrix[11];
                                float xb = cs_matrix[0]*x + y*cs_matrix[4] + z*cs_matrix[8] + cs_matrix[3];
                                float yb = cs_matrix[1]*x + y*cs_matrix[5] + z*cs_matrix[9] + cs_matrix[7];
                                float zb = cs_matrix[2]*x + y*cs_matrix[6] + z*cs_matrix[10] + cs_matrix[11];
                                float t = xb - Util::fast_floor(xb);
                                float u = yb - Util::fast_floor(yb);
                                float v = zb - Util::fast_floor(zb);
                                
                                //cout << x << " " << y << " " << z << " Box " << xb << " " << yb << " " << zb << endl;
                                int l = (x - r.x_origin()) + (y - r.y_origin())*box_nx + (z - r.z_origin())*box_nxy;
                                int k = (int) (Util::fast_floor(xb) + Util::fast_floor(yb) * nx + Util::fast_floor(zb) * nxy);
                                //cout << k << " " << l << endl;
                                if ( xb > nx - 1 || yb > ny - 1 || zb > nz - 1) {
                                        bdata[l] = 0;
                                        continue;
                                }
                                if (xb < 0 || yb < 0 || zb < 0){
                                        bdata[l] = 0;
                                        continue;
                                }

                                if (xb < (nx - 1) && yb < (ny - 1) && zb < (nz - 1)) {
                                        bdata[l] = Util::trilinear_interpolate(ddata[k], ddata[k + 1], ddata[k + nx],ddata[k + nx + 1], ddata[k + nxy], ddata[k + nxy + 1], ddata[k + nx + nxy], ddata[k + nx + nxy + 1],t, u, v);
                                }
                        }
                }
        }
        
        return box;
}
EMData * EMData::extract_plane ( const Transform tf,
Util::KaiserBessel kb 
)

extractplane -- Gridding convolution in 3D along a plane

Note: Expected to be used in combination with fourier gridding projections.

Parameters:
[in]tftransform matrix defining the intended plane.
[in]kbKaiser-Bessel window
Returns:
Complex gridding plane
See also:
P.A. Penczek, R. Renka, and H. Schomberg, J. Opt. Soc. Am. A _21_, 499-509 (2004)

Definition at line 4446 of file emdata_sparx.cpp.

References abs, cmplx(), cmplx(), get_array_offsets(), EMAN::Util::KaiserBessel::get_window_size(), EMAN::Util::KaiserBessel::i0win_tab(), ImageDimensionException, ImageFormatException, EMAN::Transform::invert(), is_complex(), nx, ny, EMAN::Util::round(), set_array_offsets(), set_array_offsets(), set_complex(), set_fftodd(), set_fftpad(), set_ri(), set_shuffled(), set_size(), EMAN::Util::sgn(), tf(), and to_zero().

Referenced by EMAN::FourierGriddingProjector::project3d(), and EMAN::Util::twoD_to_3D_ali().

                                                                       {
        if (!is_complex())
                throw ImageFormatException("extractplane requires a complex image");
        if (nx%2 != 0)
                throw ImageDimensionException("extractplane requires nx to be even");
        int nxreal = nx - 2;
        if (nxreal != ny || nxreal != nz)
                throw ImageDimensionException("extractplane requires ny == nx == nz");
        // build complex result image
        EMData* res = new EMData();
        res->set_size(nx,ny,1);
        res->to_zero();
        res->set_complex(true);
        res->set_fftodd(false);
        res->set_fftpad(true);
        res->set_ri(true);
        // Array offsets: (0..nhalf,-nhalf..nhalf-1,-nhalf..nhalf-1)
        int n = nxreal;
        int nhalf = n/2;
        vector<int> saved_offsets = get_array_offsets();
        set_array_offsets(0,-nhalf,-nhalf);
        res->set_array_offsets(0,-nhalf,0);
        // set up some temporary weighting arrays
        int kbsize =  kb.get_window_size();
        int kbmin  = -kbsize/2;
        int kbmax  = -kbmin;
        float* wy0 = new float[kbmax - kbmin + 1];
        float* wy  = wy0 - kbmin; // wy[kbmin:kbmax]
        float* wx0 = new float[kbmax - kbmin + 1];
        float* wx  = wx0 - kbmin;
        float* wz0 = new float[kbmax - kbmin + 1];
        float* wz  = wz0 - kbmin;
        float rim = nhalf*float(nhalf);
        int count = 0;
        float wsum = 0.f;
        Transform tftrans = tf; // need transpose of tf here for consistency
        tftrans.invert();      // with spider
        for (int jy = -nhalf; jy < nhalf; jy++) 
        {
                for (int jx = 0; jx <= nhalf; jx++) 
                {
                        Vec3f nucur((float)jx, (float)jy, 0.f);
                        Vec3f nunew = tftrans*nucur;
                        float xnew = nunew[0], ynew = nunew[1], znew = nunew[2];
                        if (xnew*xnew+ynew*ynew+znew*znew <= rim) 
                        {
                                count++;
                                std::complex<float> btq(0.f,0.f);
                                bool flip = false;
                                if (xnew < 0.f) {
                                        flip = true;
                                        xnew = -xnew;
                                        ynew = -ynew;
                                        znew = -znew;
                                }
                                int ixn = int(Util::round(xnew));
                                int iyn = int(Util::round(ynew));
                                int izn = int(Util::round(znew));
                                // populate weight arrays
                                for (int i=kbmin; i <= kbmax; i++) {
                                        int izp = izn + i;
                                        wz[i] = kb.i0win_tab(znew - izp);
                                        int iyp = iyn + i;
                                        wy[i] = kb.i0win_tab(ynew - iyp);
                                        int ixp = ixn + i;
                                        wx[i] = kb.i0win_tab(xnew - ixp);

                                }
                                // restrict weight arrays to non-zero elements
                                int lnbz = 0;
                                for (int iz = kbmin; iz <= -1; iz++) {
                                        if (wz[iz] != 0.f) {
                                                lnbz = iz;
                                                break;
                                        }
                                }
                                int lnez = 0;
                                for (int iz = kbmax; iz >= 1; iz--) {
                                        if (wz[iz] != 0.f) {
                                                lnez = iz;
                                                break;
                                        }
                                }
                                int lnby = 0;
                                for (int iy = kbmin; iy <= -1; iy++) {
                                        if (wy[iy] != 0.f) {
                                                lnby = iy;
                                                break;
                                        }
                                }
                                int lney = 0;
                                for (int iy = kbmax; iy >= 1; iy--) {
                                        if (wy[iy] != 0.f) {
                                                lney = iy;
                                                break;
                                        }
                                }
                                int lnbx = 0;
                                for (int ix = kbmin; ix <= -1; ix++) {
                                        if (wx[ix] != 0.f) {
                                                lnbx = ix;
                                                break;
                                        }
                                }
                                int lnex = 0;
                                for (int ix = kbmax; ix >= 1; ix--) {
                                        if (wx[ix] != 0.f) {
                                                lnex = ix;
                                                break;
                                        }
                                }
                                if    (ixn >= -kbmin      && ixn <= nhalf-1-kbmax
                                   && iyn >= -nhalf-kbmin && iyn <= nhalf-1-kbmax
                                   && izn >= -nhalf-kbmin && izn <= nhalf-1-kbmax) {
                                        // interior points
                                        for (int lz = lnbz; lz <= lnez; lz++) {
                                                int izp = izn + lz;
                                                for (int ly=lnby; ly<=lney; ly++) {
                                                        int iyp = iyn + ly;
                                                        float ty = wz[lz]*wy[ly];
                                                        for (int lx=lnbx; lx<=lnex; lx++) {
                                                                int ixp = ixn + lx;
                                                                float wg = wx[lx]*ty;
                                                                btq += cmplx(ixp,iyp,izp)*wg;
                                                                wsum += wg;
                                                        }
                                                }
                                        }
                                } else {
                                        // points "sticking out"
                                        for (int lz = lnbz; lz <= lnez; lz++) {
                                                int izp = izn + lz;
                                                for (int ly=lnby; ly<=lney; ly++) {
                                                        int iyp = iyn + ly;
                                                        float ty = wz[lz]*wy[ly];
                                                        for (int lx=lnbx; lx<=lnex; lx++) {
                                                                int ixp = ixn + lx;
                                                                float wg = wx[lx]*ty;
                                                                bool mirror = false;
                                                                int ixt(ixp), iyt(iyp), izt(izp);
                                                                if (ixt > nhalf || ixt < -nhalf) {
                                                                        ixt = Util::sgn(ixt)
                                                                                  *(n - abs(ixt));
                                                                        iyt = -iyt;
                                                                        izt = -izt;
                                                                        mirror = !mirror;
                                                                }
                                                                if (iyt >= nhalf || iyt < -nhalf) {
                                                                        if (ixt != 0) {
                                                                                ixt = -ixt;
                                                                                iyt = Util::sgn(iyt)
                                                                                          *(n - abs(iyt));
                                                                                izt = -izt;
                                                                                mirror = !mirror;
                                                                        } else {
                                                                                iyt -= n*Util::sgn(iyt);
                                                                        }
                                                                }
                                                                if (izt >= nhalf || izt < -nhalf) {
                                                                        if (ixt != 0) {
                                                                                ixt = -ixt;
                                                                                iyt = -iyt;
                                                                                izt = Util::sgn(izt)
                                                                                          *(n - abs(izt));
                                                                                mirror = !mirror;
                                                                        } else {
                                                                                izt -= Util::sgn(izt)*n;
                                                                        }
                                                                }
                                                                if (ixt < 0) {
                                                                        ixt = -ixt;
                                                                        iyt = -iyt;
                                                                        izt = -izt;
                                                                        mirror = !mirror;
                                                                }
                                                                if (iyt == nhalf) iyt = -nhalf;
                                                                if (izt == nhalf) izt = -nhalf;
                                                                if (mirror)   btq += conj(cmplx(ixt,iyt,izt))*wg;
                                                                else          btq += cmplx(ixt,iyt,izt)*wg;
                                                                wsum += wg;
                                                        }
                                                }
                                        }
                                }
                                if (flip)  res->cmplx(jx,jy) = conj(btq);
                                else       res->cmplx(jx,jy) = btq;
                        }
                }
        }
        for (int jy = -nhalf; jy < nhalf; jy++)
                for (int jx = 0; jx <= nhalf; jx++)
                        res->cmplx(jx,jy) *= count/wsum;
        delete[] wx0; delete[] wy0; delete[] wz0;
        set_array_offsets(saved_offsets);
        res->set_array_offsets(0,0,0);
        res->set_shuffled(true);
        return res;
}
EMData * EMData::extract_plane_rect ( const Transform tf,
Util::KaiserBessel kbx,
Util::KaiserBessel kby,
Util::KaiserBessel kbz 
)

Definition at line 4650 of file emdata_sparx.cpp.

References abs, cmplx(), cmplx(), get_array_offsets(), EMAN::Util::KaiserBessel::get_window_size(), EMAN::Util::KaiserBessel::i0win_tab(), ImageDimensionException, ImageFormatException, EMAN::Transform::invert(), is_complex(), max, nx, ny, EMAN::Util::round(), set_array_offsets(), set_array_offsets(), set_complex(), set_fftodd(), set_fftpad(), set_ri(), set_shuffled(), set_size(), EMAN::Util::sgn(), tf(), and to_zero().

                                                                                                                          {
        

        if (!is_complex())
                throw ImageFormatException("extractplane requires a complex image");
        if (nx%2 != 0)
                throw ImageDimensionException("extractplane requires nx to be even");

        int nxfromxyz = max( max(nx-2,ny), nz) + 2;
        //int nxfromz = nz+2;
        //int nxcircal = nxfromz - 2;
        int nxcircal = nxfromxyz - 2;
        EMData* res = new EMData();
        //res->set_size(nxfromz,nz,1);
        res->set_size(nxfromxyz,nxcircal,1);
        res->to_zero();
        res->set_complex(true);
        res->set_fftodd(false);
        res->set_fftpad(true);
        res->set_ri(true);
        // Array offsets: (0..nhalf,-nhalf..nhalf-1,-nhalf..nhalf-1)
        int n = nxcircal;
        int nhalf = n/2;
        int nxhalf = (nx-2)/2;
        int nyhalf = ny/2;
        int nzhalf = nz/2;
        
        vector<int> saved_offsets = get_array_offsets();
        set_array_offsets(0, -nyhalf, -nzhalf);
        res->set_array_offsets(0,-nhalf,0);
        // set up some temporary weighting arrays
        int kbxsize =  kbx.get_window_size();
        int kbxmin  = -kbxsize/2;
        int kbxmax  = -kbxmin;

        int kbysize =  kby.get_window_size();
        int kbymin  = -kbysize/2;
        int kbymax  = -kbymin;

        int kbzsize =  kbz.get_window_size();
        int kbzmin  = -kbzsize/2;
        int kbzmax  = -kbzmin;

        //std::cout<<"kb size x,y,z=="<<kbxsize<<" "<<kbysize<<" "<<kbzsize<<std::endl;
        float* wy0 = new float[kbymax - kbymin + 1];
        float* wy  = wy0 - kbymin; // wy[kbmin:kbmax]
        float* wx0 = new float[kbxmax - kbxmin + 1];
        float* wx  = wx0 - kbxmin;
        float* wz0 = new float[kbzmax - kbzmin + 1];
        float* wz  = wz0 - kbzmin;
        float rim = nhalf*float(nhalf);
        int count = 0;
        float wsum = 0.f;
        Transform tftrans = tf; // need transpose of tf here for consistency
        tftrans.invert();      // with spider
        float xratio=float(nx-2)/float(nxcircal);
        float yratio=float(ny)/float(nxcircal);
        float zratio=float(nz)/float(nxcircal);
        //std::cout<<"xratio,yratio=="<<xratio<<" "<<yratio<<std::endl;
        for (int jy = -nhalf; jy < nhalf; jy++) 
        {
                for (int jx = 0; jx <= nhalf; jx++) 
                {
                        Vec3f nucur((float)jx, (float)jy, 0.f);
                        Vec3f nunew = tftrans*nucur;
                        float xnew = nunew[0]*xratio, ynew = nunew[1]*yratio, znew = nunew[2]*zratio;
                        
                        if (nunew[0]*nunew[0]+nunew[1]*nunew[1]+nunew[2]*nunew[2] <= rim)
                        {
                                count++;
                                std::complex<float> btq(0.f,0.f);
                                bool flip = false;
                                if (xnew < 0.f) {
                                        flip = true;
                                        xnew = -xnew;
                                        ynew = -ynew;
                                        znew = -znew;
                                }
                                int ixn = int(Util::round(xnew));
                                int iyn = int(Util::round(ynew));
                                int izn = int(Util::round(znew));
                                // populate weight arrays
                                for (int i=kbzmin; i <= kbzmax; i++) {
                                        int izp = izn + i;
                                        wz[i] = kbz.i0win_tab(znew - izp);
                                        }
                                for (int i=kbymin; i <= kbymax; i++) {
                                        int iyp = iyn + i;
                                        wy[i] = kby.i0win_tab(ynew - iyp);
                                        }
                                for (int i=kbxmin; i <= kbxmax; i++) {
                                        int ixp = ixn + i;
                                        wx[i] = kbx.i0win_tab(xnew - ixp);
                                        }
                

                                
                                // restrict weight arrays to non-zero elements
                                int lnbz = 0;
                                for (int iz = kbzmin; iz <= -1; iz++) {
                                        if (wz[iz] != 0.f) {
                                                lnbz = iz;
                                                break;
                                        }
                                }
                                int lnez = 0;
                                for (int iz = kbzmax; iz >= 1; iz--) {
                                        if (wz[iz] != 0.f) {
                                                lnez = iz;
                                                break;
                                        }
                                }
                                int lnby = 0;
                                for (int iy = kbymin; iy <= -1; iy++) {
                                        if (wy[iy] != 0.f) {
                                                lnby = iy;
                                                break;
                                        }
                                }
                                int lney = 0;
                                for (int iy = kbymax; iy >= 1; iy--) {
                                        if (wy[iy] != 0.f) {
                                                lney = iy;
                                                break;
                                        }
                                }
                                int lnbx = 0;
                                for (int ix = kbxmin; ix <= -1; ix++) {
                                        if (wx[ix] != 0.f) {
                                                lnbx = ix;
                                                break;
                                        }
                                }
                                int lnex = 0;
                                for (int ix = kbxmax; ix >= 1; ix--) {
                                        if (wx[ix] != 0.f) {
                                                lnex = ix;
                                                break;
                                        }
                                }
                                if    (ixn >= -kbxmin      && ixn <= nxhalf-1-kbxmax
                                   && iyn >= -nyhalf-kbymin && iyn <= nyhalf-1-kbymax
                                   && izn >= -nzhalf-kbzmin && izn <= nzhalf-1-kbzmax) {
                                        // interior points
                                        for (int lz = lnbz; lz <= lnez; lz++) {
                                                int izp = izn + lz;
                                                for (int ly=lnby; ly<=lney; ly++) {
                                                        int iyp = iyn + ly;
                                                        float ty = wz[lz]*wy[ly];
                                                        for (int lx=lnbx; lx<=lnex; lx++) {
                                                                int ixp = ixn + lx;
                                                                float wg = wx[lx]*ty;
                                                                btq += cmplx(ixp,iyp,izp)*wg;
                                                                wsum += wg;
                                                        }
                                                }
                                        }
                                } 
                                else {
                                        // points "sticking out"
                                        for (int lz = lnbz; lz <= lnez; lz++) {
                                                int izp = izn + lz;
                                                for (int ly=lnby; ly<=lney; ly++) {
                                                        int iyp = iyn + ly;
                                                        float ty = wz[lz]*wy[ly];
                                                        for (int lx=lnbx; lx<=lnex; lx++) {
                                                                int ixp = ixn + lx;
                                                                float wg = wx[lx]*ty;
                                                                bool mirror = false;
                                                                int ixt(ixp), iyt(iyp), izt(izp);
                                                                if (ixt > nxhalf || ixt < -nxhalf) {
                                                                        ixt = Util::sgn(ixt)
                                                                                  *(nx-2-abs(ixt));
                                                                        iyt = -iyt;
                                                                        izt = -izt;
                                                                        mirror = !mirror;
                                                                }
                                                                if (iyt >= nyhalf || iyt < -nyhalf) {
                                                                        if (ixt != 0) {
                                                                                ixt = -ixt;
                                                                                iyt = Util::sgn(iyt)
                                                                                          *(ny - abs(iyt));
                                                                                izt = -izt;
                                                                                mirror = !mirror;
                                                                        } else {
                                                                                iyt -= ny*Util::sgn(iyt);
                                                                        }
                                                                }
                                                                if (izt >= nzhalf || izt < -nzhalf) {
                                                                        if (ixt != 0) {
                                                                                ixt = -ixt;
                                                                                iyt = -iyt;
                                                                                izt = Util::sgn(izt)
                                                                                          *(nz - abs(izt));
                                                                                mirror = !mirror;
                                                                        } else {
                                                                                izt -= Util::sgn(izt)*nz;
                                                                        }
                                                                }
                                                                if (ixt < 0) {
                                                                        ixt = -ixt;
                                                                        iyt = -iyt;
                                                                        izt = -izt;
                                                                        mirror = !mirror;
                                                                }
                                                                if (iyt == nyhalf) iyt = -nyhalf;
                                                                if (izt == nzhalf) izt = -nzhalf;
                                                                if (mirror)   btq += conj(cmplx(ixt,iyt,izt))*wg;
                                                                else          btq += cmplx(ixt,iyt,izt)*wg;
                                                                wsum += wg;
                                                        }
                                                }
                                        }
                                }
                                if (flip)  res->cmplx(jx,jy) = conj(btq);
                                else       res->cmplx(jx,jy) = btq;
                        }
                }
        }
        for (int jy = -nhalf; jy < nhalf; jy++)
                for (int jx = 0; jx <= nhalf; jx++)
                        res->cmplx(jx,jy) *= count/wsum;
        delete[] wx0; delete[] wy0; delete[] wz0;
        set_array_offsets(saved_offsets);
        res->set_array_offsets(0,0,0);
        res->set_shuffled(true);
        return res;
}
EMData * EMData::extract_plane_rect_fast ( const Transform tf,
Util::KaiserBessel kbx,
Util::KaiserBessel kby,
Util::KaiserBessel kbz 
)

Definition at line 4881 of file emdata_sparx.cpp.

References abs, cmplx(), cmplx(), get_array_offsets(), EMAN::Util::KaiserBessel::get_window_size(), EMAN::Util::KaiserBessel::i0win_tab(), ImageDimensionException, ImageFormatException, EMAN::Transform::invert(), is_complex(), nx, ny, EMAN::Util::round(), set_array_offsets(), set_array_offsets(), set_complex(), set_fftodd(), set_fftpad(), set_ri(), set_shuffled(), set_size(), EMAN::Util::sgn(), sqrt(), tf(), and to_zero().

                                                                                                                               {
        
        

        if (!is_complex())
                throw ImageFormatException("extractplane requires a complex image");
        if (nx%2 != 0)
                throw ImageDimensionException("extractplane requires nx to be even");

        int nxfromz=nz+2;
        int nxcircal = nxfromz - 2;

        // build complex result image
        float xratio=float(nx-2)/float(nz);
        float yratio=float(ny)/float(nz);
        Vec3f axis_newx,axis_newy;
        axis_newx[0] = xratio*0.5f*nz*tf[0][0];
        axis_newx[1] = yratio*0.5f*nz*tf[0][1];
        axis_newx[2] = 0.5f*nz*tf[0][2];


        float ellipse_length_x=std::sqrt(axis_newx[0]*axis_newx[0]+axis_newx[1]*axis_newx[1]+axis_newx[2]*axis_newx[2]);
        
        int ellipse_length_x_int=int(ellipse_length_x);
        float ellipse_step_x=0.5f*nz/float(ellipse_length_x_int);
        float xscale=ellipse_step_x;//scal increased

        axis_newy[0] = xratio*0.5f*nz*tf[1][0];
        axis_newy[1] = yratio*0.5f*nz*tf[1][1];
        axis_newy[2] = 0.5f*nz*tf[1][2];


        float ellipse_length_y=std::sqrt(axis_newy[0]*axis_newy[0]+axis_newy[1]*axis_newy[1]+axis_newy[2]*axis_newy[2]);
        int ellipse_length_y_int=int(ellipse_length_y);
        float ellipse_step_y=0.5f*nz/float(ellipse_length_y_int);
        float yscale=ellipse_step_y;
        //end of scaling factor calculation
        int nx_e=ellipse_length_x_int*2;
        int ny_e=ellipse_length_y_int*2;
        int nx_ec=nx_e+2;       

        EMData* res = new EMData();
        res->set_size(nx_ec,ny_e,1);
        res->to_zero();
        res->set_complex(true);
        res->set_fftodd(false);
        res->set_fftpad(true);
        res->set_ri(true);
        //std::cout<<"cpp fast extract_plane is called"<<std::endl;
        //std::cout<<"nx_e,ny_e===="<<nx_e<<"  "<<ny_e<<std::endl;
        // Array offsets: (0..nhalf,-nhalf..nhalf-1,-nhalf..nhalf-1)
        int n = nxcircal;
        int nhalf = n/2;
        int nhalfx_e = nx_e/2;
        int nhalfy_e = ny_e/2;
        int nxhalf=(nx-2)/2;
        int nyhalf=ny/2;
        int nzhalf=nz/2;
        //std::cout<<"nhalf,nxhalf,nyhalf,nzhalf=="<<nhalf<<" "<<nxhalf<<" "<<nyhalf<<" "<<nzhalf<<std::endl;
        vector<int> saved_offsets = get_array_offsets();
        set_array_offsets(0,-nyhalf,-nzhalf);
        res->set_array_offsets(0,-nhalfy_e,0);
        // set up some temporary weighting arrays
        int kbxsize =  kbx.get_window_size();
        int kbxmin  = -kbxsize/2;
        int kbxmax  = -kbxmin;

        int kbysize =  kby.get_window_size();
        int kbymin  = -kbysize/2;
        int kbymax  = -kbymin;

        int kbzsize =  kbz.get_window_size();
        int kbzmin  = -kbzsize/2;
        int kbzmax  = -kbzmin;

        //std::cout<<"kb size x,y,z=="<<kbxsize<<" "<<kbysize<<" "<<kbzsize<<std::endl;
        float* wy0 = new float[kbymax - kbymin + 1];
        float* wy  = wy0 - kbymin; // wy[kbmin:kbmax]
        float* wx0 = new float[kbxmax - kbxmin + 1];
        float* wx  = wx0 - kbxmin;
        float* wz0 = new float[kbzmax - kbzmin + 1];
        float* wz  = wz0 - kbzmin;
        float rim = nhalf*float(nhalf);
        int count = 0;
        float wsum = 0.f;
        Transform tftrans = tf; // need transpose of tf here for consistency
        tftrans.invert();      // with spider

        //std::cout<<"xratio,yratio=="<<xratio<<" "<<yratio<<std::endl;
        for (int jy = -nhalfy_e; jy < nhalfy_e; jy++) 
        {
                for (int jx = 0; jx <= nhalfx_e; jx++) 
                {
                        Vec3f nucur((float)jx, (float)jy, 0.f);
                        nucur[0]=nucur[0]*xscale;nucur[1]=nucur[1]*yscale;;
                        Vec3f nunew = tftrans*nucur;
                        float xnew = nunew[0]*xratio, ynew = nunew[1]*yratio, znew = nunew[2];
                        
                        if (nunew[0]*nunew[0]+nunew[1]*nunew[1]+nunew[2]*nunew[2] <= rim)
                        {
                                count++;
                                std::complex<float> btq(0.f,0.f);
                                bool flip = false;
                                if (xnew < 0.f) {
                                        flip = true;
                                        xnew = -xnew;
                                        ynew = -ynew;
                                        znew = -znew;
                                }
                                int ixn = int(Util::round(xnew));
                                int iyn = int(Util::round(ynew));
                                int izn = int(Util::round(znew));
                                // populate weight arrays
                                for (int i=kbzmin; i <= kbzmax; i++) {
                                        int izp = izn + i;
                                        wz[i] = kbz.i0win_tab(znew - izp);
                                        }
                                for (int i=kbymin; i <= kbymax; i++) {
                                        int iyp = iyn + i;
                                        wy[i] = kby.i0win_tab(ynew - iyp);
                                        }
                                for (int i=kbxmin; i <= kbxmax; i++) {
                                        int ixp = ixn + i;
                                        wx[i] = kbx.i0win_tab(xnew - ixp);
                                        }
                

                                
                                // restrict weight arrays to non-zero elements
                                int lnbz = 0;
                                for (int iz = kbzmin; iz <= -1; iz++) {
                                        if (wz[iz] != 0.f) {
                                                lnbz = iz;
                                                break;
                                        }
                                }
                                int lnez = 0;
                                for (int iz = kbzmax; iz >= 1; iz--) {
                                        if (wz[iz] != 0.f) {
                                                lnez = iz;
                                                break;
                                        }
                                }
                                int lnby = 0;
                                for (int iy = kbymin; iy <= -1; iy++) {
                                        if (wy[iy] != 0.f) {
                                                lnby = iy;
                                                break;
                                        }
                                }
                                int lney = 0;
                                for (int iy = kbymax; iy >= 1; iy--) {
                                        if (wy[iy] != 0.f) {
                                                lney = iy;
                                                break;
                                        }
                                }
                                int lnbx = 0;
                                for (int ix = kbxmin; ix <= -1; ix++) {
                                        if (wx[ix] != 0.f) {
                                                lnbx = ix;
                                                break;
                                        }
                                }
                                int lnex = 0;
                                for (int ix = kbxmax; ix >= 1; ix--) {
                                        if (wx[ix] != 0.f) {
                                                lnex = ix;
                                                break;
                                        }
                                }
                                if    (ixn >= -kbxmin      && ixn <= nxhalf-1-kbxmax
                                   && iyn >= -nyhalf-kbymin && iyn <= nyhalf-1-kbymax
                                   && izn >= -nzhalf-kbzmin && izn <= nzhalf-1-kbzmax) {
                                        // interior points
                                        for (int lz = lnbz; lz <= lnez; lz++) {
                                                int izp = izn + lz;
                                                for (int ly=lnby; ly<=lney; ly++) {
                                                        int iyp = iyn + ly;
                                                        float ty = wz[lz]*wy[ly];
                                                        for (int lx=lnbx; lx<=lnex; lx++) {
                                                                int ixp = ixn + lx;
                                                                float wg = wx[lx]*ty;
                                                                btq += cmplx(ixp,iyp,izp)*wg;
                                                                wsum += wg;
                                                        }
                                                }
                                        }
                                } 
                                else {
                                        // points "sticking out"
                                        for (int lz = lnbz; lz <= lnez; lz++) {
                                                int izp = izn + lz;
                                                for (int ly=lnby; ly<=lney; ly++) {
                                                        int iyp = iyn + ly;
                                                        float ty = wz[lz]*wy[ly];
                                                        for (int lx=lnbx; lx<=lnex; lx++) {
                                                                int ixp = ixn + lx;
                                                                float wg = wx[lx]*ty;
                                                                bool mirror = false;
                                                                int ixt(ixp), iyt(iyp), izt(izp);
                                                                if (ixt > nxhalf || ixt < -nxhalf) {
                                                                        ixt = Util::sgn(ixt)
                                                                                  *(nx-2-abs(ixt));
                                                                        iyt = -iyt;
                                                                        izt = -izt;
                                                                        mirror = !mirror;
                                                                }
                                                                if (iyt >= nyhalf || iyt < -nyhalf) {
                                                                        if (ixt != 0) {
                                                                                ixt = -ixt;
                                                                                iyt = Util::sgn(iyt)
                                                                                          *(ny - abs(iyt));
                                                                                izt = -izt;
                                                                                mirror = !mirror;
                                                                        } else {
                                                                                iyt -= ny*Util::sgn(iyt);
                                                                        }
                                                                }
                                                                if (izt >= nzhalf || izt < -nzhalf) {
                                                                        if (ixt != 0) {
                                                                                ixt = -ixt;
                                                                                iyt = -iyt;
                                                                                izt = Util::sgn(izt)
                                                                                          *(nz - abs(izt));
                                                                                mirror = !mirror;
                                                                        } else {
                                                                                izt -= Util::sgn(izt)*nz;
                                                                        }
                                                                }
                                                                if (ixt < 0) {
                                                                        ixt = -ixt;
                                                                        iyt = -iyt;
                                                                        izt = -izt;
                                                                        mirror = !mirror;
                                                                }
                                                                if (iyt == nyhalf) iyt = -nyhalf;
                                                                if (izt == nzhalf) izt = -nzhalf;
                                                                if (mirror)   btq += conj(cmplx(ixt,iyt,izt))*wg;
                                                                else          btq += cmplx(ixt,iyt,izt)*wg;
                                                                wsum += wg;
                                                        }
                                                }
                                        }
                                }
                                if (flip)  res->cmplx(jx,jy) = conj(btq);
                                else       res->cmplx(jx,jy) = btq;
                        }
                }
        }
        for (int jy = -nhalfy_e; jy < nhalfy_e; jy++)
                for (int jx = 0; jx <= nhalfx_e; jx++)
                        res->cmplx(jx,jy) *= count/wsum;
        delete[] wx0; delete[] wy0; delete[] wz0;
        set_array_offsets(saved_offsets);
        res->set_array_offsets(0,0,0);
        res->set_shuffled(true);
        return res;
}
EMData * EMData::extractline ( Util::KaiserBessel kb,
float  nuxnew,
float  nuynew 
)

Definition at line 4037 of file emdata_sparx.cpp.

References abs, cmplx(), cmplx(), get_array_offsets(), EMAN::Util::KaiserBessel::get_window_size(), EMAN::Util::KaiserBessel::i0win_tab(), ImageDimensionException, ImageFormatException, is_complex(), nx, ny, EMAN::Util::round(), set_array_offsets(), set_array_offsets(), set_complex(), set_fftodd(), set_fftpad(), set_ri(), set_size(), EMAN::Util::sgn(), and to_zero().

{
        if (!is_complex())
                throw ImageFormatException("extractline requires a fourier image");
        if (nx%2 != 0)
                throw ImageDimensionException("extractline requires nx to be even");
        int nxreal = nx - 2;
        if (nxreal != ny)
                throw ImageDimensionException("extractline requires ny == nx");
        // build complex result image
        EMData* res = new EMData();
        res->set_size(nx,1,1);
        res->to_zero();
        res->set_complex(true);
        res->set_fftodd(false);
        res->set_fftpad(true);
        res->set_ri(true);
        // Array offsets: (0..nhalf,-nhalf..nhalf-1)
        int n = nxreal;
        int nhalf = n/2;
        vector<int> saved_offsets = get_array_offsets();
        set_array_offsets(0,-nhalf,-nhalf);

        // set up some temporary weighting arrays
        int kbsize = kb.get_window_size();
        int kbmin = -kbsize/2;
        int kbmax = -kbmin;
        float* wy0 = new float[kbmax - kbmin + 1];
        float* wy = wy0 - kbmin; // wy[kbmin:kbmax]
        float* wx0 = new float[kbmax - kbmin + 1];
        float* wx = wx0 - kbmin;

        int   count = 0;
        float wsum = 0.f;
        bool  flip = (nuxnew < 0.f);

        for (int jx = 0; jx <= nhalf; jx++) {
                float xnew = jx*nuxnew, ynew = jx*nuynew;
                count++;
                std::complex<float> btq(0.f,0.f);
                if (flip) {
                        xnew = -xnew;
                        ynew = -ynew;
                }
                int ixn = int(Util::round(xnew));
                int iyn = int(Util::round(ynew));
                // populate weight arrays
                for (int i=kbmin; i <= kbmax; i++) {
                        int iyp = iyn + i;
                        wy[i] = kb.i0win_tab(ynew - iyp);
                        int ixp = ixn + i;
                        wx[i] = kb.i0win_tab(xnew - ixp);
                }
                // restrict weight arrays to non-zero elements

                int lnby = 0;
                for (int iy = kbmin; iy <= -1; iy++) {
                        if (wy[iy] != 0.f) {
                                lnby = iy;
                                break;
                        }
                }
                int lney = 0;
                for (int iy = kbmax; iy >= 1; iy--) {
                        if (wy[iy] != 0.f) {
                                lney = iy;
                                break;
                        }
                }
                int lnbx = 0;
                for (int ix = kbmin; ix <= -1; ix++) {
                        if (wx[ix] != 0.f) {
                                lnbx = ix;
                                break;
                        }
                }
                int lnex = 0;
                for (int ix = kbmax; ix >= 1; ix--) {
                        if (wx[ix] != 0.f) {
                                lnex = ix;
                                break;
                        }
                }
                if (ixn >= -kbmin && ixn <= nhalf-1-kbmax
                                && iyn >= -nhalf-kbmin && iyn <= nhalf-1-kbmax) {
                        // interior points
                        for (int ly=lnby; ly<=lney; ly++) {
                                int iyp = iyn + ly;
                                for (int lx=lnbx; lx<=lnex; lx++) {
                                        int ixp = ixn + lx;
                                        float wg = wx[lx]*wy[ly];
                                        btq += cmplx(ixp,iyp)*wg;
                                        wsum += wg;
                                }
                        }
                } else {
                        // points "sticking out"
                        for (int ly=lnby; ly<=lney; ly++) {
                                int iyp = iyn + ly;
                                for (int lx=lnbx; lx<=lnex; lx++) {
                                        int ixp = ixn + lx;
                                        float wg = wx[lx]*wy[ly];
                                        bool mirror = false;
                                        int ixt(ixp), iyt(iyp);
                                        if (ixt > nhalf || ixt < -nhalf) {
                                                ixt = Util::sgn(ixt)*(n - abs(ixt));
                                                iyt = -iyt;
                                                mirror = !mirror;
                                        }
                                        if (iyt >= nhalf || iyt < -nhalf) {
                                                if (ixt != 0) {
                                                        ixt = -ixt;
                                                        iyt = Util::sgn(iyt)*(n - abs(iyt));
                                                        mirror = !mirror;
                                                } else {
                                                        iyt -= n*Util::sgn(iyt);
                                                }
                                        }
                                        if (ixt < 0) {
                                                ixt = -ixt;
                                                iyt = -iyt;
                                                mirror = !mirror;
                                        }
                                        if (iyt == nhalf) iyt = -nhalf;
                                        if (mirror) btq += conj(cmplx(ixt,iyt))*wg;
                                        else        btq += cmplx(ixt,iyt)*wg;
                                        wsum += wg;
                                }
                        }
                }
                if (flip) res->cmplx(jx) = conj(btq);
                else      res->cmplx(jx) = btq;
        }
        for (int jx = 0; jx <= nhalf; jx++)  res->cmplx(jx) *= count/wsum;

        delete[] wx0; delete[] wy0;
        set_array_offsets(saved_offsets);
        res->set_array_offsets(0,0,0);
        return res;
}
std::complex< float > EMData::extractpoint ( float  xin,
float  yin,
Util::KaiserBessel kb 
)

extractpoint -- Gridding convolution

Note: Expected to be used in combination with fouriergridrot2d.

Parameters:
[in]xinx-position
[in]yiny-position
[in]kbKaiser-Bessel window
Returns:
Complex gridding result
See also:
P.A. Penczek, R. Renka, and H. Schomberg, J. Opt. Soc. Am. A _21_, (2004)

Definition at line 3925 of file emdata_sparx.cpp.

References cmplx(), get_ndim(), EMAN::Util::KaiserBessel::get_window_size(), EMAN::Util::KaiserBessel::i0win_tab(), ImageDimensionException, ImageFormatException, is_complex(), nx, ny, and EMAN::Util::round().

                                                                                       {
        if (2 != get_ndim())
                throw ImageDimensionException("extractpoint needs a 2-D image.");
        if (!is_complex())
                throw ImageFormatException("extractpoint requires a fourier image");
        int nxreal = nx - 2;
        if (nxreal != ny)
                throw ImageDimensionException("extractpoint requires ny == nx");
        int nhalf = nxreal/2;
        int kbsize = kb.get_window_size();
        int kbmin = -kbsize/2;
        int kbmax = -kbmin;
        bool flip = (nuxnew < 0.f);
        if (flip) {
                nuxnew *= -1;
                nuynew *= -1;
        }
        // put (xnew,ynew) on a grid.  The indices will be wrong for
        // the Fourier elements in the image, but the grid sizing will
        // be correct.
        int ixn = int(Util::round(nuxnew));
        int iyn = int(Util::round(nuynew));
        // set up some temporary weighting arrays
        float* wy0 = new float[kbmax - kbmin + 1];
        float* wy = wy0 - kbmin; // wy[kbmin:kbmax]
        float* wx0 = new float[kbmax - kbmin + 1];
        float* wx = wx0 - kbmin;
        for (int i = kbmin; i <= kbmax; i++) {
                        int iyp = iyn + i;
                        wy[i] = kb.i0win_tab(nuynew - iyp);
                        int ixp = ixn + i;
                        wx[i] = kb.i0win_tab(nuxnew - ixp);
        }
        // restrict loops to non-zero elements
        int iymin = 0;
        for (int iy = kbmin; iy <= -1; iy++) {
                if (wy[iy] != 0.f) {
                        iymin = iy;
                        break;
                }
        }
        int iymax = 0;
        for (int iy = kbmax; iy >= 1; iy--) {
                if (wy[iy] != 0.f) {
                        iymax = iy;
                        break;
                }
        }
        int ixmin = 0;
        for (int ix = kbmin; ix <= -1; ix++) {
                if (wx[ix] != 0.f) {
                        ixmin = ix;
                        break;
                }
        }
        int ixmax = 0;
        for (int ix = kbmax; ix >= 1; ix--) {
                if (wx[ix] != 0.f) {
                        ixmax = ix;
                        break;
                }
        }
        float wsum = 0.0f;
        for (int iy = iymin; iy <= iymax; iy++)
                for (int ix = ixmin; ix <= ixmax; ix++)
                        wsum += wx[ix]*wy[iy];
        std::complex<float> result(0.f,0.f);
        if ((ixn >= -kbmin) && (ixn <= nhalf-1-kbmax) && (iyn >= -nhalf-kbmin) && (iyn <= nhalf-1-kbmax)) {
                // (xin,yin) not within window border from the edge
                for (int iy = iymin; iy <= iymax; iy++) {
                        int iyp = iyn + iy;
                        for (int ix = ixmin; ix <= ixmax; ix++) {
                                int ixp = ixn + ix;
                                float w = wx[ix]*wy[iy];
                                std::complex<float> val = cmplx(ixp,iyp);
                                result += val*w;
                        }
                }
        } else {
                // points that "stick out"
                for (int iy = iymin; iy <= iymax; iy++) {
                        int iyp = iyn + iy;
                        for (int ix = ixmin; ix <= ixmax; ix++) {
                                int ixp = ixn + ix;
                                bool mirror = false;
                                int ixt= ixp, iyt= iyp;
                                if (ixt < 0) {
                                        ixt = -ixt;
                                        iyt = -iyt;
                                        mirror = !mirror;
                                }
                                if (ixt > nhalf) {
                                        ixt = nxreal - ixt;
                                        iyt = -iyt;
                                        mirror = !mirror;
                                }
                                if (iyt > nhalf-1)  iyt -= nxreal;
                                if (iyt < -nhalf)   iyt += nxreal;
                                float w = wx[ix]*wy[iy];
                                std::complex<float> val = this->cmplx(ixt,iyt);
                                if (mirror)  result += conj(val)*w;
                                else         result += val*w;
                        }
                }
        }
        if (flip)  result = conj(result)/wsum;
        else       result /= wsum;
        delete [] wx0;
        delete [] wy0;
        return result;
}
void EMData::fft_shuffle ( )

2-D rotation using gridding convolution.

The only requirement for the window function object is that it overload operator()(const float) and return a float.

This routine does _not_ deconvolve out the window function after rotation.

Parameters:
[in]xx-value of the desired (potentially off-grid) point
[in]yy-value of the desired (potentially off-grid) point
[in]winWindow (mask/kernel) function object.
[in]sizeSize of real-space kernel/mask.
Exceptions:
ImageDimensionExceptiononly support 2D image
Returns:
Rotated/convolved EMData image. fft_shuffle -- Shuffle a Fourier image to put the origin at (0,ny/2)

Our usual FFT convention puts the origin at (0,0), but then grid points corresponding to iy > ny/2 correspond to (unnormalized) frequencies iy-ny. This routine rearranges the columns of the Fourier image so that iy varies from -ny/2 to ny/2 (or ny/2 - 1 for ny even). This method acts as a toggle, so to unshuffle a Fourier image just call this method a second time.

Definition at line 4186 of file emdata_sparx.cpp.

References get_array_offsets(), ImageFormatException, is_complex(), is_shuffled(), nx, ny, set_array_offsets(), set_shuffled(), swapx(), and update().

Referenced by fouriergridrot2d(), fouriergridrot_shift2d(), EMAN::FourierGriddingProjector::project3d(), EMAN::Util::twoD_to_3D_ali(), and write_image().

                         {
        if (!is_complex())
                throw ImageFormatException("fft_shuffle requires a fourier image");
        vector<int> offsets = get_array_offsets();
        set_array_offsets(); // clear offsets before shuffling
        EMData& self = *this;
        int nyhalf = ny/2;
        int nzhalf = nz/2;
        int nbytes = nx*sizeof(float);
        float* temp = new float[nx];
        for (int iz=0; iz < nz; iz++)
                for (int iy=0; iy < nyhalf; iy++)
                        swapx(&self(0,iy,iz),&self(0,iy+nyhalf,iz),temp,nbytes);
        if (nz > 1) {
                for (int iy=0; iy < ny; iy++)
                        for (int iz=0; iz < nzhalf; iz++)
                                swapx(&self(0,iy,iz),&self(0,iy,iz+nzhalf),temp,nbytes);
        }
        set_shuffled(!is_shuffled()); // toggle
        set_array_offsets(offsets); // reset offsets
        update();
        delete[] temp;
}
EMData * EMData::FH2F ( int  Size,
float  OverSamplekB,
int  IntensityFlag = 0 
)

returns the fourier version of the image from the FH version.

The current image is not changed. The result is in real/imaginary format. The FH switch is set off.

Parameters:
Sizeis the size of the image to be returned
OverSamplekBis a parameter controlling the fineness of the Fourier sampling
IntensityFlag=0 is the usual; =1 means that the input was an intensity
Returns:
the shuffled version of the FFT

Definition at line 245 of file emdata_sparx.cpp.

References copy(), copy(), get_xsize(), get_ysize(), get_ysize(), get_zsize(), get_zsize(), ImageFormatException, LOGERR, nx, ny, Radialize(), set_complex(), set_complex_x(), set_fftodd(), set_FH(), set_ri(), set_shuffled(), set_size(), spline_mat(), sqrt(), to_zero(), and update().

{
        int nx=get_xsize();
        int ny=get_ysize();
        int nz=get_zsize();
        float ScalFactor=4.1f;
        int Center = (int) floor((Size+1.0)/2.0 +.1);
        int CenterM= Center-1;
        int CountMax = (Center+1)*Center/2;

        int     *PermMatTr           = new int[CountMax];
        float  *RValsSorted         = new float[CountMax];
        float  *weightofkValsSorted = new float[CountMax];
        int      *SizeReturned        = new int[1];
        Util::Radialize(PermMatTr, RValsSorted,weightofkValsSorted,Size, SizeReturned);
        int RIntMax= SizeReturned[0];  // replaces CountMax; the latter should now never be used.
//      kVec2Use = (0:1/OverSamplek:RValsSorted(RIntMax)+1/OverSamplek); %   in pixels  (otherwise need *2*pi/Size)

        int   mMax = (int) floor( ScalFactor*RValsSorted[RIntMax-1]+10.0);

        int    kIntMax  = 2+ (int) floor( RValsSorted[RIntMax-1]*OverSamplekB);
        float *kVec2Use = new float[kIntMax];
        for (int kk=0; kk<kIntMax; kk++){
                kVec2Use[kk]= ((float) kk)/OverSamplekB;}



#ifdef DEBUG
        printf("nx=%d, ny=%d, nz=%d Center=%d mMax=%d CountMax=%d kIntMax=%d Centerm1=%d  Size=%d\n\n",
            nx,ny,nz, Center, mMax, CountMax, kIntMax,  CenterM, Size);
#endif

        EMData * rhoOfkmB = this;

//     check mMax's are equal
//     check kIntMax's are equal

        if ( (nx==2*(mMax+1)) && (ny==kIntMax) &&(nz==1) ) {

        EMData *rhoOfkandm = copy();
        rhoOfkandm ->set_size(2*(mMax+1),RIntMax);
        rhoOfkandm ->to_zero();
//      MArray2D rhoOfkandm = tempCopy->get_2dview();  % Just changed Nov 20 2005
//      printf("rhoOfkandm \n");
        for (int mr=0; mr <2*(mMax+1); mr++){
                float *Row= new float[kIntMax];
                float *RowOut= new float[RIntMax];
                for (int ii=0; ii<kIntMax; ii++){ Row[ii]=(*rhoOfkmB)(mr,ii);}
                Util::spline_mat(kVec2Use, Row, kIntMax,  RValsSorted, RowOut, RIntMax );
                for (int ii=0; ii<RIntMax; ii++){
                        (*rhoOfkandm)(mr,ii) = RowOut[ii];
//                      printf("%3.3f  ",RowOut[ii]);
                }
//              printf(" \n");
//              rhoOfkandm(m+1,:) = spline(kVec2Use,rhoOfkmBReIm(m+1,1:kIntMax),kIntMax,RValsSorted);
        }
        rhoOfkandm ->update();

//          So far so good PRB ....

        EMData* outCopy = rhoOfkandm ->copy();
        outCopy->set_size(2*Size,Size,1);
        outCopy->to_zero();
//      MArray2D ImBWfftRm = outCopy->get_2dview();

        int Count =0, kInt, kIntm1;
        std::complex <float> ImfTemp;
        float kValue, thetak;

        for (int jkx=0; jkx <Center; jkx++) { // These index the outputted picture
                for (int jky=0; jky<=jkx; jky++){
                        kInt = PermMatTr[Count];
                        kIntm1= kInt-1;
                        Count++;
                        float fjkx = float(jkx);
                        float fjky = float(jky);

                        kValue = std::sqrt(fjkx*fjkx +  fjky*fjky )  ;
//                      mMaxR= floor(ScalFactor*kValue +10);

 //                   How many copies

                        thetak = atan2(fjky,fjkx);
                        ImfTemp = (*rhoOfkandm)(0, kIntm1) ;
                        for (int mm= 1; mm <mMax;mm++) {  // The index for m
                                std::complex <float> fact(0,-mm*thetak);
                                std::complex <float> expfact= exp(fact);
                                std::complex <float> tempRho((*rhoOfkandm)(2*mm,kIntm1),(*rhoOfkandm)(2*mm+1,kIntm1));
                                float mmFac = float(1-2*(mm%2));
                                if (IntensityFlag==1){ mmFac=1;}
                                ImfTemp +=   expfact * tempRho + mmFac  *conj(expfact*tempRho);//pow(float(-1),mm)
                        }
                        (*outCopy)(2*(CenterM+jkx),CenterM+jky)   = ImfTemp.real();
                        (*outCopy)(2*(CenterM+jkx)+1,CenterM+jky) = ImfTemp.imag();
//                      printf("jkx=%d, jky=%d; %f + %f i \n",jkx,jky,ImfTemp.real(), ImfTemp.imag());

                        if (jky>0) {
                                thetak = atan2(-fjky,fjkx);
                                ImfTemp = (*rhoOfkandm)(0,kIntm1);
                                for (int mm= 1; mm<mMax; mm++) { // The index for m
                                        std::complex <float> fact(0,-mm*thetak);
                                        std::complex <float> expfact= exp(fact);
                                        std::complex <float> tempRho((*rhoOfkandm)(2*mm,kIntm1), (*rhoOfkandm)(2*mm+1,kIntm1));
                                        float mmFac = float(1-2*(mm%2));
                                        if (IntensityFlag==1){ mmFac=1;}
                                        ImfTemp +=   expfact * tempRho +  mmFac  *conj(expfact*tempRho);
                                }
                                (*outCopy)(2*(CenterM+jkx),CenterM-jky)  = ImfTemp.real();

                                (*outCopy)(2*(CenterM+jkx)+1,CenterM-jky) = ImfTemp.imag();
                        }

                        if (jkx>0) {
                                thetak = atan2(fjky,-fjkx);
                                ImfTemp = (*rhoOfkandm)(0,kIntm1);
                                for (int mm= 1; mm<mMax; mm++) { // The index for m
                                        std::complex <float> fact(0,-mm*thetak);
                                        std::complex <float> expfact= exp(fact);
                                        std::complex <float> tempRho((*rhoOfkandm)(2*mm,kIntm1), (*rhoOfkandm)(2*mm+1,kIntm1));
                                        float mmFac = float(1-2*(mm%2));
                                        if (IntensityFlag==1){ mmFac=1;}
                                        ImfTemp +=   expfact * tempRho +  mmFac *conj(expfact*tempRho);
                                }
                                (*outCopy)(2*(CenterM-jkx)  ,CenterM+jky) = ImfTemp.real();
                                (*outCopy)(2*(CenterM-jkx)+1,CenterM+jky) = ImfTemp.imag();
                        }

                        if (jkx>0 && jky>0) {
                                thetak = atan2(-fjky,-fjkx);
                                ImfTemp = (*rhoOfkandm)(0 , kIntm1);
                                for (int mm= 1; mm<mMax; mm++) {  // The index for m
                                        std::complex <float> fact(0,-mm*thetak);
                                        std::complex <float> expfact= exp(fact);
                                        std::complex <float> tempRho( (*rhoOfkandm)(2*mm,kIntm1),(*rhoOfkandm)(2*mm+1,kIntm1) );
                                        float mmFac = float(1-2*(mm%2));
                                        if (IntensityFlag==1){ mmFac=1;}
                                        ImfTemp +=   expfact * tempRho +  mmFac *conj(expfact*tempRho);
                                }
                                (*outCopy)(2*(CenterM-jkx)  ,CenterM-jky) = ImfTemp.real();
                                (*outCopy)(2*(CenterM-jkx)+1,CenterM-jky) = ImfTemp.imag();
                        }

                        if (jky< jkx) {
                                thetak = atan2(fjkx,fjky);
                                ImfTemp = (*rhoOfkandm)(0,kIntm1);
                                for (int mm= 1; mm<mMax; mm++){ // The index for m
                                        std::complex <float> fact(0,-mm*thetak);
                                        std::complex <float> expfact= exp(fact);
                                        std::complex <float> tempRho((*rhoOfkandm)(2*mm,kIntm1),(*rhoOfkandm)(2*mm+1,kIntm1));
                                        float mmFac = float(1-2*(mm%2));
                                        if (IntensityFlag==1){ mmFac=1;}
                                        ImfTemp +=   expfact * tempRho +  mmFac *conj(expfact*tempRho);
                                }
                                (*outCopy)(2*(CenterM+jky)  ,CenterM+jkx) = ImfTemp.real();
                                (*outCopy)(2*(CenterM+jky)+1,CenterM+jkx) = ImfTemp.imag();

                                if (jky>0){
                                        thetak = atan2(fjkx,-fjky);
                                        ImfTemp = (*rhoOfkandm)(0, kIntm1);
                                        for (int mm= 1; mm <mMax; mm++) { // The index for m
                                                std::complex <float> fact(0,-mm*thetak);
                                                std::complex <float> expfact= exp(fact);
                                                std::complex <float> tempRho((*rhoOfkandm)(2*mm,kIntm1),(*rhoOfkandm)(2*mm+1,kIntm1));
                                        float mmFac = float(1-2*(mm%2));
                                        if (IntensityFlag==1){ mmFac=1;}
                                                ImfTemp +=  expfact * tempRho +  mmFac *conj(expfact*tempRho);
                                        }
                                        (*outCopy)(2*(CenterM-jky)  ,CenterM+jkx) = ImfTemp.real();
                                        (*outCopy)(2*(CenterM-jky)+1,CenterM+jkx) = ImfTemp.imag();
                                }

                                 if (jkx>0) {
                                         thetak = atan2(-fjkx,fjky);
                                         ImfTemp = (*rhoOfkandm)(0,kIntm1);
                                        for (int mm= 1; mm <mMax; mm++) { // The index for m
                                                std::complex <float> fact(0,-mm*thetak);
                                                std::complex <float> expfact= exp(fact);
                                                std::complex <float> tempRho((*rhoOfkandm)(2*mm,kIntm1),(*rhoOfkandm)(2*mm+1,kIntm1));
                                                float mmFac = float(1-2*(mm%2));
                                                if (IntensityFlag==1){ mmFac=1;}
                                                ImfTemp +=  expfact * tempRho +  mmFac *conj(expfact*tempRho);
                                        }
                                        (*outCopy)(2*(CenterM+jky)  ,CenterM-jkx) = ImfTemp.real();
                                        (*outCopy)(2*(CenterM+jky)+1,CenterM-jkx) = ImfTemp.imag();
                                }

                                if (jkx>0 && jky>0) {
                                        thetak = atan2(-fjkx,-fjky);
                                        ImfTemp = (*rhoOfkandm)(0,kIntm1) ;
                                        for (int mm= 1; mm <mMax; mm++) { // The index for m
                                                std::complex <float> fact(0,-mm*thetak);
                                                std::complex <float> expfact= exp(fact);
                                                std::complex <float> tempRho((*rhoOfkandm)(2*mm,kIntm1) ,(*rhoOfkandm)(2*mm+1,kIntm1) );
                                                float mmFac = float(1-2*(mm%2));
                                                if (IntensityFlag==1){ mmFac=1;}
                                                ImfTemp +=  expfact * tempRho +  mmFac *conj(expfact*tempRho);
                                        }
                                        (*outCopy)(2*(CenterM-jky)  ,CenterM-jkx) = ImfTemp.real();
                                        (*outCopy)(2*(CenterM-jky)+1,CenterM-jkx) = ImfTemp.imag();
                                }
                        } // ends jky <jkx


                } // ends jky
        } // ends jkx
        outCopy->update();
        outCopy->set_complex(true);
        if(outCopy->get_ysize()==1 && outCopy->get_zsize()==1) outCopy->set_complex_x(true);
        outCopy->set_ri(true);
        outCopy->set_FH(false);
        outCopy->set_fftodd(true);
        outCopy->set_shuffled(true);
        return outCopy;
        } else {
                LOGERR("can't be an FH image not this size");
                throw ImageFormatException("something strange about this image: not a FH");

        }
}  // ends FH2F
EMData * EMData::FH2Real ( int  Size,
float  OverSamplekB,
int  IntensityFlag = 0 
)

returns the real version of the image from the FH version.

The current image is not changed. The result is in real format.

Parameters:
Sizeis the size of the image to be returned
OverSamplekBis a parameter controlling the fineness of the Fourier sampling
IntensityFlag=0 is the usual; =1 means that the input was an intensity
Returns:
the real version of the data

Definition at line 466 of file emdata_sparx.cpp.

References do_ift(), FH2F(), and process_inplace().

{
        EMData* FFT= FH2F(Size,OverSamplekB,0);
        FFT->process_inplace("xform.fourierorigin.tocorner");
        EMData* eguess= FFT ->do_ift();
        return eguess;
}  // ends FH2F
EMData * EMData::filter_by_image ( EMData image,
bool  RetReal = true 
)

Definition at line 7467 of file emdata_sparx.cpp.

References cmplx(), copy(), depad(), do_fft_inplace(), do_ift_inplace(), fint, get_data(), get_xsize(), get_ysize(), get_zsize(), is_complex(), is_fftodd(), norm_pad(), nx, ny, set_array_offsets(), set_attr(), set_fftodd(), set_fftpad(), set_ri(), and update().

                                                           {


        bool   complex_input = this->is_complex();
        nx  = this->get_xsize();
        ny  = this->get_ysize();
        nz  = this->get_zsize();
        int nox;
        if (complex_input) nox = (nx - 2 + this->is_fftodd()); else nox = nx;

        int lsd2 = (nox + 2 - nox%2) / 2; // Extended x-dimension of the complex image

        EMData* fp = NULL; // output image
        if(complex_input) {
                // fimage must remain pristine
                fp = this->copy();
        } else {
                fp = this->norm_pad( false, 1);
                fp->do_fft_inplace();
        }
        fp->set_array_offsets(1,1,1);
        int nx2 = nox/2;
        int ny2 = ny/2;
        int nz2 = nz/2;
        float *fint = image->get_data();
        for ( int iz = 1; iz <= nz; iz++) {
                int jz=nz2-iz+1; if(jz<0) jz += nz;
                for ( int iy = 1; iy <= ny; iy++) {
                        int jy=ny2-iy+1; if(jy<0) jy += ny;
                        for ( int ix = 1; ix <= lsd2; ix++) {
                                int jx = nx2-ix+1;
                                fp->cmplx(ix,iy,iz) *= fint(jx,jy,jz);
                        }
                }
        }

        fp->set_ri(1);
        fp->set_fftpad(true);
        fp->set_attr("npad", 1);
        if (nx%2 == 1) fp->set_fftodd(true);
        else fp->set_fftodd(false);
        if(RetReal) {
                fp->do_ift_inplace();
                fp->depad();
        }
        fp->set_array_offsets(0,0,0);
        fp->update();

        return fp;
}
float EMData::find_3d_threshold ( float  mass,
float  pixel_size 
)

Definition at line 6125 of file emdata_sparx.cpp.

References abs, avagadro, C, density_protein, get_attr(), get_ndim(), ImageDimensionException, max, min, nx, ny, R, and rdata.

{
        /* Exception Handle */
        if(get_ndim()!=3)
                throw ImageDimensionException("The image should be 3D");
        /* ===============================================================*/

        /* Calculation of the volume of the voxels */
        float density_1_mole, vol_1_mole, vol_angstrom;
        int  vol_voxels;
        density_1_mole = static_cast<float>( (mass*1000.0f)/avagadro );
        vol_1_mole =  static_cast<float>( density_1_mole/density_protein );
        vol_angstrom =  static_cast<float>( vol_1_mole*(double)pow((double)pow(10.0,8),3) );
        vol_voxels = static_cast<int> (vol_angstrom/(double)pow(pixel_size,3));
        /* ===============================================================*/


        float thr1 = get_attr("maximum");
        float thr3 = get_attr("minimum");
        float thr2 = (thr1-thr3)/2 + thr3;
        size_t size = (size_t)nx*ny*nz;
        float x0 = thr1,x3 = thr3,x1,x2,THR=0;

        #ifdef _WIN32
                int ILE = _cpp_min(nx*ny*nx,_cpp_max(1,vol_voxels));
        #else
                int ILE = std::min(nx*ny*nx,std::max(1,vol_voxels));
        #endif  //_WIN32

        if (abs(thr3-thr2)>abs(thr2-thr1)) {
                x1=thr2;
                x2=thr2+C*(thr3-thr2);
        } else {
                x2=thr2;
                x1=thr2-C*(thr2-thr1);
        }

        int cnt1=0,cnt2=0;
        for (size_t i=0;i<size;++i) {
                if(rdata[i]>=x1)  cnt1++;
                if(rdata[i]>=x2)  cnt2++;
        }
        float LF1 = static_cast<float>( cnt1 - ILE );
        float F1 = LF1*LF1;
        float LF2 = static_cast<float>( cnt2 - ILE );
        float F2 = LF2*LF2;

        while ((LF1 != 0 || LF2 != 0) && (fabs(LF1-LF2) >= 1.f) && (abs(x1-x2) > (double)pow(10.0,-5) && abs(x1-x3) > (double)pow(10.0,-5) && abs(x2-x3) > (double)pow(10.0,-5)))
        {
                if(F2 < F1) {
                        x0=x1;
                        x1=x2;
                        x2 = R*x1 + C*x3;
                        F1=F2;
                        int cnt=0;
                        for(size_t i=0;i<size;++i)
                                if(rdata[i]>=x2)
                                        cnt++;
                        LF2 = static_cast<float>( cnt - ILE );
                        F2 = LF2*LF2;
                } else {
                        x3=x2;
                        x2=x1;
                        x1=R*x2 + C*x0;
                        F2=F1;
                        int cnt=0;
                        for(size_t i=0;i<size;++i)
                                if(rdata[i]>=x1)
                                        cnt++;
                        LF1 = static_cast<float>( cnt - ILE );
                        F1 = LF1*LF1;
                }
        }

        if(F1 < F2) {
                ILE = static_cast<int> (LF1 + ILE);
                THR = x1;
        } else {
                ILE = static_cast<int> (LF2 + ILE);
                THR = x2;
        }
        return THR;

}
vector< Pixel > EMData::find_pixels_with_value ( float  val)

Find pixels in the image with exactly the specified values.

Parameters:
valThe value to look for
Returns:
An array of pixels with the specified values

Definition at line 688 of file emdata_metadata.cpp.

References ENTERFUNC, EXITFUNC, get_value_at(), ImageFormatException, is_complex(), nx, ny, and nz.

{
        ENTERFUNC;
        
        if ( is_complex() ) throw ImageFormatException("Error - find_pixels_with_value real only");

        vector<Pixel> result;

        for (int k = 0; k < nz; k++) {
                for (int j = 0; j < ny; j++) {
                        for (int i = 0; i < nx; i++) {
                                if (get_value_at(i,j,k)==val) result.push_back(Pixel(i,j,k,val));
                        }
                }
        }

        EXITFUNC;
        return result;
}
EMData * EMData::Four_ds ( int  nxni,
int  nyni = 0,
int  nzni = 0,
bool  RetReal = true 
)

Definition at line 7335 of file emdata_sparx.cpp.

References copy(), depad(), do_ift_inplace(), fint, fout, get_data(), nx, ny, set_complex(), set_fftodd(), set_ri(), set_size(), to_zero(), and update().

                                                                 {

        int nyn, nzn, lsd, lsdn, inx, iny, inz;
        int i, j;

        if(ny > 1) {
                nyn = nyni;
                if(nz > 1) {
                        nzn = nzni;
                }  else {
                        nzn = 1;
                }
        } else {
                nyn = 1; nzn = 1;
        }
        lsd = nx-2 + 2 - nx%2;
        lsdn = nxn + 2 - nxn%2;
//  do out of place ft
        EMData *temp_ft = this->copy();
        EMData *ret = this->copy();
        ret->set_size(lsdn, nyn, nzn);
        ret->to_zero();
        float *fout = ret->get_data();
        float *fint = temp_ft->get_data();
//  TO KEEP EXACT VALUES ON THE ORIGINAL GRID ONE SHOULD USE
//  SQ2     = 2.0. HOWEVER, TOTAL ENERGY WILL NOT BE CONSERVED
//      float  sq2 = 1.0f/std::sqrt(2.0f);
        float  anorm = (float) nxn* (float) nyn* (float) nzn/(float) nx/ (float) ny/ (float) nz;
        for (i = 0; i < lsd*ny*nz; i++)  fint[i] *= anorm;
        inx = nxn-(nx-2); iny = nyn - ny; inz = nzn - nz;
        for (j=1; j<=nyn; j++)
                for (i=1; i<=lsdn; i++)
                        fout(i,j,1)=fint((i-1)/2*4+2-i%2,j*2-1,1);
        ret->set_complex(true);
        ret->set_ri(1);
        //ret->set_fftpad(true);
        //ret->set_attr("npad", 1);
        if (nxn%2 == 1) {ret->set_fftodd(true);} else {ret->set_fftodd(false);}
        if(RetReal) {
                ret->do_ift_inplace();
                ret->depad();
        }
        ret->update();

        delete temp_ft;
        temp_ft = 0;
        return ret;
}
EMData * EMData::Four_shuf_ds_cen_us ( int  nxni,
int  nyni = 0,
int  nzni = 0,
bool  RetReal = true 
)

Definition at line 7384 of file emdata_sparx.cpp.

References copy(), depad(), do_ift_inplace(), fint, fout, get_data(), nx, ny, set_complex(), set_fftodd(), set_ri(), set_size(), sqrt(), to_zero(), and update().

                                                                        {

        int nyn, nzn, lsd, lsdn, inx, iny, inz;
        int i, j;

        nyn = nyni;
        nzn = 1;
        lsd = nx;
        lsdn = nxn + 2 - nxn%2;

        EMData *temp_ft = this->copy();
        EMData *ret = this->copy();
        ret->set_size(lsdn, nyn, nzn);
        ret->to_zero();
        float *fout = ret->get_data();
        float *fint = temp_ft->get_data();
//  TO KEEP EXACT VALUES ON THE ORIGINAL GRID ONE SHOULD USE
//  SQ2     = 2.0. HOWEVER, TOTAL ENERGY WILL NOT BE CONSERVED
        float  sq2 = 1.0f/std::sqrt(2.0f);

        for (size_t i = 0; i < (size_t)lsd*ny*nz; i++)  fint[i] *= 4;

        inx = nxn-(nx-2); iny = nyn - ny; inz = nzn - nz;
        for (j=1; j<=ny/4; j++)
                for (i=1; i<=(nx-2)/2+2; i++) {
                        int g = (i-1)/2+1;
                        if ((g+j)%2 == 0) {
                                fout(i,j,1)=fint(g*4-2-i%2,j*2-1+ny/2,1);
                        } else {
                                fout(i,j,1)=-fint(g*4-2-i%2,j*2-1+ny/2,1);
                        }
                }

        for (j=ny/4+1; j<=ny/4+1; j++)
                for (i=1; i<=(nx-2)/2+2; i++) {
                        int g = (i-1)/2+1;
                        if ((g+j)%2 == 0) {
                                fout(i,j,1)=fint(g*4-2-i%2,j*2-1-ny/2,1);
                        } else {
                                fout(i,j,1)=-fint(g*4-2-i%2,j*2-1-ny/2,1);
                        }
                }

        for (j=ny/4+2; j<=ny/2; j++)
                for (i=1; i<=(nx-2)/2+2; i++) {
                        int g = (i-1)/2+1;
                        if ((g+j)%2 == 0) {
                                fout(i,j+ny/2,1)=fint(g*4-2-i%2,j*2-1-ny/2,1);
                        } else {
                                fout(i,j+ny/2,1)=-fint(g*4-2-i%2,j*2-1-ny/2,1);
                        }
                }

        if (nx%2 == 0) {
                for (j=1; j<=nyn; j++) {
                        fout((nx-2)/2+1,j,1) *= sq2;
                        fout((nx-2)/2+2,j,1) *= sq2;
                }
                for (i=1; i<=lsd/2+1; i++) {
                        fout(i,ny/4+1+ny/2,1) = sq2*fout(i,ny/4+1,1);
                        fout(i,ny/4+1,1) *= sq2;
                }
        }

        ret->set_complex(true);
        ret->set_ri(1);

        if (nxn%2 == 1) {ret->set_fftodd(true);} else {ret->set_fftodd(false);}
        if(RetReal) {
                ret->do_ift_inplace();
                ret->depad();
        }
        ret->update();

        delete temp_ft;
        temp_ft = 0;
        return ret;
}
EMData * EMData::fouriergridrot2d ( float  ang,
float  scale,
Util::KaiserBessel kb 
)