base package documentation¶
-
check_beamtime_status
- check_beamtime_status is a script.
-
find_dependencies
- find_dependencies is a script.
+astra¶
-
astra.
ASTRA_find_optimal_split
(cfg, num_gpu, angle_blocks, propagator)¶ - split = ASTRA_find_optimal_split(cfg, num_gpu, angle_blocks, propagator)FUNCTION Find optimal split of data and make the blocks sufficiniently small forlimited GPU memoryInputs:cfg - config structure generated by ASTRA_initializenum_gpu - number of gpu to split the dataangle_blocks - number of angular blocks (ie in SART method or FSC)propagator - which propagator should be assumed : FWD, BACK, both (default)Outputs:split - volume / angle split - [split_x,split_y,split_z,split_angles]
Returns: split
-
ASTRA_initialize
- [cfg, vectors] = ASTRA_initialize(Npix, size_projection,angles,lamino_angle, tilt_angle, pixel_scale, rotation_center)FUNCTION Generate configs needed for astra, all angles are expected in degressInputs:Npix - size of tomogramsize_projection - size of sinogram (Nlayers, width, Nangles)angles - rotation angles of projections in degreeslamino_angle - laminography angle / angles in degrees. lamino_angle ==90 is standard tomography , default = 90tilt_angle - tilt of camera with respect to the rotation axis coordinates, indegrees, default = 0pixel_scale - scale of pixels in tomogram compares to theprojection pixel size, default = 1rotation_center - center of rotation cooridinates, default = size_projection/2
-
astra.
Atx_partial
(projData, cfg, vectors, split, varargin)¶ - vol_full = Atx_partial(projData, cfg, vectors,split,varargin)FUNCTION backprojector that allows to split the full volume into smaller piecescomposed tomography back-projector based on ASTRA toolboxcan be used either for data in RAM or on GPU (automatically decided from class of volData)* volume is split based on “split” parameter, 1 == no splitting* Atx_partial tries to split data if GPU limits are exceeded (ie texture memory limits)
Returns: vol_full
-
astra.
Ax_partial
(volData, cfg, vectors, split, varargin)¶ - projData = Ax_partial(volData, cfg, vectors,split, varargin)FUNCTION forward projector that allows to split the full volume into smaller piecesInputs:composed tomography projector based on ASTRA toolboxcan be used either for data in RAM or on GPU (automatically decided from class of volData)* volume is split based on “split” parameter, 1 == no splitting* Ax_partial tries to split data if GPU limits are exceeded (ie texture memory limits)
Returns: projData
-
example
- example script for ASTRA wrappersrecompile commands(Linux, GCC 4.8.5) mexcuda -outdir private ASTRA_GPU_wrapper/ASTRA_GPU_wrapper.cu ASTRA_GPU_wrapper/util3d.cu ASTRA_GPU_wrapper/par3d_fp.cu ASTRA_GPU_wrapper/par3d_bp.cu(Windows) mexcuda -outdir private ASTRA_GPU_wrapper.. _base_astra.iradon_gpu_wrapper:
-
astra.
iradon_gpu_wrapper
(sinogram, cfg, vectors)¶ - vol = iradon_gpu_wrapper(sinogram, cfg, vectors)FUNCTION back projector that allows to split the full volume into smaller piecesInputs:composed tomography projector based on ASTRA toolboxcan be used either for data in RAM or on GPU (automatically decided from class of volData)
Returns: vol
+astra/ASTRA_GPU_wrapper¶
+astra/ASTRA_GPU_wrapper/astra¶
+astra/private¶
-
astra.
add_to_3D
(full_array, small_array, position)¶ - FUNCTION full_array = add_to_3D(full_array, small_array, position)add one small 3D block into large 3D arrayInputs:full_arraysmall_arrayposition - offset from (1,1,1) coordinate in pixels
Returns: full_array
-
astra.
astra2matlab
(sinogram)¶ - FUNCTION sinogram = astra2matlab(sinogram)simple function to reshape sinogram from ASTRA (C++) order to Matlab (FORTRAN) orderInputs:sinogram - real value sinogram
Returns: sinogram
-
astra.
matlab2astra
(sinogram)¶ - FUNCTION sinogram = astra2matlab(sinogram)simple function to reshape sinogram from Matlab (FORTRAN) order to ASTRA (C++) orderInputs:sinogram - real value sinogram
Returns: sinogram
+beamline¶
-
beamline.
OMNY_get_scan_numbers
(OMNY_angles_file, tomo_id)¶ - OMNY_get_scan_numbers( OMNY_angles_file, scannums )OMNY_angles_file - File with Scan number, angle target, angle readouttomo_id - Index specifying the range of scan numbersout - returns scan numbers for tomo_id
Returns: out
-
beamline.
beamstop_mask
(filename, varargin)¶ - Call function without arguments for a detailed explanation of its use
Returns: bmask_ind
-
beamline.
choose_beamstop_mask
(filename, varargin)¶ - [mask_coord,bmask_ind] = choose_beamstop_mask(filename,varargin)
Returns: mask_coord, bmask_ind
-
beamline.
create_mask
(varargin)¶ - CREATE_MASKcreate a binary mask for the current figureoptional
Parameters: - mask – initial mask; either a file, an array or a structure (indicies + asize)
- fig – pass figure handle; default: current figure
- ind – convert mask to indicies
- file – save mask to disk; specify path + filename
Returns: out - 2D binary mask or structure containing the asize and the indicies
see also beamline.mask2ind
-
beamline.
energy2mark
(E, calib_file)¶ - function mark = energy2mark(E,calib_file)After calibrating using beamline.mark_interpolation_setup you can usethis function to input a desired energy and a linear interpolation willdetermine and give you the markInputsE Array of energies in keVcalib_file Name of the file with the calibrationOutputsmark Array of marks corresponding to input energies
Returns: mark
-
beamline.
find_capillary
(varargin)¶ - [varargout] = find_capillary(varargin)
Returns: varargout
-
find_capillary_wrapper
- this script contains the necessary loop for ‘find_capillary.m’ to be calledas function of ‘spec’written by (last change: 2011-06-16)in case of bugs, problems, and suggestions for improvements, please contactCXS groupnote that EPICS communication works only on local machines at the beamline, i.e.,NOT on the compute nodesrun this (or related scripts that use EPICS for communication), for instance, onx12sa-cons-1
-
beamline.
find_specDatFile
(specDatFile)¶ - function specDatFile = find_specDatFile(specDatFile)find location of the spec file in the provided folder / pathif the variable specDatFile is not a complete path to a filetry to guess where a spec data file can be found, by- look for directories called ‘spec’ or ‘dat-files’- look for files called ‘*.dat’- take the newest one
Returns: specDatFile
-
flux_estimate
- beamline.flux_estimate is a script.
-
beamline.
identify_eaccount
()¶ - at the X12SA beamline, [] otherwise.
Returns: return_user_name
-
beamline.
ind2mask
(s)¶ - IND2MASKconvert mask structure (indices + framesize) to a 2D binary mask
Parameters: s – mask structure; must contain s.indices and s.framesize Returns: mask - 2D binary mask see also beamline.mask2ind
-
beamline.
integrate_range
(scan_no_from, scan_no_to, scan_no_step, varargin)¶ - Call function without arguments for instructions on how to use it
-
beamline.
intensity_calibration
(specfile, air_scanno, gc_scanno, det_dist_mm, varargin)¶ - Description:a glassy carbon sample and and airDependencies:spec_read
Returns: diodescale
-
beamline.
is_scan_finished
(specDatFile, scanno)¶ - out = is_scan_finished(specDatFile,scanno)Detect ‘X# ‘ in spec file to detect the end of a scanFrom spec compile post_scan.mac
Returns: out
-
beamline.
is_scan_started
(specDatFile, scanno)¶ - out = is_scan_started(specDatFile,scanno)Detect ‘X# ‘ in spec file to detect the end of a scanFrom spec compile post_scan.mac
Returns: out
-
mark_interpolation_setup
- If you do scans with different marks for energy you can use this code tocalibrate the marks vs energyRun this code, it will save a calibration and then you can useenergy2mark function
-
beamline.
mask2ind
(mask)¶ - MASK2INDconvert a 2D binary mask to indices
Parameters: mask – 2D binary mask Returns: s - mask structure; must contain s.indices and s.framesize see also beamline.ind2mask
-
beamline.
pilatus_valid_pixel_roi
(valid_mask, varargin)¶ - Call function without arguments for instructions on how to use it
Returns: valid_mask
-
beamline.
prep_integ_masks
(filename, center_xy, varargin)¶ - Call function without arguments for instructions on how to use it
Returns: integ_masks
-
beamline.
prep_valid_mask
(data_dir, varargin)¶ - Call function without arguments for instructions on how to use it
Returns: valid_mask
-
beamline.
radial_integ
(filename_masks, varargin)¶ - Call function without arguments for instructions on how to use it
Returns: I, vararg_remain
-
radial_integration_SAXS_and_WAXS
- radial_integration_SAXS_and_WAXS.mTemplate for radial integration made around 2015Changes:2016-08-22: define mask files at the beginning, allowing for a flag in case it needs to be repeatedadd the save fast and v6
-
beamline.
read_omny_angles
(OMNY_angles_file, scannums, tomo_id)¶ - read_omny_angles( OMNY_angles_file, scannums, tomo_id )OMNY_angles_file - File with Scan number, angle target, angle readoutscannums - Array of scan numberstomo_id - integer or list of integers, only if the scannums is emptyout - Contains fields with scan, target_angle, readout_angleerrorflag - = 1 if at least one scan was not found
Returns: out errorflag
-
beamline.
read_omny_pos
(omnyposfile)¶ - Read interferometer positions written by OrchestraInput is the filename with pathOutput is a structure containing fields:The two values of the one line header originally ‘Scan’ and ‘Samroy’Values for each point of 10 expected columns of numbers12 June 2013June6 2015 - Changed in order to accept an arbitrary numberof values in order to be compatible with 10 columns for flOMNI and 19 forOMNY
Returns: struct_out
-
beamline.
stxm_online
(first_scan_number, Ny, varargin)¶ - Call function without arguments for instructions on how to use it
Returns: varargout
-
template_stxm_online_cont_dmesh
- beamline.template_stxm_online_cont_dmesh is a script.
-
template_stxm_online_mesh
- beamline.template_stxm_online_mesh is a script.
-
beamline.
tune_valid_mask
(data_dir, varargin)¶ - Call function without arguments for instructions on how to use it
Returns: valid_mask
+beamline/private¶
-
beamline.
create_mask_GUI_export
(varargin)¶ - CREATE_MASK_GUI_EXPORT MATLAB code for create_mask_GUI_export.figCREATE_MASK_GUI_EXPORT, by itself, creates a new CREATE_MASK_GUI_EXPORT or raises the existingsingleton*.H = CREATE_MASK_GUI_EXPORT returns the handle to a new CREATE_MASK_GUI_EXPORT or the handle tothe existing singleton*.CREATE_MASK_GUI_EXPORT(‘CALLBACK’,hObject,eventData,handles,…) calls the localfunction named CALLBACK in CREATE_MASK_GUI_EXPORT.M with the given input arguments.CREATE_MASK_GUI_EXPORT(‘Property’,’Value’,…) creates a new CREATE_MASK_GUI_EXPORT or raises theexisting singleton*. Starting from the left, property value pairs areapplied to the GUI before create_mask_GUI_export_OpeningFcn gets called. Anunrecognized property name or invalid value makes property applicationstop. All inputs are passed to create_mask_GUI_export_OpeningFcn via varargin.*See GUI Options on GUIDE’s Tools menu. Choose “GUI allows only oneinstance to run (singleton)”.See also: GUIDE, GUIDATA, GUIHANDLES
Returns: varargout
+fluo¶
-
fluorescence_data
- % A template to plot fluorescence data %%%%% mcs_mesh.m could be upgraded to do this job, but here is a script in%% the meantime%% Feb 24, 2016
-
fluorescence_deconv
- Deconvolution with specified scanning positions2017-03
-
fluorescence_plot_fermat
- % A template to plot fluorescence data %%%%% mcs_mesh.m could be upgraded to do this job, but here is a script in%% the meantime%% Feb 24, 2016
-
fluorescence_save_projections
- % A template to plot fluorescence data %%%%% mcs_mesh.m could be upgraded to do this job, but here is a script in%% the meantime%% Manuel Guizar, Feb 24, 2016
-
fluorescence_tomo_lowres
- fluo.fluorescence_tomo_lowres is a script.
+fluo/private¶
-
fluo.
geom_mat_blur
(Np, kernel)¶ - FUNCTION T = geom_mat_blur(Np, kernel)generates a sparse matrix that emulates convolution with given kernelExample conv2(img,ker,’same’) is same as reshape(T*img(:), Npix)
Returns: T
-
fluo.
geom_mat_simpler
(Npix, positions, weights)¶ - FUNCTION T = geom_mat_simpler(Npix, positions, weights, varargin)creates a sparse matrix that will cause shift of the vector intogiven positionsexample:img = imread(‘cameraman’)T*img(:)
Returns: T
-
fluo.
repeat
(x, N, ax)¶ - — help for repmat —REPMAT Replicate and tile an array.B = REPMAT(A,M,N) or B = REPMAT(A,[M,N]) creates a large matrix Bconsisting of an M-by-N tiling of copies of A. If A is a matrix,the size of B is [size(A,1)*M, size(A,2)*N].B = REPMAT(A,N) creates an N-by-N tiling.B = REPMAT(A,P1,P2,…,Pn) or B = REPMAT(A,[P1,P2,…,Pn]) tiles the arrayA to produce an n-dimensional array B composed of copies of A. The sizeof B is [size(A,1)*P1, size(A,2)*P2, …, size(A,n)*Pn].If A is m-dimensional with m > n, an m-dimensional array B is returned.In this case, the size of B is [size(A,1)*P1, size(A,2)*P2, …,size(A,n)*Pn, size(A, n+1), …, size(A, m)].REPMAT(A,M,N) when A is a scalar is commonly used to produce an M-by-Nmatrix filled with A’s value and having A’s CLASS. For certain values,you may achieve the same results using other functions. Namely,REPMAT(NAN,M,N) is the same as NAN(M,N)REPMAT(SINGLE(INF),M,N) is the same as INF(M,N,’single’)REPMAT(INT8(0),M,N) is the same as ZEROS(M,N,’int8’)REPMAT(UINT32(1),M,N) is the same as ONES(M,N,’uint32’)REPMAT(EPS,M,N) is the same as EPS(ONES(M,N))Example:repmat(magic(2), 2, 3)repmat(uint8(5), 2, 3)Class support for input A:float: double, singleinteger: uint8, int8, uint16, int16, uint32, int32, uint64, int64char, logicalSee also BSXFUN, MESHGRID, ONES, ZEROS, NAN, INF.Reference page in Doc Centerdoc repmatOther functions named repmatcodistributed/repmat InputOutputModel/repmat tall/repmatgpuArray/repmat symfun/repmat
Returns: x_new
-
fluo.
replicate
(x, N, ax)¶ - fast replitaction of matrix along one dimension, faster thanrepmat / kron
Returns: x_new
+io¶
-
io.
common_header_value
(header, extension, signature)¶ - Call function without arguments for a detailed explanation of its use
Returns: value
-
io.
datread
(filename, varargin)¶ - Call function without arguments for a detailed explanation of its use
Returns: frame, vararg_remain
-
io.
edfread
(filename, varargin)¶ - Call function without arguments for a detailed explanation of its use
Returns: frame, vararg_remain
-
export_for_SASfit
- This script is to plot, correct and export solution SAXS data to SASfitaccounts for transmission, time and thickness correctionscales the data to a calibration factorbackground correction, removal of bad pixelsnot suitable for anisotropic datasaves the output to be used in SASfit
-
io.
fliread
(filename, varargin)¶ - Call function without arguments for a detailed explanation of its use
Returns: frame, vararg_remain
-
image_default_orientation
- [orient_vec] = image_default_orientation(header, extension, varargin)Determine default orientation for an image_orient.m call based on thefile extension
-
io.
image_info
(filenames, varargin)¶ - [im_info,vararg_remain] = image_info(filenames,varargin)Get information like the dimensions of the data stored in an image file
Returns: im_info, vararg_remain
-
io.
image_orient
(frame, varargin)¶ - Call function without arguments for instructions on how to use it
Returns: frame_out, vararg_remain
-
io.
image_read
(filenames, varargin)¶ - Call function without arguments for instructions on how to use it
Returns: frames, vararg_remain
-
io.
image_read_help
(extension, m_file_name, varargin)¶ - image_read_help(extension,m_file_name,varargin)parameter help for image_read
-
io.
json2mat
(J)¶ - io.json2mat is a function.M = json2mat(J)
Returns: M
-
io.
load_prepared_data
(filename, return_intensity, enum, return_fftshifted)¶ - LOAD_PREPARED_DATA Load prepared data file and convert it into the default Matlabstructurefilename… path and filename of the h5 fileoptionalscan… select scan, either integer or array
Returns: fmag, fmask, pos, max_power, scanindexrange
-
io.
load_ptycho_recons
(filename_with_path, varargin)¶ - LOAD_PTYCHO_RECONS Load data from cxs/h5 or mat file and return it asstructure, single dataset or directly into the workspace.An additional argument can be passed to select subsections of the data.Loading single datasets is only supported for at least 2 outputarguments.file… path to cxs/h5 or mat fileoptionalsection… ‘full’, ‘probe’, ‘object’, ‘recon’ or ‘p’ to selectsubsections of the data; default: ‘full’EXAMPLES:%% recommended usage %%% load into a structureS = load_ptycho_recons(‘./recon.h5’);% load a subsetS = load_ptycho_recons(‘./recon.h5’, ‘probe’);% load into single datasets[object, probe, p] = load_ptycho_recons(‘./recon.h5’);%% not recommended, only works in ‘base’ workspace %%% load directly into workspaceload_ptycho_recons(‘./recon.h5’);full = object, probe (current scan) and precon = object and probe (current scan)probe = probe (current scan)object = object (current scan)
Returns: varargout
-
io.
marread
(filename, varargin)¶ - Call function without arguments for instructions on how to use it
Returns: frame, vararg_remain
-
io.
mat2json
(M, F)¶ - io.mat2json is a function.J = mat2json(M, F)
Returns: J
-
io.
mcs_mesh
(first_scan_no, no_of_intervals, varargin)¶ - Call function without arguments for instructions on how to use it
Returns: mcs_data, data_adjusted, pos_data
-
io.
multiple_mcs_headers
(scan_no_from, scan_no_to)¶ - [] = multiple_mcs_headers(scan_no_from,scan_no_to)
-
io.
read_scan_positions_spec
(specdatafile, scans, motors)¶ - [pos] = read_scan_positions_spec(specdatafile,scans,motors)positions = read_scan_positions(specdatafile,scan,motors) returns thepositions of a SPEC file corresponding to two given motor namesInput parameters:specdatafile: string with the file name of the SPEC data file(e.g.’~/Data10/specES1/dat-files/specES1_started_2017_07_11_1633.dat’ )scans: scan number(s) (e.g. [2:77,88])motors: 1x2 cell array with scanning motor names (e.g. {‘samx’,’samy’})The output is a structure array with length(scans) number of elements,each element containing in the field ‘data’ an Nx2 array with Nbeing the number of points in the scan. The two columns contain motorpositions for motors samx and samy, respectively, if motors={‘samx’,’samy’}Example:pos=read_scan_positions_spec(‘~/Data10/specES1/dat-files/specES1_started_2017_07_11_1633.dat’,[58:59],{‘samx’,’samy’});
Returns: pos
-
io.
save_append
(filename, vars, x)¶ - Append the varible to the filefunction save_append(filename, vars, x)Input:filename - file to which the varible will be appendedvars - the varible to save, eg, savemex - the string of the variable name, eg, ‘saveme’Note:This is a temporary solution because either‘save’ nor ‘vars=evalin(‘caller’, varargin{1})’works for parfor..
-
io.
savefast_safe
(filename, varargin)¶ - savefast: fast saves of large arrays to .mat filesMatlab’s ‘save’ command can be very slow when saving large arrays,because by default Matlab attempts to use compression. This functionprovides a much faster alternative, at the cost of larger files.The syntax is identical to that of the Matlab save command.Example:>> ops = struct(‘algorithm’, ‘greedy’);>> A = int32(randi(20, 1000, 1200, 40));>> B = randn(500, 1800, 60);>> tic; save /tmp/test ops A B; tocElapsed time is 22.980294 seconds.>> tic; savefast /tmp/test ops A B; tocElapsed time is 0.571098 seconds.
-
io.
sendSMS
(recipient, msg, varargin)¶ - SENDSMS send message to given phone number(s)
Parameters: - recipient – phone number(s);
- msg – message
optionalParameters: - binary_path – path to sendmail binary file
- server – server address
- sleep – sleep time between messages
- logfile – logfile+path to keep track of past activities
EXAMPLESsendSMS(‘0041123456789’, ‘done!’);sendSMS({‘076123456’, ‘076987654’}, ‘done!’)sendSMS({‘076123456’, ‘076987654’}, {‘message1’, ‘message2’})sendSMS({‘076123456’, ‘076987654’}, ‘done!’, ‘sleep’, 3600)
-
io.
spec_help
(m_file_name)¶ - [] = spec_help(m_file_name)
-
io.
spec_read
(specDatFile, varargin)¶ - function [varargout] = spec_read(specDatFile, varargin)call ‘spec_read()’ for further helpplease reports bugs, problems, suggestions for improvements to:CXS groupthe case of duplicate scannumbers in the spec file, and how toaddress them remains to be implemented
Returns: varargout
-
io.
speread
(filename, varargin)¶ - Call function without arguments for instructions on how to use it
Returns: frame, vararg_remain
+io/+CBF¶
-
io.CBF.
cbfread
(filename, varargin)¶ - Call function without arguments for a detailed explanation of its use
Returns: frame, vararg_remain
-
io.CBF.
cbfwrite
(filename, frame, varargin)¶ - Call function without arguments for a detailed explanation of its use
Returns: fcount_total
+io/+HDF¶
-
io.HDF.
add_content
(data, gid, plist, comp, overwrite)¶ - ADD_CONTENT write matlab structure to H5 file
-
io.HDF.
add_groups
(fileID, gpath, plist, varargin)¶ - ADD_GROUPS add groups or open them if they exist
Returns: gid
-
io.HDF.
get_datatype
(data)¶ - Determine datatype for HDF files
Returns: datatype_h5, data
-
io.HDF.
hdf5_append_attr
(file, attr, loc)¶ - HDF5_APPEND_ATTR Append an attribute to a datasetfile… HDF filenameattr… structure of attributesloc… location of the dataset that needs to be removed
-
io.HDF.
hdf5_attr_exists
(file, name, varargin)¶ - HDF5_ATTR_EXISTS check if attribute exists in given filefile… h5 file pathattr… dataset nameoptionalgpath… path within the h5 file; default root (/)
Returns: out
-
io.HDF.
hdf5_cp_file
(orig_filename, duplicate_filename, varargin)¶ - HDF5_CP_FILE copy HDF filesorig_filename… source fileduplicate_filename… target fileoptional given as name/value pairgroups… groups to copy; either string or cell ofstrings; default: everything in rootcopy_type… ‘deep’, ‘normal’ or ‘shallow’ copy;‘shallow’ creates external links in target file;‘normal’ is similar to linux ‘cp’ command;‘deep’ dereferences all internal and external links;default: ‘shallow’EXAMPLES:hdf5_cp_file(‘./test.h5’, ‘./test_new.h5’)hdf5_cp_file(‘./test.h5’, ‘./test_new.h5’, ‘copy_type’, ‘deep’);
-
io.HDF.
hdf5_dset_exists
(file, dset, varargin)¶ - HDF5_DSET_EXISTS check if dataset exists in given filefile… h5 file pathdset… dataset nameoptionalgpath… path within the h5 file; default root (/)check_links… include links; default trueEXAMPLES:out = io.HDF.hdf5_dset_exists(‘./recons.h5’,‘object_phase_unwrapped’, ‘/reconstruction’, true);
Returns: out
-
io.HDF.
hdf5_load
(filename, varargin)¶ - HDF5_LOAD Load an hdf5 fileDATA = HDF5_LOAD(filename) reads a complete file hierarchy recursively, withfile name/path being specified by the ‘filename’ argumentDATA = HDF5_LOAD(filename, ‘-a’) reads a complete file hierarchyrecursively, including attributesDATA = HDF5_LOAD(filename, location) reads a particular group, link, or a single datasetspecified by the ‘location’ argumentATT = HDF5_LOAD(filename, location, ‘-a’) reads all datasets and attributes associatedwith a particular location in the file (group, link or dataset)ATT = HDF5_LOAD(filename, location, ‘-ca’) reads all datasets and attributes associatedwith a particular location in the file (group, link or dataset) andconverts datasets to a specific matlab class based on attribute ‘MATLAB_class’SLICE = HDF5_LOAD(filename, location, {rowRange, colRange, frameRange, …}) reads aportion of a dataset along specified dimentions, where slicing ranges can be defined inthe following ways (negative indexes count from the end of the corresponding dimensions):range = scalar_index - reads a particular row/col/frame/… (indentical to‘range = [scalar_index, scalar_index]’)range = [start_index, end_index] - reads all data between start and endindexesrange = [start_index, Inf] - reads all data from start_index to the lastexisting element in the filerange = [], or range is omitted at the end - reads the full range of values for thatdimention (indentical to ‘range = [1, Inf]’)Examples:hdf5_load(‘scan_003.hdf5’)hdf5_load(‘scan_003.hdf5’, ‘/entry/sample/description’)hdf5_load(‘scan_003.hdf5’, ‘/entry/collection/data/spec’, ‘-a’)hdf5_load(‘scan_003.hdf5’, ‘/entry/instrument/Pilatus_2M/data’, {5})hdf5_load(‘scan_003.hdf5’, ‘/entry/instrument/Pilatus_2M/data’, {[-100, Inf]})hdf5_load(‘scan_003.hdf5’, ‘/entry/instrument/Pilatus_2M/data’, {5, [500, Inf], [1, 100]})hdf5_load(‘scan_003.hdf5’, ‘/entry/instrument/Pilatus_2M/data’, {[], [], [1, 100]})
Returns: data
-
io.HDF.
hdf5_mv_data
(file, loc_origin, loc_dest)¶ - HDF5_MV_DATA Move data within an HDF5 filehdf5_mv_data creates a new (UNIX-like) hard link at loc_dest to the dataset atloc_origin and deletes the hard link to the dataset at loc_origin.file… HDF filenameloc_origin… location of the data that needs to be movedloc_dest… destination and name of the new dataEXAMPLE:% move dataset probe from root to group measurementshdf5_mv_data(‘./awesome_file.h5’, ‘probe’, ‘measurements/probe’)Please notice that all groups and datasets have to exist before runningthe script!
-
io.HDF.
hdf5_rm_attr
(file, loc, attr_name)¶ - HDF5_RM_ATTR Delete attribute(s) from HDF filefile… HDF filenameloc… location within the HDF fileattr_name… string or cell of strings containing the names of theobsolete attributes
-
io.HDF.
hdf5_rm_data
(file, loc)¶ - HDF5_RM_DATA Delete a dataset within an HDF5 filefile… HDF filenameloc… location of the dataset that needs to be removedPlease notice that HDF5 does not free the space after removing datasets!
-
io.HDF.
hdf5read_main
(filename, varargin)¶ - Call function without arguments for instructions on how to use it
Returns: frame, vararg_remain
-
io.HDF.
save2hdf5
(filename, data, varargin)¶ - SAVE2HDF5 saves matlab data to a Hierarchical Data Format file (hdf5)filename… full path to file, including file extensiondata… matlab structure or array or linkdata_name… needed if input data is not a matlab structure, needsto be given as name/value pairoptionaloverwrite… replace existing file if it existsgpath… specify the group to which you want to append the data(only if data is an array); default root (‘/’)Attributes… structure of attributes; will be appended to currentgpathcomp… compression level; default 0 (no compression)creator… attribute in root; default ‘ptycho_recons’If you want to save a structure, everything declared within an ‘Attributes’fieldname will be treated as an attribute to the current group.If you want to add attributes to a dataset, you have to define yourdata within .Value and your attributes within .Attributes.A simple structure could look like:h5_struc = [];h5_struc.probe_mask = ones(256,256);h5_struc.Attributes.probe_id = 1;h5_struc.measurement.n0.diff = fmag(:,:,1);h5_struc.measurement.n0.Attributes.detector = 0;h5_struc.measurement.n1.diff.Value = fmag(:,:,2);h5_struc.measurement.n1.diff.Attributes.slice = 2;fmag(:,:,1) will be written to dataset ‘diff’ in group ‘/measurement/n0’fmag(:,:,2) with attribute ‘slice’ will be written to dataset ‘diff’ ingroup ‘/measurement/n1’EXAMPLES:-) if data is a matlab structure:save2hdf5(‘./awesome_file.h5’, data);save2hdf5(‘./awesome_file.h5’, data, ‘overwrite’, true);-) if data is a matlab array:save2hdf5(‘./awesome_file.h5’, data, ‘data_name’, data_name);save2hdf5(‘./awesome_file.h5’, data, ‘data_name’, ‘my_dataset’,…‘gpath’, ‘group1/group2’, ‘Attributes’, attr_struc);-) if data is a link:currently, only external links (‘ext’) and internal soft links(‘int_soft’) are supportedexternal links have to be specified by a single string with3 sections: ‘<link_type>:<file_path>:<target_object>’e.g.: ‘ext:./awesome_file2.h5:/data’save2hdf5(‘./awesome_file.h5’,…‘ext:./awesome_file2.h5:/data’, ‘data_name’, data_name)will create a link called $data_name to dataset (or group) ‘/data’in ‘./awesome_file2.h5’internal links have to be specified by a single string with2 sections: ‘<link_type>:<target_object>’e.g.: ‘int_soft:/data’save2hdf5(‘./awesome_file.h5’,…‘int_soft:/data’, ‘data_name’, data_name, ‘gpath’, ‘g1/g2’)will create a link called $data_name to dataset (or group) ‘/data’in ‘/g1/g2’Please notice that structures are not supported as attributes, i.e.h5_struc = [];h5_struc.attr.probe.probe_id = 1;save2hdf5(‘./awesome_file.h5’, h5_struc)will crash!
-
io.HDF.
write_attribute
(gid, data, data_name, varargin)¶ - WRITE_ATTRIBUTE write attribute data_name with value data to ID gid
-
io.HDF.
write_dataset
(data, gid, data_name, plist, varargin)¶ - WRITE_DATASET write dataset data_name, containing data to ID gid
+io/+HDF/private¶
-
io.HDF.
rm_delimiter
(path)¶ - RM_DELIMITER makes sure that the path does not start with /
Returns: path
+io/private¶
-
io.
image_orient_help
(m_file_name, varargin)¶ - [] = image_orient_help(m_file_name,varargin)parameter help for image_orient and calling functions
-
io.
image_read_sub_help
(m_file_name, extension, varargin)¶ - [] = image_read_sub_help(m_file_name,extension,varargin)parameter help for sub-routines of image_read like cbfread, edfread,speread and fliread
+io/private/ptycho_reader¶
+math¶
-
math.
argmax
(x)¶ - FUNCTION varargout = argmax(x)INputs:X - Ndim arrayOutputs:coordinates of the first value equal to maximumExample: [i,j] = argmax(randn(10))
Returns: varargout
-
math.
argmin
(x)¶ - FUNCTION varargout = argmin(x)INputs:X - Ndim arrayOutputs:coordinates of the first value equal to maximumExample: [i,j] = argmin(randn(10))
Returns: varargout
-
math.
center
(X, use_shift)¶ - ———————————————————————–This file is part of the PTYCHOMAT ToolboxAuthor: Michal Odstrcil, 2016License: Open Source under GPLv3Contact: ptychomat@gmail.com———————————————————————–Description: find center of mass of matrix X, calculate variance ifneededinputs:X 2D stacked imagesuse_shift, if true, CoM will be calculated relatively to the centerof the image, default == true
Returns: pos_x, pos_y, mass, mu, sigma
-
math.
double2int
(p)¶ - DOUBLE2INT Convert structure values from double to int if precision can bepreserved.EXAMPLE:p.value1 = 10.25;p.value2 = 2;p_int = double2int(p);p_int.value1ans =10.2500p_int.value2ans =uint322
Returns: p
-
math.
fft2_partial
(x, split, inverse)¶ - FUNCTION x = fft2_partial(x,split)apply fft only on smaller blocks (important for GPU)
Returns: x
-
math.
fft_partial
(x, fft_axis, split_axis, split, inverse)¶ - FUNCTION x = fft_partial(x,fft_axis,split_axis, split, inverse = false)apply fft only on smaller blocks (important for GPU)
Returns: x
-
math.
fftn_partial
(x, split)¶ - FUNCTION x = fftn_partial(x,split)apply fft only on smaller blocks (important for GPU)
Returns: x
-
math.
fftshift_2D
(x)¶ - ———————————————————————–This file is part of the PTYCHOMAT ToolboxAuthor: Michal Odstrcil, 2016License: Open Source under GPLv3Contact: ptychomat@gmail.com———————————————————————–Description: faster version of matlab fftshift to work for stack of2D imagesInputs: 2D or stack of 2D imagesOutputs:x - 2D or stack of 2D images after fftshift along first 2 dimensionsidx - precalculated indices for fftshift operation
Returns: x, idx
-
math.
fsvd
(A, k, i, usePowerMethod)¶ - FSVD Fast Singular Value Decomposition[U,S,V] = FSVD(A,k,i,usePowerMethod) computes the truncated singularvalue decomposition of the input matrix A upto rank k using i levels ofKrylov method as given in [1], p. 3.If usePowerMethod is given as true, then only exponent i is used (i.e.as power method). See [2] p.9, Randomized PCA algorithm for details.[1] Halko, N., Martinsson, P. G., Shkolnisky, Y., & Tygert, M. (2010).An algorithm for the principal component analysis of large data sets.Arxiv preprint arXiv:1007.5510, 0526. Retrieved April 1, 2011, from[2] Halko, N., Martinsson, P. G., & Tropp, J. A. (2009). Findingstructure with randomness: Probabilistic algorithms for constructingapproximate matrix decompositions. Arxiv preprint arXiv:0909.4061.Retrieved April 1, 2011, from http://arxiv.org/abs/0909.4061.See also SVD.Copyright 2011 Ismail Ari, http://ismailari.com.
Returns: U, S, V
-
math.
get_img_grad
(img, axis, split)¶ - FUNCTION [dX, dY] = get_img_grad(img, axis, split)get vertical and horizontal gradient of the image using FFTInputs:img - stack of imagessplit - split for GPU fft_partialaxis - direction of the derivative
Returns: dX, dY
-
math.
get_img_int_1D
(img, ax)¶ - FUNCTION integer = get_img_int(img, ax)use FFT to integate the image along one axis -> can be used for phaseunwrappingInputs:img - stack of imagesax - integration axis
Returns: integer
-
math.
get_img_int_2D
(dX, dY)¶ - FUNCTION integral = get_img_int_2D(dX,dY)use FFT2 to integate the image along both axis -> can be used for phaseunwrappingInputs:dX - horizontal phase gradientdY - vertical phase gradient
Returns: integral
-
math.
get_phase_gradient_1D
(img, ax, step, shift)¶ - d_img = get_phase_gradient_1D(img, ax, step)FUNCTION get gradient of phase of image IMG along axis AX. Accept eithercomplex image or unwrapped phaseInputsimg - stack of complex valued input imagesax - axis of derivative, default = 2step - step used to caluclate the central difference
Returns: d_img
-
math.
get_phase_gradient_2D
(img, step, padding)¶ - [d_X, d_Y] = get_phase_gradient_2D(img, step)FUNCTION get 2D gradient of phase of image IMG. Accept eithercomplex image or unwrapped phaseInputsimg - stack of complex valued input imagesstep - step used to caluclate the central difference
Returns: d_X, d_Y
-
math.
ifft2_partial
(x, split)¶ - FUNCTION x = ifft2_partial(x,split)apply fft only on smaller blocks (important for GPU)
Returns: x
-
math.
ifft_partial
(x, fft_axis, split_axis, split)¶ - FUNCTION x = ifft_partial(x,fft_axis,split_axis, split)apply ifft only on smaller blocks (important for GPU)
Returns: x
-
math.
ifftn_partial
(x, split)¶ - FUNCTION x = ifftn_partial(x,split)apply fftn only on smaller blocks (important for GPU)
Returns: x
-
math.
ifftshift_2D
(x)¶ - ———————————————————————–This file is part of the PTYCHOMAT ToolboxAuthor: Michal Odstrcil, 2016License: Open Source under GPLv3Contact: ptychomat@gmail.com———————————————————————–Description: faster version of matlab fftshift to work for stack of2D imagesInputs: 2D or stack of 2D imagesOutputs:x - 2D or stack of 2D images after fftshift along first 2 dimensionsidx - precalculated indices for fftshift operation
Returns: x, idx
-
math.
isint
(x, prec)¶ - true if all values or X is integers, but class can be arbitrarynumerical array
Returns: val
-
math.
legendrepoly1D_2
(X, maxorder, w)¶ - Generates a 1D orthonormal polynomial basepolys = legendrepoly1D_2(X,maxorder,w);The weighting function has not been tested extensivelyManuel Guizar - March 10, 2009
Returns: polys
-
math.
max2
(x)¶ - max along first two dimensions
Returns: x
-
math.
mean2
(x)¶ - mean along first two dimensions
Returns: y
-
math.
min2
(x)¶ - min along first two dimensions
Returns: x
-
math.
nnorm
(a)¶ - FUNCTION N = NNORM(a)N-Dimensional norm.
Returns: n
-
math.
norm2
(x)¶ - 1/N * Euclidean norm aling first 2 dims
Returns: x
-
math.
peakfit2d
(Z)¶ - Find sub-sample location of a global peak within 2D-matrix by applyingtwo dimensional polynomial fit & extremum detection.Sample usage:>> M = exp(-((1:30) - 19.5).^2/(2*5^2)); % gauss: center=19.5; sigma=5>> P = peakfit2d(M’*M); % find peak in 2D-gauss>> disp(P);19.5050 19.5050Algebraic solution derived with the following steps:0.) Define Approximation-Function:F(x,y) => z = a*x^2+b*x*y+c*x+d+e*y^2+f*y1.) Formulate equation for sum of squared differences withx=-1:1,y=-1:1,z=Z(x,y)SSD = [ a*(-1)^2+b*(-1)*(-1)+c*(-1)+d+e*(-1)^2+f*(-1) - Z(-1,-1) ]^2 + ……a*(+1)^2+b*(+1)*(+1)+c*(+1)+d+e*(+1)^2+f*(+1) - Z(-1,-1) ]^22.) Differentiate SSD towards each parameterdSSD / da = ……dSSD / df = …3.) Solve linear system to get [a..f]4.) Differentiate F towards x and y and solve linear system for x & ydF(x,y) / dx = a*… = 0 !dF(x,y) / dy = b*… = 0 !
Returns: P
-
math.
projectleg1D_2
(input, maxorder, Xext, w)¶ - Proyects a 1D function onto orthonormalized base, returns residual tooThe weighting function has not been tested extensively[coeffs reconstrproj] = projectleg1D_2(input,maxorder,Xext,w);March 10, 2009
Returns: coeffs, reconstrproj
-
math.
sp_quantile
(x, q, reduce)¶ - FUNCTION: sp_quantile(array,quantile,reduce)sparse quantile (just make a fast guess)Inputs:array - inputs ndim arrayquantile - number or vector from 0 to 1 denoting quantilesreduce - use every n-th element for calculationOutputs:Q - scalar or vector of quantiles of the reduced array
Returns: Q
-
math.
sum2
(x)¶ - sum along first two dimensions
Returns: x
-
math.
unwrap2D_fft
(phase_diff, axis, empty_region, step)¶ - phase = unwrap2D_fft(img, axis, empty_region, step)FUNCTION simple and very fast phase unwrappingInputs:img either complex valued image or real valued phase gradientaxis axis along which the gradient is takenempty_region - 2x1 or 1x1 vector, size of empty region assumedaround edges for phase offset removal
Returns: phase, phase_diff, residues
-
math.
unwrap2D_fft2
(img, empty_region, step, weights, polyfit_order)¶ - [phase, residues] = unwrap2D_fft2(img, empty_region, step, weights, polyfit_order)FUNCTION simple and very fast 2D phase unwrappingInputs:img either complex valued image or real valued phase gradientempty_region - 2x1 or 1x1 vector, size of empty region assumedaround edges for phase offset removalstep used to calculate finite difference gradient, 0 = analytical (default)expression
Returns: phase, residues
+plotting¶
-
XANES_plot_transmission
- plotting.XANES_plot_transmission is a script.
-
XANES_ptycho
- Loading data
-
plotting.
banana_plot
(basepath, scan, Nx, Ny)¶ - function [varargout] = banana_scan(basepath, scan, Nx, Ny)This function only works for mesh scans done to see the undulator bananawith spec. This is an example pf such scans:dmesh idgap -0.05 0.05 50 sl1cv -0.4 0.4 8 0.250 steps (51 points) along the fast axis8 steps (9 points) along the slow axisInput parameters:basepath: main path where you are workingscan: scan number of spec mesh scanNx: number of points in fast axisNy: number of steps in slow axisplease reports bugs, problems, suggestions for improvements to:CXS groupthe case of duplicate scannumbers in the spec file, and how toaddress them remains to be implemented
Returns: varargout
-
plotting.
c2image
(a, varargin)¶ - FUNCTION IM = C2IMAGE(A)the phase is mapped to hue, and the amplitudeis mapped to brightness.
Returns: im
-
plotting.
display_integ_masks
(filename_frame, varargin)¶ - Call function without arguments for a detailed explanation of its use
Returns: valid_mask
-
plotting.
display_valid_mask
(varargin)¶ - Call function without arguments for a detailed explanation of its use
Returns: valid_mask
-
plotting.
franzmap
(m)¶ - Function FM = FRANZMAP(M)Franz’s modified jet color mapThis function returns the colormap and shouldbe used like any other colormaps, e.g.colormap(franzmap(128));orimwrite(uint8(255*myarray/max(max(myarray))),franzmap(256),’myarray.jpg’);
Returns: fm
-
plotting.
ginput_ax_mod2
(ha, n)¶ - plotting.ginput_ax_mod2 is a function.varargout = ginput_ax_mod2(ha, n)
Returns: varargout
-
plotting.
hline
(y, in1, in2)¶ - function h=hline(y, linetype, label)Draws a horizontal line on the current axes at the location specified by ‘y’. Optional arguments are‘linetype’ (default is ‘r:’) and ‘label’, which applies a text label to the graph near the line. Thelabel appears in the same color as the line.The line is held on the current axes, and after plotting the line, the function returns the axes toits prior hold state.The HandleVisibility property of the line object is set to “off”, so not only does it not appear onlegends, but it is not findable by using findobj. Specifying an output argument causes the function tooverridden by setting the root’s ShowHiddenHandles property to on.h = hline(42,’g’,’The Answer’)the current axes, close to the line, which reads “The Answer”.hline also supports vector inputs to draw multiple lines at once. For example,hline([4 8 12],{‘g’,’r’,’b’},{‘l1’,’lab2’,’LABELC’})draws three lines with the appropriate labels and colors.
Returns: hhh
-
plotting.
image_show
(filename, varargin)¶ - Call function without arguments for instructions on how to use it
Returns: frame, image_handle
-
plotting.
image_spec
(det_no, varargin)¶ - Call function without arguments for instructions on how to use it
-
plotting.
imagesc3D
(varargin)¶ - IMAGESC3D 3D wrapper for imagescimagesc3D supports the same parameters as Matlab’s imagesc. In addition, the followingparameters can be setinit_frame… starting frame number (default 1)slider_axis… axis along which you want to use imagesc (default 3)fps… frames per second (default 25); will be adjusted by a factor of 1.2 to account for internal overheadtitle_list… individual title for each frame (default {})loop… run in a loop (default false)reset_frame… stop resets frame to init_frame (default false)autoplay… stark movie automatically (default false)slider_position… slider position [left bottom width height] (default center of axis)play_position… play button position [left bottom width height]edit_position… edit box position [left bottom width height]show_play_button… show/hide button; needs to be visible if loop=true; (default true)show_edit_box… show/hide boxfnct… data processing functionorder… change slice order in stacksave_movie… specify filename if a movie shall be writtenmovie_quality… image quality of the saved movieComplex images will be converted to RGB using c2image.If you are not using ‘autplay’, you can also set a global title insteadof a title list (similar to imagesc) and use ‘%d’ to get the slice numbertitle(‘Random block - slice %d’)EXAMPLES:imagesc3D(rand(256, 256, 100), ‘fps’, 10, ‘loop’, true)imagesc3D(rand(256, 256)*1j)imagesc3D(rand(20, 256, 256), ‘slider_axis’, 1);Additionally, you can use imagesc/imagesc3D routines and trigger the movie bycalling the play method of a specified axis:figure(1);imagesc3D(rand(256, 256, 100), ‘fps’, 20);title(‘Random block - slice %d’);colorbar();ax = gca;ax.play();
-
plotting.
imagesc_tomo
(varargin)¶ - Function [im_out]=imagesc_tomo( varargin )Parameters:data - 3D array to be showncolormap - name of standard matlab colormap, default = boneclim - range of the colorbar, default is [] (auto range)axis - cell of strings with axis parameters, eg. {‘image’, ‘off’}
Returns: im_out
-
plotting.
integrate_frames
(base_path, scan_num, plotfigure, det_num, savedata, maskfile, masktype)¶ - Integrates frames from a loopscanSyntax:[int] = integrate_frames(base_path,scan_num,plotfigure,det_num,savedata,maskfilename,masktype)Needed parameters: base_path (e.g. ‘~/Data10/’)scan_num (scan number)Optional parameters: plotfigure (figure number for final plot, 0 for no plotting, by default is 0)det_num (detector number, default 1)savedata (=1 to save data in ‘analysis/integrated_frames/’, default 0)maskfilename (valid mask file name. If empty [], no mask used)masktype (type of valid mask file name: ‘bin’ for binary or ‘Oliver’)14-11-2012
Returns: int
-
plotting.
integrated_intensity
(filename_mask, varargin)¶ - Call function without arguments for instructions on how to use it
Returns: int_int
-
plotting.
plot_radial_integ
(filename_masks, varargin)¶ - Call function without arguments for instructions on how to use it
Returns: x_values_returned, y_values_returned
-
plot_radial_integ_template
- plotting.plot_radial_integ_template is a script.
-
plot_sgalil_positions
- this script is used to visualize the sgalil positions
-
plot_sgalil_positions_step_by_step
- this script is used to plot the sgalil positions in the order that theyoccur
-
plotting.
ptycho_show_recons
(file, varargin)¶ - [p object probe] = ptycho_show_recons(file,param1,val1,…)Receives a path+filename, reads it and makes plots of the ptychographyreconstructionOptional parameters‘imagesavefolder’ ‘~/Data10/analysis/online/ptycho/show_recons/’(default = [], which means no plot is saved)param can be updated with another struct[p, probe, object] = core.ptycho_show_recons(filepath, p_updated)and / or with single field names[p, probe, object] = core.ptycho_show_recons(filepath, p_updated, ‘windowautopos’, 1, ‘extrastringtitle’, ‘Final recon’)
Returns: p, object, probe
-
plotting.
scan_movie
(filenames, varargin)¶ - Call function without arguments for instructions on how to use it
Returns: vararg_remain
-
plotting.
spec_plot
(specDatFile, varargin)¶ - function [varargout] = spec_plot(specDatFile, varargin)call ‘spec_plot()’ for further helpplease reports bugs, problems, suggestions for improvements to:CXS group
Returns: varargout
-
plotting.
suptitle
(str)¶ - Function modified by CXS group from:SUPTITLE puts a title above all subplots.SUPTITLE(‘text’) adds text to the top of the figureabove all subplots (a “super title”). Use this functionafter all subplot commands.SUPTITLE is a helper function for yeastdemo.Copyright 2003-2014 The MathWorks, Inc.
Returns: hout
-
template_plot_radial_integ
- plotting.template_plot_radial_integ is a script.
-
plotting.
tight_subplot
(Nh, Nw, gap, marg_h, marg_w)¶ - tight_subplot creates “subplot” axes with adjustable gaps and marginsha = tight_subplot(Nh, Nw, gap, marg_h, marg_w)in: Nh number of axes in hight (vertical direction)Nw number of axes in width (horizontaldirection)gap gaps between the axes in normalized units (0…1)or [gap_h gap_w] for different gaps in height and widthmarg_h margins in height in normalized units (0…1)or [lower upper] for different lower and upper marginsmarg_w margins in width in normalized units (0…1)or [left right] for different left and right marginsout: ha array of handles of the axes objectsstarting from upper left corner, going row-wise as ingoing row-wise as inExample: ha = tight_subplot(3,2,[.01 .03],[.1 .01],[.01 .01])for ii = 1:6; axes(ha(ii)); plot(randn(10,ii)); endset(ha(1:4),’XTickLabel’,’‘); set(ha,’YTickLabel’,’‘)
Returns: ha
-
plotting.
vline
(x, in1, in2)¶ - function h=vline(x, linetype, label)Draws a vertical line on the current axes at the location specified by ‘x’. Optional arguments are‘linetype’ (default is ‘r:’) and ‘label’, which applies a text label to the graph near the line. Thelabel appears in the same color as the line.The line is held on the current axes, and after plotting the line, the function returns the axes toits prior hold state.The HandleVisibility property of the line object is set to “off”, so not only does it not appear onlegends, but it is not findable by using findobj. Specifying an output argument causes the function tooverridden by setting the root’s ShowHiddenHandles property to on.h = vline(42,’g’,’The Answer’)the current axes, close to the line, which reads “The Answer”.vline also supports vector inputs to draw multiple lines at once. For example,vline([4 8 12],{‘g’,’r’,’b’},{‘l1’,’lab2’,’LABELC’})draws three lines with the appropriate labels and colors.
Returns: hhh
+utils¶
-
utils.
abspath
(filename_with_path)¶ - FUNCTION filename_with_path = abspath(filename_with_path)translate special symbols such as ~, ../, ./, in path to the absolutepath
Returns: filename_with_path
-
utils.
add_to_3D_projection
(small_array, full_array, positions, indices, add_values, use_MEX)¶ - full_array = add_to_3D_projection(small_array,full_array, positions, indices,add_values)add one small 3D block into large 3D arrayInputs:full_array - array to which the small_array will be added / writtensmall_array - array used to be added to large arraypositions - [Nangles x 2] offset from (1,1) coordinate in pixelsfor each sliceindices - add only to selected sliced of the full_arrayadd_values - add values instead of rewrittingCompilation from Matlab:mex -R2018a ‘CFLAGS=”.. _base_utils.adjust_projection:
-
utils.
adjust_projection
(input, snake_scan, fast_axis_x, positions)¶ - function used to correct the image orientation of mcs_mesh data.[output, output_pos] = adjust_projection(input, snake_scan, fast_axis_x, positions)input = data to be corrected. For mcs the data should be a 2D matrix.snake_scan = 0 for off and 1 for onfast_axis_x = 1 for fast axis along x, 0 for fast axis along youtput = corrected dataoutput_pos = corrected output positions, could be used to see ifthere was a problem with the correctionFor snake scans the routine decides the flipping based on the positions
Returns: output, output_pos
-
utils.
auto_mask_find
(im, varargin)¶ - mask = auto_mask_find(im,[<name>,<value>])im Input complex valued imageOptional parameters:margins Two element array that indicates the (y,x) margins to excludefrom the edge of the mask window. For example to exclude thenoise around ptychography reconstructions, default 0.smoothing Size of averaging window on the phase derivative, default10.gradientrange Size of the histogram windown when selecting valid gradientregions, in radians per pixel, default 1;show_bivariate Show the bivariate histogram of the gradient, usefulfor debugging. Set to the number of figure you’d likeit to appear.Morphological operations to remove point details in the maskclose_size Size of closing window, removes dark bubbles from the mask,default 15. ( = 1 for no effect)open_size Size of opening window, removes bright bubbles from mask,default 120. ( = 1 for no effect)
Returns: mask
-
utils.
binning_2D
(x, binning, centered)¶ - FUNCTION x = binning_2D(x, binning)perform binning in first two dimensions
Returns: x
-
utils.
binning_3D
(x, binning, centered)¶ - FUNCTION x = binning_3D(x, binning)perform fast binning in three dimensions
Returns: x
-
utils.
char_to_cellstr
(inchars, nl_only)¶ - [outstr] = char_to_cellstr(inchars,nl_only)Convert an array of text to a cell array of lines.
Returns: outstr
-
utils.
check_available_memory
()¶ - FUNCTION [mem_avail, mem_total] = check_availible_memory()get availible free memory in linux in MB
Returns: varargout
-
utils.
check_cpu_load
(varargin)¶ - CHECK_CPU_LOAD returns user cpu usage of specified hostshosts (optional)… list of nodes; use ‘x12sa’ for all x12sa nodesused_nodes (optional)… prints warning/summary for used nodes (default: true)ssh_auth (optional) … system echo if ssh authentication is needed (default: false)thr (optional)… set threshold for used nodes (default: 15 %)vm_cycles (optional)… number of cycles for cpu usage (default: 2)
Returns: cpu_load_bl, any_used_cpu
-
utils.
check_matlab_version
(ver)¶ - CHECK_MATLAB_VERSION check matlab version to make sure it is compatiblever… compatible version numberEXAMPLE:check_matlab_version(9.2)MATLAB 9.0 - 2016aMATLAB 9.1 - 2016bMATLAB 9.2 - 2017aMATLAB 9.3 - 2017b
-
utils.
check_perm
(path)¶ - CHECK_PERM check r w x permissions for given path
Returns: result
-
utils.
compile_x12sa_dirname
(scan_no)¶ - COMPILE_X12SA_DIRNAME returns the default cSAXS directory tree for agiven scan numberEXAMPLE:scan_dir = utils.compile_x12sa_dirname(10);-> scan_dir = ‘S00000-00999/S00010/’
Returns: scan_dir
-
utils.
compile_x12sa_filename
(scan_no, point_no, varargin)¶ - Call function without arguments for a detailed explanation of its use
Returns: filename, vararg_remain
-
utils.
crop_pad
(img, outsize, varargin)¶ - CROP_PAD adjusts the size by zero padding or croppingimg… input imageoutsize… size of final image(fill)… value to fill padded regions
Returns: imout
-
default_parameter_value
- [default_value] = default_parameter_value(mfile_name,parameter_name,vararg)identify the current system to set useful default parameters
-
utils.
dftregistration
(buf1ft, buf2ft, usfac)¶ - function [output Greg] = dftregistration(buf1ft,buf2ft,usfac);Efficient subpixel image registration by crosscorrelation. This codegives the same precision as the FFT upsampled cross correlation in asmall fraction of the computation time and with reduced memoryrequirements. It obtains an initial estimate of the crosscorrelation peakby an FFT and then refines the shift estimation by upsampling the DFTonly in a small neighborhood of that estimate by means of amatrix-multiply DFT. With this procedure all the image points are used tocompute the upsampled crosscorrelation.Manuel Guizar - Dec 13, 2007Rewrote all code not authored by either Manuel Guizar or Jim FienupManuel Guizar - May 13, 2016Citation for this algorithm:Manuel Guizar-Sicairos, Samuel T. Thurman, and James R. Fienup,“Efficient subpixel image registration algorithms,” Opt. Lett. 33,156-158 (2008).Inputsbuf1ft Fourier transform of reference image,DC in (1,1) [DO NOT FFTSHIFT]buf2ft Fourier transform of image to register,DC in (1,1) [DO NOT FFTSHIFT]usfac Upsampling factor (integer). Images will be registered towithin 1/usfac of a pixel. For example usfac = 20 means theimages will be registered within 1/20 of a pixel. (default = 1)Outputsoutput = [error,diffphase,net_row_shift,net_col_shift]error Translation invariant normalized RMS error between f and gdiffphase Global phase difference between the two images (should bezero if images are non-negative).net_row_shift net_col_shift Pixel shifts between imagesGreg (Optional) Fourier transform of registered version of buf2ft,the global phase difference is compensated for.
Returns: output Greg
-
utils.
dose_calc
(ptycho_recon, ptycho_data, param)¶ - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%Function:dose_calc(ptycho_recon, ptycho_data, param)Description:The function (1) takes one reconstruction and its data and estimate thedose (2) saves the dose estimation into a .txt file.Input:ptycho_recon: reconstruction, including object, probe, and pptycho_data: data for the reconstructionparam_dose.mu = 1/(451*1e-6); % 1/attenuation_length in 1/m (for CH2 @6.2keV)% 1/(152.7*1e-6) for zeolite Na2Al2Si3O102H4O with 2 g/cm3 density at 6.2 keVparam_dose.rho = 1000; % Density in kg/m^3param_dose.setup_transmission = 0.55; % Intensity transmission of sample% (e.g. air path after the sample, windows, He, detector efficiency)% 0.943 for 700 cm He gas at 760 Torr and 295 K @ 6.2 keV% 0.780 for 10 cm air at 760 Torr and 295 K @ 6.2 keV% 0.976 for 13 micron Kapton (polymide) with 1.43% g/cm3 @ 6.2 keV% 0.841 for 7 micron muskovite mica% (KAl3Si3O11.8H1.8F0.2) with 2.76 g/cm3 @ 6.2 keV% 0.914 for 5 cm of air at 6.2 keV 750 Torr 295 K% 0.55 for 300 micron of mylar C10H8O4 with density 1.38 g/cm3 at 6.2 keVparam_dose.overhead = 0.0; % Extra dose during movement overhead, only applicable% if shutter is not closed between exposuresparam_dose.fmaskparam_dose.scan_numberparam_dose.num_projparam_dose.output_folder (default: ./)Output:one jpg for one_data_frameone jpg for photons_per_shot_allone jpg for photons_per_obj_pixone txt for dose_estimate2017-03-30%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-
utils.
filt2d
(outputdim, unmodsize, varargin)¶ - FILT2D creates a 2d filter, based on fract_hanningoutputdim… Size of the output array.unmodsize… Size of the central array containing no modulation.shape (optional)… ‘rect’ (default) or ‘circ’filter_type (optional)… ‘hann’ (default) or ‘hamm’, chebishev (only for unmodsize=0)example:filt1 = filt2d(256,100,’circ’,’hann’);filt2 = filt2d(256,100);Adapted from fract_hanning:fract_hanning(outputdim,unmodsize)out = Square array containing a fractional separable Hanning window withDC in upper left corner.outputdim = size of the output arrayunmodsize = Size of the central array containing no modulation.Creates a square hanning window if unmodsize = 0 (or ommited), otherwise the output arraywill contain an array of ones in the center and cosine modulation on theedges, the array of ones will have DC in upper left corner.
Returns: out
-
utils.
filt2d_pad
(outputdim, filterdim, unmodsize, varargin)¶ - filt2d_pad(outputdim,filterdim,unmodsize)out = Square array containing a fractional separable Hanning window withDC in upper left corner.outputdim = size of the output arrayfilterdim = size of filter (it will zero pad if filterdim<outputdimunmodsize = Size of the central array containing no modulation.Creates a square hanning window if unmodsize = 0 (or ommited), otherwise the output arraywill contain an array of ones in the center and cosine modulation on theedges, the array of ones will have DC in upper left corner.Code based in fract_hanning_pad
Returns: out
-
utils.
find_files
(filename_mask, varargin)¶ - Call function without arguments for a detailed explanation of its use
Returns: directory, fnames, vararg_remain
-
utils.
find_latest_file
(varargin)¶ - FIND_LATEST_FILE find latest file in given directory and return pathoptional inputpath… search path; default ‘./’file mask… limit results to a specific name or fileextension; default noneoffset… take latest-offset; default 0EXAMPLE:out = find_latest_file;out = find_latest_file(‘../analysis’);out = find_latest_file(‘../analysis’, ‘*.h5’);out = find_latest_file(‘../analysis’, ‘recons.h5’);out = find_latest_file(‘../analysis’, {recons.h5, recons.mat});out = find_latest_file(‘../analysis’, ‘*.h5’, -2);
Returns: out
-
utils.
find_package_refs
(base_path, path, varargin)¶ - FIND_PACKAGE_REFS update references in <path> and its subfolders topackage structure in <base_path>.base_path… repository with new package structurepath… repository which needs to be updatedoptional given as name/value pairextension… file extension; default ‘.m’recursive… recursive behavior; default falseshow_files… show file names, otherwise progressbar; default falsefilename… change output file name and path; default./references.txtExample:find_package_refs(‘./cSAXS_matlab_base’, ‘./cSAXS_matlab_ptycho’)find_package_refs(‘./cSAXS_matlab_base’, ‘./cSAXS_matlab_ptycho’, ‘recursive’, false);
-
utils.
findresidues
(phase)¶ - function residues = findresidues(phase)Receives phase in radians, returns map of residuesManuel Guizar - Sept 27, 2011R. M. Goldstein, H. A. Zebker and C. L. Werner, Radio Science 23, 713-720(1988).Inputsphase Phase in radiansdisp = 0, No feedback= 1, Text feedback (additional computation)= 2, Text and graphic display (additional computation)Outputsresidues Map of residues, note they are valued +1 or -1
Returns: residues
-
utils.
focus_series_fit
(scans, p)¶ - function [ out ] = focus_series_fit( scans, p )Receives scan numbers and parameters as a structure pInput:scansFor SPEC variablesp.motor_name From SPECp.counter From SPECFor sgalil position filep.position_file Example ‘~/Data10/sgalil/S%05d.dat’p.fast_axis_index (= 1 or 2) for x or y scan respectivelyFor mcs counterp.mcs_file Example sprintf(‘~/Data10/mcs/S%02d000-%02d999/S%%05d/%s_%%05d.dat’,floor(scans(ii)/1000),floor(scans(ii)/1000),beamline.identify_eaccount);p.mcs_channel Channel number, e.g. = 3Optionalp.motor_unitsp.plotp.title_strp.coarse_motorOutputout.fitout Parameters of quadratic fitout.coarse_motor Coarse motor name is passed backout.fwhm A vector with the fwhm for each scanout.vertex The position of coarse motor with minimum fwhm from the quadratic fit
Returns: out
-
focus_series_template
- A script to analyze vertica and horizontal through focus scans todetermine the size and position of the horizontal and vertical focii
-
follow_feature
- % Following a feature
-
utils.
fopen_until_exists
(filename, varargin)¶ - Call function without arguments for a detailed explanation of its use
Returns: fid, vararg_remain
-
utils.
fourier_shell_corr_3D_2
(img1, img2, param, varargin)¶ - [resolution FSC T freq n stat] = fourier_shell_corr_3D_2(img1,img2,param, varargin)Computes the Fourier shell correlation between img1 and img2. It can alsocompute the threshold function T. Images can be complex-valued.Can handle non-cube arrays but assumes the voxel is isotropicInputs:img1, img2 Compared imagesparam Structure containing parametersParameters:dispfsc = 1; Display resultsSNRt = 0.5 Power SNR for threshold, popular options:SNRt = 0.5; 1 bit threshold for averageSNRt = 0.2071; 1/2 bit threshold for averagethickring Normally the pixels get assigned to the closest integer pixel ring in Fourier domain.With thickring the thickness of the rings is increased bythickring, so each ring gets more pixels and more statisticsauto_thickring do not calculate overlaps if thickring > 1 is usedst_title optional extra title in the plotfreq_thr =0.05 mimimal freq value above which the resolution is detectedshow_fourier_corr show 2D Fourier correlationmask bool array equal to false for ignored pixels of the fft spaceOutputs:resolution [min, max] resolution estimated from FSC curveFSC FSC curve valuesT Threshold valuesfreq spatial frequenciesstat stat - structure containing other statistics such asSSNR, area under FSC curve. average SNR, ….
Returns: resolution FSC T freq n stat
-
utils.
fract_hanning
(outputdim, unmodsize)¶ - fract_hanning(outputdim,unmodsize)out = Square array containing a fractional separable Hanning window withDC in upper left corner.outputdim = size of the output arrayunmodsize = Size of the central array containing no modulation.Creates a square hanning window if unmodsize = 0 (or ommited), otherwise the output arraywill contain an array of ones in the center and cosine modulation on theedges, the array of ones will have DC in upper left corner.
Returns: out
-
utils.
fract_hanning_pad
(outputdim, filterdim, unmodsize)¶ - fract_hanning_pad(outputdim,filterdim,unmodsize)out = Square array containing a fractional separable Hanning window withDC in upper left corner.outputdim = size of the output arrayfilterdim = size of filter (it will zero pad if filterdim<outputdimunmodsize = Size of the central array containing no modulation.Creates a square hanning window if unmodsize = 0 (or ommited), otherwise the output arraywill contain an array of ones in the center and cosine modulation on theedges, the array of ones will have DC in upper left corner.
Returns: out
-
utils.
get_att_length
(formula, energy, varargin)¶ - GET_ATT_LENGTH returns attenuation length of a material for a given energy (range)formula… chemical formulaenergy… single value in keV or energy range in keV(optional) dens… density, negative number for default values(optional) ang… grazing angle (default 90)(optional) npts… number of points(optional) plot… set to 1 for plottingatt… (energy in keV, transmission)req_density… density in g/cm^3examples:get_att_length(‘Au’, 8.7, -1, 45)get_att_length(‘Pb’, [11.2 24], 0.1, -1, 100)03/2017
Returns: att, req_density
-
utils.
get_beam_center
(filename, varargin)¶ - Call function without arguments for a detailed explanation of its use
Returns: center_xy
-
utils.
get_fil_trans
(formula, energy, thickness, varargin)¶ - GET_FIL_TRANS returns transmission of a solid for a given energy (range)formula… chemical formulaenergy… single value in keV or energy range in keVthickness… thickness in micron(optional) dens… density, negative number for default values(optional) npts… number of points(optional) plot… set to 1 for plottingtrans… (energy in keV, transmission)req_density… density in g/cm^3examples:get_fil_trans(‘Au’, 8.7, 2)get_fil_trans(‘Pb’, [11.2 24], 0.1, -1, 100)03/2017
Returns: trans, req_density
-
utils.
get_from_3D_projection
(small_array, full_array, positions, indices)¶ - full_array = get_from_3D_projection(small_array,full_array, positions, indices)add one small 3D block into large 3D arrayInputs:full_array - array from which the small_array will loadedsmall_array - empty array for storing the datapositions - [Nangles x 2] offset from (1,1) coordinate in pixelsfor each sliceindices - add only to selected sliced of the full_arrayCompilation from Matlab:mex -R2018a ‘CFLAGS=”.. _base_utils.get_gas_trans:
-
utils.
get_gas_trans
(formula, energy, thickness, varargin)¶ - GET_GAS_TRANS returns transmission of a solid for a given energy (range)formula… chemical formulaenergy… single value in keV or energy range in keVthickness… thickness in cm(optional) press… pressure in Torr (default 30)(optional) tempr… temperature in Kelvin (default 295)(optional) npts… number of points(optional) plot… set to 1 for plottingtrans… (energy in keV, transmission)req_press… pressureexamples:get_gas_trans(‘Air’, 8.7, 2)get_gas_trans(‘CO2’, [11.2 24], 20, 30, 100)03/2017
Returns: trans, req_press
-
utils.
get_grid
(ish, px)¶ - get_grid returns coordinate system for input shape ish and pixel size pxExample:[g1,g2] = get_grid(512, 29e-9);
Returns: gx, gy
-
utils.
get_hdr_val
(header, signature, format, ...)¶ - Call function without arguments for instructions on how to use it
Returns: outval, line_number, err
-
utils.
get_option
(p, option_name, default)¶ - bool = get_option(p, option_name, default)
Returns: bool
-
utils.
get_ref_index
(formula, energy, varargin)¶ - GET_REF_INDEX returns refractive index for the specified chemical formula at a given energy (range)formula… chemical formulaenergy… single value in keV or energy range in keV(optional) dens… density, negative number for default value(optional) npts… number of points(optional) plot… set to 1 for plotting the refractive indexref… (energy in keV, delta, beta)req_density… density in g/cm^3examples:get_ref_index(‘Au’, 8.7)get_ref_index(‘Pb’, [11.2 24], -1, 100)03/2017
Returns: ref, req_density
-
utils.
goldstein_unwrap2D
(a, max_box_radius)¶ - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%GoldsteinUnwrap2D implements 2D Goldstein branch cut phase unwrapping algorithm.References::1. R. M. Goldstein, H. A. Zebken, and C. L. Werner, �Satellite radar interferometry:Two-dimensional phase unwrapping,� Radio Sci., vol. 23, no. 4, pp. 713�720, 1988.2. D. C. Ghiglia and M. D. Pritt, Two-Dimensional Phase Unwrapping:Theory, Algorithms and Software. New York: Wiley-Interscience, 1998.Inputs: 1. Complex image in .mat double format2. Binary mask (optional)Outputs: 1. Unwrapped phase image2. Phase quality mapThis code can easily be extended for 3D phase unwrapping.Posted by Bruce Spottiswoode on 22 December 2008%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Returns: unph
-
utils.
goldsteinunwrap2
(fase, disp, start)¶ - Implementation of Goldstein unwrap algorithm based on location ofresidues and introduction of branchcuts.R. M. Goldstein, H. A. Zebker and C. L. Werner, Radio Science 23, 713-720(1988).Inputsfase Phase in radians, wrapped between (-pi,pi)disp (optional) = 1 to show progress (will slow down code)will also display the branch cutsstart (optional) [y,x] position to start unwrapping. Typically fasterat the center of the arrayOutputsfaserecon Unwrapped phase ( = fase where phase could not be unwrapped)shadow = 1 where phase could not be unwrapped31 August, 2010 - Acknowledge if used
Returns: faserecon shadow
-
utils.
identify_system
()¶ - Identify the current system to set useful default parameter values indefault_parameter_value.m.A modified version of both macros at the beginning of the Matlab searchpath may be used to define local standard parameters.
Returns: return_system_id_str return_other_system_flags
-
utils.
imdeform_affine_fft
(img, affine_matrix, linear_shift)¶ - img = affine_deform_fft(img, affine_matrix, linear_shift)apply affine deformation on image, use only for small corrections !!Inputs:img - 2D or stack of 2D imagesaffine_matrix - 2x2xN affine matrix
Returns: img
-
utils.
imgaussfilt2_fft
(A, sigma, split)¶ - FUNCTION A = imgaussfilt2_fft(A,sigma, split)apply fast gaussian smoothing along first two dimensionssplit = number of blocks for fft_split
Returns: A
-
utils.
imgaussfilt3_conv
(X, filter_size)¶ - FUNCTION A = imgaussfilt3_conv(X, filter_size)apply gaussian smoothing along all three dimensions, faster than matlab alternativesplit = number of blocks for fft_split
Returns: X
-
utils.
imgaussfilt3_fft
(A, sigma, split)¶ - FUNCTION A = imgaussfilt3_fft(A,sigma)apply gaussian smoothing along all three dimensions, faster than matlab alternativesplit = number of blocks for fft_split
Returns: A
-
utils.
imrescale_fft
(img, scale)¶ - IMRESCALE_FFT subpixel precision rescaling based on mulitplication by amatrix of fourier transformationInputs:img - 2D or stack of 2D imagesscale - scaling factorOutputs: 2D or stack of 2D images scaled by factor scale
Returns: img_rescale
-
utils.
imrescale_frft
(img, scale_x, scale_y, scale_z)¶ - function img = imrescale_frft(img, scale_x, scale_y, scale_z)IMRESCALE_FRFT based on fractional fourier transformationsubpixel precision image rescalingInputs:img 2D or stack of 2D imagesscale_x - horizontal scaling factorscale_y - vertical scaling factor, if not provided scale_x is usedOutputs: 2D or stack of 2D images scaled by factors scale_x / scale_y
Returns: img
-
utils.
imrotate_ax
(img_stack, angle, ax, val, method)¶ - FUNCTION mg_stack = imrotate_ax(img_stack, angle, ax)bilinear rotate stack of images along given axis
Returns: img_stack
-
utils.
imrotate_ax_fft
(img, theta, axis)¶ - FUNCTION img_stack = imrotate_ax_fft(img_stack, theta, ax)fft based image rotate for a stack of images along given axisbased on “Fast Fourier method for the accurate rotation of sampled images”, Optic Communications, 1997
Returns: img
-
utils.
imshear_fft
(img, theta, shear_axis)¶ - FUNCTION img_stack = imshear_fft(img_stack, theta, ax)fft based image rotate for a stack of images along given axisbased on “Fast Fourier method for the accurate rotation of sampled images”, Optic Communications, 1997
Returns: img
-
utils.
imshift_ax
(img, shift, ax)¶ - IMSHIFT_AX will apply integer shift that can be differentfor each frame along axis AX. If apply_fft == false,then images will be assumed to be in fourier space
Returns: img_out
-
utils.
imshift_fast
(img_0, x, y, Npix_new, type, default_val)¶ - IMSHIFT_FAST will shift of stack of images by given number ofpixels and if needed crop / pad image to fit into Npix_newParameters:img_0 - stack of imagesx,y - horizontal / vertical shift in pixels (scalars)Npix_new - empty/missing => keep original size, 2x1 vector => embed new image into given frame sizetype - linear / nearest nbr interpolation , (missing = linear)default_val - default value to fill empty regions created after the image shift
Returns: img_new
-
utils.
imshift_fft
(img, x, y, apply_fft)¶ - IMSHIFT_FFT will apply subpixel shift that can be different foreach frame. If apply_fft == false, then images will beassumed to be in fourier space
Returns: img
-
utils.
imshift_fft_ax
(img, shift, ax, apply_fft)¶ - IMSHIFT_FFT_AX will apply subpixel shift that can be different for each frame along one dimension onlyIf apply_fft == false, then images will be assumed to be in fourier spaceInputs:img - inputs ndim array to be shifted along first 2 dimensionsshift - Nx1 vector of shifts, positive direction is upapply_fft = false - if the img is already after fft, default is false
Returns: img
-
utils.
interpolateFT
(im, outsize)¶ - imout = interpolateFT(im,outsize)Computes 2D interpolated image using Fourier transform, i.e. dirichletinterpolation. Computes the FT and then adjusts the size by zero paddingor cropping then it computes the IFT. A real valued input may haveresidual imaginary components, which is given by numerical precision ofthe FT and IFT.Inputsim - Input complex arrayoutsize - Output size of array [ny nx]Outputsimout - Output complex image2014.06.02
Returns: imout
-
utils.
interpolateFT_ax
(im, outsize, ax)¶ - imout = interpolateFT_ax(im,outsize,ax)Computes interpolated array using 1D Fourier transform, i.e. dirichletinterpolation along single axis. Computes the FT and then adjusts the size by zero paddingor cropping then it computes the IFT. A real valued input may haveresidual imaginary components, which is given by numerical precision ofthe FT and IFT.Inputsim - Input complex arrayoutsize - Output size of array [N pixels]ax - index of axis along which interpolation is doneOutputsimout - Output complex imageExample:x = randn(10,20,30);x_int = utils.interpolateFT_ax(x, 10, 3) % downsample to 10 pixels along 3rd axis
Returns: imout
-
utils.
interpolate_linear
(img, sizeOut)¶ - function interpolate_linear(img, scale, method)rescaling based on interp2, faster than utils.interpolateFT, works with GPUInputs:img - 2D or stack of 2D imagesscale - scaling factormethod - linear (default), cubic,Outputs: 2D or stack of 2D images scaled by factor scale
Returns: img_out
-
utils.
onCleanup
(functionHandle, varargin)¶ - ONCLEANUP - modified MATLAB classEXAMPLES:%% cleanup function with no arguments %%1.) define cleanup routine:function cleanexit()fprintf(‘Reconstruction stopped!’)end2.) get instance of onCleanup:finishup = utils.onCleanup(@() cleanexit());%% cleanup function with one or more arguments1.) define cleanup routine:function cleanexit(p)if ~p.getReport.completedfprintf(‘Reconstruction stopped!’)endend2.) get instance of onCleanup:finishup = utils.onCleanup(p, @(x) cleanexit(x));3.) if needed, update parameters that are passed to your cleanupfunction:finishup.update(p);onCleanup - Specify cleanup work to be done on function completion.C = onCleanup(S), when called in function F, specifies any cleanup tasksthat need to be performed when F completes. S is a handle to a functionthat performs necessary cleanup work when F exits (e.g., closing files thathave been opened by F). S will be called whether F exits normally orbecause of an error.onCleanup is a MATLAB class and C = onCleanup(S) constructs an instance C ofthat class. Whenever an object of this class is explicitly or implicitlycleared from the workspace, it runs the cleanup function, S. Objects thatare local variables in a function are implicitly cleared at the terminationof that function.Example 1: Use onCleanup to close a file.function fileOpenSafely(fileName)fid = fopen(fileName, ‘w’);c = onCleanup(@()fclose(fid));functionThatMayError(fid);end % c will execute fclose(fid) hereExample 2: Use onCleanup to restore the current directory.function changeDirectorySafely(fileName)currentDir = pwd;c = onCleanup(@()cd(currentDir));functionThatMayError;end % c will execute cd(currentDir) hereSee also: CLEAR, CLEARVARSReference page in Doc Centerdoc utils.onCleanup
-
utils.
param_protect_field
(varargin)¶ - PARAM_PROTECT_FIELDparam_protect_field(param)… check for protected field; returnsbooleanaccepts struct or string as inputparam_protect_field()… return protected fieldsparam_protect_field(param, ‘p’)… add param to protected fieldsparam_protect_field(param, ‘r’)… remove param from protected fields
Returns: varout
-
utils.
peakfinder
(x0, sel, thresh, extrema)¶ - PEAKFINDER Noise tolerant fast peak finding algorithmINPUTS:x0 - A real vector from the maxima will be found (required)sel - The amount above surrounding data for a peak to beidentified (default = (max(x0)-min(x0))/4). Larger values meanthe algorithm is more selective in finding peaks.thresh - A threshold value which peaks must be larger than to bemaxima or smaller than to be minima.extrema - 1 if maxima are desired, -1 if minima are desired(default = maxima, 1)OUTPUTS:peakLoc - The indicies of the identified peaks in x0peakMag - The magnitude of the identified peaks[peakLoc] = peakfinder(x0) returns the indicies of local maxima thatare at least 1/4 the range of the data above surrounding data.[peakLoc] = peakfinder(x0,sel) returns the indicies of local maximathat are at least sel above surrounding data.[peakLoc] = peakfinder(x0,sel,thresh) returns the indicies of localmaxima that are at least sel above surrounding data and larger(smaller) than thresh if you are finding maxima (minima).[peakLoc] = peakfinder(x0,sel,thresh,extrema) returns the maxima of thedata if extrema > 0 and the minima of the data if extrema < 0[peakLoc, peakMag] = peakfinder(x0,…) returns the indicies of thelocal maxima as well as the magnitudes of those maximaIf called with no output the identified maxima will be plotted alongwith the input data.Note: If repeated values are found the first is identified as the peakEx:t = 0:.0001:10;x = 12*sin(10*2*pi*t)-3*sin(.1*2*pi*t)+randn(1,numel(t));x(1250:1255) = max(x);peakfinder(x)Copyright Nathanael C. Yoder 2011 (nyoder@gmail.com)
Returns: varargout
-
utils.
pixel_to_q
(pixel, pixel_size_mm, det_dist_mm, E_keV)¶ - Call function without arguments for instructions on how to use it
Returns: q_A
-
utils.
power_spectral_density
(img, air, varargin)¶ - [PSD, freq] = power_spectral_density(img, varargin)Computes the power spectral density of the provided 3D image.Can handle non-cube arrays but assumes the voxel is isotropicInputs:img input image (2D or 3D)Parameters:thickring Normally the pixels get assigned to the closest integer pixel ring in Fourier domain.With thickring the thickness of the rings is increased bythickring, so each ring gets more pixels and more statisticsauto_binning apply binning if dimensions are significanlty different along each axismask bool array equal to false for ignored pixels of the fft spaceOutputs:PSD PSD curve valuesfreq normalized spatial frequencies to 1Example of use:img = randn(512,512,512);utils.power_spectral_density(img, ‘thickring’, 3);
Returns: PSD, freq
-
utils.
progressbar
(n, N, w)¶ - progressbar - display a progress barprogressbar(n,N,w);displays the progress of n out of N.n should start at 1.w is the width of the bar (default w=20).
-
utils.
prop2focus
(img, lam, dx, varargin)¶ - PROP2FOCUS propagate img to focusprop2focus uses ‘phase detection autofocus’ to find the focusimg… complex-valued objectlam… wavelengthdx… pixel sizeoptional parametersd_start… initial guess of propagation distance to focusfov… crop to fov and apodize edges
Returns: d, img_prop
-
utils.
prop_free_ff
(win, lambda, z, pixsize)¶ - PROP_FREE_FF Far field propagationPROP_FREE_FF(WIN, LAMBDA, Z, PIXSIZE) returns the propagated wavefieldWIN by a distance Z, using wavelength LAMBDA. PIXSIZE is the dimensionof one pixel.PROP_FREE_FF(WIN, LAMBDA, Z) is the same as above, assuming PIXSIZE=1(that is, Z and LAMBDA are expressed in pixel units).In this implementation, the output wave pixel size becomesZ*LAMBDA/(N*PIXSIZE) (where N is the linear dimension of the array).
Returns: wout
-
utils.
prop_free_nf
(win, lambda, z, dx)¶ - PROP_FREE_NF Near field propagationwout = prop_free_nf(win, lambda, z, pixsize) returns the propagated wavefieldWIN by a distance Z, using wavelength LAMBDA. PIXSIZE is the dimensionof one pixel.wout = prop_free_nf(win, lambda, z) is the same as above, assuming PIXSIZE=1(that is, Z and LAMBDA are expressed in pixel units).[~,H] = prop_free_nf(win, lambda, z, pixsize) Does not compute propagation onlycomputes and returns H, the Fourier domain propagation function
Returns: wout, H
-
utils.
pshift
(ain, ctrpos, varargin)¶ - AOUT = pshift(AIN, CTRPOS)Shift array AIN periodically so that CTRPOS is placed at (1,1).
Returns: aout
-
utils.
registersubimages_2
(img1, img2, x1, y1, x2, y2, upsamp, displ, Wfilt)¶ - Finds common subregions in img1 and img2 and computes registration (alignment)Does not perform global search, so an approximate initial estimate isnecessary[subim1, subim2, delta, deltafine,regionsout] = registersubimages_2(img1, img2, x1, y1, x2, y2, upsamp, displ,Wfilt);Inputsimg1 - Reference imagex1, y1 - Vectors indicating the region of interest of img1, e.g. x1 =[30:100]. If left empty the code starts with full window andthen reduces to the common partimg2, x2, y2 - Same as 1 but for the image to alignupsamp - Fraction of a pixel for the fine search, default = 1displ = 0 no information displayed (default)= 1 to display text information> 1 also shows images in figure(display)Wfilt Fourier domain filter for registration (= 1 for no effect)Outputssubim1, subim2 - Common subimages taken from img1 and img2, subim2 is realigned subpixeldelta - Registration values (dy,dx)deltafine - Only the subpixel components of the alignmentregionsout - Structure with final regions for registrationPlease cite and acknowledge if you use it. Algorithm extended from that inM. Guizar-Sicairos, S. T. Thurman and J. R. Fienup, “Efficient subpixelimage registration algorithms,” Opt. Lett. 33, 156 (2008).Report bugs to mguizar@gmail.comThis code is intended for finding the same object in two differentimages. It is a local search, so the code will go with the first solutionit finds, an approximately good initial estimate is required.This code uses integer pixel and subpixel cross-correlation to find thelocal solution. The intended purpose is for this code to be able to findtwo similar subimages in the same image so the global search would beinadequate. This code does not remove the global phase between thesubimages.Keep your eyes open, this code has not been throughly debugged or testedHistoryAllow for iterative refinement of chosen subwindowAllow for empty input for subwindow regionsManuel Guizar - January 22, 2013Modified on 24 Aug 2010 to return deltafine and receive a Fourier filterAlso modified to have initial estimate with upsamp 2 and then round andso that the final registration is done with an upsam accuracyModified on 25 Aug 2010. If coarse alignment exceeds image dimensionsassume error in coarse alignment and perform only subpixel.Original code by Manuel Guizar - August 4, 2009
Returns: subim1, subim2, delta, deltafine, regionsout
-
utils.
relative_path
(path1, path2)¶ - RELATIVE_PATH returns relative path from absolute path <path1> to <path2>
Returns: rel_path
-
utils.
remove_linear_phase_smart
(im, varargin)¶ - im_output = remove_linear_phase_smart(im_input, [,<name>,<value>] …])Receives a complex valued array, returns the complex array after removingthe linear and the constant phase offset. Different options are given fordefining a reference area on the sampleim_input Input complex valued imageThe optional <name>,<value> pairs are:‘mask’, maskarray Binary array with ones where the linear phase should beremoved. Alternatively the mask can be an array ofnon unitary weights for the computation of averagephase ramp and average phase. For example, themagnitude can be use to weightJune 21,2016
Returns: im_output, ph_err
-
utils.
remove_linearphase
(testim, mask, upsamp)¶ - Removes linear phase from object considering only pixels where mask isunity, arrays have center on center of arraytestim Imagemask Binary array with ones where the linear phase should becomputed fromupsamp Linear phase will be removed within 2*pi/upsamp peak to valleyin radianserrorm Optional ouput with NRMSAugust 19 2010
Returns: output errorm
-
utils.
remove_linearphase_v2
(testim, mask, upsamp)¶ - [output errorm] = remove_linearphase_v2(testim,mask,upsamp)Removes linear phase from object considering only pixels where mask isunity, arrays have center on center of arraytestim Imagemask Binary array with ones where the linear phase should becomputed fromupsamp Linear phase will be removed within 2*pi/upsamp peak to valleyin radianserrorm Optional ouput with all outputs from dftregistrationAugust 19 2010Updated on Feb 18 2011, to return all outputs from dftregistration
Returns: output errorm
-
utils.
remove_sinogram_ramp
(sinogram, air_gap, polyfit_order)¶ - sinogram = remove_sinogram_ramp(sinogram,air_gap,polyfit_order )FUNCTION simple and fast phase ramp/offset removal from already unwrapped sinogramusing linear interpolation between air on both sidesInputs:sinogram - unwrapped projectionsair_gap = [2x1] vector with number of pixels on both sides where canbe assumed to be airpolyfit_order - -1 = dont assume anything about the removed phase0 = assume that it is constant offset1 = assume that it is 2D plane
Returns: sinogram
-
utils.
rmphaseramp
(a, varargin)¶ - Function [A1, P] = RMPHASERAMP(A)A1 = RMPHASERAMP(A)Removes the phase ramp from the image A.[A1, P] = RMPHASERAMP(A)such that A1 = A.* P.… = RMPHASERAMP(A, M)Uses M as a mask.… = RMPHASERAMP(A, ‘abs’)Uses the absolute value of A as a weight.… = RMPHASERAMP(A, ‘roi’)Prompts user to select a polygonal mask to define flat phase.
Returns: b, p, varargout
-
utils.
savefast_safe
(filename, varargin)¶ - FUNCTION savefast_safe(filename, varargin)savefast: fast saves of large arrays to .mat filesMatlab’s ‘save’ command can be very slow when saving large arrays,because by default Matlab attempts to use compression. This functionprovides a much faster alternative, at the cost of larger files.The syntax is identical to that of the Matlab save command.Example:>> ops = struct(‘algorithm’, ‘greedy’);>> A = int32(randi(20, 1000, 1200, 40));>> B = randn(500, 1800, 60);>> tic; save /tmp/test ops A B; tocElapsed time is 22.980294 seconds.>> tic; savefast /tmp/test ops A B; tocElapsed time is 0.571098 seconds.
-
utils.
sbb
(varargin)¶ - SBB returns station board for PSI Westsyntax:as station board:sbb (from, number_of_connections)as connection finder:sbb (from, to, number_of_connections)03/2017
-
utils.
shiftpp2
(rows*Nr/nr+cols*Nc/nc)¶ - function out=shiftpp(in,rows,cols)performs partial-pixel shift (with wraparound) using FFTModified from shiftpp.m to correct a phase factor that appeared when usingodd sized arrays.Manuel Guizar - Dec 13, 2007
Returns: Nc, Nr
-
utils.
shiftwrapbilinear
(in, dy, dx)¶ - out = shiftwraplinear(in,dy,dx)Shifts an image with wrap around and bilinear interpolation
Returns: out
-
utils.
smooth_edges
(img, win_size, dims)¶ - FUNCTION img = smooth_edges(img, win_size)takes stack of 2D images and smooths boundaries to avoid sharp edge artefacts during imshift_fftInputs:img - 2D / 3D array, smoothing is done along first two dimensionswin_size - size of the smoothing region, default is 3dims - list of dimensions along which will by smoothing done
Returns: img
-
utils.
stabilize_phase
(img, varargin)¶ - [img, gamma,gamma_x, gamma_y, c_offset] = stabilize_phase(img, varargin)Description: adjust phase of the object to be mostly around zero andremove linear rampInputs:img - complex image to stabilizeimg_ref - complex images used as reference, if empty ones is usedVarargins:weights - 0<x<1 numeric array denoting reliable unwrapping regionsplit - split FFTon smaller blocks on GPUfourier_guess - (bool), use maximum in Fourier space to get initialguess of the phase rampremove_ramp - (bool), if false, remove only phase offset (scalar)smoothing - smooth image before removing ramp, makes it more robustOutputs:img - phase ramp / offset subtracted complex-valued imagegamma,gamma_x, gamma_y - (1,1,N arrays) offset, ramp horizontal / verticalc_offset - either constant or phase ramp offset subtracted from thecomplex data as img .* exp(1i*c_offset)
Returns: img, gamma, gamma_x, gamma_y, c_offset
-
utils.
struc2cell
(data)¶ - STRUC2CELL recursively converts a structure into a cellEXAMPLE:Define structure:p = [];p.verbose_level = 2;p.energy = 6.2;p.engines.engine0.name = ‘DM’;p.engines.engine0.iter = 200;Convert to cell:fn = struc2cell(p)Output:1×4 cell array‘verbose_level’ ‘energy’ ‘engines.engine0.name’ ‘engines.engine0.iter’
Returns: entry
-
utils.
update_param
(p, varargin)¶ - UPDATE_PARAM Use update_param to update a struct with another struct and /or fields and their corresponding values.Update struct with another struct:p = update_param(p, p_updated);Update struct with another struct and fields:p = update_param(p, p_updated, ‘windowautopos’, 1, ‘extrastringtitle’, ‘Final recon’);Update struct with fields:p = update_param(p, ‘windowautopos’, 1, ‘extrastringtitle’,’Final recon’);Use field force_update to select different update types:force_update = 0 … add fields but don’t overwrite themforce_update = 1 … overwrite fields but leave protectedfields unchanged (default)force_update = 2 … overwrite everythingp = update_param(p, ‘windowautopos’, 1, ‘force_update’, 0);
Returns: p
-
utils.
verbose
(varargin)¶ - Function verbose(level, message)verbose : shows current verbose levelverbose(n): set the level to nverbose(n, message): displays the message if n <= current verbose levelverbose(n, message, v1, v2, …) behaves like sprintf(message, v1, v2, …)Suggested levels:1: important information2: general information3: debugging
Returns: varargout
+utils/private¶
trash¶
-
trash/create_mask_GUI(varargin)
- CREATE_MASK_GUI MATLAB code for create_mask_GUI.figCREATE_MASK_GUI, by itself, creates a new CREATE_MASK_GUI or raises the existingsingleton*.H = CREATE_MASK_GUI returns the handle to a new CREATE_MASK_GUI or the handle tothe existing singleton*.CREATE_MASK_GUI(‘CALLBACK’,hObject,eventData,handles,…) calls the localfunction named CALLBACK in CREATE_MASK_GUI.M with the given input arguments.CREATE_MASK_GUI(‘Property’,’Value’,…) creates a new CREATE_MASK_GUI or raises theexisting singleton*. Starting from the left, property value pairs areapplied to the GUI before create_mask_GUI_OpeningFcn gets called. Anunrecognized property name or invalid value makes property applicationstop. All inputs are passed to create_mask_GUI_OpeningFcn via varargin.*See GUI Options on GUIDE’s Tools menu. Choose “GUI allows only oneinstance to run (singleton)”.See also: GUIDE, GUIDATA, GUIHANDLES
Returns: varargout
-
create_mask_GUI_export_backup
- CREATE_MASK_GUI_EXPORT MATLAB code for create_mask_GUI_export.figCREATE_MASK_GUI_EXPORT, by itself, creates a new CREATE_MASK_GUI_EXPORT or raises the existingsingleton*.H = CREATE_MASK_GUI_EXPORT returns the handle to a new CREATE_MASK_GUI_EXPORT or the handle tothe existing singleton*.CREATE_MASK_GUI_EXPORT(‘CALLBACK’,hObject,eventData,handles,…) calls the localfunction named CALLBACK in CREATE_MASK_GUI_EXPORT.M with the given input arguments.CREATE_MASK_GUI_EXPORT(‘Property’,’Value’,…) creates a new CREATE_MASK_GUI_EXPORT or raises theexisting singleton*. Starting from the left, property value pairs areapplied to the GUI before create_mask_GUI_export_OpeningFcn gets called. Anunrecognized property name or invalid value makes property applicationstop. All inputs are passed to create_mask_GUI_export_OpeningFcn via varargin.*See GUI Options on GUIDE’s Tools menu. Choose “GUI allows only oneinstance to run (singleton)”.See also: GUIDE, GUIDATA, GUIHANDLES