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 for
limited GPU memory
Inputs:
cfg - config structure generated by ASTRA_initialize
num_gpu - number of gpu to split the data
angle_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 degress
Inputs:
Npix - size of tomogram
size_projection - size of sinogram (Nlayers, width, Nangles)
angles - rotation angles of projections in degrees
lamino_angle - laminography angle / angles in degrees. lamino_angle ==
90 is standard tomography , default = 90
tilt_angle - tilt of camera with respect to the rotation axis coordinates, in
degrees, default = 0
pixel_scale - scale of pixels in tomogram compares to the
projection pixel size, default = 1
rotation_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 pieces
composed tomography back-projector based on ASTRA toolbox
can 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 pieces
Inputs:
composed tomography projector based on ASTRA toolbox
can 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 wrappers
recompile 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 pieces
Inputs:
composed tomography projector based on ASTRA toolbox
can 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 array
Inputs:
full_array
small_array
position - 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) order
Inputs:
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++) order
Inputs:
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 readout
tomo_id - Index specifying the range of scan numbers
out - 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_MASK
create a binary mask for the current figure
optional
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

beamline.energy2mark(E, calib_file)
function mark = energy2mark(E,calib_file)
After calibrating using beamline.mark_interpolation_setup you can use
this function to input a desired energy and a linear interpolation will
determine and give you the mark
Inputs
E Array of energies in keV
calib_file Name of the file with the calibration
Outputs
mark 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 called
as function of ‘spec’
written by (last change: 2011-06-16)
in case of bugs, problems, and suggestions for improvements, please contact
CXS group
note that EPICS communication works only on local machines at the beamline, i.e.,
NOT on the compute nodes
run this (or related scripts that use EPICS for communication), for instance, on
x12sa-cons-1
beamline.find_specDatFile(specDatFile)
function specDatFile = find_specDatFile(specDatFile)
find location of the spec file in the provided folder / path
if the variable specDatFile is not a complete path to a file
try 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)
IND2MASK
convert 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
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 air
Dependencies:
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 scan
From 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 scan
From spec compile post_scan.mac
Returns:out
mark_interpolation_setup
If you do scans with different marks for energy you can use this code to
calibrate the marks vs energy
Run this code, it will save a calibration and then you can use
energy2mark function
beamline.mask2ind(mask)
MASK2IND
convert a 2D binary mask to indices
Parameters:mask – 2D binary mask
Returns:s - mask structure; must contain s.indices and s.framesize
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.m
Template for radial integration made around 2015
Changes:
2016-08-22: define mask files at the beginning, allowing for a flag in case it needs to be repeated
add 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 readout
scannums - Array of scan numbers
tomo_id - integer or list of integers, only if the scannums is empty
out - Contains fields with scan, target_angle, readout_angle
errorflag - = 1 if at least one scan was not found
Returns:out errorflag
beamline.read_omny_pos(omnyposfile)
Read interferometer positions written by Orchestra
Input is the filename with path
Output 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 numbers
12 June 2013
June6 2015 - Changed in order to accept an arbitrary number
of values in order to be compatible with 10 columns for flOMNI and 19 for
OMNY
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.fig
CREATE_MASK_GUI_EXPORT, by itself, creates a new CREATE_MASK_GUI_EXPORT or raises the existing
singleton*.
H = CREATE_MASK_GUI_EXPORT returns the handle to a new CREATE_MASK_GUI_EXPORT or the handle to
the existing singleton*.
CREATE_MASK_GUI_EXPORT(‘CALLBACK’,hObject,eventData,handles,…) calls the local
function 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 the
existing singleton*. Starting from the left, property value pairs are
applied to the GUI before create_mask_GUI_export_OpeningFcn gets called. An
unrecognized property name or invalid value makes property application
stop. All inputs are passed to create_mask_GUI_export_OpeningFcn via varargin.
*See GUI Options on GUIDE’s Tools menu. Choose “GUI allows only one
instance 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 positions
2017-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 kernel
Example 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 into
given positions
example:
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 B
consisting 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 array
A to produce an n-dimensional array B composed of copies of A. The size
of 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-N
matrix 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, single
integer: uint8, int8, uint16, int16, uint32, int32, uint64, int64
char, logical
See also BSXFUN, MESHGRID, ONES, ZEROS, NAN, INF.
Reference page in Doc Center
doc repmat
Other functions named repmat
codistributed/repmat InputOutputModel/repmat tall/repmat
gpuArray/repmat symfun/repmat
Returns:x_new
fluo.replicate(x, N, ax)
fast replitaction of matrix along one dimension, faster than
repmat / 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 SASfit
accounts for transmission, time and thickness correction
scales the data to a calibration factor
background correction, removal of bad pixels
not suitable for anisotropic data
saves 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 the
file 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 Matlab
structure
filename… path and filename of the h5 file
optional
scan… 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 as
structure, 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 output
arguments.
file… path to cxs/h5 or mat file
optional
section… ‘full’, ‘probe’, ‘object’, ‘recon’ or ‘p’ to select
subsections of the data; default: ‘full’
EXAMPLES:
%% recommended usage %%
% load into a structure
S = load_ptycho_recons(‘./recon.h5’);
% load a subset
S = 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 workspace
load_ptycho_recons(‘./recon.h5’);
full = object, probe (current scan) and p
recon = 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 the
positions of a SPEC file corresponding to two given motor names
Input 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 N
being the number of points in the scan. The two columns contain motor
positions 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 file
function save_append(filename, vars, x)
Input:
filename - file to which the varible will be appended
vars - the varible to save, eg, saveme
x - 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 files
Matlab’s ‘save’ command can be very slow when saving large arrays,
because by default Matlab attempts to use compression. This function
provides 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; toc
Elapsed time is 22.980294 seconds.
>> tic; savefast /tmp/test ops A B; toc
Elapsed 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
optional
Parameters:
  • binary_path – path to sendmail binary file
  • server – server address
  • sleep – sleep time between messages
  • logfile – logfile+path to keep track of past activities
EXAMPLES
sendSMS(‘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 help
please reports bugs, problems, suggestions for improvements to:
CXS group
the case of duplicate scannumbers in the spec file, and how to
address 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 dataset
file… HDF filename
attr… structure of attributes
loc… 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 file
file… h5 file path
attr… dataset name
optional
gpath… path within the h5 file; default root (/)
Returns:out
io.HDF.hdf5_cp_file(orig_filename, duplicate_filename, varargin)
HDF5_CP_FILE copy HDF files
orig_filename… source file
duplicate_filename… target file
optional given as name/value pair
groups… groups to copy; either string or cell of
strings; default: everything in root
copy_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 file
file… h5 file path
dset… dataset name
optional
gpath… path within the h5 file; default root (/)
check_links… include links; default true
EXAMPLES:
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 file
DATA = HDF5_LOAD(filename) reads a complete file hierarchy recursively, with
file name/path being specified by the ‘filename’ argument
DATA = HDF5_LOAD(filename, ‘-a’) reads a complete file hierarchy
recursively, including attributes
DATA = HDF5_LOAD(filename, location) reads a particular group, link, or a single dataset
specified by the ‘location’ argument
ATT = HDF5_LOAD(filename, location, ‘-a’) reads all datasets and attributes associated
with a particular location in the file (group, link or dataset)
ATT = HDF5_LOAD(filename, location, ‘-ca’) reads all datasets and attributes associated
with a particular location in the file (group, link or dataset) and
converts datasets to a specific matlab class based on attribute ‘MATLAB_class’
SLICE = HDF5_LOAD(filename, location, {rowRange, colRange, frameRange, …}) reads a
portion of a dataset along specified dimentions, where slicing ranges can be defined in
the 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 end
indexes
range = [start_index, Inf] - reads all data from start_index to the last
existing element in the file
range = [], or range is omitted at the end - reads the full range of values for that
dimention (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 file
hdf5_mv_data creates a new (UNIX-like) hard link at loc_dest to the dataset at
loc_origin and deletes the hard link to the dataset at loc_origin.
file… HDF filename
loc_origin… location of the data that needs to be moved
loc_dest… destination and name of the new data
EXAMPLE:
% move dataset probe from root to group measurements
hdf5_mv_data(‘./awesome_file.h5’, ‘probe’, ‘measurements/probe’)
Please notice that all groups and datasets have to exist before running
the script!
io.HDF.hdf5_rm_attr(file, loc, attr_name)
HDF5_RM_ATTR Delete attribute(s) from HDF file
file… HDF filename
loc… location within the HDF file
attr_name… string or cell of strings containing the names of the
obsolete attributes
io.HDF.hdf5_rm_data(file, loc)
HDF5_RM_DATA Delete a dataset within an HDF5 file
file… HDF filename
loc… location of the dataset that needs to be removed
Please 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 extension
data… matlab structure or array or link
data_name… needed if input data is not a matlab structure, needs
to be given as name/value pair
optional
overwrite… replace existing file if it exists
gpath… 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 current
gpath
comp… 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 your
data 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’ in
group ‘/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 supported
external links have to be specified by a single string with
3 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 with
2 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 array
Outputs:
coordinates of the first value equal to maximum
Example: [i,j] = argmax(randn(10))
Returns:varargout
math.argmin(x)
FUNCTION varargout = argmin(x)
INputs:
X - Ndim array
Outputs:
coordinates of the first value equal to maximum
Example: [i,j] = argmin(randn(10))
Returns:varargout
math.center(X, use_shift)
———————————————————————–
This file is part of the PTYCHOMAT Toolbox
Author: Michal Odstrcil, 2016
License: Open Source under GPLv3
———————————————————————–
Description: find center of mass of matrix X, calculate variance if
needed
inputs:
X 2D stacked images
use_shift, if true, CoM will be calculated relatively to the center
of 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 be
preserved.
EXAMPLE:
p.value1 = 10.25;
p.value2 = 2;
p_int = double2int(p);
p_int.value1
ans =
10.2500
p_int.value2
ans =
uint32
2
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 Toolbox
Author: Michal Odstrcil, 2016
License: Open Source under GPLv3
———————————————————————–
Description: faster version of matlab fftshift to work for stack of
2D images
Inputs: 2D or stack of 2D images
Outputs:
x - 2D or stack of 2D images after fftshift along first 2 dimensions
idx - 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 singular
value decomposition of the input matrix A upto rank k using i levels of
Krylov 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). Finding
structure with randomness: Probabilistic algorithms for constructing
approximate 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 FFT
Inputs:
img - stack of images
split - split for GPU fft_partial
axis - 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 phase
unwrapping
Inputs:
img - stack of images
ax - 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 phase
unwrapping
Inputs:
dX - horizontal phase gradient
dY - 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 either
complex image or unwrapped phase
Inputs
img - stack of complex valued input images
ax - axis of derivative, default = 2
step - 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 either
complex image or unwrapped phase
Inputs
img - stack of complex valued input images
step - 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 Toolbox
Author: Michal Odstrcil, 2016
License: Open Source under GPLv3
———————————————————————–
Description: faster version of matlab fftshift to work for stack of
2D images
Inputs: 2D or stack of 2D images
Outputs:
x - 2D or stack of 2D images after fftshift along first 2 dimensions
idx - precalculated indices for fftshift operation
Returns:x, idx
math.isint(x, prec)
true if all values or X is integers, but class can be arbitrary
numerical array
Returns:val
math.legendrepoly1D_2(X, maxorder, w)
Generates a 1D orthonormal polynomial base
polys = legendrepoly1D_2(X,maxorder,w);
The weighting function has not been tested extensively
Manuel 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 applying
two 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.5050
Algebraic 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*y
1.) Formulate equation for sum of squared differences with
x=-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) ]^2
2.) Differentiate SSD towards each parameter
dSSD / da = …
dSSD / df = …
3.) Solve linear system to get [a..f]
4.) Differentiate F towards x and y and solve linear system for x & y
dF(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 too
The 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 array
quantile - number or vector from 0 to 1 denoting quantiles
reduce - use every n-th element for calculation
Outputs:
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 unwrapping
Inputs:
img either complex valued image or real valued phase gradient
axis axis along which the gradient is taken
empty_region - 2x1 or 1x1 vector, size of empty region assumed
around 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 unwrapping
Inputs:
img either complex valued image or real valued phase gradient
empty_region - 2x1 or 1x1 vector, size of empty region assumed
around edges for phase offset removal
step 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 banana
with spec. This is an example pf such scans:
dmesh idgap -0.05 0.05 50 sl1cv -0.4 0.4 8 0.2
50 steps (51 points) along the fast axis
8 steps (9 points) along the slow axis
Input parameters:
basepath: main path where you are working
scan: scan number of spec mesh scan
Nx: number of points in fast axis
Ny: number of steps in slow axis
please reports bugs, problems, suggestions for improvements to:
CXS group
the case of duplicate scannumbers in the spec file, and how to
address them remains to be implemented
Returns:varargout
plotting.c2image(a, varargin)
FUNCTION IM = C2IMAGE(A)
the phase is mapped to hue, and the amplitude
is 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 map
This function returns the colormap and should
be used like any other colormaps, e.g.
colormap(franzmap(128));
or
imwrite(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. The
label 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 to
its prior hold state.
The HandleVisibility property of the line object is set to “off”, so not only does it not appear on
legends, but it is not findable by using findobj. Specifying an output argument causes the function to
overridden 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.
By Brandon Kuczenski for Kensington Labs.
8 November 2001
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 imagesc
imagesc3D supports the same parameters as Matlab’s imagesc. In addition, the following
parameters can be set
init_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 overhead
title_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 box
fnct… data processing function
order… change slice order in stack
save_movie… specify filename if a movie shall be written
movie_quality… image quality of the saved movie
Complex images will be converted to RGB using c2image.
If you are not using ‘autplay’, you can also set a global title instead
of a title list (similar to imagesc) and use ‘%d’ to get the slice number
title(‘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 by
calling 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 shown
colormap - name of standard matlab colormap, default = bone
clim - 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 loopscan
Syntax:
[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 they
occur
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 ptychography
reconstruction
Optional 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 help
please 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 figure
above all subplots (a “super title”). Use this function
after 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 margins
ha = 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 width
marg_h margins in height in normalized units (0…1)
or [lower upper] for different lower and upper margins
marg_w margins in width in normalized units (0…1)
or [left right] for different left and right margins
out: ha array of handles of the axes objects
starting from upper left corner, going row-wise as in
going row-wise as in
Example: ha = tight_subplot(3,2,[.01 .03],[.1 .01],[.01 .01])
for ii = 1:6; axes(ha(ii)); plot(randn(10,ii)); end
set(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. The
label 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 to
its prior hold state.
The HandleVisibility property of the line object is set to “off”, so not only does it not appear on
legends, but it is not findable by using findobj. Specifying an output argument causes the function to
overridden 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.
By Brandon Kuczenski for Kensington Labs.
8 November 2001
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 absolute
path
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 array
Inputs:
full_array - array to which the small_array will be added / written
small_array - array used to be added to large array
positions - [Nangles x 2] offset from (1,1) coordinate in pixels
for each slice
indices - add only to selected sliced of the full_array
add_values - add values instead of rewritting
Compilation 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 on
fast_axis_x = 1 for fast axis along x, 0 for fast axis along y
output = corrected data
output_pos = corrected output positions, could be used to see if
there was a problem with the correction
For 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 image
Optional parameters:
margins Two element array that indicates the (y,x) margins to exclude
from the edge of the mask window. For example to exclude the
noise around ptychography reconstructions, default 0.
smoothing Size of averaging window on the phase derivative, default
10.
gradientrange Size of the histogram windown when selecting valid gradient
regions, in radians per pixel, default 1;
show_bivariate Show the bivariate histogram of the gradient, useful
for debugging. Set to the number of figure you’d like
it to appear.
Morphological operations to remove point details in the mask
close_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 hosts
hosts (optional)… list of nodes; use ‘x12sa’ for all x12sa nodes
used_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 compatible
ver… compatible version number
EXAMPLE:
check_matlab_version(9.2)
MATLAB 9.0 - 2016a
MATLAB 9.1 - 2016b
MATLAB 9.2 - 2017a
MATLAB 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 a
given scan number
EXAMPLE:
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 cropping
img… input image
outsize… 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 code
gives the same precision as the FFT upsampled cross correlation in a
small fraction of the computation time and with reduced memory
requirements. It obtains an initial estimate of the crosscorrelation peak
by an FFT and then refines the shift estimation by upsampling the DFT
only in a small neighborhood of that estimate by means of a
matrix-multiply DFT. With this procedure all the image points are used to
compute the upsampled crosscorrelation.
Manuel Guizar - Dec 13, 2007
Rewrote all code not authored by either Manuel Guizar or Jim Fienup
Manuel Guizar - May 13, 2016
Citation for this algorithm:
Manuel Guizar-Sicairos, Samuel T. Thurman, and James R. Fienup,
“Efficient subpixel image registration algorithms,” Opt. Lett. 33,
156-158 (2008).
Inputs
buf1ft 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 to
within 1/usfac of a pixel. For example usfac = 20 means the
images will be registered within 1/20 of a pixel. (default = 1)
Outputs
output = [error,diffphase,net_row_shift,net_col_shift]
error Translation invariant normalized RMS error between f and g
diffphase Global phase difference between the two images (should be
zero if images are non-negative).
net_row_shift net_col_shift Pixel shifts between images
Greg (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 the
dose (2) saves the dose estimation into a .txt file.
Input:
ptycho_recon: reconstruction, including object, probe, and p
ptycho_data: data for the reconstruction
param_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 keV
param_dose.rho = 1000; % Density in kg/m^3
param_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 keV
param_dose.overhead = 0.0; % Extra dose during movement overhead, only applicable
% if shutter is not closed between exposures
param_dose.fmask
param_dose.scan_number
param_dose.num_proj
param_dose.output_folder (default: ./)
Output:
one jpg for one_data_frame
one jpg for photons_per_shot_all
one jpg for photons_per_obj_pix
one txt for dose_estimate
2017-03-30
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
utils.filt2d(outputdim, unmodsize, varargin)
FILT2D creates a 2d filter, based on fract_hanning
outputdim… 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 with
DC in upper left corner.
outputdim = size of the output array
unmodsize = Size of the central array containing no modulation.
Creates a square hanning window if unmodsize = 0 (or ommited), otherwise the output array
will contain an array of ones in the center and cosine modulation on the
edges, 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 with
DC in upper left corner.
outputdim = size of the output array
filterdim = size of filter (it will zero pad if filterdim<outputdim
unmodsize = Size of the central array containing no modulation.
Creates a square hanning window if unmodsize = 0 (or ommited), otherwise the output array
will contain an array of ones in the center and cosine modulation on the
edges, 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 path
optional input
path… search path; default ‘./’
file mask… limit results to a specific name or file
extension; default none
offset… take latest-offset; default 0
EXAMPLE:
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 to
package structure in <base_path>.
base_path… repository with new package structure
path… repository which needs to be updated
optional given as name/value pair
extension… file extension; default ‘.m’
recursive… recursive behavior; default false
show_files… show file names, otherwise progressbar; default false
filename… change output file name and path; default
./references.txt
Example:
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 residues
Manuel Guizar - Sept 27, 2011
R. M. Goldstein, H. A. Zebker and C. L. Werner, Radio Science 23, 713-720
(1988).
Inputs
phase Phase in radians
disp = 0, No feedback
= 1, Text feedback (additional computation)
= 2, Text and graphic display (additional computation)
Outputs
residues 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 p
Input:
scans
For SPEC variables
p.motor_name From SPEC
p.counter From SPEC
For sgalil position file
p.position_file Example ‘~/Data10/sgalil/S%05d.dat’
p.fast_axis_index (= 1 or 2) for x or y scan respectively
For mcs counter
p.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. = 3
Optional
p.motor_units
p.plot
p.title_str
p.coarse_motor
Output
out.fitout Parameters of quadratic fit
out.coarse_motor Coarse motor name is passed back
out.fwhm A vector with the fwhm for each scan
out.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 to
determine 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 also
compute the threshold function T. Images can be complex-valued.
Can handle non-cube arrays but assumes the voxel is isotropic
Inputs:
img1, img2 Compared images
param Structure containing parameters
Parameters:
dispfsc = 1; Display results
SNRt = 0.5 Power SNR for threshold, popular options:
SNRt = 0.5; 1 bit threshold for average
SNRt = 0.2071; 1/2 bit threshold for average
thickring Normally the pixels get assigned to the closest integer pixel ring in Fourier domain.
With thickring the thickness of the rings is increased by
thickring, so each ring gets more pixels and more statistics
auto_thickring do not calculate overlaps if thickring > 1 is used
st_title optional extra title in the plot
freq_thr =0.05 mimimal freq value above which the resolution is detected
show_fourier_corr show 2D Fourier correlation
mask bool array equal to false for ignored pixels of the fft space
Outputs:
resolution [min, max] resolution estimated from FSC curve
FSC FSC curve values
T Threshold values
freq spatial frequencies
stat stat - structure containing other statistics such as
SSNR, 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 with
DC in upper left corner.
outputdim = size of the output array
unmodsize = Size of the central array containing no modulation.
Creates a square hanning window if unmodsize = 0 (or ommited), otherwise the output array
will contain an array of ones in the center and cosine modulation on the
edges, 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 with
DC in upper left corner.
outputdim = size of the output array
filterdim = size of filter (it will zero pad if filterdim<outputdim
unmodsize = Size of the central array containing no modulation.
Creates a square hanning window if unmodsize = 0 (or ommited), otherwise the output array
will contain an array of ones in the center and cosine modulation on the
edges, 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 formula
energy… 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 plotting
att… (energy in keV, transmission)
req_density… density in g/cm^3
examples:
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 formula
energy… single value in keV or energy range in keV
thickness… thickness in micron
(optional) dens… density, negative number for default values
(optional) npts… number of points
(optional) plot… set to 1 for plotting
trans… (energy in keV, transmission)
req_density… density in g/cm^3
examples:
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 array
Inputs:
full_array - array from which the small_array will loaded
small_array - empty array for storing the data
positions - [Nangles x 2] offset from (1,1) coordinate in pixels
for each slice
indices - add only to selected sliced of the full_array
Compilation 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 formula
energy… single value in keV or energy range in keV
thickness… 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 plotting
trans… (energy in keV, transmission)
req_press… pressure
examples:
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 px
Example:
[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 formula
energy… 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 index
ref… (energy in keV, delta, beta)
req_density… density in g/cm^3
examples:
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 format
2. Binary mask (optional)
Outputs: 1. Unwrapped phase image
2. Phase quality map
This 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 of
residues and introduction of branchcuts.
R. M. Goldstein, H. A. Zebker and C. L. Werner, Radio Science 23, 713-720
(1988).
Inputs
fase Phase in radians, wrapped between (-pi,pi)
disp (optional) = 1 to show progress (will slow down code)
will also display the branch cuts
start (optional) [y,x] position to start unwrapping. Typically faster
at the center of the array
Outputs
faserecon Unwrapped phase ( = fase where phase could not be unwrapped)
shadow = 1 where phase could not be unwrapped
31 August, 2010 - Acknowledge if used
Returns:faserecon shadow
utils.identify_system()
Identify the current system to set useful default parameter values in
default_parameter_value.m.
A modified version of both macros at the beginning of the Matlab search
path 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 images
affine_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 dimensions
split = 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 alternative
split = 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 alternative
split = number of blocks for fft_split
Returns:A
utils.imrescale_fft(img, scale)
IMRESCALE_FFT subpixel precision rescaling based on mulitplication by a
matrix of fourier transformation
Inputs:
img - 2D or stack of 2D images
scale - scaling factor
Outputs: 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 transformation
subpixel precision image rescaling
Inputs:
img 2D or stack of 2D images
scale_x - horizontal scaling factor
scale_y - vertical scaling factor, if not provided scale_x is used
Outputs: 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 axis
based 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 axis
based 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 different
for 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 of
pixels and if needed crop / pad image to fit into Npix_new
Parameters:
img_0 - stack of images
x,y - horizontal / vertical shift in pixels (scalars)
Npix_new - empty/missing => keep original size, 2x1 vector => embed new image into given frame size
type - 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 for
each frame. If apply_fft == false, then images will be
assumed 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 only
If apply_fft == false, then images will be assumed to be in fourier space
Inputs:
img - inputs ndim array to be shifted along first 2 dimensions
shift - Nx1 vector of shifts, positive direction is up
apply_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. dirichlet
interpolation. Computes the FT and then adjusts the size by zero padding
or cropping then it computes the IFT. A real valued input may have
residual imaginary components, which is given by numerical precision of
the FT and IFT.
Inputs
im - Input complex array
outsize - Output size of array [ny nx]
Outputs
imout - Output complex image
2014.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. dirichlet
interpolation along single axis. Computes the FT and then adjusts the size by zero padding
or cropping then it computes the IFT. A real valued input may have
residual imaginary components, which is given by numerical precision of
the FT and IFT.
Inputs
im - Input complex array
outsize - Output size of array [N pixels]
ax - index of axis along which interpolation is done
Outputs
imout - Output complex image
Example:
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 GPU
Inputs:
img - 2D or stack of 2D images
scale - scaling factor
method - linear (default), cubic,
Outputs: 2D or stack of 2D images scaled by factor scale
Returns:img_out
utils.onCleanup(functionHandle, varargin)
ONCLEANUP - modified MATLAB class
EXAMPLES:
%% cleanup function with no arguments %%
1.) define cleanup routine:
function cleanexit()
fprintf(‘Reconstruction stopped!’)
end
2.) get instance of onCleanup:
finishup = utils.onCleanup(@() cleanexit());
%% cleanup function with one or more arguments
1.) define cleanup routine:
function cleanexit(p)
if ~p.getReport.completed
fprintf(‘Reconstruction stopped!’)
end
end
2.) get instance of onCleanup:
finishup = utils.onCleanup(p, @(x) cleanexit(x));
3.) if needed, update parameters that are passed to your cleanup
function:
finishup.update(p);
onCleanup - Specify cleanup work to be done on function completion.
C = onCleanup(S), when called in function F, specifies any cleanup tasks
that need to be performed when F completes. S is a handle to a function
that performs necessary cleanup work when F exits (e.g., closing files that
have been opened by F). S will be called whether F exits normally or
because of an error.
onCleanup is a MATLAB class and C = onCleanup(S) constructs an instance C of
that class. Whenever an object of this class is explicitly or implicitly
cleared from the workspace, it runs the cleanup function, S. Objects that
are local variables in a function are implicitly cleared at the termination
of 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) here
Example 2: Use onCleanup to restore the current directory.
function changeDirectorySafely(fileName)
currentDir = pwd;
c = onCleanup(@()cd(currentDir));
functionThatMayError;
end % c will execute cd(currentDir) here
See also: CLEAR, CLEARVARS
Reference page in Doc Center
doc utils.onCleanup
utils.param_protect_field(varargin)
PARAM_PROTECT_FIELD
param_protect_field(param)… check for protected field; returns
boolean
accepts struct or string as input
param_protect_field()… return protected fields
param_protect_field(param, ‘p’)… add param to protected fields
param_protect_field(param, ‘r’)… remove param from protected fields
Returns:varout
utils.peakfinder(x0, sel, thresh, extrema)
PEAKFINDER Noise tolerant fast peak finding algorithm
INPUTS:
x0 - A real vector from the maxima will be found (required)
sel - The amount above surrounding data for a peak to be
identified (default = (max(x0)-min(x0))/4). Larger values mean
the algorithm is more selective in finding peaks.
thresh - A threshold value which peaks must be larger than to be
maxima 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 x0
peakMag - The magnitude of the identified peaks
[peakLoc] = peakfinder(x0) returns the indicies of local maxima that
are at least 1/4 the range of the data above surrounding data.
[peakLoc] = peakfinder(x0,sel) returns the indicies of local maxima
that are at least sel above surrounding data.
[peakLoc] = peakfinder(x0,sel,thresh) returns the indicies of local
maxima 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 the
data if extrema > 0 and the minima of the data if extrema < 0
[peakLoc, peakMag] = peakfinder(x0,…) returns the indicies of the
local maxima as well as the magnitudes of those maxima
If called with no output the identified maxima will be plotted along
with the input data.
Note: If repeated values are found the first is identified as the peak
Ex:
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 isotropic
Inputs:
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 by
thickring, so each ring gets more pixels and more statistics
auto_binning apply binning if dimensions are significanlty different along each axis
mask bool array equal to false for ignored pixels of the fft space
Outputs:
PSD PSD curve values
freq normalized spatial frequencies to 1
Example 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 bar
progressbar(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 focus
prop2focus uses ‘phase detection autofocus’ to find the focus
img… complex-valued object
lam… wavelength
dx… pixel size
optional parameters
d_start… initial guess of propagation distance to focus
fov… crop to fov and apodize edges
Returns:d, img_prop
utils.prop_free_ff(win, lambda, z, pixsize)
PROP_FREE_FF Far field propagation
PROP_FREE_FF(WIN, LAMBDA, Z, PIXSIZE) returns the propagated wavefield
WIN by a distance Z, using wavelength LAMBDA. PIXSIZE is the dimension
of 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 becomes
Z*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 propagation
wout = prop_free_nf(win, lambda, z, pixsize) returns the propagated wavefield
WIN by a distance Z, using wavelength LAMBDA. PIXSIZE is the dimension
of 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 only
computes 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 is
necessary
[subim1, subim2, delta, deltafine,regionsout] = registersubimages_2(img1, img2, x1, y1, x2, y2, upsamp, displ,Wfilt);
Inputs
img1 - Reference image
x1, y1 - Vectors indicating the region of interest of img1, e.g. x1 =
[30:100]. If left empty the code starts with full window and
then reduces to the common part
img2, x2, y2 - Same as 1 but for the image to align
upsamp - Fraction of a pixel for the fine search, default = 1
displ = 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)
Outputs
subim1, subim2 - Common subimages taken from img1 and img2, subim2 is realigned subpixel
delta - Registration values (dy,dx)
deltafine - Only the subpixel components of the alignment
regionsout - Structure with final regions for registration
Please cite and acknowledge if you use it. Algorithm extended from that in
M. Guizar-Sicairos, S. T. Thurman and J. R. Fienup, “Efficient subpixel
image registration algorithms,” Opt. Lett. 33, 156 (2008).
Report bugs to mguizar@gmail.com
This code is intended for finding the same object in two different
images. It is a local search, so the code will go with the first solution
it finds, an approximately good initial estimate is required.
This code uses integer pixel and subpixel cross-correlation to find the
local solution. The intended purpose is for this code to be able to find
two similar subimages in the same image so the global search would be
inadequate. This code does not remove the global phase between the
subimages.
Keep your eyes open, this code has not been throughly debugged or tested
History
Allow for iterative refinement of chosen subwindow
Allow for empty input for subwindow regions
Manuel Guizar - January 22, 2013
Modified on 24 Aug 2010 to return deltafine and receive a Fourier filter
Also modified to have initial estimate with upsamp 2 and then round and
so that the final registration is done with an upsam accuracy
Modified on 25 Aug 2010. If coarse alignment exceeds image dimensions
assume 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 removing
the linear and the constant phase offset. Different options are given for
defining a reference area on the sample
im_input Input complex valued image
The optional <name>,<value> pairs are:
‘mask’, maskarray Binary array with ones where the linear phase should be
removed. Alternatively the mask can be an array of
non unitary weights for the computation of average
phase ramp and average phase. For example, the
magnitude can be use to weight
June 21,2016
Returns:im_output, ph_err
utils.remove_linearphase(testim, mask, upsamp)
Removes linear phase from object considering only pixels where mask is
unity, arrays have center on center of array
testim Image
mask Binary array with ones where the linear phase should be
computed from
upsamp Linear phase will be removed within 2*pi/upsamp peak to valley
in radians
errorm Optional ouput with NRMS
August 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 is
unity, arrays have center on center of array
testim Image
mask Binary array with ones where the linear phase should be
computed from
upsamp Linear phase will be removed within 2*pi/upsamp peak to valley
in radians
errorm Optional ouput with all outputs from dftregistration
August 19 2010
Updated 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 sinogram
using linear interpolation between air on both sides
Inputs:
sinogram - unwrapped projections
air_gap = [2x1] vector with number of pixels on both sides where can
be assumed to be air
polyfit_order - -1 = dont assume anything about the removed phase
0 = assume that it is constant offset
1 = 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 files
Matlab’s ‘save’ command can be very slow when saving large arrays,
because by default Matlab attempts to use compression. This function
provides 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; toc
Elapsed time is 22.980294 seconds.
>> tic; savefast /tmp/test ops A B; toc
Elapsed time is 0.571098 seconds.
utils.sbb(varargin)
SBB returns station board for PSI West
syntax:
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 FFT
Modified from shiftpp.m to correct a phase factor that appeared when using
odd 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_fft
Inputs:
img - 2D / 3D array, smoothing is done along first two dimensions
win_size - size of the smoothing region, default is 3
dims - 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 and
remove linear ramp
Inputs:
img - complex image to stabilize
img_ref - complex images used as reference, if empty ones is used
Varargins:
weights - 0<x<1 numeric array denoting reliable unwrapping region
split - split FFTon smaller blocks on GPU
fourier_guess - (bool), use maximum in Fourier space to get initial
guess of the phase ramp
remove_ramp - (bool), if false, remove only phase offset (scalar)
smoothing - smooth image before removing ramp, makes it more robust
Outputs:
img - phase ramp / offset subtracted complex-valued image
gamma,gamma_x, gamma_y - (1,1,N arrays) offset, ramp horizontal / vertical
c_offset - either constant or phase ramp offset subtracted from the
complex 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 cell
EXAMPLE:
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 them
force_update = 1 … overwrite fields but leave protected
fields unchanged (default)
force_update = 2 … overwrite everything
p = update_param(p, ‘windowautopos’, 1, ‘force_update’, 0);
Returns:p
utils.verbose(varargin)
Function verbose(level, message)
verbose : shows current verbose level
verbose(n): set the level to n
verbose(n, message): displays the message if n <= current verbose level
verbose(n, message, v1, v2, …) behaves like sprintf(message, v1, v2, …)
Suggested levels:
1: important information
2: general information
3: debugging
Returns:varargout

+utils/private

trash

trash/create_mask_GUI(varargin)
CREATE_MASK_GUI MATLAB code for create_mask_GUI.fig
CREATE_MASK_GUI, by itself, creates a new CREATE_MASK_GUI or raises the existing
singleton*.
H = CREATE_MASK_GUI returns the handle to a new CREATE_MASK_GUI or the handle to
the existing singleton*.
CREATE_MASK_GUI(‘CALLBACK’,hObject,eventData,handles,…) calls the local
function 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 the
existing singleton*. Starting from the left, property value pairs are
applied to the GUI before create_mask_GUI_OpeningFcn gets called. An
unrecognized property name or invalid value makes property application
stop. All inputs are passed to create_mask_GUI_OpeningFcn via varargin.
*See GUI Options on GUIDE’s Tools menu. Choose “GUI allows only one
instance 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.fig
CREATE_MASK_GUI_EXPORT, by itself, creates a new CREATE_MASK_GUI_EXPORT or raises the existing
singleton*.
H = CREATE_MASK_GUI_EXPORT returns the handle to a new CREATE_MASK_GUI_EXPORT or the handle to
the existing singleton*.
CREATE_MASK_GUI_EXPORT(‘CALLBACK’,hObject,eventData,handles,…) calls the local
function 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 the
existing singleton*. Starting from the left, property value pairs are
applied to the GUI before create_mask_GUI_export_OpeningFcn gets called. An
unrecognized property name or invalid value makes property application
stop. All inputs are passed to create_mask_GUI_export_OpeningFcn via varargin.
*See GUI Options on GUIDE’s Tools menu. Choose “GUI allows only one
instance to run (singleton)”.
See also: GUIDE, GUIDATA, GUIHANDLES