initial commit

This commit is contained in:
2026-08-07 15:56:42 +09:00
commit 91ad25aca9
1012 changed files with 159314 additions and 0 deletions
@@ -0,0 +1,49 @@
%COMPILE_SWING_DIRNAME returns the default SWING directory tree for a
% given scan number
%
% EXAMPLE:
% scan_dir = compile_SWING_dirname(10);
% -> scan_dir = 'S00000-00999/'
%
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function scan_dir = compile_swing_dirname(scan_no)
scan_dir = sprintf('S%05d-%05d/',floor(scan_no/1000)*1000, ...
floor(scan_no/1000)*1000 + 999);
end
@@ -0,0 +1,93 @@
%GET_FILENAMES_SWING compile filenames of raw data files
% receives
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for maximum likelihood:
% P. Thibault and M. Guizar-Sicairos, Maximum-likelihood refinement for coherent diffractive imaging, New J. Phys. 14, 063004 (2012).
% (doi: 10.1088/1367-2630/14/6/063004),
% for mixed coherent modes:
% P. Thibault and A. Menzel, Reconstructing state mixtures from diffraction measurements, Nature 494, 6871 (2013). (doi: 10.1038/nature11806),
% and/or for multislice:
% E. H. R. Tsai, I. Usov, A. Diaz, A. Menzel, and M. Guizar-Sicairos, X-ray ptychography with extended depth of field, Opt. Express 24, 2908929108 (2016).
% (doi: 10.1364/OE.24.029089).
% 6. Except for the above-mentioned acknowledgment, LICENSEE shall not use the PROGRAM title or the names or logos of LICENSOR, nor any adaptation thereof, nor the
% names of any of its employees or laboratories, in any advertising, promotional or sales material without prior written consent obtained from LICENSOR in each case.
% 7. Ownership of all rights, including copyright in the PROGRAM and in any material associated therewith, shall at all times remain with LICENSOR, and LICENSEE
% agrees to preserve same. LICENSEE agrees not to use any portion of the PROGRAM or of any IMPROVEMENTS in any machine-readable form outside the PROGRAM, nor to
% make any copies except for its internal use, without prior written consent of LICENSOR. LICENSEE agrees to place the following copyright notice on any such copies:
% © All rights reserved. PAUL SCHERRER INSTITUT, Switzerland, Laboratory for Macromolecules and Bioimaging, 2017.
% 8. The LICENSE shall not be construed to confer any rights upon LICENSEE by implication or otherwise except as specifically set forth herein.
% 9. DISCLAIMER: LICENSEE shall be aware that Phase Focus Limited of Sheffield, UK has an international portfolio of patents and pending applications which relate
% to ptychography and that the PROGRAM may be capable of being used in circumstances which may fall within the claims of one or more of the Phase Focus patents,
% in particular of patent with international application number PCT/GB2005/001464. The LICENSOR explicitly declares not to indemnify the users of the software
% in case Phase Focus or any other third party will open a legal action against the LICENSEE due to the use of the program.
% 10. This Agreement shall be governed by the material laws of Switzerland and any dispute arising out of this Agreement or use of the PROGRAM shall be brought before
% the courts of Zürich, Switzerland.
function [p] = get_filenames_swing(p)
import utils.*
% get detector paramters
det = p.detectors(p.scanID).params;
read_path = p.raw_data_path_full{p.scanID};
detStorage = p.detectors(p.scanID).detStorage;
% if no filename pattern was specified, just load everything containing the specified file extension
[datadir, files] = find_files(fullfile(read_path, sprintf([p.detector.data_prefix '%05d_*.' det.file_extension], p.scan_number(p.scanID))));
if numel(files)==0
error('Could not find any files using the filename pattern %s.\n ', fullfile(read_path, sprintf([p.detector.data_prefix '%05d_*.' det.file_extension], p.scan_number(p.scanID))))
end
% for now, we assume to have only 1 file per scan (number)
%for ii=1:length(files)
% detStorage.files{ii} = fullfile(datadir, files(ii).name);
%end
detStorage.files = [];
detStorage.files{1} = fullfile(datadir, files(1).name);
% find data entry
h = h5info(files(1).name);
gName = h.Groups.Name;
detStorage.h5_group{1} = [gName '/scan_data/' det.nexus_entry];
end
+114
View File
@@ -0,0 +1,114 @@
%FP_FSC_PREPROCESS
% [recon] = FP_FSC_preprocess(recon)
%
% adjust the loaded Fourier Ptycho data for FSC calculations
%
% ** recon cell array of reconstructions
%
% returns:
% ++ recon cell array of reconstructions
%
% see also: aligned_FSC
%
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for maximum likelihood:
% P. Thibault and M. Guizar-Sicairos, Maximum-likelihood refinement for coherent diffractive imaging, New J. Phys. 14, 063004 (2012).
% (doi: 10.1088/1367-2630/14/6/063004),
% for mixed coherent modes:
% P. Thibault and A. Menzel, Reconstructing state mixtures from diffraction measurements, Nature 494, 6871 (2013). (doi: 10.1038/nature11806),
% and/or for multislice:
% E. H. R. Tsai, I. Usov, A. Diaz, A. Menzel, and M. Guizar-Sicairos, X-ray ptychography with extended depth of field, Opt. Express 24, 2908929108 (2016).
% (doi: 10.1364/OE.24.029089).
% 6. Except for the above-mentioned acknowledgment, LICENSEE shall not use the PROGRAM title or the names or logos of LICENSOR, nor any adaptation thereof, nor the
% names of any of its employees or laboratories, in any advertising, promotional or sales material without prior written consent obtained from LICENSOR in each case.
% 7. Ownership of all rights, including copyright in the PROGRAM and in any material associated therewith, shall at all times remain with LICENSOR, and LICENSEE
% agrees to preserve same. LICENSEE agrees not to use any portion of the PROGRAM or of any IMPROVEMENTS in any machine-readable form outside the PROGRAM, nor to
% make any copies except for its internal use, without prior written consent of LICENSOR. LICENSEE agrees to place the following copyright notice on any such copies:
% © All rights reserved. PAUL SCHERRER INSTITUT, Switzerland, Laboratory for Macromolecules and Bioimaging, 2017.
% 8. The LICENSE shall not be construed to confer any rights upon LICENSEE by implication or otherwise except as specifically set forth herein.
% 9. DISCLAIMER: LICENSEE shall be aware that Phase Focus Limited of Sheffield, UK has an international portfolio of patents and pending applications which relate
% to ptychography and that the PROGRAM may be capable of being used in circumstances which may fall within the claims of one or more of the Phase Focus patents,
% in particular of patent with international application number PCT/GB2005/001464. The LICENSOR explicitly declares not to indemnify the users of the software
% in case Phase Focus or any other third party will open a legal action against the LICENSEE due to the use of the program.
% 10. This Agreement shall be governed by the material laws of Switzerland and any dispute arising out of this Agreement or use of the PROGRAM shall be brought before
% the courts of Zürich, Switzerland.
function [recon] = FP_FSC_preprocess(recon, recon_fn, param)
import utils.*
% import parameters
p.object{1} = recon.object;
p.plot.FP_maskdim = io.HDF.hdf5_load(recon_fn, '/reconstruction/p/plot/FP_maskdim');
p.dx_spec = io.HDF.hdf5_load(recon_fn, '/reconstruction/p/dx_spec');
p.object_size = double(io.HDF.hdf5_load(recon_fn, '/reconstruction/p/object_size'));
p.numobjs = io.HDF.hdf5_load(recon_fn, '/reconstruction/p/numobjs');
p.z_lens = io.HDF.hdf5_load(recon_fn, '/reconstruction/p/z_lens');
p.lambda = io.HDF.hdf5_load(recon_fn, '/reconstruction/p/lambda');
if ~isempty(param.crop_asize)
p.object{1} = crop_pad(p.object{1}, param.crop_asize);
p.object_size = [];
p.object_size = size(p.object{1});
end
if param.filter_FFT
% calculate mask
ob_mask{1} = abs(ifftshift(filt2d_pad(p.object_size, round(p.plot.FP_maskdim/p.dx_spec(1)), round(p.plot.FP_maskdim/p.dx_spec(1)-5), 'circ')));
else
ob_mask{1} = ones(p.object_size);
end
if isempty(param.z_lens)
param.z_lens = p.z_lens;
end
% calculate phase factor for backpropagation
k = 2*pi/p.lambda;
objpix = p.lambda*p.z_lens/(p.object_size(1)*p.dx_spec(1));
[Xp,Yp] = get_grid(p.object_size(1,:), objpix);
pre_phase_factor = exp(1i*k*((Xp).^2+(Yp).^2)/(2*param.z_lens));
% propagate back to sample plane
obnum = 1; % fix for multiple scans
ob = (ifft2(ifftshift(p.object{obnum}(:,:,1).*ob_mask{obnum})))*p.object_size(1).*ifftshift((pre_phase_factor));
ob = utils.crop_pad(ob, round(p.object_size.*param.crop_factor));
p.objpix = objpix;
recon.object = conj(ob);
recon.p = p;
end
+606
View File
@@ -0,0 +1,606 @@
% [resolution stat] = aligned_FSC(file1,file2,param)
%
% Receives two filenames with path for ptychography reconstructions and a
% structure with parameters. The routine reads the reconstructions, matches
% the linear phase between them, registers the images, and returns the
% resolution estimates based on first and last crossing of the FSC with the
% threshold.
%
% Modified by YJ for electron ptychography
%
% References relevant to this code:
% For using this FSC code with ptychography: J. Vila-Comamala, et al., "Characterization of high-resolution diffractive X-ray optics by ptychographic coherent diffractive imaging," Opt. Express 19, 21333-21344 (2011).
% For subpixel alignment: M. Guizar-Sicairos, et al., "Efficient subpixel image registration algorithms," Opt. Lett. 33, 156 (2008).
% For matching of phase ramp by approximate least squared error: M. Guizar-Sicairos, et al., "Phase tomography from x-ray coherent diffractive imaging projections," Opt. Express 19, 21345-21357 (2011).
%
% Outputs:
%
% resolution A two element variable that contains the resolution
% obtained from first and last crossing of the FSC curve with
% the threshold curve.
% stat structure containing other statistics such as
% spectral signal to noise ratio (SSNR), average SNR and area under FSC curve
%
% Inputs:
%
% file1 Filename with path of reconstruction 1 or directly a 2D numerical array
% file2 Filename with path of reconstruction 2 or directly a 2D numerical array
% param Structure with parameters as describred below
%
% param.flipped_images Flip one input image horizontally (= true or false).
% Useful when comparing 0 and 180 degree projections
% in tomography (default = false).
% param.crop = ''; for using the default half size of the probe
% = 'manual' for using GUI to select region. This will display the range, e.g. {600:800, 600:800}
% = {600:800, 600:800} for custom vertical and horizontal cropping, respectively
% param.GUIguess To click for an initial alignment guess, if used it ignores
% the values of param.guessx and param.guessy (default
% = false)
% param.guessx
% param.guessy An intial guess for x and y alignment (default = [])
% param.remove_ramp Try to remove linear phase from whole image before initial
% alignment (default = true)
% param.image_prop = 'complex'
% = 'phasor' (phase with unit amplitude, default)
% = 'phase' (Note: phase should not be used if there is phase wrapping)
% param.taper = 20 (default) Pixels to taper images - Increase until the FSC does not change anymore
% param.plotting Display plots (default = false)
% param.dispfsc Display FSC plot (default = true)
% param.SNRt SNR for FSC threshold curve
% SNRt = 0.2071 for 1/2 bit threshold for resolution of the average of the 2 images
% SNRt = 0.5 for 1 bit threshold for resolution of each individual image (default)
% param.thickring Thickness of Fourier domain ring for FSC in pixels (default = 1)
% param.freq_thr To ignore the crossings before freq_thr for determining resolution (default 0.02)
% param.out_fn Filename of output of jpeg for FSC
% param.pixel_size Pixel size in the reconstruction, it is used only
% if file1 / file2 are not paths to the reconsturcted files
function [resolution,stat] = aligned_FSC(file1,file2,param)
import utils.*
import math.*
import io.*
import plotting.*
file{1} = file1;
file{2} = file2;
for ii = 1:2
if ischar(file{ii})
[~,file_path{ii},~] = fileparts(file{ii});
else
file_path{ii} = sprintf('image_id_%i', ii);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Checks and defaults %%%
if isfield(param,'flag_imread')
flag_imread = param.flag_imread;
else
if ~(ischar(file1) && ischar(file2)) || (~isempty(regexpi(file1,'\.mat|\.h5')) && ~isempty(regexpi(file2,'\.mat|\.h5')))
flag_imread = false;
else
flag_imread = true;
warning('Files not in .mat: using ''imread'' for loading; image in real number (ignoring remove_ramp and image_prop)')
end
end
% parse inputs
check_input = @(x) islogical(x) || isnumeric(x);
check_crop = @(x) isempty(x) || ischar(x) || iscell(x);
check_image_prop = @(x) assert(any(contains({'complex', 'phasor', 'phase', 'variation'}, x)), ...
'image_prop must be either "complex", "phasor", "phase" or "variation".');
parse_param = inputParser;
parse_param.KeepUnmatched = true;
parse_param.addParameter('flipped_images', false, check_input)
parse_param.addParameter('crop', '', check_crop)
parse_param.addParameter('GUIguess', false, check_input)
parse_param.addParameter('guessx', [], check_input)
parse_param.addParameter('guessy', [], check_input)
parse_param.addParameter('plotting',false, check_input)
parse_param.addParameter('remove_ramp', false, check_input)
parse_param.addParameter('image_prop', 'phasor', check_image_prop)
parse_param.addParameter('SNRt', 0.5, @isnumeric)
parse_param.addParameter('thickring', 1, @isnumeric)
parse_param.addParameter('freq_thr', 0.02, @isnumeric)
parse_param.addParameter('prop_obj', [], check_input)
parse_param.addParameter('apod', [], check_input)
parse_param.addParameter('filter_FFT', [], check_input)
parse_param.addParameter('crop_factor', 1, @isnumeric)
parse_param.addParameter('crop_asize', [], @isnumeric)
parse_param.addParameter('z_lens', [], @isnumeric)
parse_param.addParameter('fourier_ptycho', false, check_input)
parse_param.addParameter('lambda', [], @isnumeric)
parse_param.addParameter('pixel_size', [], @isnumeric)
parse_param.addParameter('electron', false, check_input) %added by YJ for electron ptychography
parse_param.addParameter('verbose_level', 3, @isnumeric)
parse_param.addParameter('fname', [], @iscell)
parse_param.addParameter('show_summary', true, check_input)
parse_param.addParameter('xlabel_type', 'nyquist', @(x)ismember(lower(x), {'nyquist', 'resolution'})) % select X axis units
parse_param.parse(param)
param = parse_param.Results;
if isempty(param.crop)
utils.verbose(3,'Cropping half size of the probe (default)')
end
if isfield(param,'taper')
taper = param.taper;
else
taper = 20;
utils.verbose(3,'Using taper = 20 (default)')
end
if isempty(param.fname)
param.fname = file_path;
end
utils.verbose(param.verbose_level);
utils.verbose(struct('prefix', {'FSC'}))
% set dispfsc value - used in utils.fourier_shell_corr_3D_2
param.dispfsc = (param.plotting > 0);
%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ischar(file{1})
if ~flag_imread
%%% Checking if file exist and loading %%%
if exist(file{1},'file')
param.fourier_ptycho = io.HDF.hdf5_load(file{1}, '/reconstruction/p/fourier_ptycho');
utils.verbose(2, ['Loading: ' file{1}])
recons{1} = load_ptycho_recons(file{1}, 'object');
if param.fourier_ptycho
recons{1} = FP_FSC_preprocess(recons{1}, file{1}, param);
end
else
error(['Not found: ' file{1}])
end
if exist(file{2},'file')
utils.verbose(2, ['Loading: ' file{2}])
recons{2} = load_ptycho_recons(file{2}, 'object');
if param.fourier_ptycho
recons{2} = FP_FSC_preprocess(recons{2}, file{2}, param);
end
else
error(['Not found: ' file{2}])
end
img1 = recons{1}.object;
img2 = recons{2}.object;
% load additional parameters
asize = double(io.HDF.hdf5_load(file{1}, '/reconstruction/p/asize'));
if ~param.fourier_ptycho
param.pixel_size = io.HDF.hdf5_load(file{1}, '/reconstruction/p/dx_spec');
else
param.pixel_size = recons{1}.p.objpix;
end
try
if isempty(param.lambda) && io.HDF.hdf5_dset_exists(file{1}, 'lambda', '/reconstruction/p', true)
param.lambda = io.HDF.hdf5_load(file{1}, '/reconstruction/p/lambda');
end
end
else
if ~isnumeric(file{1})
img1 = imread(file{1});
else
img1 = file{1}; %input provides directly the numeric array
end
if ~isnumeric(file{2})
img2 = imread(file{2});
else
img2 = file{2}; %input provides directly the numeric array
end
asize = [1 1];
if isempty(param.pixel_size)
param.pixel_size = 1e-6;
warning('Using pixel size 1um')
end
end
else
img1 = file{1}; %input provides directly the numeric array
img2 = file{2}; %input provides directly the numeric array
if ~isfield(param, 'asize')
asize = [1 1];
else
asize = param.asize;
end
if isempty(param.pixel_size)
param.pixel_size = 1e-6;
warning('Using pixel size 1um')
end
end
if param.flipped_images
img2 = fliplr(img2);
end
% apply apodization
% check if apodization was used in the reconstruction
if isempty(param.apod)
try
param.apod = io.HDF.hdf5_load(file{1}, '/reconstruction/p/plot/obj_apod');
catch
warning('Unable to load apodization parameter from reconstruction file.')
param.apod = false;
end
end
if param.apod
img1 = apply_apod(img1, asize);
img2 = apply_apod(img2, asize);
end
% propagate if needed
if isempty(param.prop_obj) || param.prop_obj
if isempty(param.lambda)
try
param.lambda = io.HDF.hdf5_load(file{1}, '/reconstruction/p/lambda');
catch
try
param.energy = io.HDF.hdf5_load(file{1}, '/reconstruction/p/energy');
param.lambda = 12.4/param.energy*1e-10;
catch
error('Please specify your wavelength (param.lambda).')
end
end
end
if isempty(param.prop_obj) || islogical(param.prop_obj) && param.prop_obj
% get values from file
try
param.prop_obj = io.HDF.hdf5_load(file{1}, '/reconstruction/p/prop_obj');
catch
error('Please specify the propagation distance or set it to "false" (param.prop_obj).')
end
end
img1 = utils.prop_free_nf(img1, param.lambda, param.prop_obj, param.pixel_size);
img2 = utils.prop_free_nf(img2, param.lambda, param.prop_obj, param.pixel_size);
end
screensize = get( 0, 'Screensize' );
% Show phase images (not cropped)%
if param.plotting > 1
plotting.smart_figure(21)
set(gcf,'Outerposition',[1 screensize(4)-550 500 500]) %[left, bottom, width, height
if ~isreal(img1)
imagesc(angle(img1), math.sp_quantile(angle(img1),[1e-2, 1-1e-2],10));
if ~param.fourier_ptycho
rectangle('Position',[asize([2,1])/2, [size(img1,2),size(img1,1)]-asize([2,1])], 'EdgeColor', 'red')
end
else
imagesc(img1, math.sp_quantile((img1),[1e-2, 1-1e-2],10));
end
axis xy equal tight
colormap bone
colorbar
if param.prop_obj
[si_unit, val] = utils.get_unit_length(param.prop_obj);
title(sprintf([param.fname{1} '\npropagated by %d %s'], val, si_unit),'interpreter','none')
else
title(param.fname{1},'interpreter','none')
end
plotting.smart_figure(22)
if ~isreal(img1)
imagesc(angle(img2), math.sp_quantile(angle(img2),[1e-2, 1-1e-2],10));
else
imagesc(img2, math.sp_quantile(img2,[1e-2, 1-1e-2],10));
end
if ~param.fourier_ptycho
rectangle('Position',[asize([2,1])/2, [size(img2,2),size(img2,1)]-asize([2,1])], 'EdgeColor', 'red')
end
axis xy equal tight
colormap bone
colorbar
if param.prop_obj
[si_unit, val] = utils.get_unit_length(param.prop_obj);
title(sprintf([param.fname{2} '\npropagated by %d %s'], val, si_unit),'interpreter','none')
else
title(param.fname{2},'interpreter','none')
end
set(gcf,'Outerposition',[500 screensize(4)-550 500 500]) %[left, bottom, width, height
end
% Crop images - default is half the size of the probe on each side plus
% whatever needed to make them of equal size
if isempty(param.crop)
minsize = min(size(img1),size(img2))-asize;
img1 = crop_pad(img1,minsize );
img2 = crop_pad(img2,minsize );
elseif strcmpi(param.crop, 'manual')
figure()
imagesc(angle(img1), math.sp_quantile(angle(img1),[1e-2, 1-1e-2],10));
if ~param.fourier_ptycho
rectangle('Position',[asize([2,1])/2, [size(img1,2),size(img1,1)]-asize([2,1])], 'EdgeColor', 'red')
end
colormap bone
axis image xy
title('Select compared region')
disp('Manually select the compared region ... ')
rect = round(getrect);
param.crop = {rect(2)+(1:rect(4)),rect(1)+(1:rect(3))};
disp('===========================')
fprintf('Selected region: {%i:%i,%i:%i}\n',rect(2), rect(2)+rect(4), rect(1), rect(1)+rect(3));
disp('===========================')
pause(1)
end
if ~isempty(param.crop)
img1 = img1(param.crop{:});
img2 = img2(param.crop{:});
end
if param.GUIguess
plotting.smart_figure(21)
disp(['Click on a feature on figure 2'])
[xin yin] = ginput(1);
plotting.smart_figure(22)
disp(['Click on a feature on figure 3'])
[xin2 yin2] = ginput(1);
param.guessx = round(xin-xin2);
param.guessy = round(yin-yin2);
end
if ~isempty(param.guessx)
switch sign(param.guessx)
case 1
img1 = img1(:,1+param.guessx:end);
img2 = img2(:,1:end-param.guessx);
case -1
img1 = img1(:,1:end+param.guessx);
img2 = img2(:,1-param.guessx:end);
end
end
if ~isempty(param.guessy)
switch sign(param.guessy)
case 1
img1 = img1(1+param.guessy:end,:);
img2 = img2(1:end-param.guessy,:);
case -1
img1 = img1(1:end+param.guessy,:);
img2 = img2(1-param.guessy:end,:);
end
end
% Remove ramp
if param.remove_ramp
utils.verbose(3,'Removing ramp for initial alignment')
img1 = utils.stabilize_phase(img1,'binning', 4);
img2 = utils.stabilize_phase(img2, img1, 'binning', 4);
end
if param.plotting >2
plotting.smart_figure(23)
set(gcf,'Outerposition',[1 1 500 476]) %[left, bottom, width, height
if ~isreal(img1)
imagesc(angle(img1));
else
imagesc(img1);
end
axis xy equal tight
colormap bone; colorbar
ax23 = gca;
title(param.fname{1},'interpreter','none')
plotting.smart_figure(24);
if ~isreal(img2)
imagesc(angle(img2));
else
imagesc(img2);
end
axis xy equal tight
colormap bone; colorbar
title(param.fname{2},'interpreter','none')
set(gcf,'Outerposition',[500 1 500 476]) %[left, bottom, width, height]
ax34 = gca;
linkaxes([ax23, ax34], 'xy')
end
% img1 = img1 - utils.imgaussfilt2_fft(img1, 20);
% img2 = img2 - utils.imgaussfilt2_fft(img2, 20);
% image_prop= 'complex';
%%% Initial alignment %%%
utils.verbose(2,'Initial alignment')
if ~flag_imread
switch lower(param.image_prop)
case 'complex'
imgalign1 = img1;
imgalign2 = img2;
utils.verbose(2,'Registering complex valued images')
case 'phasor'
imgalign1 = ones(size(img1)).*exp(1i*angle(img1));
imgalign2 = ones(size(img2)).*exp(1i*angle(img2));
utils.verbose(2,'Registering phasor of complex valued images')
case 'phase'
imgalign1 = angle(img1);
imgalign2 = angle(img2);
utils.verbose(2,'Registering phase of complex valued images')
case 'variation'
[dX,dY] = math.get_phase_gradient_2D(img1);
imgalign1 = sqrt(dX.^2+dY.^2);
[dX,dY] = math.get_phase_gradient_2D(img2);
imgalign2 = sqrt(dX.^2+dY.^2);
end
else
imgalign1 = img1;
imgalign2 = img2;
end
upsamp = 100;
displ = utils.verbose>3;
W = 1;
x1 = [];%[1:150];
x2 = x1;
y1 = [];%[1:238];
y2 = y1;
% imgalign2 = shiftpp2(imgalign2,10,-10); % To test range adjustment
[subim1, subim2, delta, deltafine, regionsout] = registersubimages_2(imgalign1,imgalign2, x1, y1, x2, y2, upsamp, displ,1);
%%% Fine alignment (second round) %%%
% Remove ramp for fine alignment
utils.verbose(2,'Removing ramp for fine alignment')
%%% A patch for deltafine large
if max(regionsout.y2+round(delta(1)))>size(img2,1)
warning('First subpixel registration refinement found large values')
regionsout.y2 = [min(regionsout.y2):size(img2,1)-round(delta(1))];
regionsout.y1 = regionsout.y2;
end
if max(regionsout.x2+round(delta(2)))>size(img2,2)
warning('First subpixel registration refinement found large values')
regionsout.x2 = [min(regionsout.x2):size(img2,2)-round(delta(2))];
regionsout.x1 = regionsout.x2;
end
%%%
subimg1 = img1(regionsout.y1,regionsout.x1);
subimg2 = img2(regionsout.y2+round(delta(1)),regionsout.x2+round(delta(2)));
if ~flag_imread
subimg1 = remove_linearphase_v2(subimg1,ones(size(subimg1)),100);
subimg2 = remove_linearphase_v2(subimg2,ones(size(subimg2)),100);
end
% Remove ramp
if param.remove_ramp
utils.verbose(2,'Removing ramp for initial alignment')
subimg1 = utils.stabilize_phase(subimg1,'binning', 4);
subimg2 = utils.stabilize_phase(subimg2, subimg1, 'binning', 4);
end
if ~flag_imread
switch lower(param.image_prop)
case 'complex'
subimgalign1 = subimg1;
subimgalign2 = subimg2;
utils.verbose(2,'Registering complex valued images')
case 'phasor'
subimgalign1 = ones(size(subimg1)).*exp(1i*angle(subimg1));
subimgalign2 = ones(size(subimg1)).*exp(1i*angle(subimg2));
utils.verbose(2,'Registering phasor of complex valued images')
case 'phase'
subimgalign1 = angle(subimg1);
subimgalign2 = angle(subimg2);
utils.verbose(2,'Registering phase of complex valued images')
case 'variation'
[dX,dY] = math.get_phase_gradient_2D(subimg1);
subimgalign1 = sqrt(dX.^2+dY.^2);
[dX,dY] = math.get_phase_gradient_2D(subimg2);
subimgalign2 = sqrt(dX.^2+dY.^2);
end
else
subimgalign1 = subimg1;
subimgalign2 = subimg2;
end
% Fine alignment %
utils.verbose(2,'Fine alignment')
[subim1, subim2, delta, deltafine, regionsout] = registersubimages_2(subimgalign1,subimgalign2, x1, y1, x2, y2, upsamp, displ,1);
%%% propare images for FSC if variation was used for alignement
if strcmpi(param.image_prop, 'variation')
subim1 = subimg1(regionsout.y1, regionsout.x1);
subim2 = subimg2(regionsout.y2, regionsout.x2);
subim2 = shiftpp2(subim2,-deltafine(1), -deltafine(2)); %% Suboptimal, change to use a routine that receives FT data
% convert images to phasor
subim1 = exp(1i*angle(subim1));
subim2 = exp(1i*angle(subim2));
end
%%% Tapering %%%
filterx = fract_hanning_pad(size(subim1,2),size(subim1,2),size(subim1,2)-2*taper);
filterx = fftshift(filterx(1,:));
filtery = fract_hanning_pad(size(subim1,1),size(subim1,1),size(subim1,1)-2*taper);
filtery = fftshift(filtery(:,1));
filterxy = filterx.*filtery;
% Taper subimages %
subim1 = subim1.*filterxy;% + (1-filterxy).*mean(subim1(:));
subim2 = subim2.*filterxy;% + (1-filterxy).*mean(subim2(:));
if param.plotting > 1
plotting.smart_figure(23)
set(gcf,'Outerposition',[1 1 500 476]) %[left, bottom, width, height
if strcmpi(param.image_prop,'phase') || flag_imread
imagesc(subim1);
else
imagesc(angle(subim1));
end
axis xy equal tight
colormap bone; colorbar
if param.prop_obj
[si_unit, val] = utils.get_unit_length(param.prop_obj);
title(sprintf([param.fname{1} '\npropagated by %d %s'], val, si_unit),'interpreter','none')
else
title(param.fname{1},'interpreter','none')
end
plotting.smart_figure(24)
if strcmpi(param.image_prop,'phase') || flag_imread
imagesc(real(subim2));
else
imagesc(angle(subim2));
end
axis xy equal tight
colormap bone; colorbar
if param.prop_obj
[si_unit, val] = utils.get_unit_length(param.prop_obj);
title(sprintf([param.fname{2} '\npropagated by %d %s'], val, si_unit),'interpreter','none')
else
title(param.fname{2},'interpreter','none')
end
set(gcf,'Outerposition',[500 1 500 476]) %[left, bottom, width, height
end
%% Computing the FSC
param.st_title = sprintf('%s\n %s\n flipped_images %d, taper %d',param.fname{1}, param.fname{2}, param.flipped_images, taper);
if flag_imread
subim1 = real(subim1);
subim2 = real(subim2);
warning('Assuming images are in real number!');
end
subim1 = utils.stabilize_phase(subim1, subim2, 'binning', 4, 'fourier_guess', false);
if param.electron %special version for electron ptychography. unit: angstrom
[resolution,FSC,T,freq,n,stat] = fourier_shell_corr_3D_2e(subim1,subim2, param);
else
[resolution,FSC,T,freq,n,stat] = fourier_shell_corr_3D_2(subim1,subim2, param);
end
%% visually compare alignment quality
if param.plotting>2
plotting.smart_figure(4545)
subplot(1,2,1)
imagesc3D(angle(subim1 .* conj( subim2)))
colormap bone
axis off image
colorbar
title('Phase difference between aligned sub-images')
subplot(1,2,2)
imagesc3D(cat(3,angle(subim1),angle(subim2)))
colormap bone
axis off image
title('Compare aligned sub-images')
colorbar
plotting.suptitle('Visually compare quality and verify alignement / drifts')
end
end
function img = apply_apod(img, asize)
ob_good_range = {asize(1)/2:size(img,1)-asize(1)/2, asize(2)/2:size(img,2)-asize(2)/2};
filt_size = [size(ob_good_range{1},2) size(ob_good_range{2},2)];
img = img.*fftshift(utils.filt2d_pad(size(img), max(1,filt_size), max(1,filt_size-min(floor(filt_size.*0.05)))));
end
+114
View File
@@ -0,0 +1,114 @@
%CHECK_OPTION
% check if required option exists and is equal to the given value,
% otherwise return false
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for maximum likelihood:
% P. Thibault and M. Guizar-Sicairos, Maximum-likelihood refinement for coherent diffractive imaging, New J. Phys. 14, 063004 (2012).
% (doi: 10.1088/1367-2630/14/6/063004),
% for mixed coherent modes:
% P. Thibault and A. Menzel, Reconstructing state mixtures from diffraction measurements, Nature 494, 6871 (2013). (doi: 10.1038/nature11806),
% and/or for multislice:
% E. H. R. Tsai, I. Usov, A. Diaz, A. Menzel, and M. Guizar-Sicairos, X-ray ptychography with extended depth of field, Opt. Express 24, 2908929108 (2016).
% (doi: 10.1364/OE.24.029089).
% 6. Except for the above-mentioned acknowledgment, LICENSEE shall not use the PROGRAM title or the names or logos of LICENSOR, nor any adaptation thereof, nor the
% names of any of its employees or laboratories, in any advertising, promotional or sales material without prior written consent obtained from LICENSOR in each case.
% 7. Ownership of all rights, including copyright in the PROGRAM and in any material associated therewith, shall at all times remain with LICENSOR, and LICENSEE
% agrees to preserve same. LICENSEE agrees not to use any portion of the PROGRAM or of any IMPROVEMENTS in any machine-readable form outside the PROGRAM, nor to
% make any copies except for its internal use, without prior written consent of LICENSOR. LICENSEE agrees to place the following copyright notice on any such copies:
% © All rights reserved. PAUL SCHERRER INSTITUT, Switzerland, Laboratory for Macromolecules and Bioimaging, 2017.
% 8. The LICENSE shall not be construed to confer any rights upon LICENSEE by implication or otherwise except as specifically set forth herein.
% 9. DISCLAIMER: LICENSEE shall be aware that Phase Focus Limited of Sheffield, UK has an international portfolio of patents and pending applications which relate
% to ptychography and that the PROGRAM may be capable of being used in circumstances which may fall within the claims of one or more of the Phase Focus patents,
% in particular of patent with international application number PCT/GB2005/001464. The LICENSOR explicitly declares not to indemnify the users of the software
% in case Phase Focus or any other third party will open a legal action against the LICENSEE due to the use of the program.
% 10. This Agreement shall be governed by the material laws of Switzerland and any dispute arising out of this Agreement or use of the PROGRAM shall be brought before
% the courts of Zürich, Switzerland.
function out_value = check_option(p, option_name, required_value )
import utils.*
assert(isstruct(p), 'First input has to be structure')
assert(ischar(option_name), 'Second input has to be string')
if nargin < 3
% default required_value is true
required_value = true;
end
out_value = false;
if ~isfield(p, option_name)
return
end
option_value = get_option(p, option_name);
if isempty(option_value) && isempty(required_value)
out_value = true;
return
end
if (isnumeric(option_value) || islogical(option_value)) && ~isscalar(option_value)
% assume that if the value is matrix, it is ok
out_value = true;
return
end
if islogical(option_value) && isscalar(option_value) && isscalar(required_value)
out_value = option_value == required_value;
return
end
if isnumeric(option_value) && isscalar(option_value) && nargin < 3
out_value = option_value ~= 0;
return
elseif isnumeric(option_value) && isscalar(option_value)
out_value = option_value == required_value;
end
if ischar(required_value)
out_value = strcmpi(required_value, option_value);
return
end
if ~isa(option_value, class(required_value)) && nargin == 3
% class is different => value is different -> false
return
end
if nargin == 2 && ~isempty(option_value)
% there is something, return true
out_value = true;
return
end
error('Unsupported class to compare')
end
+37
View File
@@ -0,0 +1,37 @@
function [n_out, w, trivalwin] = check_order(n_in)
%CHECK_ORDER Checks the order passed to the window functions.
% [N,W,TRIVALWIN] = CHECK_ORDER(N_ESTIMATE) will round N_ESTIMATE to the
% nearest integer if it is not already an integer. In special cases (N is
% [], 0, or 1), TRIVALWIN will be set to flag that W has been modified.
% Copyright 1988-2002 The MathWorks, Inc.
w = [];
trivalwin = 0;
if ~(isnumeric(n_in) && isfinite(n_in))
error(message('signal:check_order:InvalidOrderFinite', 'N'));
end
% Special case of negative orders:
if n_in < 0
error(message('signal:check_order:InvalidOrderNegative'));
end
% Check if order is already an integer or empty
% If not, round to nearest integer.
if isempty(n_in) || n_in == floor(n_in)
n_out = n_in;
else
n_out = round(n_in);
warning(message('signal:check_order:InvalidOrderRounding'));
end
% Special cases:
if isempty(n_out) || n_out == 0
w = zeros(0,1); % Empty matrix: 0-by-1
trivalwin = 1;
elseif n_out == 1
w = 1;
trivalwin = 1;
end
+17
View File
@@ -0,0 +1,17 @@
%COMPILE_APS_DIRNAME returns the default APS directory tree for a
% given scan number
%
% EXAMPLE:
% scan_dir = utils.compile_x12sa_dirname(10);
% -> scan_dir = 'S00000-00999/S00010/'
%
% written by Yi Jiang, based on PSI's code
function scan_dir = compile_aps_dirname(scan_no)
scan_dir = sprintf('S%05d-%05d/S%05d/',floor(scan_no/1000)*1000, ...
floor(scan_no/1000)*1000 + 999, ...
scan_no);
end
+17
View File
@@ -0,0 +1,17 @@
%COMPILE_APS_DIRNAME returns the default APS directory tree for a
% given scan number
%
% EXAMPLE:
% scan_dir = utils.compile_x12sa_dirname(10);
% -> scan_dir = 'S00000-00999/S00010/'
%
% written by Yi Jiang, based on PSI's code
function scan_dir = compile_cu_dirname(scan_no)
scan_dir = sprintf('S%05d-%05d/S%05d/',floor(scan_no/1000)*1000, ...
floor(scan_no/1000)*1000 + 999, ...
scan_no);
end
+25
View File
@@ -0,0 +1,25 @@
% COMPOSE_AFFINE_MATRIX calculate affine matrix when provided rotation, shear, asymmetry and scale
%
% affine_mat = compose_affine_matrix(scale, asymmetry, rotation, shear)
%
% Inputs:
% **scale A1 = [scale, 0; 0, scale]
% **asymmetry A2 = [1+asymmetry/2,0; 0,1-asymmetry/2]
% **rotation A3 = [cosd(rotation), sind(rotation); -sind(rotation), cosd(rotation)]
% **shear A4 = [1,0;tand(shear),1];
%
% returns:
% ++ affine_mat affine matrix = A1*A2*A3*A4
function affine_mat = compose_affine_matrix(scale, asymmetry, rotation, shear)
if isscalar(scale) && isscalar(asymmetry) && isscalar(rotation) && isscalar(shear)
affine_mat = scale(1)*[1+asymmetry/2,0; 0,1-asymmetry/2]*[cosd(rotation), sind(rotation); -sind(rotation), cosd(rotation)] * [1,0;tand(shear),1];
else
for ii = 1:max([numel(scale), numel(asymmetry), numel(rotation), numel(shear)])
affine_mat(:,:,ii) = scale(min(ii,end))*...
[1+asymmetry(min(ii,end))/2,0; 0,1-asymmetry(min(ii,end))/2]*...
[cosd(rotation(min(ii,end))), sind(rotation(min(ii,end))); -sind(rotation(min(ii,end))), cosd(rotation(min(ii,end)))] *...
[1,0;tand(shear(min(ii,end))),1];
end
end
end
+17
View File
@@ -0,0 +1,17 @@
%convert_APS_ptycho_recon.m
flip_probe = false;
%% load probe
probe_temp = outputs.probe{1};
probe = zeros(size(probe_temp,1),size(probe_temp,2),length(outputs.probe));
for i=1:length(outputs.probe)
probe(:,:,i) = outputs.probe{i}(:,:,1,1);
if flip_probe
probe(:,:,i) = rot90(probe(:,:,i),2);
end
end
clear i probe_temp
%% add parameters
p = {};
p.binning = false;
p.detector.binning = false;
+49
View File
@@ -0,0 +1,49 @@
%load('/home/beams0/YJIANG/ptychography/electron/Nb3Cl8/0205_83/data/data_Nb3Cl8_0205_83_roi3.mat');
%load('/home/beams0/YJIANG/ptychography/electron/Nb3Cl8/19/data/data_Nb3Cl8_19_roi8.mat');
load('//home/beams0/YJIANG/ptychography/electron/PrScO3/18/data/data_PSO_18_roi3.mat');
%load('//home/beams0/YJIANG/ptychography/electron/mos2/22/data_mos2_22_roi6_pos.mat');
roi = '3';
Ndp = 256;
rot_angle = 30;
bg_level = 0;
transpose = true;
%%
dp(dp<bg_level) = 0;
Ny = size(dp,3);
Nx = size(dp,4);
dp = reshape(dp,size(dp,1), size(dp,2),Ny*Nx);
if transpose
dp = permute(dp,[2,1,3]);
end
if Ndp~=size(dp,1)
dp = crop_pad_3D( dp, [Ndp,Ndp,size(dp,3)]);
end
saveName = strcat('data_roi',roi,'_dp.hdf5');
h5create(saveName, '/dp', size(dp),'ChunkSize',[Ndp Ndp min([Ny,Nx,100])],'Deflate',4)
h5write(saveName, '/dp', dp)
%{
py = linspace(1,Ny,Ny)*scanStepSize_y;
%py = py - mean(py);
px = linspace(1,Nx,Nx)*scanStepSize_x;
%px = px - mean(px);
[ppX0,ppY0] = meshgrid(px,py);
ppY_rot = ppX0*-sind(rot_angle) + ppY0*cosd(rot_angle);
ppX_rot = ppX0*cosd(rot_angle) + ppY0*sind(rot_angle);
ppX_rot = ppX_rot(:);
ppY_rot = ppY_rot(:);
%ppX_rot = ppX_rot - mean(ppX_rot);
%ppY_rot = ppY_rot - mean(ppY_rot);
saveName = strcat('data_roi',roi,'_para.hdf5');
hdf5write(saveName, '/ppX', ppX(:))
hdf5write(saveName, '/ppY', ppY(:),'WriteMode','append')
%}
+193
View File
@@ -0,0 +1,193 @@
% CREATE_FILE_QUEUE create directories and .dat files for a file queue
% only needed if OMNY/flOMNI is not available
% ** start start scan number
% ** stop stop scan number
% ** step reconstruction bundle size
%
% *optional* given as name/value pair
% ** dirpath path to the .dat files directory; default: '../reconstruction'
% ** prop structure with parameters that need to be saved to the .dat file
% ** prop_name structure name; default: 'p'
% ** spec path to spec file; needed for check2detpos
% ** check2detpos check detector positions to avoid repeated scans
% ** det_motor detector motor; default 'dettrx'
% ** verbose set verbose level; default 0
%
% EXAMPLE:
% s.lockfile = false;
% s.energy = 6.2015;
% s.check_nextscan_started = 1;
%
% create_file_queue(646, 650, 2, 'prop', s)
%
%
% create_file_queue(287, 2553, 2, 'prop', s, 'spec', '/das/work/p16/p16812/data/pilatus/e16403/', 'check2detpos', true, 'det_motor', 'dettrx')
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for maximum likelihood:
% P. Thibault and M. Guizar-Sicairos, Maximum-likelihood refinement for coherent diffractive imaging, New J. Phys. 14, 063004 (2012).
% (doi: 10.1088/1367-2630/14/6/063004),
% for mixed coherent modes:
% P. Thibault and A. Menzel, Reconstructing state mixtures from diffraction measurements, Nature 494, 6871 (2013). (doi: 10.1038/nature11806),
% and/or for multislice:
% E. H. R. Tsai, I. Usov, A. Diaz, A. Menzel, and M. Guizar-Sicairos, X-ray ptychography with extended depth of field, Opt. Express 24, 2908929108 (2016).
% (doi: 10.1364/OE.24.029089).
% 6. Except for the above-mentioned acknowledgment, LICENSEE shall not use the PROGRAM title or the names or logos of LICENSOR, nor any adaptation thereof, nor the
% names of any of its employees or laboratories, in any advertising, promotional or sales material without prior written consent obtained from LICENSOR in each case.
% 7. Ownership of all rights, including copyright in the PROGRAM and in any material associated therewith, shall at all times remain with LICENSOR, and LICENSEE
% agrees to preserve same. LICENSEE agrees not to use any portion of the PROGRAM or of any IMPROVEMENTS in any machine-readable form outside the PROGRAM, nor to
% make any copies except for its internal use, without prior written consent of LICENSOR. LICENSEE agrees to place the following copyright notice on any such copies:
% © All rights reserved. PAUL SCHERRER INSTITUT, Switzerland, Laboratory for Macromolecules and Bioimaging, 2017.
% 8. The LICENSE shall not be construed to confer any rights upon LICENSEE by implication or otherwise except as specifically set forth herein.
% 9. DISCLAIMER: LICENSEE shall be aware that Phase Focus Limited of Sheffield, UK has an international portfolio of patents and pending applications which relate
% to ptychography and that the PROGRAM may be capable of being used in circumstances which may fall within the claims of one or more of the Phase Focus patents,
% in particular of patent with international application number PCT/GB2005/001464. The LICENSOR explicitly declares not to indemnify the users of the software
% in case Phase Focus or any other third party will open a legal action against the LICENSEE due to the use of the program.
% 10. This Agreement shall be governed by the material laws of Switzerland and any dispute arising out of this Agreement or use of the PROGRAM shall be brought before
% the courts of Zürich, Switzerland.
function create_file_queue(start, stop, step, varargin)
import utils.*
par = inputParser;
par.addParameter('dirpath', '../reconstruction', @ischar)
par.addParameter('prop', [], @isstruct)
par.addParameter('prop_name', 'p', @ischar)
par.addParameter('spec', [], @ischar)
par.addParameter('check2detpos', false, @logical)
par.addParameter('det_motor', 'dettrx', @ischar)
par.addParameter('verbose', 0, @isnumeric)
par.parse(varargin{:})
var = par.Results;
% reduce verbose level
vbl = utils.verbose;
utils.verbose(var.verbose);
% prepare directories
if ~exist(fullfile(var.dirpath), 'dir')
mkdir(fullfile(var.dirpath))
end
if ~exist(fullfile(var.dirpath, 'in_progress'), 'dir')
mkdir(fullfile(var.dirpath, 'in_progress'))
mkdir(fullfile(var.dirpath, 'done'))
mkdir(fullfile(var.dirpath, 'failed'))
end
% filename pattern
fname_pattern = repmat('scan%05d_',1,step);
fname_pattern = [fname_pattern(1:end-1) '.dat'];
scan_number_pattern = repmat('%d ',1,step);
scan_number_pattern = scan_number_pattern(1:end-1);
% get value for p.detector.check_2_detpos
if var.check2detpos
S = io.spec_read(var.spec, 'ScanNr', start);
detpos1 = S.(var.det_motor);
for ii=start+1:stop
S = io.spec_read(var.spec, 'ScanNr', ii);
if S.(var.det_motor)~=detpos1
detpos2=S.(var.det_motor);
break
end
end
var.prop.detector.check_2_detpos = abs(detpos1-detpos2)/2+detpos2;
end
% if needed, prepare structure
if ~isempty(var.prop)
prop_fnames = utils.struc2cell(var.prop);
else
prop_fnames = [];
end
utils.verbose(0, 'Creating file queue.');
ii = start;
if utils.verbose < 2
utils.progressbar(1, round((stop-start)/step))
end
while ii<=stop
% check if detector positions are repeated
if var.check2detpos
detpos = [];
kk= 1;
for jj=ii:ii+step-1
S = io.spec_read(var.spec, 'ScanNr', jj);
detpos(kk) = S.(var.det_motor);
kk = kk+1;
end
if all(detpos == detpos(1))
utils.verbose(2,'Found repeated detector positions.')
ii = ii+1;
continue
end
end
% write file
fname = sprintf(fname_pattern, ii:ii+step-1);
fid = fopen(fullfile(var.dirpath, fname), 'w');
fprintf(fid, ['p.scan_number \t ' scan_number_pattern '\n'], ii:ii+step-1);
if ~isempty(prop_fnames)
for jj=1:numel(prop_fnames)
cval = eval(['var.prop.' prop_fnames{jj}]);
if islogical(cval) || isnumeric(cval)
%eval(['var.prop.' prop_fnames{jj} '= double(var.prop.' prop_fnames{jj} ')']);
prop_val = num2str(cval);
else
prop_val = cval;
end
prop_val = replace(prop_val, '%', '%%'); % avoid interpretation of special characters in strings
fprintf(fid, [var.prop_name '.' prop_fnames{jj} '\t ' prop_val '\n']);
end
end
fclose(fid);
ii = ii+step;
if utils.verbose < 2
utils.progressbar(ii-start, round((stop-start)/step))
end
end
utils.verbose(0, '\nDone.');
% revert changes to verbose level
utils.verbose(vbl);
end
+91
View File
@@ -0,0 +1,91 @@
% CROP_PAD_3D adjusts the size by zero padding or cropping
%
% [ imout ] = crop_pad_3D( img, outsize, varargin)
%
% Inputs
% **img input 3D volume
% **outsize size of output volume
% **fill value to fill the padded regions
% Outputs
% ++imout output volume after cropping / padding to size "outsize"
%
% Example :
% volData = ones(100,100,100)
% [ volData_out ] = crop_pad_3D( volData, [50,50,200])
% size(volData_out) == [50,50,200]
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function [ imout ] = crop_pad_3D( img, outsize, fill)
if nargin < 1
fprintf('CROP_PAD: adjusts the size by zero padding or cropping\n');
fprintf('crop_pad(img, outsize)\n');
return
end
if nargin < 3
fill = 0;
end
Nout = outsize(1:3);
Nin = size(img);
if all(Nin ==Nout) % dont do anything if input array size == output size
imout = img;
return
end
center = floor(Nin(1:3)/2)+1;
imout = zeros(outsize,'like',img) + fill;
centerout = floor(Nout/2)+1;
cenout_cen = centerout - center;
imout(max(cenout_cen(1)+1,1):min(cenout_cen(1)+Nin(1),Nout(1)),...
max(cenout_cen(2)+1,1):min(cenout_cen(2)+Nin(2),Nout(2)),...
max(cenout_cen(3)+1,1):min(cenout_cen(3)+Nin(3),Nout(3))) ...
= img(max(-cenout_cen(1)+1,1):min(-cenout_cen(1)+Nout(1),Nin(1)),...
max(-cenout_cen(2)+1,1):min(-cenout_cen(2)+Nout(2),Nin(2)),...
max(-cenout_cen(3)+1,1):min(-cenout_cen(3)+Nout(3),Nin(3)));
if ~isreal(img)
imout = complex(imout);
end
end
+170
View File
@@ -0,0 +1,170 @@
% filename_with_path = find_ptycho_filename(base_analysis_path,scan_number,fileprefix,filesuffix)
% Looks for a ptychography reconstruction name inside the path given as
% initial argument. I will look in the folder given and also try with
% adding analysis. If the scan_number is given it will compile an analysis
% folder and look for it. e.g. find_ptycho_filename('~/Data10',235);
% Use verbose(2) in order to see all directories and names attempted.
% Inputs
% base_analysis_path % String with path to start looking
% scan_number % (optional) Number with the scan number, used to
% compile folder
% fileprefix % String specifying the starting of the name
% filesuffix % String specifying the ending of the name
% Output
% filename_with_path % String with the first file found that satisfies
% the input arguments
% 15 June 2015;
% September 2017 Return all files matching the criteria;
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for maximum likelihood:
% P. Thibault and M. Guizar-Sicairos, Maximum-likelihood refinement for coherent diffractive imaging, New J. Phys. 14, 063004 (2012).
% (doi: 10.1088/1367-2630/14/6/063004),
% for mixed coherent modes:
% P. Thibault and A. Menzel, Reconstructing state mixtures from diffraction measurements, Nature 494, 6871 (2013). (doi: 10.1038/nature11806),
% and/or for multislice:
% E. H. R. Tsai, I. Usov, A. Diaz, A. Menzel, and M. Guizar-Sicairos, X-ray ptychography with extended depth of field, Opt. Express 24, 2908929108 (2016).
% (doi: 10.1364/OE.24.029089).
% 6. Except for the above-mentioned acknowledgment, LICENSEE shall not use the PROGRAM title or the names or logos of LICENSOR, nor any adaptation thereof, nor the
% names of any of its employees or laboratories, in any advertising, promotional or sales material without prior written consent obtained from LICENSOR in each case.
% 7. Ownership of all rights, including copyright in the PROGRAM and in any material associated therewith, shall at all times remain with LICENSOR, and LICENSEE
% agrees to preserve same. LICENSEE agrees not to use any portion of the PROGRAM or of any IMPROVEMENTS in any machine-readable form outside the PROGRAM, nor to
% make any copies except for its internal use, without prior written consent of LICENSOR. LICENSEE agrees to place the following copyright notice on any such copies:
% © All rights reserved. PAUL SCHERRER INSTITUT, Switzerland, Laboratory for Macromolecules and Bioimaging, 2017.
% 8. The LICENSE shall not be construed to confer any rights upon LICENSEE by implication or otherwise except as specifically set forth herein.
% 9. DISCLAIMER: LICENSEE shall be aware that Phase Focus Limited of Sheffield, UK has an international portfolio of patents and pending applications which relate
% to ptychography and that the PROGRAM may be capable of being used in circumstances which may fall within the claims of one or more of the Phase Focus patents,
% in particular of patent with international application number PCT/GB2005/001464. The LICENSOR explicitly declares not to indemnify the users of the software
% in case Phase Focus or any other third party will open a legal action against the LICENSEE due to the use of the program.
% 10. This Agreement shall be governed by the material laws of Switzerland and any dispute arising out of this Agreement or use of the PROGRAM shall be brought before
% the courts of Zürich, Switzerland.
function [ filename_with_path ] = find_ptycho_filename( base_analysis_path, varargin)
import utils.verbose
% Checks and defaults
if nargin < 5
fileextension = 'h5';
else
fileextension = varargin{4};
end
if nargin < 4
filesuffix = [];
else
filesuffix = varargin{3};
end
if nargin < 3
fileprefix = [];
else
fileprefix = varargin{2};
end
if nargin < 2
scan_number = [];
else
scan_number = varargin{1};
end
%%% Give all matching files
trial_path = fullfile(base_analysis_path, utils.compile_x12sa_dirname(scan_number));
if isempty(filesuffix)
searchstring = [fileprefix '*.' fileextension];
else
searchstring = [fileprefix '*' filesuffix '*.' fileextension];
end
search_filename = fullfile(trial_path, searchstring);
output = dir(search_filename);
if numel(output) == 0
verbose(2,['Did not find any file matching' search_filename]);
% Then see if analysis folder exists here
trial_path = fullfile(base_analysis_path,'analysis');
if exist(trial_path,'dir')~=0
search_filename = fullfile(trial_path,searchstring);
output = dir(search_filename);
else
trial_path = base_analysis_path;
end
if numel(output) == 0
verbose(2,['Did not find any file matching' search_filename]);
if ~isempty(scan_number)
% Then add the string for the scan folder
trial_path = fullfile(trial_path,sprintf('S%05d',scan_number));
search_filename = fullfile(trial_path,searchstring);
output = dir(search_filename);
if numel(output) == 0
verbose(2,['Did not find any file matching' search_filename]);
filename_with_path = [];
% return
end
else
verbose(2,['Did not find any file matching' search_filename]);
filename_with_path = [];
% return
end
end
end
for ii = 1:length(output)
filename_with_path{ii} = fullfile(trial_path, output(ii).name);
end
if numel(filename_with_path)~=0
if iscell(filename_with_path) && numel(filename_with_path)==1
filename_with_path = filename_with_path{1};
else
verbose(1,'Found %d file matching the criteria -> providing all in cell', numel(filename_with_path))
end
else
verbose(1,'Found no file matching %s', fullfile(base_analysis_path, utils.compile_x12sa_dirname(scan_number),searchstring ))
filename_with_path = [];
end
end
+40
View File
@@ -0,0 +1,40 @@
function [OUT]=fresnel_propagation(IN,dxy,z,lambda)
%FRESNEL_PROP Summary of this function goes here
% Detailed explanation goes here
%Parameters: dx,dy -> the pixel pitch of the object
% z -> the distance of the propagation
% lambda -> the wave length
% X,Y -> meshgrid of coordinate
% IN -> input object
[M,N]=size(IN);
k=2*pi/lambda;
%coodinate grid
lx=linspace(-dxy*M/2,dxy*M/2,M);
[x,y]=meshgrid(lx);
% coordinate on the output plane
fc=1/dxy;
fu=lambda*z*fc;
lu=ifftshift(ifftshift(linspace(-fu/2,fu/2,M),1),2);
[u,v]=meshgrid(lu);
if z>0
pf=exp(1j*k*z)*exp(1j*k*(u.^2+v.^2)/2/z);
kern=IN.*exp(1j*k*(x.^2+y.^2)/2/z);
kerntemp=fftshift(kern);
cgh=fft2(kerntemp);
OUT=fftshift(fftshift(cgh.*pf,1),2);
else
z=abs(z);
pf = exp(1j*k*z)*exp(1j*k*(x.^2+y.^2)/2/z);
cgh = ifft2(ifftshift(IN)./exp(1j*k*(u.^2+v.^2)/2/z));
OUT = fftshift(cgh)./pf;
end
+40
View File
@@ -0,0 +1,40 @@
function [OUT]=fresnel_propagation(IN,dxy,z,lambda)
%FRESNEL_PROP Summary of this function goes here
% Detailed explanation goes here
%Parameters: dx,dy -> the pixel pitch of the object
% z -> the distance of the propagation
% lambda -> the wave length
% X,Y -> meshgrid of coordinate
% IN -> input object
[M,N]=size(IN);
k=2*pi/lambda;
%coodinate grid
lx=linspace(-dxy*M/2,dxy*M/2,M);
[x,y]=meshgrid(lx);
% coordinate on the output plane
fc=1/dxy;
fu=lambda*z*fc;
lu=ifftshift(ifftshift(linspace(-fu/2,fu/2,M),1),2);
[u,v]=meshgrid(lu);
if z>0
pf=exp(1j*k*z)*exp(1j*k*(u.^2+v.^2)/2/z);
kern=IN.*exp(1j*k*(x.^2+y.^2)/2/z);
kerntemp=fftshift(kern);
cgh=fft2(kerntemp);
OUT=fftshift(fftshift(cgh.*pf,1),2);
else
z=abs(z);
pf = exp(1j*k*z)*exp(1j*k*(x.^2+y.^2)/2/z);
cgh = ifft2(ifftshift(IN)./exp(1j*k*(u.^2+v.^2)/2/z));
OUT = fftshift(cgh)./pf;
end
+364
View File
@@ -0,0 +1,364 @@
function [img1_aligned, img2_aligned, delta_all] = fun_align_img(img1,img2,asize,pix)
% [resolution] = aligned_FSC(file1,file2,params)
%
% Receives two filenames with path for ptychography reconstructions and a
% structure with parameters. The routine reads the reconstructions, matches
% the linear phase between them, registers the images, and returns the
% resolution estimates based on first and last crossing of the FSC with the
% threshold.
%
% References relevant to this code:
% For using this FSC code with ptychography: J. Vila-Comamala, et al., "Characterization of high-resolution diffractive X-ray optics by ptychographic coherent diffractive imaging," Opt. Express 19, 21333-21344 (2011).
% For subpixel alignment: M. Guizar-Sicairos, et al., "Efficient subpixel image registration algorithms," Opt. Lett. 33, 156 (2008).
% For matching of phase ramp by approximate least squared error: M. Guizar-Sicairos, et al., "Phase tomography from x-ray coherent diffractive imaging projections," Opt. Express 19, 21345-21357 (2011).
%
% Outputs:
%
% resolution A two element variable that contains the resolution
% obtained from first and last crossing of the FSC curve with
% the threshold curve.
%
% Inputs:
%
% file1 Filename with path of reconstruction 1
% file2 Filename with path of reconstruction 2
% params Structure with parameters as described below
%
% params.flipped_images Flip one input image horizontally (= true or false).
% Useful when comparing 0 and 180 degree projections
% in tomography (default = false).
% params.crop = ''; for using the default half size of the probe
% = 'manual' for using GUI to select region. This will display the range, e.g. {600:800, 600:800}
% = {600:800, 600:800} for custom vertical and horizontal cropping, respectively
% params.GUIguess To click for an initial alignment guess, if used it ignores
% the values of params.guessx and params.guessy (default
% = false)
% params.guessx
% params.guessy An intial guess for x and y alignment (default = [])
% params.remove_ramp Try to remove linear phase from whole image before initial
% alignment (default = true)
% params.image_prop = 'complex'
% = 'phasor' (phase with unit amplitude, default)
% = 'phase' (Note: phase should not be used if there is phase wrapping)
% params.taper = 20 (default) Pixels to taper images - Increase until the FSC does not change anymore
% params.plotting Display plots (default = false)
% params.dispfsc Display FSC plot (default = true)
% params.SNRt SNR for FSC threshold curve
% SNRt = 0.2071 for 1/2 bit threshold for resolution of the average of the 2 images
% SNRt = 0.5 for 1 bit threshold for resolution of each individual image (default)
% params.thickring Thickness of Fourier domain ring for FSC in pixels (default = 1)
% params.freq_thr To ignore the crossings before freq_thr for determining resolution (default 0.02)
% params.out_fn Filename of output of jpeg for FSC
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Authors: CXS group
%|                                                                       |
%*-----------------------------------------------------------------------*
%
% You may use this code with the following provisions:
%
% If this code, or subfunctions or parts of it, is used for research in a
%   publication or if it is fully or partially rewritten for another
%   computing language the authors and institution should be acknowledged
%   in written form and additionally you should cite the references relevant
% to this code.
%
% A publication that focuses on describing features, or parameters, that
%    are already existing in the code should be first discussed with the
%    authors.
%   
% This code and subroutines are part of a continuous development, they
%    are provided as they are without guarantees or liability on part
%    of PSI or the authors. It is the user responsibility to ensure its
%    proper use and the correctness of the results.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Checks and defaults %%%
flag_imread = 1;
GUIguess = false;
plotting = false;
crop = '';
guessx = [];
guessy = [];
remove_ramp = false;
image_prop = 'complex';
taper = 20;
dispfsc = true;
SNRt = 0.5;
thickring = 5;
freq_thr = 0.02;
%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%
img1_orig = img1;
img2_orig = img2;
screensize = get( 0, 'Screensize' );
% Show phase images (not cropped)%
if plotting
figure(2)
set(gcf,'Outerposition',[1 screensize(4)-550 500 500]) %[left, bottom, width, height
if ~flag_imread
imagesc(angle(img1));
else
imagesc(img1);
end
axis xy equal tight
colormap bone
if ~flag_imread
aux = angle(img1); %angle(img1(round(asize(1)/2):end-round(asize(1)/2),round(asize(2)/2):end-round(asize(2)/2)));
else
aux = img1;
end
caxis([min(aux(:)) max(aux(:))]); colorbar
title(file{1},'interpreter','none')
figure(3)
if ~flag_imread
imagesc(angle(img2));
else
imagesc(img2);
end
axis xy equal tight
colormap bone
if ~flag_imread
aux = angle(img2); %angle(img2(round(asize(1)/2):end-round(asize(1)/2),round(asize(2)/2):end-round(asize(2)/2)));
else
aux = img2;
end
caxis([min(aux(:)) max(aux(:))]); colorbar
title(file{2},'interpreter','none')
set(gcf,'Outerposition',[500 screensize(4)-550 500 500]) %[left, bottom, width, height
end
% Crop images - default is half the size of the probe on each side plus
% whatever needed to make them of equal size
minsize1 = min(size(img1,1),size(img2,1));
minsize2 = min(size(img1,2),size(img2,2));
if isempty(crop)
crop = {round(asize(1)/2):minsize1-round(asize(1)/2), ...
round(asize(2)/2):minsize2-round(asize(1)/2)};
elseif strcmpi(crop, 'manual')
figure()
imagesc(angle(img1))
colormap bone
axis image xy
title('Select compared region')
rect = round(getrect);
crop = {rect(2)+(1:rect(4)),rect(1)+(1:rect(3))};
disp('===========================')
fprintf('Selected region: {%i:%i,%i:%i}\n',rect(2), rect(2)+rect(4), rect(1), rect(1)+rect(3));
disp('===========================')
pause(1)
end
img1 = img1(crop{:});
img2 = img2(crop{:});
if GUIguess
figure(2)
disp(['Click on a feature on figure 2'])
[xin yin] = ginput(1);
figure(3)
disp(['Click on a feature on figure 3'])
[xin2 yin2] = ginput(1);
guessx = round(xin-xin2);
guessy = round(yin-yin2);
end
if ~isempty(guessx)
switch sign(guessx)
case 1
img1 = img1(:,1+guessx:end);
img2 = img2(:,1:end-guessx);
case -1
img1 = img1(:,1:end+guessx);
img2 = img2(:,1-guessx:end);
end
end
if ~isempty(guessy)
switch sign(guessy)
case 1
img1 = img1(1+guessy:end,:);
img2 = img2(1:end-guessy,:);
case -1
img1 = img1(1:end+guessy,:);
img2 = img2(1-guessy:end,:);
end
end
% Remove ramp
if remove_ramp
disp('Removing ramp for initial alignment')
img1 = remove_linearphase_v2(img1,ones(size(img1)),100);
img2 = remove_linearphase_v2(img2,ones(size(img2)),100);
end
if plotting
figure(4)
set(gcf,'Outerposition',[1 1 500 476]) %[left, bottom, width, height
if ~flag_imread
imagesc(angle(img1));
else
imagesc(img1);
end
axis xy equal tight
colormap bone; colorbar
title(file{1},'interpreter','none')
figure(5)
if ~flag_imread
imagesc(angle(img2));
else
imagesc(img2);
end
axis xy equal tight
colormap bone; colorbar
title(file{2},'interpreter','none')
set(gcf,'Outerposition',[500 1 500 476]) %[left, bottom, width, height
end
%%% Initial alignment %%%
fprintf('\nInitial alignment\n')
if ~flag_imread
switch lower(image_prop)
case 'complex'
imgalign1 = img1;
imgalign2 = img2;
disp('Registering complex valued images')
case 'phasor'
imgalign1 = ones(size(img1)).*exp(1i*angle(img1));
imgalign2 = ones(size(img1)).*exp(1i*angle(img2));
disp('Registering phasor of complex valued images')
case 'phase'
imgalign1 = angle(img1);
imgalign2 = angle(img2);
disp('Registering phase of complex valued images')
end
else
imgalign1 = img1;
imgalign2 = img2;
end
upsamp = 100;
displ = 1;
W = 1;
x1 = [];%[1:150];
x2 = x1;
y1 = [];%[1:238];
y2 = y1;
% imgalign2 = shiftpp2(imgalign2,10,-10); % To test range adjustment
[subim1, subim2, delta, deltafine, regionsout] = registersubimages_2(imgalign1,imgalign2, x1, y1, x2, y2, upsamp, displ,1);
%%% Fine alignment (second round) %%%
% Remove ramp for fine alignment
disp('Removing ramp for fine alignment')
%%% A patch for deltafine large
if max(regionsout.y2+round(delta(1)))>size(img2,1)
warning('First subpixel registration refinement found large values')
regionsout.y2 = [min(regionsout.y2):size(img2,1)-round(delta(1))];
regionsout.y1 = regionsout.y2;
end
if max(regionsout.x2+round(delta(2)))>size(img2,2)
warning('First subpixel registration refinement found large values')
regionsout.x2 = [min(regionsout.x2):size(img2,2)-round(delta(2))];
regionsout.x1 = regionsout.x2;
end
%%%
subimg1 = img1(regionsout.y1,regionsout.x1);
subimg2 = img2(regionsout.y2+round(delta(1)),regionsout.x2+round(delta(2)));
if ~flag_imread
subimg1 = remove_linearphase_v2(subimg1,ones(size(subimg1)),100);
subimg2 = remove_linearphase_v2(subimg2,ones(size(subimg2)),100);
end
if ~flag_imread
switch lower(image_prop)
case 'complex'
subimgalign1 = subimg1;
subimgalign2 = subimg2;
disp('Registering complex valued images')
case 'phasor'
subimgalign1 = ones(size(subimg1)).*exp(1i*angle(subimg1));
subimgalign2 = ones(size(subimg1)).*exp(1i*angle(subimg2));
disp('Registering phasor of complex valued images')
case 'phase'
subimgalign1 = angle(subimg1);
subimgalign2 = angle(subimg2);
disp('Registering phase of complex valued images')
end
else
subimgalign1 = subimg1;
subimgalign2 = subimg2;
end
% Fine alignment %
disp(sprintf('\nFine alignment'))
[subim1, subim2, delta2, deltafine2, regionsout] = registersubimages_2(subimgalign1,subimgalign2, x1, y1, x2, y2, upsamp, displ,1);
%%% Tapering %%%
filterx = fract_hanning_pad(size(subim1,2),size(subim1,2),size(subim1,2)-2*taper);
filterx = fftshift(filterx(1,:));
filterx = repmat(filterx,[size(subim1,1) 1]);
filtery = fract_hanning_pad(size(subim1,1),size(subim1,1),size(subim1,1)-2*taper);
filtery = fftshift(filtery(:,1));
filtery = repmat(filtery,[1 size(subim1,2)]);
filterxy = filterx.*filtery;
% Taper subimages %
subim1 = subim1.*filterxy;% + (1-filterxy).*mean(subim1(:));
subim2 = subim2.*filterxy;% + (1-filterxy).*mean(subim2(:));
if plotting
figure(4)
set(gcf,'Outerposition',[1 1 500 476]) %[left, bottom, width, height
if strcmpi(image_prop,'phase') || flag_imread
imagesc(subim1);
else
imagesc(angle(subim1));
end
axis xy equal tight
colormap bone; colorbar
title(file{1},'interpreter','none')
figure(5)
if strcmpi(image_prop,'phase') || flag_imread
imagesc(real(subim2));
else
imagesc(angle(subim2));
end
axis xy equal tight
colormap bone; colorbar
title(file{2},'interpreter','none')
set(gcf,'Outerposition',[500 1 500 476]) %[left, bottom, width, height
end
%% Computing the FSC
param.st_title = sprintf('taper %d',taper);
param.pixel_size = pix;
[resolution FSC T freq] = fourier_shell_corr_3D_2(subim1,subim2, param);
if 0
img1_aligned = img1_orig;
img1_aligned(asize(1)/2:asize(1)/2+size(subim1,1)-1, asize(2)/2:asize(2)/2+size(subim1,2)-1) = subim1;
img2_aligned = img2_orig;
img2_aligned(asize(1)/2:asize(1)/2+size(subim2,1)-1, asize(2)/2:asize(2)/2+size(subim2,2)-1) = subim2;
else
img1_aligned = subim1;
img2_aligned = subim2;
end
delta_all = round(delta) + delta2;
return
+146
View File
@@ -0,0 +1,146 @@
function [outputDir, paramInfo] = generateResultDir(param, resultDir, extra)
%Generate output directory for GPU and GPU_MS engines
% Written by YJ
paramInfo = strcat(param.method,'_',param.opt_errmetric,'_p',num2str(param.probe_modes),'_g',num2str(param.grouping));
if isfield(param,'asize_presolve') && length(param.asize_presolve)==2
paramInfo = strcat(paramInfo,'_Ndp',num2str(param.asize_presolve(1)));
end
if strcmp(param.method, 'MLc') && param.accelerated_gradients_start < param.number_iterations
paramInfo = strcat(paramInfo,'_ag',num2str(param.accelerated_gradients_start));
end
if strcmp(param.method, 'MLc') && param.momentum ~=0
paramInfo = strcat(paramInfo,'_m',num2str(param.momentum));
end
if param.beta_object < 1
paramInfo = strcat(paramInfo,'_betaO',num2str(param.beta_object));
end
if param.beta_probe < 1
paramInfo = strcat(paramInfo,'_betaP',num2str(param.beta_probe));
end
%{
if isfield(param,'beta_LSQ')
paramInfo = strcat(paramInfo,'_betaLSQ',num2str(param.beta_LSQ));
end
if param.delta_p ~= 0.1
paramInfo = strcat(paramInfo,'_LSQdamping',num2str(param.delta_p));
end
%}
if param.probe_position_search < param.number_iterations
paramInfo = strcat(paramInfo,'_pc',num2str(param.probe_position_search));
if isfield(param,'apply_relaxed_position_constraint') && ~param.apply_relaxed_position_constraint
paramInfo = strcat(paramInfo,'_noModel');
elseif ~isempty(param.probe_geometry_model)
if ismember('scale', param.probe_geometry_model)
paramInfo = strcat(paramInfo,'_scale');
end
if ismember('asymmetry', param.probe_geometry_model)
paramInfo = strcat(paramInfo,'_asym');
end
if ismember('rotation', param.probe_geometry_model)
paramInfo = strcat(paramInfo,'_rot');
end
if ismember('shear', param.probe_geometry_model)
paramInfo = strcat(paramInfo,'_shear');
end
%for i=1:length(param.probe_geometry_model)
% paramInfo = strcat(paramInfo,'_',param.probe_geometry_model{i});
%end
end
if isfield(param,'update_pos_weight_every') && param.update_pos_weight_every< param.number_iterations
paramInfo = strcat(paramInfo,'_updW',num2str(param.update_pos_weight_every));
end
if param.probe_position_error_max < inf
%paramInfo = strcat(paramInfo,'_maxError',num2str(param.probe_position_error_max/1e-9),'nm');
paramInfo = strcat(paramInfo,'_maxError',num2str(param.probe_position_error_max));
end
if isfield(param,'max_pos_update_shift') && param.max_pos_update_shift~=0.1
paramInfo = strcat(paramInfo,'_maxUpdShift',num2str(param.max_pos_update_shift));
end
if isfield(param,'probe_position_search_momentum') && param.probe_position_search_momentum>0
paramInfo = strcat(paramInfo,'_m',num2str(param.probe_position_search_momentum));
end
end
if param.detector_scale_search < param.number_iterations
paramInfo = strcat(paramInfo,'_detScaleSearch',num2str(param.detector_scale_search));
end
if param.probe_fourier_shift_search < param.number_iterations
paramInfo = strcat(paramInfo,'_fpc',num2str(param.probe_fourier_shift_search));
end
if param.background>0
paramInfo = strcat(paramInfo,'_bg',num2str(param.background));
end
if param.delta>0
paramInfo = strcat(paramInfo,'_delta',num2str(param.delta));
end
if param.reg_mu>0
paramInfo = strcat(paramInfo,'_regSmooth',num2str(param.reg_mu));
end
if isfield(param,'TV_lambda') && param.TV_lambda>0
paramInfo = strcat(paramInfo,'_TV',num2str(param.TV_lambda));
end
if param.positivity_constraint_object>0
paramInfo = strcat(paramInfo,'_posObj',num2str(param.positivity_constraint_object));
end
if param.variable_probe
paramInfo = strcat(paramInfo,'_vp',num2str(param.variable_probe_modes));
if param.variable_probe_smooth>0
paramInfo = strcat(paramInfo,'_smooth',num2str(param.variable_probe_smooth));
end
end
if param.variable_intensity
paramInfo = strcat(paramInfo,'_vi');
end
if param.apply_multimodal_update
paramInfo = strcat(paramInfo,'_mm');
end
if is_used(param, 'fly_scan')
paramInfo = strcat(paramInfo,'_apFly',num2str(param.Nmodes));
end
if ~isempty(param.delta_z)
paramInfo = strcat(paramInfo,'_Ns',num2str(length(param.delta_z)));
paramInfo = strcat(paramInfo,'_dz',num2str(mean(param.delta_z)));
if param.regularize_layers~=0
paramInfo = strcat(paramInfo,'_reg',num2str(param.regularize_layers));
end
if param.preshift_ML_probe
paramInfo = strcat(paramInfo,'_centerProbe');
end
end
if any(param.custom_data_flip)
paramInfo = strcat(paramInfo,'_dpFlip');
if param.custom_data_flip(1)==1
paramInfo = strcat(paramInfo,'_lr');
end
if param.custom_data_flip(2)==1
paramInfo = strcat(paramInfo,'_ud');
end
if param.custom_data_flip(3)==1
paramInfo = strcat(paramInfo,'_T');
end
end
%{
if any(param.det_bad_pixels(:))
output = strcat(output,'_badPixels');
end
%}
if nargin==3
paramInfo = strcat(paramInfo,extra);
end
outputDir = strcat(resultDir,'/',paramInfo,'/');
end
+43
View File
@@ -0,0 +1,43 @@
function [probe] = generate_probe(N, lambda, dx, Ls, setup)
%UNTITLED Summary of this function goes here
% Detailed explanation goes here
%Parameters: N -> number of pixels
% lambda -> the wave length
% dx -> pixel size (in sample plane)
% Ls -> distance from focal plane to sample
%Fresnel Zone Plate
switch setup
case "velo"
Rn=90e-6;
dRn=50e-9;
case "barry"
Rn=80e-6;
dRn=70e-9;
case "barry2"
Rn=70e-6;
dRn=160e-9;
otherwise
Rn=90e-6;
dRn=50e-9;
end
fl=2*Rn*dRn/lambda;%focal length corresponding to central wavelength
D_FZP=180e-6;%dimeter of the FZP
D_H=60e-6;%central beamstop
%pixel size on FZP plane
dx_fzp=lambda*fl/N/dx;
%Coordinate on FZP plane
lx_fzp=linspace(-dx_fzp*N/2,dx_fzp*N/2,N);
[x_fzp,y_fzp]=meshgrid(lx_fzp);
%Transmission function of the FZP
T=exp(-1j*2*pi/lambda*(x_fzp.^2+y_fzp.^2)/2/fl);
C=double(sqrt(x_fzp.^2+y_fzp.^2)<=(D_FZP/2));% Cercular function of FZP
H=double(sqrt(x_fzp.^2+y_fzp.^2)>=(D_H/2));%cental block
%probe on sample plane
probe=fresnel_propagation(C.*T.*H,dx_fzp,(fl+Ls),lambda);
%figure(1);imagesc(abs(probe));axis image
%figure(2);imagesc(angle(probe));axis image
end
+14
View File
@@ -0,0 +1,14 @@
function [object] = get_ptycho_object(reconDir, varargin)
%Get object function from a ptychographic reconstruction
% Input: reconDir-dir to the recon file (.h5)
% Output: object-complex object function
if nargin==1
objectPath = '/reconstruction/p/objects/object_0';
else
objectPath = varargin{1};
end
h = h5read(reconDir,objectPath);
object = h.r + 1i*h.i;
end
@@ -0,0 +1,171 @@
%GET_TILTED_PLANE_CORRECTION_MATRIX
% create a sparse matrix that applies deformation on measured farfield to correct for effects of
% sample tilt
%
% T = get_tilted_plane_correction_matrix(Npix, detectorDistance,detectorPixel,Chi,Theta,Psi)
%
% Inputs:
% **Npix - size of the dataset
% **detectorDistance - sample to detector distance
% **detectorPixel - size of detector pixel
% **Theta - rotation around X axis
% **Chi - rotation around Y axis
% **Psi - rotation around beam axis
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for maximum likelihood:
% P. Thibault and M. Guizar-Sicairos, Maximum-likelihood refinement for coherent diffractive imaging, New J. Phys. 14, 063004 (2012).
% (doi: 10.1088/1367-2630/14/6/063004),
% for mixed coherent modes:
% P. Thibault and A. Menzel, Reconstructing state mixtures from diffraction measurements, Nature 494, 6871 (2013). (doi: 10.1038/nature11806),
% and/or for multislice:
% E. H. R. Tsai, I. Usov, A. Diaz, A. Menzel, and M. Guizar-Sicairos, X-ray ptychography with extended depth of field, Opt. Express 24, 2908929108 (2016).
% (doi: 10.1364/OE.24.029089).
% 6. Except for the above-mentioned acknowledgment, LICENSEE shall not use the PROGRAM title or the names or logos of LICENSOR, nor any adaptation thereof, nor the
% names of any of its employees or laboratories, in any advertising, promotional or sales material without prior written consent obtained from LICENSOR in each case.
% 7. Ownership of all rights, including copyright in the PROGRAM and in any material associated therewith, shall at all times remain with LICENSOR, and LICENSEE
% agrees to preserve same. LICENSEE agrees not to use any portion of the PROGRAM or of any IMPROVEMENTS in any machine-readable form outside the PROGRAM, nor to
% make any copies except for its internal use, without prior written consent of LICENSOR. LICENSEE agrees to place the following copyright notice on any such copies:
% © All rights reserved. PAUL SCHERRER INSTITUT, Switzerland, Laboratory for Macromolecules and Bioimaging, 2017.
% 8. The LICENSE shall not be construed to confer any rights upon LICENSEE by implication or otherwise except as specifically set forth herein.
% 9. DISCLAIMER: LICENSEE shall be aware that Phase Focus Limited of Sheffield, UK has an international portfolio of patents and pending applications which relate
% to ptychography and that the PROGRAM may be capable of being used in circumstances which may fall within the claims of one or more of the Phase Focus patents,
% in particular of patent with international application number PCT/GB2005/001464. The LICENSOR explicitly declares not to indemnify the users of the software
% in case Phase Focus or any other third party will open a legal action against the LICENSEE due to the use of the program.
% 10. This Agreement shall be governed by the material laws of Switzerland and any dispute arising out of this Agreement or use of the PROGRAM shall be brought before
% the courts of Zürich, Switzerland.
function T = get_tilted_plane_correction_matrix(Npix, detectorDistance,detectorPixel,Theta,Chi,Psi)
Npix = Npix(1); %% hardcoded assumption of square image
[qxx,qyy] = tilted_ewald_plane(Npix, Npix,detectorDistance,detectorPixel, Theta,Chi, Psi);
% transform coordinates to regular grid 1:Npix
qxx = qxx' / cosd(Chi) +Npix/2+1;
qyy = qyy' / cosd(Theta) +Npix/2+1;
M1 = [00,0;0,1;1,0;1,1];
W = zeros( Npix, Npix, 4, 'single');
pos = cat(3, qxx, qyy);
pos_ = floor(pos);
dX = 1 - (pos - pos_);
clear pos
dX = dX(:,:,[2,1]);
W(:,:,1) = dX(:,:,1) .* dX(:,:,2);
W(:,:,2) = (1-dX(:,:,1)) .* dX(:,:,2);
W(:,:,3) = dX(:,:,1) .* (1-dX(:,:,2));
W(:,:,4) = (1-dX(:,:,1)) .* (1-dX(:,:,2));
clear dX
ind_wrong = any(pos_<=0,3) | pos_(:,:,1) > Npix | pos_(:,:,2) > Npix ;
W = W .* ~ind_wrong;
clear ind_wrong
for j = 1:2
P{j} = zeros( Npix, Npix,4, 'single');
for i = 1:4
P{j}(:,:,i) = pos_(:,:,j) + M1(i, j);
end
end
clear pos_
[Y,X] = meshgrid(1:Npix, 1:Npix);
ind_x = single((X-1)*Npix+Y);
ind_x = repmat(reshape(ind_x, [Npix, Npix]), [1,1,4]);
ind_y = (P{1}-1)*Npix+P{2};
out = P{1} > Npix | P{2} > Npix | P{1} < 1 | P{2} < 1;
S = [ind_x(:), ind_y(:), W(:)];
S(out(:),:) = [];
T = sparse(double(S(:,1)), double(S(:,2)), double(S(:,3)), Npix*Npix, Npix*Npix );
% renormalize the deformation to preserve flux !!
T = T ./ max(eps, sqrt(sum(T'*T,1)));
end
function [qyy,qxx] = tilted_ewald_plane(dimx, dimy,detectorDistance,detectorPixel, Theta,Chi,Psi)
xgrid = linspace(-dimx/2,dimx/2, dimx);
ygrid = linspace(-dimy/2,dimy/2, dimy);
[y, x] = meshgrid(xgrid,ygrid);
x = x * detectorPixel;
y = y * detectorPixel;
R = sqrt(x.^2 + y.^2 + detectorDistance^2);
qx = x ./ R;
qy = y ./ R;
qz = (detectorDistance ./ R -1);
RotMat = utils.get_rotation_matrix_3D(Chi, Theta, -Psi); % make rotation consistent with imrotate in matlab
rotCoords = RotMat*[qx(:)';qy(:)';qz(:)'];% rotate Ewald sphere
qxx = rotCoords(1,:);
qyy = rotCoords(2,:);
qxx =reshape(qxx, dimx, dimy);
qyy =reshape(qyy, dimx, dimy);
% the qzz coordinates are lost
%calculate Cartesian FFT of model to use for interpolation
% [Y, X] = meshgrid(xgrid,ygrid);
%convert coordinates to correct units
% X = cosd(Theta)*X;
% Y = cosd(Chi)*Y;
scale = detectorPixel / detectorDistance;
qxx = qxx / scale;
qyy = qyy / scale;
% imagesc(X)
% if method == 1
% img = interp2(Y,X,double(img),qyy,qxx);
% else
% img = griddata(qyy,qxx,double(img),Y,X);
% end
end
+100
View File
@@ -0,0 +1,100 @@
% PROP_TILTED_PLANE Near field propagation into a surface tilted with respect to the beam
%
% [u_1, H, h_tilted] = prop_free_tilted_plane(u_0, z, lambda, pixel_size, ax=1)
% returns the propagated wavefield
% Inputs:
% **u_0 stack of images
% **rotation [alpha, beta] - along first, second axis [deg]
% **lambda wavelenght [m]
% **pixel_size pixel size [m] - in the rotated coordinates, ie. pixel size can be anisotropic
% *returns*
% ++u_1 propagated stack of images
%
% see utils.prop_free_tilted_plane for more details
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function [fwd_propag, back_propag] = get_tilted_plane_propagators(img_sample, rotation, lambda, pixel_size)
%% nearfield propagator into tilted plane
import utils.*
fwd_propag = @(x)x;
back_propag = @(x)x;
if all(rotation == 0)
return
end
Npix = size(img_sample);
if any(rotation(1:2)~= 0 )
% provide tilt of the sample
assert(sum(rotation(1:2)~=0) < 2, 'Only rotation along one axis is supported')
ax = find(rotation(1:2)~=0);
% propagation distance for each row / column to reach the tilted plane
% extend * cosd(alpha) * tand(alpha)
grid = ((-Npix(ax)/2+1):Npix(ax)/2)*pixel_size(min(ax,end)) * sind(rotation(ax));
[~, H, h_tilted] = prop_free_nonparallel_plane(zeros(Npix(1:2), 'like', img_sample), grid, lambda, pixel_size, ax);
% precalculate conjuged and transposed matrices
H_t = H.'*1; % enforce copy
Hc = conj(H);
Hc_t = Hc.'*1;
h_tilted_t = h_tilted'*1; % enforce copy
%%%%%%%%%%%%%% propagate the image, see utils.prop_free_tilted_plane for more details %%%%%%%%%%%%%%%%%%%%%
if ax == 1
fwd_propag = @(x)(utils.mtimes_stack(h_tilted,ifft(H_t .* fft(x,[],2),[],2)));
back_propag = @(x)(ifft(Hc_t.*fft(utils.mtimes_stack(h_tilted_t,x),[],2),[],2));
else
fwd_propag = @(x)(utils.mtimes_stack(ifft(H .* fft(x,[],1),[],1),h_tilted));
back_propag = @(x)(ifft(Hc.*fft(utils.mtimes_stack(x,h_tilted_t),[],1),[],1));
end
end
if rotation(3)~= 0
% rotate image around beam axis
fwd_propag = @(x)fwd_propag(utils.imrotate_ax_fft(x, rotation(3), 3));
back_propag = @(x)back_propag(utils.imrotate_ax_fft(x, -rotation(3), 3));
end
end
Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 438 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 234 KiB

+89
View File
@@ -0,0 +1,89 @@
% IS_USED Check if the extension/extensions is set to be used
%
% used = is_used(param, extension)
% Example: is_used(param, {'ext1', 'ext2'})
%
% ++ param parametrer structure
% ++ extension string or cell of the extension names
% returns:
% ** used bool if method is used
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for mixed coherent modes:
% P. Thibault and A. Menzel, Reconstructing state mixtures from diffraction measurements, Nature 494, 6871 (2013). (doi: 10.1038/nature11806),
% for LSQ-ML method
% M. Odstrcil, A. Menzel, M.G. Sicairos, Iterative least-squares solver for generalized maximum-likelihood ptychography, Optics Express, 2018
% for OPRP method
% M. Odstrcil, P. Baksh, S. A. Boden, R. Card, J. E. Chad, J. G. Frey, W. S. Brocklesby, "Ptychographic coherent diffractive imaging with orthogonal probe relaxation." Optics express 24.8 (2016): 8360-8369
% and/or for multislice:
% E. H. R. Tsai, I. Usov, A. Diaz, A. Menzel, and M. Guizar-Sicairos, X-ray ptychography with extended depth of field, Opt. Express 24, 2908929108 (2016).
% 6. Except for the above-mentioned acknowledgment, LICENSEE shall not use the PROGRAM title or the names or logos of LICENSOR, nor any adaptation thereof, nor the
% names of any of its employees or laboratories, in any advertising, promotional or sales material without prior written consent obtained from LICENSOR in each case.
% 7. Ownership of all rights, including copyright in the PROGRAM and in any material associated therewith, shall at all times remain with LICENSOR, and LICENSEE
% agrees to preserve same. LICENSEE agrees not to use any portion of the PROGRAM or of any IMPROVEMENTS in any machine-readable form outside the PROGRAM, nor to
% make any copies except for its internal use, without prior written consent of LICENSOR. LICENSEE agrees to place the following copyright notice on any such copies:
% © All rights reserved. PAUL SCHERRER INSTITUT, Switzerland, Laboratory for Macromolecules and Bioimaging, 2017.
% 8. The LICENSE shall not be construed to confer any rights upon LICENSEE by implication or otherwise except as specifically set forth herein.
% 9. DISCLAIMER: LICENSEE shall be aware that Phase Focus Limited of Sheffield, UK has an international portfolio of patents and pending applications which relate
% to ptychography and that the PROGRAM may be capable of being used in circumstances which may fall within the claims of one or more of the Phase Focus patents,
% in particular of patent with international application number PCT/GB2005/001464. The LICENSOR explicitly declares not to indemnify the users of the software
% in case Phase Focus or any other third party will open a legal action against the LICENSEE due to the use of the program.
% 10. This Agreement shall be governed by the material laws of Switzerland and any dispute arising out of this Agreement or use of the PROGRAM shall be brought before
% the courts of Zürich, Switzerland.
%
%
function used = is_used(param, extension)
if ~isfield(param, 'extension'); used = false; return ; end
if ~iscell(param.extension) && ~iscell(extension)
used = strcmpi(param.extension, extension);
else
if ~iscell(extension)
extension = {extension};
end
if ~iscell( param.extension)
param.extension = {param.extension};
end
used = false;
for i = 1:length(param.extension)
for j = 1:length(extension)
used = used | strcmpi(param.extension{i}, extension{j});
if used; break; end
end
if used; break; end
end
end
end
+325
View File
@@ -0,0 +1,325 @@
%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)
%
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for maximum likelihood:
% P. Thibault and M. Guizar-Sicairos, Maximum-likelihood refinement for coherent diffractive imaging, New J. Phys. 14, 063004 (2012).
% (doi: 10.1088/1367-2630/14/6/063004),
% for mixed coherent modes:
% P. Thibault and A. Menzel, Reconstructing state mixtures from diffraction measurements, Nature 494, 6871 (2013). (doi: 10.1038/nature11806),
% and/or for multislice:
% E. H. R. Tsai, I. Usov, A. Diaz, A. Menzel, and M. Guizar-Sicairos, X-ray ptychography with extended depth of field, Opt. Express 24, 2908929108 (2016).
% (doi: 10.1364/OE.24.029089).
% 6. Except for the above-mentioned acknowledgment, LICENSEE shall not use the PROGRAM title or the names or logos of LICENSOR, nor any adaptation thereof, nor the
% names of any of its employees or laboratories, in any advertising, promotional or sales material without prior written consent obtained from LICENSOR in each case.
% 7. Ownership of all rights, including copyright in the PROGRAM and in any material associated therewith, shall at all times remain with LICENSOR, and LICENSEE
% agrees to preserve same. LICENSEE agrees not to use any portion of the PROGRAM or of any IMPROVEMENTS in any machine-readable form outside the PROGRAM, nor to
% make any copies except for its internal use, without prior written consent of LICENSOR. LICENSEE agrees to place the following copyright notice on any such copies:
% © All rights reserved. PAUL SCHERRER INSTITUT, Switzerland, Laboratory for Macromolecules and Bioimaging, 2017.
% 8. The LICENSE shall not be construed to confer any rights upon LICENSEE by implication or otherwise except as specifically set forth herein.
% 9. DISCLAIMER: LICENSEE shall be aware that Phase Focus Limited of Sheffield, UK has an international portfolio of patents and pending applications which relate
% to ptychography and that the PROGRAM may be capable of being used in circumstances which may fall within the claims of one or more of the Phase Focus patents,
% in particular of patent with international application number PCT/GB2005/001464. The LICENSOR explicitly declares not to indemnify the users of the software
% in case Phase Focus or any other third party will open a legal action against the LICENSEE due to the use of the program.
% 10. This Agreement shall be governed by the material laws of Switzerland and any dispute arising out of this Agreement or use of the PROGRAM shall be brought before
% the courts of Zürich, Switzerland.
function varargout = load_ptycho_recons( filename_with_path, varargin )
import io.HDF.hdf5_load
varargout = {};
if ~ischar(filename_with_path)
error('First argument has to be string')
end
filename_with_path = utils.abspath(filename_with_path);
if ~exist(filename_with_path, 'file')
error('Could not find reconstruction file %s', filename_with_path)
end
if nargin > 1
switch varargin{1}
case {'pr'; 'probe'; 'probes'}
section = 'probe';
case {'ob'; 'obj'; 'objects'}
section = 'object';
otherwise
section = varargin{1};
end
else
section = 'full';
end
if ~nargout
output = 0;
elseif nargout >=2
output = 2;
else
output = 1;
end
function assign_struct(val, val_name)
switch output
case 1
varargout{1}.(val_name) = val;
case 2
varargout{end+1} = val;
otherwise
assignin('base', val_name, val);
end
end
function assign_val(struc)
switch output
case 1
varargout{1} = struc;
case 2
if isfield(struc, 'object')
varargout{end+1} = struc.object;
end
if isfield(struc, 'probe')
varargout{end+1} = struc.probe;
end
if isfield(struc, 'p')
varargout{end+1} = struc.p;
end
otherwise
fn = fieldnames(struc);
for ii=1:length(fn)
assignin('base', fn{ii}, struc.(fn{ii}))
end
end
end
% check if it is a .mat file or a .cxs file
[~, ~, ext] = fileparts(filename_with_path);
switch ext
case '.mat'
switch section
case 'recon'
S = load(filename_with_path, 'object', 'probe');
assign_val(S);
case 'full'
S = load(filename_with_path);
assign_val(S);
case 'object'
S = load(filename_with_path, 'object');
assign_val(S);
case 'probe'
S = load(filename_with_path, 'probe');
size(S)
assign_val(S);
case 'p'
S = load(filename_with_path, 'p');
assign_val(S);
otherwise
error('Unknown data section %s', section);
end
case {'.cxs','.h5'}
if io.HDF.hdf5_dset_exists(filename_with_path, 'object', '/reconstruction', true)
h5_path = '/reconstruction';
else
h5_path = '';
end
% reconstruction
switch section
case 'recon'
% load object
h = hdf5_load(filename_with_path, [h5_path '/object']);
assign_struct(load_data_cell(h), 'object');
% load probe
h = hdf5_load(filename_with_path, [h5_path '/probes']);
assign_struct(load_data_cell(h), 'probe');
case 'full'
% load object
h = hdf5_load(filename_with_path, [h5_path '/object']);
assign_struct(load_data_cell(h), 'object');
% load probe
h = hdf5_load(filename_with_path, [h5_path '/probes']);
assign_struct(load_data_cell(h), 'probe');
% load p
p = convert2p(hdf5_load(filename_with_path, '/reconstruction/p', '-c'));
if io.HDF.hdf5_dset_exists(filename_with_path, 'meta_all', '/measurement', true)
p.meta = hdf5_load(filename_with_path, '/measurement/meta_all', '-c');
elseif io.HDF.hdf5_dset_exists(filename_with_path, 'spec_all', '/measurement', true)
p.meta = hdf5_load(filename_with_path, '/measurement/spec_all', '-c');
end
assign_struct(p, 'p');
case 'object'
% load object
h = hdf5_load(filename_with_path, [h5_path '/object']);
assign_struct(load_data_cell(h), 'object');
case 'probe'
% load probe
h = hdf5_load(filename_with_path, [h5_path '/probes']);
assign_struct(load_data_cell(h), 'probe');
case 'p'
% load p
p = convert2p(hdf5_load(filename_with_path, '/reconstruction/p', '-c'));
if io.HDF.hdf5_dset_exists(filename_with_path, 'meta_all', '/measurement', true)
p.meta = hdf5_load(filename_with_path, '/measurement/meta_all', '-c');
elseif io.HDF.hdf5_dset_exists(filename_with_path, 'spec_all', '/measurement', true)
p.meta = hdf5_load(filename_with_path, '/measurement/spec_all', '-c');
end
assign_struct(p, 'p');
otherwise
error('Unknown data section %s', section);
end
otherwise
error('Unknown ptycho datatype %s.', ext)
end
end
function tmp = load_data_cell(h)
fn = fieldnames(h);
num_end = str2double(subsref(strsplit(fn{1}, '_'), struct('type', '{}', 'subs',{{length(strsplit(fn{1},'_'))}})));
if length(fn)==2 && (strcmpi(fn{1}, 'i') || strcmpi(fn{1}, 'r'))
tmp = permute(h.r + 1i*h.i, [2,1,3,4]);
elseif isnumeric(num_end) && ~isnan(num_end)
for ii=1:length(fn)
if isstruct(h.(fn{ii}))
tmp{ii} = load_data_cell(h.(fn{ii}));
else
if isnumeric(h.(fn{ii}))
tmp{ii} = double(h.(fn{ii}));
else
tmp{ii} = h.(fn{ii});
end
end
end
% tmp = h;
else
for ii=1:length(fn)
if isstruct(h.(fn{ii}))
tmp.(fn{ii}) = load_data_cell(h.(fn{ii}));
else
if isnumeric(h.(fn{ii}))
tmp.(fn{ii}) = double(h.(fn{ii}));
else
tmp.(fn{ii}) = h.(fn{ii});
end
end
end
end
end
function tmp = convert2p(h)
fn = fieldnames(h);
for ii=1:length(fn)
if isstruct(h.(fn{ii}))
h.(fn{ii}) = load_data_cell(h.(fn{ii}));
elseif isnumeric(h.(fn{ii}))
h.(fn{ii}) = double(h.(fn{ii}));
else
continue;
end
end
tmp = h;
% object
for ii=1:length(h.objects)
tmp.object{ii} = permute(h.objects{ii}, [2 1 3 4]);
end
tmp = rmfield(tmp, 'objects');
% probes
pr = tmp.probes;
tmp.probes = [];
for ii=1:length(pr)
tmp.probes(:,:,ii,:) = permute(pr{ii}, [2 1 3 4]);
end
% positions
tmp.positions = transpose(tmp.positions);
tmp.positions_real = transpose(tmp.positions_real);
tmp.positions_orig = transpose(tmp.positions_orig);
% ctr
tmp.ctr = transpose(tmp.ctr);
end
+354
View File
@@ -0,0 +1,354 @@
function [X,ndx,dbg] = natsort(X,xpr,varargin) %#ok<*SPERR>
%
% Copyright (c) 2018, Stephen Cobeldick
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%
% * Redistributions of source code must retain the above copyright notice, this
% list of conditions and the following disclaimer.
%
% * Redistributions in binary form must reproduce the above copyright notice,
% this list of conditions and the following disclaimer in the documentation
% and/or other materials provided with the distribution
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
% DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
% FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
% DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
% SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
% CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
% OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
% OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
%
% Alphanumeric / Natural-Order sort the strings in a cell array of strings (1xN char).
%
% (c) 2012 Stephen Cobeldick
%
% Alphanumeric sort of a cell array of strings: sorts by character order
% and also by the values of any numbers that are within the strings. The
% default is case-insensitive ascending with integer number substrings:
% optional inputs control the sort direction, case sensitivity, and number
% matching (see the section "Number Substrings" below).
%
%%% Example:
% X = {'x2', 'x10', 'x1'};
% sort(X)
% ans = 'x1' 'x10' 'x2'
% natsort(X)
% ans = 'x1' 'x2' 'x10'
%
%%% Syntax:
% Y = natsort(X)
% Y = natsort(X,xpr)
% Y = natsort(X,xpr,<options>)
% [Y,ndx] = natsort(X,...)
% [Y,ndx,dbg] = natsort(X,...)
%
% To sort filenames or filepaths use NATSORTFILES (File Exchange 47434).
% To sort the rows of a cell array of strings use NATSORTROWS (File Exchange 47433).
%
% See also NATSORTFILES NATSORTROWS SORT CELLSTR IREGEXP REGEXP SSCANF INTMAX
%
%% Number Substrings %%
%
% By default consecutive digit characters are interpreted as an integer.
% The optional regular expression pattern <xpr> permits the numbers to also
% include a +/- sign, decimal digits, exponent E-notation, or any literal
% characters, quantifiers, or look-around requirements. For more information:
% http://www.mathworks.com/help/matlab/matlab_prog/regular-expressions.html
%
% The substrings are then parsed by SSCANF into numeric variables, using
% either the *default format '%f' or the user-supplied format specifier.
%
% This table shows some example regular expression patterns for some common
% notations and ways of writing numbers (see section "Examples" for more):
%
% <xpr> Regular | Number Substring | Number Substring | SSCANF
% Expression: | Match Examples: | Match Description: | Format Specifier:
% ==============|==================|===============================|==================
% * \d+ | 0, 1, 234, 56789 | unsigned integer | %f %u %lu %i
% --------------|------------------|-------------------------------|------------------
% (-|+)?\d+ | -1, 23, +45, 678 | integer with optional +/- sign| %f %d %ld %i
% --------------|------------------|-------------------------------|------------------
% \d+\.?\d* | 012, 3.45, 678.9 | integer or decimal | %f
% --------------|------------------|-------------------------------|------------------
% \d+|Inf|NaN | 123, 4, Inf, NaN | integer, infinite or NaN value| %f
% --------------|------------------|-------------------------------|------------------
% \d+\.\d+e\d+ | 0.123e4, 5.67e08 | exponential notation | %f
% --------------|------------------|-------------------------------|------------------
% 0[0-7]+ | 012, 03456, 0700 | octal prefix & notation | %o %i
% --------------|------------------|-------------------------------|------------------
% 0X[0-9A-F]+ | 0X0, 0XFF, 0X7C4 | hexadecimal prefix & notation | %x %i
% --------------|------------------|-------------------------------|------------------
% 0B[01]+ | 0B101, 0B0010111 | binary prefix & notation | %b (not SSCANF)
% --------------|------------------|-------------------------------|------------------
%
% The SSCANF format specifier (including %b) can include literal characters
% and skipped fields. The octal, hexadecimal and binary prefixes are optional.
% For more information: http://www.mathworks.com/help/matlab/ref/sscanf.html
%
%% Debugging Output Array %%
%
% The third output is a cell array <dbg>, to check if the numbers have
% been matched by the regular expression <rgx> and converted to numeric
% by the SSCANF format. The rows of <dbg> are linearly indexed from <X>:
%
% [~,~,dbg] = natsort(X)
% dbg =
% 'x' [ 2]
% 'x' [10]
% 'x' [ 1]
%
%% Relative Sort Order %%
%
% The sort order of the number substrings relative to the characters
% can be controlled by providing one of the following string options:
%
% Option Token:| Relative Sort Order: | Example:
% =============|======================================|====================
% 'beforechar' | numbers < char(0:end) | '1' < '#' < 'A'
% -------------|--------------------------------------|--------------------
% 'afterchar' | char(0:end) < numbers | '#' < 'A' < '1'
% -------------|--------------------------------------|--------------------
% 'asdigit' *| char(0:47) < numbers < char(48:end) | '#' < '1' < 'A'
% -------------|--------------------------------------|--------------------
%
% Note that the digit characters have character values 48 to 57, inclusive.
%
%% Examples %%
%
%%% Multiple integer substrings (e.g. release version numbers):
% B = {'v10.6', 'v9.10', 'v9.5', 'v10.10', 'v9.10.20', 'v9.10.8'};
% sort(B)
% ans = 'v10.10' 'v10.6' 'v9.10' 'v9.10.20' 'v9.10.8' 'v9.5'
% natsort(B)
% ans = 'v9.5' 'v9.10' 'v9.10.8' 'v9.10.20' 'v10.6' 'v10.10'
%
%%% Integer, decimal or Inf number substrings, possibly with +/- signs:
% C = {'test+Inf', 'test11.5', 'test-1.4', 'test', 'test-Inf', 'test+0.3'};
% sort(C)
% ans = 'test' 'test+0.3' 'test+Inf' 'test-1.4' 'test-Inf' 'test11.5'
% natsort(C, '(-|+)?(Inf|\d+\.?\d*)')
% ans = 'test' 'test-Inf' 'test-1.4' 'test+0.3' 'test11.5' 'test+Inf'
%
%%% Integer or decimal number substrings, possibly with an exponent:
% D = {'0.56e007', '', '4.3E-2', '10000', '9.8'};
% sort(D)
% ans = '' '0.56e007' '10000' '4.3E-2' '9.8'
% natsort(D, '\d+\.?\d*(E(+|-)?\d+)?')
% ans = '' '4.3E-2' '9.8' '10000' '0.56e007'
%
%%% Hexadecimal number substrings (possibly with '0X' prefix):
% E = {'a0X7C4z', 'a0X5z', 'a0X18z', 'aFz'};
% sort(E)
% ans = 'a0X18z' 'a0X5z' 'a0X7C4z' 'aFz'
% natsort(E, '(?<=a)(0X)?[0-9A-F]+', '%x')
% ans = 'a0X5z' 'aFz' 'a0X18z' 'a0X7C4z'
%
%%% Binary number substrings (possibly with '0B' prefix):
% F = {'a11111000100z', 'a0B101z', 'a0B000000000011000z', 'a1111z'};
% sort(F)
% ans = 'a0B000000000011000z' 'a0B101z' 'a11111000100z' 'a1111z'
% natsort(F, '(0B)?[01]+', '%b')
% ans = 'a0B101z' 'a1111z' 'a0B000000000011000z' 'a11111000100z'
%
%%% UINT64 number substrings (with full precision!):
% natsort({'a18446744073709551615z', 'a18446744073709551614z'}, [], '%lu')
% ans = 'a18446744073709551614z' 'a18446744073709551615z'
%
%%% Case sensitivity:
% G = {'a2', 'A20', 'A1', 'a10', 'A2', 'a1'};
% natsort(G, [], 'ignorecase') % default
% ans = 'A1' 'a1' 'a2' 'A2' 'a10' 'A20'
% natsort(G, [], 'matchcase')
% ans = 'A1' 'A2' 'A20' 'a1' 'a2' 'a10'
%
%%% Sort direction:
% H = {'2', 'a', '3', 'B', '1'};
% natsort(H, [], 'ascend') % default
% ans = '1' '2' '3' 'a' 'B'
% natsort(H, [], 'descend')
% ans = 'B' 'a' '3' '2' '1'
%
%%% Relative sort-order of number substrings compared to characters:
% V = num2cell(char(32+randperm(63)));
% cell2mat(natsort(V, [], 'asdigit')) % default
% ans = '!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_'
% cell2mat(natsort(V, [], 'beforechar'))
% ans = '0123456789!"#$%&'()*+,-./:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_'
% cell2mat(natsort(V, [], 'afterchar'))
% ans = '!"#$%&'()*+,-./:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_0123456789'
%
%% Input and Output Arguments %%
%
%%% Inputs (*=default):
% X = CellArrayOfCharRowVectors, to be sorted into natural-order.
% xpr = CharRowVector, regular expression for number substrings, '\d+'*.
% <options> tokens can be entered in any order, as many as required:
% - Sort direction: 'descend'/'ascend'*.
% - Case sensitive/insensitive matching: 'matchcase'/'ignorecase'*.
% - Relative sort of numbers: 'beforechar'/'afterchar'/'asdigit'*.
% - The SSCANF number conversion format, e.g.: '%x', '%i', '%f'*, etc.
%
%%% Outputs:
% Y = CellArrayOfCharRowVectors, <X> sorted into natural-order.
% ndx = NumericArray, such that Y = X(ndx). The same size as <X>.
% dbg = CellArray of the parsed characters and number values. Each row is
% one input char vector, linear-indexed from <X>. To help debug <xpr>.
%
% [X,ndx,dbg] = natsort(X,xpr*,<options>)
%% Input Wrangling %%
%
assert(iscell(X),'First input <X> must be a cell array.')
tmp = cellfun('isclass',X,'char') & cellfun('size',X,1)<2 & cellfun('ndims',X)<3;
assert(all(tmp(:)),'First input <X> must be a cell array of char row vectors (1xN char).')
%
% Regular expression:
if nargin<2 || isnumeric(xpr)&&isempty(xpr)
xpr = '\d+';
else
assert(ischar(xpr)&&isrow(xpr),'Second input <xpr> must be a regular expression (char row vector).')
end
%
% Optional arguments:
tmp = cellfun('isclass',varargin,'char') & 1==cellfun('size',varargin,1) & 2==cellfun('ndims',varargin);
assert(all(tmp(:)),'All optional arguments must be char row vectors (1xN char).')
% Character case matching:
ChrM = strcmpi(varargin,'matchcase');
ChrX = strcmpi(varargin,'ignorecase')|ChrM;
% Sort direction:
DrnD = strcmpi(varargin,'descend');
DrnX = strcmpi(varargin,'ascend')|DrnD;
% Relative sort-order of numbers compared to characters:
RsoB = strcmpi(varargin,'beforechar');
RsoA = strcmpi(varargin,'afterchar');
RsoX = strcmpi(varargin,'asdigit')|RsoB|RsoA;
% SSCANF conversion format:
FmtX = ~(ChrX|DrnX|RsoX);
%
if nnz(FmtX)>1
tmp = sprintf(', ''%s''',varargin{FmtX});
error('Overspecified optional arguments:%s.',tmp(2:end))
end
if nnz(DrnX)>1
tmp = sprintf(', ''%s''',varargin{DrnX});
error('Sort direction is overspecified:%s.',tmp(2:end))
end
if nnz(RsoX)>1
tmp = sprintf(', ''%s''',varargin{RsoX});
error('Relative sort-order is overspecified:%s.',tmp(2:end))
end
%
%% Split Strings %%
%
% Split strings into number and remaining substrings:
[MtS,MtE,MtC,SpC] = regexpi(X(:),xpr,'start','end','match','split',varargin{ChrX});
%
% Determine lengths:
MtcD = cellfun(@minus,MtE,MtS,'UniformOutput',false);
LenZ = cellfun('length',X(:))-cellfun(@sum,MtcD);
LenY = max(LenZ);
LenX = numel(MtC);
%
dbg = cell(LenX,LenY);
NuI = false(LenX,LenY);
ChI = false(LenX,LenY);
ChA = char(double(ChI));
%
ndx = 1:LenX;
for k = ndx(LenZ>0)
% Determine indices of numbers and characters:
ChI(k,1:LenZ(k)) = true;
if ~isempty(MtS{k})
tmp = MtE{k} - cumsum(MtcD{k});
dbg(k,tmp) = MtC{k};
NuI(k,tmp) = true;
ChI(k,tmp) = false;
end
% Transfer characters into char array:
if any(ChI(k,:))
tmp = SpC{k};
ChA(k,ChI(k,:)) = [tmp{:}];
end
end
%
%% Convert Number Substrings %%
%
if nnz(FmtX) % One format specifier
fmt = varargin{FmtX};
err = ['The supplied format results in an empty output from sscanf: ''',fmt,''''];
pct = '(?<!%)(%%)*%'; % match an odd number of % characters.
[T,S] = regexp(fmt,[pct,'(\d*)([bdiuoxfeg]|l[diuox])'],'tokens','split');
assert(isscalar(T),'Unsupported optional argument: ''%s''',fmt)
assert(isempty(T{1}{2}),'Format specifier cannot include field-width: ''%s''',fmt)
switch T{1}{3}(1)
case 'b' % binary
fmt = regexprep(fmt,[pct,'(\*?)b'],'$1%$2[01]');
val = dbg(NuI);
if numel(S{1})<2 || ~strcmpi('0B',S{1}(end-1:end))
% Remove '0B' if not specified in the format string:
val = regexprep(val,'(0B)?([01]+)','$2','ignorecase');
end
val = cellfun(@(s)sscanf(s,fmt),val, 'UniformOutput',false);
assert(~any(cellfun('isempty',val)),err)
NuA(NuI) = cellfun(@(s)sum(pow2(s-'0',numel(s)-1:-1:0)),val);
case 'l' % 64-bit
NuA(NuI) = cellfun(@(s)sscanf(s,fmt),dbg(NuI)); %slow!
otherwise % double
NuA(NuI) = sscanf(sprintf('%s\v',dbg{NuI}),[fmt,'\v']); % fast!
end
else % No format specifier -> double
NuA(NuI) = sscanf(sprintf('%s\v',dbg{NuI}),'%f\v');
end
% Note: NuA's class is determined by SSCANF or the custom binary parser.
NuA(~NuI) = 0;
NuA = reshape(NuA,LenX,LenY);
%
%% Debugging Array %%
%
if nargout>2
dbg(:) = {''};
for k = reshape(find(NuI),1,[])
dbg{k} = NuA(k);
end
for k = reshape(find(ChI),1,[])
dbg{k} = ChA(k);
end
end
%
%% Sort Columns %%
%
if ~any(ChrM) % ignorecase
ChA = upper(ChA);
end
%
ide = ndx.';
% From the last column to the first...
for n = LenY:-1:1
% ...sort the characters and number values:
[C,idc] = sort(ChA(ndx,n),1,varargin{DrnX});
[~,idn] = sort(NuA(ndx,n),1,varargin{DrnX});
% ...keep only relevant indices:
jdc = ChI(ndx(idc),n); % character
jdn = NuI(ndx(idn),n); % number
jde = ~ChI(ndx,n)&~NuI(ndx,n); % empty
% ...define the sort-order of numbers and characters:
jdo = any(RsoA)|(~any(RsoB)&C<'0');
% ...then combine these indices in the requested direction:
if any(DrnD) % descending
idx = [idc(jdc&~jdo);idn(jdn);idc(jdc&jdo);ide(jde)];
else % ascending
idx = [ide(jde);idc(jdc&jdo);idn(jdn);idc(jdc&~jdo)];
end
ndx = ndx(idx);
end
%
ndx = reshape(ndx,size(X));
X = X(ndx);
%
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+66
View File
@@ -0,0 +1,66 @@
% [] = break_check(filename)
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for maximum likelihood:
% P. Thibault and M. Guizar-Sicairos, Maximum-likelihood refinement for coherent diffractive imaging, New J. Phys. 14, 063004 (2012).
% (doi: 10.1088/1367-2630/14/6/063004),
% for mixed coherent modes:
% P. Thibault and A. Menzel, Reconstructing state mixtures from diffraction measurements, Nature 494, 6871 (2013). (doi: 10.1038/nature11806),
% and/or for multislice:
% E. H. R. Tsai, I. Usov, A. Diaz, A. Menzel, and M. Guizar-Sicairos, X-ray ptychography with extended depth of field, Opt. Express 24, 2908929108 (2016).
% (doi: 10.1364/OE.24.029089).
% 6. Except for the above-mentioned acknowledgment, LICENSEE shall not use the PROGRAM title or the names or logos of LICENSOR, nor any adaptation thereof, nor the
% names of any of its employees or laboratories, in any advertising, promotional or sales material without prior written consent obtained from LICENSOR in each case.
% 7. Ownership of all rights, including copyright in the PROGRAM and in any material associated therewith, shall at all times remain with LICENSOR, and LICENSEE
% agrees to preserve same. LICENSEE agrees not to use any portion of the PROGRAM or of any IMPROVEMENTS in any machine-readable form outside the PROGRAM, nor to
% make any copies except for its internal use, without prior written consent of LICENSOR. LICENSEE agrees to place the following copyright notice on any such copies:
% © All rights reserved. PAUL SCHERRER INSTITUT, Switzerland, Laboratory for Macromolecules and Bioimaging, 2017.
% 8. The LICENSE shall not be construed to confer any rights upon LICENSEE by implication or otherwise except as specifically set forth herein.
% 9. DISCLAIMER: LICENSEE shall be aware that Phase Focus Limited of Sheffield, UK has an international portfolio of patents and pending applications which relate
% to ptychography and that the PROGRAM may be capable of being used in circumstances which may fall within the claims of one or more of the Phase Focus patents,
% in particular of patent with international application number PCT/GB2005/001464. The LICENSOR explicitly declares not to indemnify the users of the software
% in case Phase Focus or any other third party will open a legal action against the LICENSEE due to the use of the program.
% 10. This Agreement shall be governed by the material laws of Switzerland and any dispute arising out of this Agreement or use of the PROGRAM shall be brought before
% the courts of Zürich, Switzerland.
function [] = break_check(filename)
fid = fopen(filename);
if (fid ~= -1)
fprintf('The file %s exists.',filename);
fprintf('It will be deleted now and then the program terminates.\n');
delete(filename);
error('Terminating program upon user request.');
end
return;
+118
View File
@@ -0,0 +1,118 @@
%% Data path info
asize = [128 128];
a2 = prod(asize);
%% Physical parameters for this dataset
% all lengths in meter
energy = 6.2; % Energy (in keV)
lambda = 1.2398e-9/energy; % wavelength
dr = 0.5e-6; % shell step size
lx = 10e-6; % field of view (x)
ly = 10e-6; % field of view (y)
nth = 5 ; % theta intervals in first shell
dwell_time = 0.4; % Counts per diffraction pattern in seconds
projections = 1; % Number of scans to be run
z = 7.2; % Distance from object to screen
ds = 172e-6; % Camera pixel size
dx_spec = lambda*z ./ (asize*ds); % resolution in the specimen plane
theta_offset = 0; % Offset the whole scan by this number of degrees
%% Prepare field of view
rmax = sqrt((lx/2)^2 + (ly/2)^2);
nr = 1 + floor(rmax/dr);
real_positions = [];
positions = [];
for ir=1:nr+1
rr = ir*dr;
dth = 2*pi / (nth*ir);
for ith=0:nth*ir-1
th = ith*dth + (theta_offset*pi/180);
x2 = rr * cos(th);
x1 = rr * sin(th);
if( abs(x1) >= ly/2 || (abs(x2) > lx/2) )
continue
end
real_positions(end+1,:) = [x1 x2]; %#ok<AGROW>
end
end
numpts = size(real_positions,1);
% For now: round this up
positions(:,1) = (real_positions(:,1) - min(real_positions(:,1)))./dx_spec(1);
positions(:,2) = (real_positions(:,2) - min(real_positions(:,2)))./dx_spec(2);
positions = round(positions);
object_size = asize + max(positions,[],1);
fprintf('\nNumber of points: %d\n',numpts)
fprintf('Estimated time for %d projections at %g sec per point: %g hours\n',projections,dwell_time,numpts*dwell_time*projections/3600);
fprintf('Estimated time for %d projections at %g sec per point: %g minutes\n',projections,dwell_time,numpts*dwell_time*projections/60);
%%
figure(1)
plot((positions(:,2)-max(positions(:,2))/2).*dx_spec(2).*1e6, ...
(positions(:,1)-max(positions(:,1))/2).*dx_spec(1).*1e6, 'o-')
axis xy image
title('Round\_ROI Ptychography Scan Positions(x,y) in scan plane')
xlabel('X-position (micron)'); ylabel('Y-position (micron)')
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for maximum likelihood:
% P. Thibault and M. Guizar-Sicairos, Maximum-likelihood refinement for coherent diffractive imaging, New J. Phys. 14, 063004 (2012).
% (doi: 10.1088/1367-2630/14/6/063004),
% for mixed coherent modes:
% P. Thibault and A. Menzel, Reconstructing state mixtures from diffraction measurements, Nature 494, 6871 (2013). (doi: 10.1038/nature11806),
% and/or for multislice:
% E. H. R. Tsai, I. Usov, A. Diaz, A. Menzel, and M. Guizar-Sicairos, X-ray ptychography with extended depth of field, Opt. Express 24, 2908929108 (2016).
% (doi: 10.1364/OE.24.029089).
% 6. Except for the above-mentioned acknowledgment, LICENSEE shall not use the PROGRAM title or the names or logos of LICENSOR, nor any adaptation thereof, nor the
% names of any of its employees or laboratories, in any advertising, promotional or sales material without prior written consent obtained from LICENSOR in each case.
% 7. Ownership of all rights, including copyright in the PROGRAM and in any material associated therewith, shall at all times remain with LICENSOR, and LICENSEE
% agrees to preserve same. LICENSEE agrees not to use any portion of the PROGRAM or of any IMPROVEMENTS in any machine-readable form outside the PROGRAM, nor to
% make any copies except for its internal use, without prior written consent of LICENSOR. LICENSEE agrees to place the following copyright notice on any such copies:
% © All rights reserved. PAUL SCHERRER INSTITUT, Switzerland, Laboratory for Macromolecules and Bioimaging, 2017.
% 8. The LICENSE shall not be construed to confer any rights upon LICENSEE by implication or otherwise except as specifically set forth herein.
% 9. DISCLAIMER: LICENSEE shall be aware that Phase Focus Limited of Sheffield, UK has an international portfolio of patents and pending applications which relate
% to ptychography and that the PROGRAM may be capable of being used in circumstances which may fall within the claims of one or more of the Phase Focus patents,
% in particular of patent with international application number PCT/GB2005/001464. The LICENSOR explicitly declares not to indemnify the users of the software
% in case Phase Focus or any other third party will open a legal action against the LICENSEE due to the use of the program.
% 10. This Agreement shall be governed by the material laws of Switzerland and any dispute arising out of this Agreement or use of the PROGRAM shall be brought before
% the courts of Zürich, Switzerland.
+71
View File
@@ -0,0 +1,71 @@
% change_file_names.m
% small script to remove lock files from certain scans
first_scan=2277;
last_scan=2342;
base_path='/afs/psi.ch/project/cxs/CDI/cSAXS_sxdm_2010_08_tomo/';
for ii=first_scan:last_scan
scan_str=['S',sprintf('%05d',ii)];
path=[base_path,'analysis/',scan_str,'/'];
orig_filename= [path 'e13056_cement_' scan_str 'run_1_recons.mat'];
new_filename = [path 'e13056_cement_192x192_' scan_str '_run_1_recons.mat'];
unix(['mv ' orig_filename ' ' new_filename]);
disp(['rewriting file ',orig_filename, ' into ', new_filename])
end
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for maximum likelihood:
% P. Thibault and M. Guizar-Sicairos, Maximum-likelihood refinement for coherent diffractive imaging, New J. Phys. 14, 063004 (2012).
% (doi: 10.1088/1367-2630/14/6/063004),
% for mixed coherent modes:
% P. Thibault and A. Menzel, Reconstructing state mixtures from diffraction measurements, Nature 494, 6871 (2013). (doi: 10.1038/nature11806),
% and/or for multislice:
% E. H. R. Tsai, I. Usov, A. Diaz, A. Menzel, and M. Guizar-Sicairos, X-ray ptychography with extended depth of field, Opt. Express 24, 2908929108 (2016).
% (doi: 10.1364/OE.24.029089).
% 6. Except for the above-mentioned acknowledgment, LICENSEE shall not use the PROGRAM title or the names or logos of LICENSOR, nor any adaptation thereof, nor the
% names of any of its employees or laboratories, in any advertising, promotional or sales material without prior written consent obtained from LICENSOR in each case.
% 7. Ownership of all rights, including copyright in the PROGRAM and in any material associated therewith, shall at all times remain with LICENSOR, and LICENSEE
% agrees to preserve same. LICENSEE agrees not to use any portion of the PROGRAM or of any IMPROVEMENTS in any machine-readable form outside the PROGRAM, nor to
% make any copies except for its internal use, without prior written consent of LICENSOR. LICENSEE agrees to place the following copyright notice on any such copies:
% © All rights reserved. PAUL SCHERRER INSTITUT, Switzerland, Laboratory for Macromolecules and Bioimaging, 2017.
% 8. The LICENSE shall not be construed to confer any rights upon LICENSEE by implication or otherwise except as specifically set forth herein.
% 9. DISCLAIMER: LICENSEE shall be aware that Phase Focus Limited of Sheffield, UK has an international portfolio of patents and pending applications which relate
% to ptychography and that the PROGRAM may be capable of being used in circumstances which may fall within the claims of one or more of the Phase Focus patents,
% in particular of patent with international application number PCT/GB2005/001464. The LICENSOR explicitly declares not to indemnify the users of the software
% in case Phase Focus or any other third party will open a legal action against the LICENSEE due to the use of the program.
% 10. This Agreement shall be governed by the material laws of Switzerland and any dispute arising out of this Agreement or use of the PROGRAM shall be brought before
% the courts of Zürich, Switzerland.
@@ -0,0 +1,162 @@
% Detect an interruption of the scan in the Log file
% From spec compile post_scan.mac
% = 1, if the scan is ready for processing
% = 0, if the scan was interrupted and is not yet repeated, or if the scan
% is being repeated now
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for maximum likelihood:
% P. Thibault and M. Guizar-Sicairos, Maximum-likelihood refinement for coherent diffractive imaging, New J. Phys. 14, 063004 (2012).
% (doi: 10.1088/1367-2630/14/6/063004),
% for mixed coherent modes:
% P. Thibault and A. Menzel, Reconstructing state mixtures from diffraction measurements, Nature 494, 6871 (2013). (doi: 10.1038/nature11806),
% and/or for multislice:
% E. H. R. Tsai, I. Usov, A. Diaz, A. Menzel, and M. Guizar-Sicairos, X-ray ptychography with extended depth of field, Opt. Express 24, 2908929108 (2016).
% (doi: 10.1364/OE.24.029089).
% 6. Except for the above-mentioned acknowledgment, LICENSEE shall not use the PROGRAM title or the names or logos of LICENSOR, nor any adaptation thereof, nor the
% names of any of its employees or laboratories, in any advertising, promotional or sales material without prior written consent obtained from LICENSOR in each case.
% 7. Ownership of all rights, including copyright in the PROGRAM and in any material associated therewith, shall at all times remain with LICENSOR, and LICENSEE
% agrees to preserve same. LICENSEE agrees not to use any portion of the PROGRAM or of any IMPROVEMENTS in any machine-readable form outside the PROGRAM, nor to
% make any copies except for its internal use, without prior written consent of LICENSOR. LICENSEE agrees to place the following copyright notice on any such copies:
% © All rights reserved. PAUL SCHERRER INSTITUT, Switzerland, Laboratory for Macromolecules and Bioimaging, 2017.
% 8. The LICENSE shall not be construed to confer any rights upon LICENSEE by implication or otherwise except as specifically set forth herein.
% 9. DISCLAIMER: LICENSEE shall be aware that Phase Focus Limited of Sheffield, UK has an international portfolio of patents and pending applications which relate
% to ptychography and that the PROGRAM may be capable of being used in circumstances which may fall within the claims of one or more of the Phase Focus patents,
% in particular of patent with international application number PCT/GB2005/001464. The LICENSOR explicitly declares not to indemnify the users of the software
% in case Phase Focus or any other third party will open a legal action against the LICENSEE due to the use of the program.
% 10. This Agreement shall be governed by the material laws of Switzerland and any dispute arising out of this Agreement or use of the PROGRAM shall be brought before
% the courts of Zürich, Switzerland.
function out = check_scan_interruption(specLogFile,scanno)
specLogFile = find_specLogFile(specLogFile);
cmd = sprintf('cat -n %s | grep "S %d " | cut -f 1 -d ''#''', specLogFile,scanno);
[~,sysout] = system(cmd);
arroutbegin = regexp(sysout,'[:\n]','split');
cmd = sprintf('cat -n %s | grep "X %d" | cut -f 1 -d ''#''', specLogFile,scanno);
[~,sysout] = system(cmd);
cmd = sprintf('cat -n %s | grep "X %d" | cut -f 2 -d ''#''', specLogFile,scanno);
[~,sysout_2] = system(cmd);
arroutend = regexp(sysout,'[:\n]','split');
arroutend_text = regexp(sysout_2,'[:\n]','split');
numbegin = [];
numend = [];
for ii = 1:numel(arroutbegin)-1
numbegin(ii) = str2num(arroutbegin{ii});
end
count = 1;
for ii = 1:numel(arroutend)-1
if strcmp(arroutend_text{ii}(3:end),num2str(scanno))
numend(count) = str2num(arroutend{ii});
count = count+1;
end
end
if numel(numbegin)~=numel(numend)
% The experiment is being repeated now
out = 0;
return
else
cmd = sprintf('head -n %d %s | tail -n %d|grep chk',numend(end) ,specLogFile,numend(end)-numbegin(end));
[~,sysout] = system(cmd);
errorout = regexp(sysout,'[:\n]','split');
if isempty(errorout{1})
out = 1;
else
% There was an error in this scan
out = 0;
end
return
end
% if any(strcmp(arrout,sprintf('#X %d',scanno)))
% out = true;
% else
% out = false;
% end
end
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function specLogFile = find_specLogFile(specLogFile)
while (exist(specLogFile,'file') ~= 2)
% if the variable specLogFile 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
compare_str = specLogFile;
fname = dir(specLogFile);
if (exist(specLogFile,'dir'))
if (specLogFile(end) ~= '/')
specLogFile = strcat(specLogFile,'/');
end
for ii=1:numel(fname)
if (regexp(fname(ii).name,'.log$'))
specLogFile = strcat(specLogFile,'*.log');
fname = [];
break;
end
end
for ii=1:numel(fname)
if (strcmp(fname(ii).name,'log-files'))
specLogFile = strcat(specLogFile,fname(ii).name);
fname = [];
break;
end
end
for ii=1:numel(fname)
if (strcmp(fname(ii).name,'specES1'))
specLogFile = strcat(specLogFile,fname(ii).name);
break;
end
if (strcmp(fname(ii).name,'spec'))
specLogFile = strcat(specLogFile,fname(ii).name);
break;
end
end
else
if (numel(fname)>0)
[~,ii] = max(cell2mat({fname.datenum}));
specLogFile = regexprep(specLogFile,'\*\.log$',fname(ii).name);
else
error('''%s'' cannot be found.', specLogFile);
break
end
end
if (strcmp(specLogFile,compare_str))
break
end
end
end
+70
View File
@@ -0,0 +1,70 @@
% change_file_names.m
% small script to remove lock files from certain scans
first_scan=2277;
last_scan=2637;
base_path='/afs/psi.ch/project/cxs/CDI/cSAXS_sxdm_2010_08_tomo/';
for ii=first_scan:last_scan
scan_str=['S',sprintf('%05d',ii)];
path=[base_path,'analysis/',scan_str,'/'];
filename= [path 'e13056_cement_192x192_' scan_str '_run_1_recons.mat'];
if exist(filename) ~= 2
disp(['file not found: ', filename])
end
end
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for maximum likelihood:
% P. Thibault and M. Guizar-Sicairos, Maximum-likelihood refinement for coherent diffractive imaging, New J. Phys. 14, 063004 (2012).
% (doi: 10.1088/1367-2630/14/6/063004),
% for mixed coherent modes:
% P. Thibault and A. Menzel, Reconstructing state mixtures from diffraction measurements, Nature 494, 6871 (2013). (doi: 10.1038/nature11806),
% and/or for multislice:
% E. H. R. Tsai, I. Usov, A. Diaz, A. Menzel, and M. Guizar-Sicairos, X-ray ptychography with extended depth of field, Opt. Express 24, 2908929108 (2016).
% (doi: 10.1364/OE.24.029089).
% 6. Except for the above-mentioned acknowledgment, LICENSEE shall not use the PROGRAM title or the names or logos of LICENSOR, nor any adaptation thereof, nor the
% names of any of its employees or laboratories, in any advertising, promotional or sales material without prior written consent obtained from LICENSOR in each case.
% 7. Ownership of all rights, including copyright in the PROGRAM and in any material associated therewith, shall at all times remain with LICENSOR, and LICENSEE
% agrees to preserve same. LICENSEE agrees not to use any portion of the PROGRAM or of any IMPROVEMENTS in any machine-readable form outside the PROGRAM, nor to
% make any copies except for its internal use, without prior written consent of LICENSOR. LICENSEE agrees to place the following copyright notice on any such copies:
% © All rights reserved. PAUL SCHERRER INSTITUT, Switzerland, Laboratory for Macromolecules and Bioimaging, 2017.
% 8. The LICENSE shall not be construed to confer any rights upon LICENSEE by implication or otherwise except as specifically set forth herein.
% 9. DISCLAIMER: LICENSEE shall be aware that Phase Focus Limited of Sheffield, UK has an international portfolio of patents and pending applications which relate
% to ptychography and that the PROGRAM may be capable of being used in circumstances which may fall within the claims of one or more of the Phase Focus patents,
% in particular of patent with international application number PCT/GB2005/001464. The LICENSOR explicitly declares not to indemnify the users of the software
% in case Phase Focus or any other third party will open a legal action against the LICENSEE due to the use of the program.
% 10. This Agreement shall be governed by the material laws of Switzerland and any dispute arising out of this Agreement or use of the PROGRAM shall be brought before
% the courts of Zürich, Switzerland.
+134
View File
@@ -0,0 +1,134 @@
% 14-11-2012
% Integrates frames from a loopscan
%
% Syntax:
% [int] = integrate_frames(base_path,scan_num,plotfigure,det_num,savedata,maskfilename)
% Needed parameters: base_path (e.g. '~/Data10/')
% scan_num (scan number)
% Optional parameters: plotfigure (figure number for fial 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)
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for maximum likelihood:
% P. Thibault and M. Guizar-Sicairos, Maximum-likelihood refinement for coherent diffractive imaging, New J. Phys. 14, 063004 (2012).
% (doi: 10.1088/1367-2630/14/6/063004),
% for mixed coherent modes:
% P. Thibault and A. Menzel, Reconstructing state mixtures from diffraction measurements, Nature 494, 6871 (2013). (doi: 10.1038/nature11806),
% and/or for multislice:
% E. H. R. Tsai, I. Usov, A. Diaz, A. Menzel, and M. Guizar-Sicairos, X-ray ptychography with extended depth of field, Opt. Express 24, 2908929108 (2016).
% (doi: 10.1364/OE.24.029089).
% 6. Except for the above-mentioned acknowledgment, LICENSEE shall not use the PROGRAM title or the names or logos of LICENSOR, nor any adaptation thereof, nor the
% names of any of its employees or laboratories, in any advertising, promotional or sales material without prior written consent obtained from LICENSOR in each case.
% 7. Ownership of all rights, including copyright in the PROGRAM and in any material associated therewith, shall at all times remain with LICENSOR, and LICENSEE
% agrees to preserve same. LICENSEE agrees not to use any portion of the PROGRAM or of any IMPROVEMENTS in any machine-readable form outside the PROGRAM, nor to
% make any copies except for its internal use, without prior written consent of LICENSOR. LICENSEE agrees to place the following copyright notice on any such copies:
% © All rights reserved. PAUL SCHERRER INSTITUT, Switzerland, Laboratory for Macromolecules and Bioimaging, 2017.
% 8. The LICENSE shall not be construed to confer any rights upon LICENSEE by implication or otherwise except as specifically set forth herein.
% 9. DISCLAIMER: LICENSEE shall be aware that Phase Focus Limited of Sheffield, UK has an international portfolio of patents and pending applications which relate
% to ptychography and that the PROGRAM may be capable of being used in circumstances which may fall within the claims of one or more of the Phase Focus patents,
% in particular of patent with international application number PCT/GB2005/001464. The LICENSOR explicitly declares not to indemnify the users of the software
% in case Phase Focus or any other third party will open a legal action against the LICENSEE due to the use of the program.
% 10. This Agreement shall be governed by the material laws of Switzerland and any dispute arising out of this Agreement or use of the PROGRAM shall be brought before
% the courts of Zürich, Switzerland.
function [int] = integrate_frames(base_path,scan_num,plotfigure,det_num,savedata,maskfile)
import beamline.pilatus_valid_pixel_roi
import io.image_read
import io.spec_read
import plotting.integrate_frames
if exist('det_num') == 0
det_num=1;
end
if exist('savedata') == 0
savedata=0;
end
if exist('maskfile') == 0
maskfile=[];
end
if exist('plotfigure') == 0
plotfigure = 0;
end
%maskfile=[];
if savedata
savefolder=[base_path 'analysis/integrated_frames/'];
if savefolder ~= 7
mkdir(savefolder)
end
end
path=sprintf('%spilatus_%01d',base_path,det_num);
filename0=compile_x12sa_filename(scan_num,0);
data0=image_read(filename0);
img0=data0.data;
dims=size(img0);
S=spec_read(base_path,'ScanNr',scan_num);
num=size(S.bpm4i,1);
if ~isempty(maskfile)
load(maskfile)
valid_mask = pilatus_valid_pixel_roi(valid_mask,'RoiSize',size(img0));
mask = zeros(size(img0));
mask(valid_mask.indices) = 1;
else
mask = ones(size(img0));
end
int=img0*0;
stack=zeros(dims(1),dims(2),num);
for jj=1:num
filename=compile_x12sa_filename(scan_num,jj-1);
data1=image_read(filename);
img=data1.data.*mask;
int=int+img;
stack(:,:,jj)=img;
end
if plotfigure ~= 0
figure(plotfigure)
figure_position=[187 295 817 650];
set(gcf,'Position',figure_position);
imagesc(log10(int)); axis xy equal tight; colorbar; colormap jet
title(sprintf('integrated frames S%05d',scan_num))
end
if savedata
savefilename=sprintf('%s/S%05d_%01d_integrated_frames',savefolder,scan_num,det_num);
save([savefilename '.mat'],'int')
print('-f2','-djpeg','-r300',[ savefilename '.jpg'] );
print('-f2','-depsc','-r1200',[savefilename '.eps'] );
end
+180
View File
@@ -0,0 +1,180 @@
% Evaluate registration error in an angle series. Returns the error between
% subsequent images. The last image is evaluated against the first but
% flipped in x. Recieves image FT with DC in (1,1), the image should have
% had the center in center of array.
% filt_stackFT FT of stack of images, previously filtered if needed
% deltastack Estimates of positions
% xmax Vector with positions of horizontal edges of rectangular
% window for registration
% ymax Same as xmax but vertical edges of window
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for maximum likelihood:
% P. Thibault and M. Guizar-Sicairos, Maximum-likelihood refinement for coherent diffractive imaging, New J. Phys. 14, 063004 (2012).
% (doi: 10.1088/1367-2630/14/6/063004),
% for mixed coherent modes:
% P. Thibault and A. Menzel, Reconstructing state mixtures from diffraction measurements, Nature 494, 6871 (2013). (doi: 10.1038/nature11806),
% and/or for multislice:
% E. H. R. Tsai, I. Usov, A. Diaz, A. Menzel, and M. Guizar-Sicairos, X-ray ptychography with extended depth of field, Opt. Express 24, 2908929108 (2016).
% (doi: 10.1364/OE.24.029089).
% 6. Except for the above-mentioned acknowledgment, LICENSEE shall not use the PROGRAM title or the names or logos of LICENSOR, nor any adaptation thereof, nor the
% names of any of its employees or laboratories, in any advertising, promotional or sales material without prior written consent obtained from LICENSOR in each case.
% 7. Ownership of all rights, including copyright in the PROGRAM and in any material associated therewith, shall at all times remain with LICENSOR, and LICENSEE
% agrees to preserve same. LICENSEE agrees not to use any portion of the PROGRAM or of any IMPROVEMENTS in any machine-readable form outside the PROGRAM, nor to
% make any copies except for its internal use, without prior written consent of LICENSOR. LICENSEE agrees to place the following copyright notice on any such copies:
% © All rights reserved. PAUL SCHERRER INSTITUT, Switzerland, Laboratory for Macromolecules and Bioimaging, 2017.
% 8. The LICENSE shall not be construed to confer any rights upon LICENSEE by implication or otherwise except as specifically set forth herein.
% 9. DISCLAIMER: LICENSEE shall be aware that Phase Focus Limited of Sheffield, UK has an international portfolio of patents and pending applications which relate
% to ptychography and that the PROGRAM may be capable of being used in circumstances which may fall within the claims of one or more of the Phase Focus patents,
% in particular of patent with international application number PCT/GB2005/001464. The LICENSOR explicitly declares not to indemnify the users of the software
% in case Phase Focus or any other third party will open a legal action against the LICENSEE due to the use of the program.
% 10. This Agreement shall be governed by the material laws of Switzerland and any dispute arising out of this Agreement or use of the PROGRAM shall be brought before
% the courts of Zürich, Switzerland.
function [errorreg grad] = loopregerror(deltastack,filt_stackFT,xmask,ymask)
import utils.dftregistration
[nr, nc, nim] = size(filt_stackFT);
errorreg = 0;
% Compute shifted stack FT
for ii = 1:nim-1,
filt_stackFT(:,:,ii) = shiftpp3(filt_stackFT(:,:,ii),deltastack(1,ii),deltastack(2,ii));
end
filt_stack = ifft2(filt_stackFT); % Compute the stack
filt_stack = filt_stack(ymask,xmask,:); % Registration window
filt_stackp1 = filt_stack(:,:,2:end); % Slicing variable, takes more memory
% necessary for parallelizaiton
for ii = 1:nim-1 % Error of ii vs ii+1
output = dftregistration(filt_stack(:,:,ii),filt_stackp1(:,:,ii),0);
errorreg(ii) = output(1);
end
% Compute first vs last
output = dftregistration(filt_stack(:,:,end),fliplr(filt_stackp1(:,:,1)),0);
errorreg(nim) = output(1);
if nargout == 2,
grad = deltastack*0;
stepe = 1e1; % For forward derivative
Nr = ifftshift([-fix(nr/2):ceil(nr/2)-1]);
Nc = ifftshift([-fix(nc/2):ceil(nc/2)-1]);
[Nc,Nr] = meshgrid(Nc,Nr);
expx = exp(1i*2*pi*(stepe*Nc/nc));
expy = exp(1i*2*pi*(stepe*Nr/nr));
for ii = 2:nim-1,
auxim = filt_stackFT(:,:,ii).*expx; % FT{fn(x-(xn+eps))}
auxim = ifft2(auxim); % fn(x-(xn+eps)) Compute the image
auxim = auxim(ymask,xmask,:); % Registration window
output = dftregistration(auxim,filt_stackp1(:,:,ii),0);
errorregepsx = output(1); % En(xn+eps)
grad(2,ii) = grad(2,ii) + (errorregepsx - errorreg(ii))/stepe;
output = dftregistration(auxim,filt_stack(:,:,ii-1),0);
errorregepsx = output(1); % En-1(xn+eps)
grad(2,ii) = grad(2,ii) + (errorregepsx - errorreg(ii))/stepe;
auxim = filt_stackFT(:,:,ii).*expy; % FT{fn(y-(yn+eps))}
auxim = ifft2(auxim); % fn(y-(yn+eps)) Compute the image
auxim = auxim(ymask,xmask,:); % Registration window
output = dftregistration(auxim,filt_stackp1(:,:,ii),0);
errorregepsy = output(1); % En(yn+eps)
grad(1,ii) = grad(1,ii) + (errorregepsy - errorreg(ii))/stepe;
output = dftregistration(auxim,filt_stack(:,:,ii-1),0);
errorregepsy = output(1); % En-1(xn+eps)
grad(1,ii) = grad(1,ii) + (errorregepsy - errorreg(ii))/stepe;
end
% grad(1)
clear ii,
auxim = filt_stackFT(:,:,1).*expx; % FT{fn(x-(xn+eps))}
auxim = ifft2(auxim); % fn(x-(xn+eps)) Compute the image
auxim = auxim(ymask,xmask,:); % Registration window
output = dftregistration(auxim,filt_stackp1(:,:,1),0);
errorregepsx = output(1); % En(xn+eps)
grad(2,1) = grad(2,1) + (errorregepsx - errorreg(1))/stepe;
output = dftregistration(auxim,fliplr(filt_stack(:,:,nim)),0);
errorregepsx = output(1); % En-1(xn+eps)
grad(2,1) = grad(2,1) + (errorregepsx - errorreg(1))/stepe;
auxim = filt_stackFT(:,:,1).*expy; % FT{fn(y-(yn+eps))}
auxim = ifft2(auxim); % fn(y-(yn+eps)) Compute the image
auxim = auxim(ymask,xmask,:); % Registration window
output = dftregistration(auxim,filt_stackp1(:,:,1),0);
errorregepsy = output(1); % En(yn+eps)
grad(1,1) = grad(1,1) + (errorregepsy - errorreg(1))/stepe;
output = dftregistration(fliplr(auxim),filt_stack(:,:,nim),0);
errorregepsy = output(1); % En-1(xn+eps)
grad(1,1) = grad(1,1) + (errorregepsy - errorreg(1))/stepe;
%grad(nim)
auxim = filt_stackFT(:,:,nim).*expx; % FT{fn(x-(xn+eps))}
auxim = ifft2(auxim); % fn(x-(xn+eps)) Compute the image
auxim = auxim(ymask,xmask,:); % Registration window
output = dftregistration(auxim,fliplr(filt_stackp1(:,:,1)),0);
errorregepsx = output(1); % En(xn+eps)
grad(2,nim) = grad(2,nim) + (errorregepsx - errorreg(nim))/stepe;
output = dftregistration(auxim,filt_stack(:,:,nim-1),0);
errorregepsx = output(1); % En-1(xn+eps)
grad(2,nim) = grad(2,nim) + (errorregepsx - errorreg(nim))/stepe;
auxim = filt_stackFT(:,:,nim).*expy; % FT{fn(y-(yn+eps))}
auxim = ifft2(auxim); % fn(y-(yn+eps)) Compute the image
auxim = auxim(ymask,xmask,:); % Registration window
output = dftregistration(auxim,fliplr(filt_stackp1(:,:,1)),0);
errorregepsy = output(1); % En(yn+eps)
grad(1,nim) = grad(1,nim) + (errorregepsy - errorreg(nim))/stepe;
output = dftregistration(auxim,filt_stack(:,:,nim-1),0);
errorregepsy = output(1); % En-1(xn+eps)
grad(1,nim) = grad(1,nim) + (errorregepsy - errorreg(nim))/stepe;
end
errorreg = sum(errorreg),
%
% for ii = 1:nim-1,
% aux1 = ifft2(shiftpp3(filt_stackFT(:,:,ii),deltastack(1,ii),deltastack(2,ii)));
% aux2 = ifft2(shiftpp3(filt_stackFT(:,:,ii+1),deltastack(1,ii+1),deltastack(2,ii+1)));
% aux1 = aux1(ymask,xmask);
% aux2 = aux2(ymask,xmask);
% output = dftregistration(aux1,aux2,0);
% errorreg = errorreg + output(1);
% end
% INCLUDE THE LAST TO FIRST ERROR
+68
View File
@@ -0,0 +1,68 @@
scan_init=592;
scan_final=670;
for i=scan_init:scan_final
lock_filename=['/afs/psi.ch/project/cxs/CDI/cSAXS_sxdm_2010_06_tomo/analysis/S',sprintf('%05d',i),'/S',sprintf('%05d',i),'_lock'];
if exist(lock_filename, 'file')
continue
else
disp(['executing: touch ' lock_filename]);
unix(['touch ' lock_filename]);
end
end
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for maximum likelihood:
% P. Thibault and M. Guizar-Sicairos, Maximum-likelihood refinement for coherent diffractive imaging, New J. Phys. 14, 063004 (2012).
% (doi: 10.1088/1367-2630/14/6/063004),
% for mixed coherent modes:
% P. Thibault and A. Menzel, Reconstructing state mixtures from diffraction measurements, Nature 494, 6871 (2013). (doi: 10.1038/nature11806),
% and/or for multislice:
% E. H. R. Tsai, I. Usov, A. Diaz, A. Menzel, and M. Guizar-Sicairos, X-ray ptychography with extended depth of field, Opt. Express 24, 2908929108 (2016).
% (doi: 10.1364/OE.24.029089).
% 6. Except for the above-mentioned acknowledgment, LICENSEE shall not use the PROGRAM title or the names or logos of LICENSOR, nor any adaptation thereof, nor the
% names of any of its employees or laboratories, in any advertising, promotional or sales material without prior written consent obtained from LICENSOR in each case.
% 7. Ownership of all rights, including copyright in the PROGRAM and in any material associated therewith, shall at all times remain with LICENSOR, and LICENSEE
% agrees to preserve same. LICENSEE agrees not to use any portion of the PROGRAM or of any IMPROVEMENTS in any machine-readable form outside the PROGRAM, nor to
% make any copies except for its internal use, without prior written consent of LICENSOR. LICENSEE agrees to place the following copyright notice on any such copies:
% © All rights reserved. PAUL SCHERRER INSTITUT, Switzerland, Laboratory for Macromolecules and Bioimaging, 2017.
% 8. The LICENSE shall not be construed to confer any rights upon LICENSEE by implication or otherwise except as specifically set forth herein.
% 9. DISCLAIMER: LICENSEE shall be aware that Phase Focus Limited of Sheffield, UK has an international portfolio of patents and pending applications which relate
% to ptychography and that the PROGRAM may be capable of being used in circumstances which may fall within the claims of one or more of the Phase Focus patents,
% in particular of patent with international application number PCT/GB2005/001464. The LICENSOR explicitly declares not to indemnify the users of the software
% in case Phase Focus or any other third party will open a legal action against the LICENSEE due to the use of the program.
% 10. This Agreement shall be governed by the material laws of Switzerland and any dispute arising out of this Agreement or use of the PROGRAM shall be brought before
% the courts of Zürich, Switzerland.
+72
View File
@@ -0,0 +1,72 @@
% remove_lock_files.m
% small script to remove lock files from certain scans
first_scan=1606;
last_scan=1786;
base_path='~/Data10/';
for ii=first_scan:last_scan
scan_str=['S',sprintf('%05d',ii)];
path=[base_path,'analysis/',scan_str,'/'];
lock_filename = [path scan_str '_lock'];
if exist(lock_filename, 'file')
unix(['rm ' lock_filename]);
disp(['removing file ',lock_filename])
else
continue
end
end
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for maximum likelihood:
% P. Thibault and M. Guizar-Sicairos, Maximum-likelihood refinement for coherent diffractive imaging, New J. Phys. 14, 063004 (2012).
% (doi: 10.1088/1367-2630/14/6/063004),
% for mixed coherent modes:
% P. Thibault and A. Menzel, Reconstructing state mixtures from diffraction measurements, Nature 494, 6871 (2013). (doi: 10.1038/nature11806),
% and/or for multislice:
% E. H. R. Tsai, I. Usov, A. Diaz, A. Menzel, and M. Guizar-Sicairos, X-ray ptychography with extended depth of field, Opt. Express 24, 2908929108 (2016).
% (doi: 10.1364/OE.24.029089).
% 6. Except for the above-mentioned acknowledgment, LICENSEE shall not use the PROGRAM title or the names or logos of LICENSOR, nor any adaptation thereof, nor the
% names of any of its employees or laboratories, in any advertising, promotional or sales material without prior written consent obtained from LICENSOR in each case.
% 7. Ownership of all rights, including copyright in the PROGRAM and in any material associated therewith, shall at all times remain with LICENSOR, and LICENSEE
% agrees to preserve same. LICENSEE agrees not to use any portion of the PROGRAM or of any IMPROVEMENTS in any machine-readable form outside the PROGRAM, nor to
% make any copies except for its internal use, without prior written consent of LICENSOR. LICENSEE agrees to place the following copyright notice on any such copies:
% © All rights reserved. PAUL SCHERRER INSTITUT, Switzerland, Laboratory for Macromolecules and Bioimaging, 2017.
% 8. The LICENSE shall not be construed to confer any rights upon LICENSEE by implication or otherwise except as specifically set forth herein.
% 9. DISCLAIMER: LICENSEE shall be aware that Phase Focus Limited of Sheffield, UK has an international portfolio of patents and pending applications which relate
% to ptychography and that the PROGRAM may be capable of being used in circumstances which may fall within the claims of one or more of the Phase Focus patents,
% in particular of patent with international application number PCT/GB2005/001464. The LICENSOR explicitly declares not to indemnify the users of the software
% in case Phase Focus or any other third party will open a legal action against the LICENSEE due to the use of the program.
% 10. This Agreement shall be governed by the material laws of Switzerland and any dispute arising out of this Agreement or use of the PROGRAM shall be brought before
% the courts of Zürich, Switzerland.
@@ -0,0 +1,79 @@
% remove_lock_files.m
% small script to remove lock files from certain scans
first_scan=411;
last_scan=1851;
%base_path='~/Data10/';
base_path='/afs/psi.ch/project/cxs/CDI/cSAXS_sxdm_2010_12_tomo/';
for ii=first_scan:2:last_scan
scan_str=['S',sprintf('%05d',ii)];
path=[base_path,'analysis/',scan_str,'/'];
lock_filename = [path scan_str '_lock'];
filename=[path 'honda_wrap_' sprintf('%05d',ii) '_400x400_run_1_recons.mat'];
if ~exist(filename, 'file')
if exist(lock_filename, 'file')
unix(['rm ' lock_filename]);
disp(['removing file ',lock_filename])
end
if ~exist(lock_filename, 'file')
disp(['warning: ' lock_filename ' does not exist']);
end
else
continue
end
end
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for maximum likelihood:
% P. Thibault and M. Guizar-Sicairos, Maximum-likelihood refinement for coherent diffractive imaging, New J. Phys. 14, 063004 (2012).
% (doi: 10.1088/1367-2630/14/6/063004),
% for mixed coherent modes:
% P. Thibault and A. Menzel, Reconstructing state mixtures from diffraction measurements, Nature 494, 6871 (2013). (doi: 10.1038/nature11806),
% and/or for multislice:
% E. H. R. Tsai, I. Usov, A. Diaz, A. Menzel, and M. Guizar-Sicairos, X-ray ptychography with extended depth of field, Opt. Express 24, 2908929108 (2016).
% (doi: 10.1364/OE.24.029089).
% 6. Except for the above-mentioned acknowledgment, LICENSEE shall not use the PROGRAM title or the names or logos of LICENSOR, nor any adaptation thereof, nor the
% names of any of its employees or laboratories, in any advertising, promotional or sales material without prior written consent obtained from LICENSOR in each case.
% 7. Ownership of all rights, including copyright in the PROGRAM and in any material associated therewith, shall at all times remain with LICENSOR, and LICENSEE
% agrees to preserve same. LICENSEE agrees not to use any portion of the PROGRAM or of any IMPROVEMENTS in any machine-readable form outside the PROGRAM, nor to
% make any copies except for its internal use, without prior written consent of LICENSOR. LICENSEE agrees to place the following copyright notice on any such copies:
% © All rights reserved. PAUL SCHERRER INSTITUT, Switzerland, Laboratory for Macromolecules and Bioimaging, 2017.
% 8. The LICENSE shall not be construed to confer any rights upon LICENSEE by implication or otherwise except as specifically set forth herein.
% 9. DISCLAIMER: LICENSEE shall be aware that Phase Focus Limited of Sheffield, UK has an international portfolio of patents and pending applications which relate
% to ptychography and that the PROGRAM may be capable of being used in circumstances which may fall within the claims of one or more of the Phase Focus patents,
% in particular of patent with international application number PCT/GB2005/001464. The LICENSOR explicitly declares not to indemnify the users of the software
% in case Phase Focus or any other third party will open a legal action against the LICENSEE due to the use of the program.
% 10. This Agreement shall be governed by the material laws of Switzerland and any dispute arising out of this Agreement or use of the PROGRAM shall be brought before
% the courts of Zürich, Switzerland.
+220
View File
@@ -0,0 +1,220 @@
% Another script for STXM evaluation of round roi scans
%
% Does not use Gaussians centered on grid points which leads to inaccuarate
% values at the center positions (due to adding up all the Gaussians)
% but rather uses the Matlab's "griddata" function.
clear all
import utils.compile_x12sa_filename
import utils.verbose
%% scan parameters
scannumber = 2370;
scans = ['S' num2str(scannumber,'%05d')];
asize = [128 128];
%pathdir = sprintf('/afs/psi.ch/project/cxs/CDI/cSAXS_sxdm_2009_05_tomo/analysis/%s/', scans);
pathdir = sprintf('../../analysis/%s/', scans);
datafile = [pathdir, sprintf('%s_data_%03dx%03d.mat', scans, asize(1), asize(2))];
scan_type = 'round_roi';
dr = 1.5e-6;
lx = 30e-6;
ly = 36e-6;
nth = 5;
dx_spec = [65.4e-9 65.4e-9];
export_figures_to_svg = 0;
%% create positions
rmax = sqrt((lx/2)^2 + (ly/2)^2);
nr = 1 + floor(rmax/dr);
positions = [];
for ir=1:nr+1
rr = ir*dr;
dth = 2*pi / (nth*ir);
for ith=0:nth*ir-1
th = ith*dth;
x1 = rr * cos(th);
x2 = rr * sin(th);
if( abs(x1) > lx/2 || (abs(x2) >= ly/2) )
continue
end
positions(end+1,:) = [x1/dx_spec(2) x2/dx_spec(2)]; %#ok<AGROW>
end
end
numpts = size(positions,1);
%% load data
if ~exist(datafile,'file')
while ~exist(compile_x12sa_filename(scannumber,numpts-1),'file');
disp(['Waiting for scan ' scans ' to finish.'])
pause(10)
end
verbose(1); core.prepare_data_2d(asize, numpts, scannumber, [100,268],'','','',147576);
end
load(datafile)
%% intialize variables for STXM analysis and upsampling
upsample =4;
ndx = ceil(upsample*(2+lx/dr));
ndy = ceil(upsample*(2+ly/dr));
[xx,yy] = meshgrid((1:ndx) - ndx/2, (1:ndy) - ndy/2);
pos = positions;
pos(:,1) = upsample*pos(:,1)*dx_spec(1)/dr;
pos(:,2) = upsample*pos(:,2)*dx_spec(2)/dr;
trans = zeros(ndy,ndx);
dpcx = zeros(ndy,ndx);
dpcy = zeros(ndy,ndx);
% put the STXM results into linear vectors first
lin_trans = zeros(numpts,1);
lin_dpcx = zeros(numpts,1);
lin_dpcy = zeros(numpts,1);
%% STXM analysis loop
for ii=1:numpts
s1 = sum(data(:,:,ii),1);
s2 = sum(data(:,:,ii),2);
Atrans = sum(s1);
Adpcx = sum(((1:asize(1))-asize(1)/2).*s1)/Atrans;
Adpcy = sum(((1:asize(1))-asize(1)/2)'.*s2)/Atrans;
lin_trans(ii) = Atrans;
lin_dpcx(ii) = Adpcx;
lin_dpcy(ii) = Adpcy;
end
%% upsample
trans=griddata(pos(:,1),pos(:,2),lin_trans,xx,yy,'linear');
dpcx_nearest=griddata(pos(:,1),pos(:,2),lin_dpcx,xx,yy,'nearest');
dpcx_linear =griddata(pos(:,1),pos(:,2),lin_dpcx,xx,yy,'linear');
%dpcy=griddata(pos(:,1),pos(:,2),lin_dpcy,xx,yy,'linear');
%I0 = mean(trans(10:20,3));
[n,x] = hist(trans(:),asize(1));
I0 = x(find(diff(n)>0,1,'last')+1);
% Compute integrated linear attenuation coefficient
mu = -log(trans./ I0 );
%% plot
%figure(1)
% scatter(positions(:,1),positions(:,2),300,lin_dpcx,'filled');
% colormap bone(256)
%colorbar
% title([scans ': scattered photons per diffraction pattern'])
% axis ij image off
% figure(2);
%imagesc(dpcx_nearest);
%axis image ij tight off
%colormap bone(256); colorbar
%title([scans ': scattered photons (upsampled by a factor of ' num2str(upsample) ', nearest neighbour interpolation)'])
%scalebar(dr,'fontsize',20, 'linewidth',10)
figure(1);
imagesc(dpcx_linear);
axis image ij tight off
colormap bone(256); colorbar
title([scans ': DPC x'])
scalebar(upsample*dx_spec(1),'fontsize',20, 'linewidth',10)
figure(4)
imagesc(trans)
axis image ij tight off
colormap bone(256); colorbar
scalebar(upsample*dx_spec(1),'fontsize',20, 'linewidth',10)
title([scans ': transmission'])
figure(5)
imagesc(mu)
axis image ij tight off
colormap bone(256); colorbar
scalebar(upsample*dx_spec(1),'fontsize',20, 'linewidth',10)
%
% roi_half = floor(upsample*nr/sqrt(2));
% roi_mask = zeros(size(trans));
% roi_mask(size(trans,1)/2-roi_half+1:size(trans,1)/2+roi_half,...
% size(trans,2)/2-roi_half+1:size(trans,2)/2+roi_half) =1;
% roi_mask(size(trans,1)/2-upsample+1:size(trans,1)/2+upsample,...
% size(trans,2)/2-upsample+1:size(trans,2)/2+upsample) =0;
%
% roi_ind = find(roi_mask == 1);
%% export figures
if export_figures_to_svg
saveas(1,fullfile(pathdir,'/S00327_dpcx_scatterplot.png'))
%plot2svg(fullfile(pathdir,'/S00327_dpcx_scatterplot.svg'),1)
plot2svg(fullfile(pathdir,'/S00327_dpcx_interpol_nearest.svg'),2)
plot2svg(fullfile(pathdir,'/S00327_dpcx_interpol_linear.svg'),3)
plot2svg(fullfile(pathdir,'/S00327_trans_interpol_linear.svg'),4)
plot2svg(fullfile(pathdir,'/S00327_abs_mu_interpol_linear.svg'),5)
disp(['Image files saved.']);
end
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for maximum likelihood:
% P. Thibault and M. Guizar-Sicairos, Maximum-likelihood refinement for coherent diffractive imaging, New J. Phys. 14, 063004 (2012).
% (doi: 10.1088/1367-2630/14/6/063004),
% for mixed coherent modes:
% P. Thibault and A. Menzel, Reconstructing state mixtures from diffraction measurements, Nature 494, 6871 (2013). (doi: 10.1038/nature11806),
% and/or for multislice:
% E. H. R. Tsai, I. Usov, A. Diaz, A. Menzel, and M. Guizar-Sicairos, X-ray ptychography with extended depth of field, Opt. Express 24, 2908929108 (2016).
% (doi: 10.1364/OE.24.029089).
% 6. Except for the above-mentioned acknowledgment, LICENSEE shall not use the PROGRAM title or the names or logos of LICENSOR, nor any adaptation thereof, nor the
% names of any of its employees or laboratories, in any advertising, promotional or sales material without prior written consent obtained from LICENSOR in each case.
% 7. Ownership of all rights, including copyright in the PROGRAM and in any material associated therewith, shall at all times remain with LICENSOR, and LICENSEE
% agrees to preserve same. LICENSEE agrees not to use any portion of the PROGRAM or of any IMPROVEMENTS in any machine-readable form outside the PROGRAM, nor to
% make any copies except for its internal use, without prior written consent of LICENSOR. LICENSEE agrees to place the following copyright notice on any such copies:
% © All rights reserved. PAUL SCHERRER INSTITUT, Switzerland, Laboratory for Macromolecules and Bioimaging, 2017.
% 8. The LICENSE shall not be construed to confer any rights upon LICENSEE by implication or otherwise except as specifically set forth herein.
% 9. DISCLAIMER: LICENSEE shall be aware that Phase Focus Limited of Sheffield, UK has an international portfolio of patents and pending applications which relate
% to ptychography and that the PROGRAM may be capable of being used in circumstances which may fall within the claims of one or more of the Phase Focus patents,
% in particular of patent with international application number PCT/GB2005/001464. The LICENSOR explicitly declares not to indemnify the users of the software
% in case Phase Focus or any other third party will open a legal action against the LICENSEE due to the use of the program.
% 10. This Agreement shall be governed by the material laws of Switzerland and any dispute arising out of this Agreement or use of the PROGRAM shall be brought before
% the courts of Zürich, Switzerland.
+104
View File
@@ -0,0 +1,104 @@
% Usage:
% function numpts = round_roi_numpts(lx,ly,dr,nth)
%
% Description:
% Calculates the number of points of a round roi scan
% for a set of parameters used in a Spec call.
%
% Parameters:
% lx = horizontal field of view in meter
% ly = vertical field of view in meter
% dr = radial shell step size in meter
% dth = angluar intervals in first shell
%
% Changelog:
% 2010-12-04, First version.
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for maximum likelihood:
% P. Thibault and M. Guizar-Sicairos, Maximum-likelihood refinement for coherent diffractive imaging, New J. Phys. 14, 063004 (2012).
% (doi: 10.1088/1367-2630/14/6/063004),
% for mixed coherent modes:
% P. Thibault and A. Menzel, Reconstructing state mixtures from diffraction measurements, Nature 494, 6871 (2013). (doi: 10.1038/nature11806),
% and/or for multislice:
% E. H. R. Tsai, I. Usov, A. Diaz, A. Menzel, and M. Guizar-Sicairos, X-ray ptychography with extended depth of field, Opt. Express 24, 2908929108 (2016).
% (doi: 10.1364/OE.24.029089).
% 6. Except for the above-mentioned acknowledgment, LICENSEE shall not use the PROGRAM title or the names or logos of LICENSOR, nor any adaptation thereof, nor the
% names of any of its employees or laboratories, in any advertising, promotional or sales material without prior written consent obtained from LICENSOR in each case.
% 7. Ownership of all rights, including copyright in the PROGRAM and in any material associated therewith, shall at all times remain with LICENSOR, and LICENSEE
% agrees to preserve same. LICENSEE agrees not to use any portion of the PROGRAM or of any IMPROVEMENTS in any machine-readable form outside the PROGRAM, nor to
% make any copies except for its internal use, without prior written consent of LICENSOR. LICENSEE agrees to place the following copyright notice on any such copies:
% © All rights reserved. PAUL SCHERRER INSTITUT, Switzerland, Laboratory for Macromolecules and Bioimaging, 2017.
% 8. The LICENSE shall not be construed to confer any rights upon LICENSEE by implication or otherwise except as specifically set forth herein.
% 9. DISCLAIMER: LICENSEE shall be aware that Phase Focus Limited of Sheffield, UK has an international portfolio of patents and pending applications which relate
% to ptychography and that the PROGRAM may be capable of being used in circumstances which may fall within the claims of one or more of the Phase Focus patents,
% in particular of patent with international application number PCT/GB2005/001464. The LICENSOR explicitly declares not to indemnify the users of the software
% in case Phase Focus or any other third party will open a legal action against the LICENSEE due to the use of the program.
% 10. This Agreement shall be governed by the material laws of Switzerland and any dispute arising out of this Agreement or use of the PROGRAM shall be brought before
% the courts of Zürich, Switzerland.
function numpts = round_roi_numpts(lx,ly,dr,nth)
if nargin~=4
help round_roi_numpts
error '4 input arguments required (see above).'
end
%% Prepare field of view
rmax = sqrt((lx/2)^2 + (ly/2)^2);
nr = 1 + floor(rmax/dr);
positions = [];
for ir=1:nr+1
rr = ir*dr;
dth = 2*pi / (nth*ir);
for ith=0:nth*ir-1
th = ith*dth; %+ (theta_offset*pi/180);
x2 = rr * cos(th);
x1 = rr * sin(th);
if( abs(x1) > ly/2 || (abs(x2) >= lx/2) )
continue
end
positions(end+1,:) = [x1 x2]; %#ok<AGROW>
end
end
numpts = size(positions,1);
% For now: round this up
positions(:,1) = positions(:,1) - min(positions(:,1));
positions(:,2) = positions(:,2) - min(positions(:,2));
positions = round(positions);
%fprintf('\nNumber of points: %d\n',numpts)
end
@@ -0,0 +1,121 @@
% [frame_unwrapped, frame_replaced_from_lowcount] = unwrap_pilatus(frame_low, frame_high, numbad, slope)
%
% unwraps the pilatus pixels that had too high intensity.
% slope and numbad are optional.
% slope should be (high exposure time / low exposure time), but can be
% evaluated from the data.
% numbad is the rough number of bad pixels - it should be greater than the actual
% value. It is used only if the slope needs to be evaluated.
%
% The first output is the result of unwrapping the high intensity counts.
% The second is equal to the high intensity frame with all wrapped values
% replaced with scaled counts from the low exposure frame. These two should
% be equal, but the first output is biased by the intensity correction done
% by the pilatus.
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for maximum likelihood:
% P. Thibault and M. Guizar-Sicairos, Maximum-likelihood refinement for coherent diffractive imaging, New J. Phys. 14, 063004 (2012).
% (doi: 10.1088/1367-2630/14/6/063004),
% for mixed coherent modes:
% P. Thibault and A. Menzel, Reconstructing state mixtures from diffraction measurements, Nature 494, 6871 (2013). (doi: 10.1038/nature11806),
% and/or for multislice:
% E. H. R. Tsai, I. Usov, A. Diaz, A. Menzel, and M. Guizar-Sicairos, X-ray ptychography with extended depth of field, Opt. Express 24, 2908929108 (2016).
% (doi: 10.1364/OE.24.029089).
% 6. Except for the above-mentioned acknowledgment, LICENSEE shall not use the PROGRAM title or the names or logos of LICENSOR, nor any adaptation thereof, nor the
% names of any of its employees or laboratories, in any advertising, promotional or sales material without prior written consent obtained from LICENSOR in each case.
% 7. Ownership of all rights, including copyright in the PROGRAM and in any material associated therewith, shall at all times remain with LICENSOR, and LICENSEE
% agrees to preserve same. LICENSEE agrees not to use any portion of the PROGRAM or of any IMPROVEMENTS in any machine-readable form outside the PROGRAM, nor to
% make any copies except for its internal use, without prior written consent of LICENSOR. LICENSEE agrees to place the following copyright notice on any such copies:
% © All rights reserved. PAUL SCHERRER INSTITUT, Switzerland, Laboratory for Macromolecules and Bioimaging, 2017.
% 8. The LICENSE shall not be construed to confer any rights upon LICENSEE by implication or otherwise except as specifically set forth herein.
% 9. DISCLAIMER: LICENSEE shall be aware that Phase Focus Limited of Sheffield, UK has an international portfolio of patents and pending applications which relate
% to ptychography and that the PROGRAM may be capable of being used in circumstances which may fall within the claims of one or more of the Phase Focus patents,
% in particular of patent with international application number PCT/GB2005/001464. The LICENSOR explicitly declares not to indemnify the users of the software
% in case Phase Focus or any other third party will open a legal action against the LICENSEE due to the use of the program.
% 10. This Agreement shall be governed by the material laws of Switzerland and any dispute arising out of this Agreement or use of the PROGRAM shall be brought before
% the courts of Zürich, Switzerland.
function varargout = unwrap_pilatus_weird(frame_low, frame_high, varargin)
ratio = .95;
max_counts = 2^20;
sz = size(frame_low);
N = numel(frame_low);
if nargin >= 3 && ~isempty(varargin{1})
ratio = varargin{1} / N;
end
slope = -1;
if nargin == 4
slope = varargin{2};
end
Nr = round(N*ratio);
% Flatten the frames
I_low = reshape(frame_low, [1 N]);
I_high = reshape(frame_high, [1 N]);
% sort
%[dum, ind] = sort(I_low);
% fit the lowest values
%if slope == -1
% slope = I_low(ind(1:Nr))'\I_high(ind(1:Nr))';
%end
%figure(10); plot(I_low(ind), I_high(ind), 'k.', [0 max_counts], [0, max_counts*slope], 'b-'); pause;
% Here we find all the out liers.
bad_guys = (I_low - I_high/slope) > 1e-1 * max_counts / slope;
%[dum, ind] = sort(I_low);
%figure(5); plot(I_low(ind), I_high(ind), 'k.', [0 max_counts], [0, max_counts*slope], 'b-', I_low(ind), I_high(ind) .* (double(bad_guys(ind)) ./ bad_guys(ind)), 'ro');
%idcut = find(bad_guys(ind),1);
%axis(2*[0 I_low(ind(idcut)) 0 slope*I_low(ind(idcut))]);
%pause;
I_high_replaced = I_high;
I_high_replaced(bad_guys) = slope*I_low(bad_guys);
varargout{1} = reshape(I_high_replaced, sz);
%figure(1); plot(I_low(ind), I_high(ind), 'k.', [0 I_low(ind(end))], [0, I_low(ind(end))*slope], 'b-', I_low(ind), I_high_unwrapped(ind),'r.', I_low(ind), I_high_replaced(ind),'m.');
return;
+120
View File
@@ -0,0 +1,120 @@
% Integrates the phase from a combination of x and y gradients.
% phase_from_dpc(dpcx,dpcy,'fourier') uses the Fourier method (default),
% phase_from_dpc(dpcx,dpcy,'finitdiff') uses a finite difference method.
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for maximum likelihood:
% P. Thibault and M. Guizar-Sicairos, Maximum-likelihood refinement for coherent diffractive imaging, New J. Phys. 14, 063004 (2012).
% (doi: 10.1088/1367-2630/14/6/063004),
% for mixed coherent modes:
% P. Thibault and A. Menzel, Reconstructing state mixtures from diffraction measurements, Nature 494, 6871 (2013). (doi: 10.1038/nature11806),
% and/or for multislice:
% E. H. R. Tsai, I. Usov, A. Diaz, A. Menzel, and M. Guizar-Sicairos, X-ray ptychography with extended depth of field, Opt. Express 24, 2908929108 (2016).
% (doi: 10.1364/OE.24.029089).
% 6. Except for the above-mentioned acknowledgment, LICENSEE shall not use the PROGRAM title or the names or logos of LICENSOR, nor any adaptation thereof, nor the
% names of any of its employees or laboratories, in any advertising, promotional or sales material without prior written consent obtained from LICENSOR in each case.
% 7. Ownership of all rights, including copyright in the PROGRAM and in any material associated therewith, shall at all times remain with LICENSOR, and LICENSEE
% agrees to preserve same. LICENSEE agrees not to use any portion of the PROGRAM or of any IMPROVEMENTS in any machine-readable form outside the PROGRAM, nor to
% make any copies except for its internal use, without prior written consent of LICENSOR. LICENSEE agrees to place the following copyright notice on any such copies:
% © All rights reserved. PAUL SCHERRER INSTITUT, Switzerland, Laboratory for Macromolecules and Bioimaging, 2017.
% 8. The LICENSE shall not be construed to confer any rights upon LICENSEE by implication or otherwise except as specifically set forth herein.
% 9. DISCLAIMER: LICENSEE shall be aware that Phase Focus Limited of Sheffield, UK has an international portfolio of patents and pending applications which relate
% to ptychography and that the PROGRAM may be capable of being used in circumstances which may fall within the claims of one or more of the Phase Focus patents,
% in particular of patent with international application number PCT/GB2005/001464. The LICENSOR explicitly declares not to indemnify the users of the software
% in case Phase Focus or any other third party will open a legal action against the LICENSEE due to the use of the program.
% 10. This Agreement shall be governed by the material laws of Switzerland and any dispute arising out of this Agreement or use of the PROGRAM shall be brought before
% the courts of Zürich, Switzerland.
function p = phase_from_dpc(dpcx,dpcy,varargin)
if nargin > 2
method = varargin{1};
else
%method = 'fourier';
method = 'finitediff';
end
px = -dpcy;
py = -dpcx;
sz = size(px);
if nargin > 3
start = varargin{2};
else
start = zeros(sz);
end
switch lower(method)
case 'fourier'
f = zeros(2*sz);
f(1:sz(1),1:sz(2)) = px + 1i*py;
f(1:sz(1),sz(2)+1:end) = fliplr(px + 1i*py);
f(sz(1)+1:end,1:sz(2)) = flipud(px + 1i*py);
f(sz(1)+1:end,sz(2)+1:end) = fliplr(flipud(px + 1i*py));
[x1,x2] = ndgrid(-sz(1):(sz(1)-1),-sz(2):(sz(2)-1));
q1 = pi*fftshift(x1)/sz(1);
q2 = pi*fftshift(x2)/sz(2);
qc = q2 - 1i*q1;
inv_qc = 1./qc;
inv_qc(1,1) = 0;
nf = ifftn(fftn(f).*inv_qc);
p = real(nf(1:sz(1),1:sz(2)));
case 'finitediff'
ggx = pgradient(dpcx);
[dum, ggy] = pgradient(dpcy);
f = .25*(ggx + ggy);
ta = start;
for i = 1:100
ta = ta + (pdel2(ta) - f);
% Zero boundary conditions
%ta(1,:) = 0;
%ta(:,1) = 0;
%ta(end,:) = 0;
%ta(:,end) = 0;
% Zero normal gradient boundary condition
ta(1,:) = ta(2,:);
ta(:,1) = ta(:,2);
ta(end,:) = ta(end-1,:);
ta(:,end) = ta(:,end-1);
if mod(i,1000)==0
figure(1); imagesc(real(ta)); colormap(bone(256)); colorbar; drawnow;
end
p = ta;
end
end
+99
View File
@@ -0,0 +1,99 @@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Unwrapping phase based on Ghiglia and Romero (1994) based on weighted and unweighted least-square method
% URL: https://doi.org/10.1364/JOSAA.11.000107
% Inputs:
% * psi: wrapped phase from -pi to pi
% * weight: weight of the phase (optional, default: all ones)
% Output:
% * phi: unwrapped phase from the weighted (or unweighted) least-square phase unwrapping
% Author: Muhammad F. Kasim (University of Oxford, 2016)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function phi = phase_unwrap(psi, weight)
if (nargin < 2) % unweighted phase unwrap
% get the wrapped differences of the wrapped values
dx = [zeros([size(psi,1),1]), wrapToPi(diff(psi, 1, 2)), zeros([size(psi,1),1])];
dy = [zeros([1,size(psi,2)]); wrapToPi(diff(psi, 1, 1)); zeros([1,size(psi,2)])];
rho = diff(dx, 1, 2) + diff(dy, 1, 1);
% get the result by solving the poisson equation
phi = solvePoisson(rho);
else % weighted phase unwrap
% check if the weight has the same size as psi
if (~all(size(weight) == size(psi)))
error('Argument error: Size of the weight must be the same as size of the wrapped phase');
end
% vector b in the paper (eq 15) is dx and dy
dx = [wrapToPi(diff(psi, 1, 2)), zeros([size(psi,1),1])];
dy = [wrapToPi(diff(psi, 1, 1)); zeros([1,size(psi,2)])];
% multiply the vector b by weight square (W^T * W)
WW = weight .* weight;
WWdx = WW .* dx;
WWdy = WW .* dy;
% applying A^T to WWdx and WWdy is like obtaining rho in the unweighted case
WWdx2 = [zeros([size(psi,1),1]), WWdx];
WWdy2 = [zeros([1,size(psi,2)]); WWdy];
rk = diff(WWdx2, 1, 2) + diff(WWdy2, 1, 1);
normR0 = norm(rk(:));
% start the iteration
eps = 1e-6;
k = 0;
phi = zeros(size(psi));
while (~all(rk == 0))
zk = solvePoisson(rk);
k = k + 1;
if (k == 1) pk = zk;
else
betak = sum(sum(rk .* zk)) / sum(sum(rkprev .* zkprev));
pk = zk + betak * pk;
end
% save the current value as the previous values
rkprev = rk;
zkprev = zk;
% perform one scalar and two vectors update
Qpk = applyQ(pk, WW);
alphak = sum(sum(rk .* zk)) / sum(sum(pk .* Qpk));
phi = phi + alphak * pk;
rk = rk - alphak * Qpk;
% check the stopping conditions
if ((k >= numel(psi)) || (norm(rk(:)) < eps * normR0)) break; end;
end
end
end
function phi = solvePoisson(rho)
% solve the poisson equation using dct
dctRho = dct2(rho);
[N, M] = size(rho);
[I, J] = meshgrid([0:M-1], [0:N-1]);
dctPhi = dctRho ./ 2 ./ (cos(pi*I/M) + cos(pi*J/N) - 2);
dctPhi(1,1) = 0; % handling the inf/nan value
% now invert to get the result
phi = idct2(dctPhi);
end
% apply the transformation (A^T)(W^T)(W)(A) to 2D matrix
function Qp = applyQ(p, WW)
% apply (A)
dx = [diff(p, 1, 2), zeros([size(p,1),1])];
dy = [diff(p, 1, 1); zeros([1,size(p,2)])];
% apply (W^T)(W)
WWdx = WW .* dx;
WWdy = WW .* dy;
% apply (A^T)
WWdx2 = [zeros([size(p,1),1]), WWdx];
WWdy2 = [zeros([1,size(p,2)]); WWdy];
Qp = diff(WWdx2,1,2) + diff(WWdy2,1,1);
end
+135
View File
@@ -0,0 +1,135 @@
% PREPARE_FLYSCAN_POSITIONS from finit number of measured position interpolate possitions for each
% measured frame when fly scan is used
%
% self = prepare_flyscan_positions(self, par)
%
%
% ** self structure containing inputs: e.g. current reconstruction results, data, mask, positions, pixel size, ..
% ** par structure containing parameters for the engines
%
% returns:
% ++ self structure containing inputs: e.g. current reconstruction results, data, mask, positions, pixel size, ..
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for mixed coherent modes:
% P. Thibault and A. Menzel, Reconstructing state mixtures from diffraction measurements, Nature 494, 6871 (2013). (doi: 10.1038/nature11806),
% for LSQ-ML method
% M. Odstrcil, A. Menzel, M.G. Sicairos, Iterative least-squares solver for generalized maximum-likelihood ptychography, Optics Express, 2018
% for OPRP method
% M. Odstrcil, P. Baksh, S. A. Boden, R. Card, J. E. Chad, J. G. Frey, W. S. Brocklesby, "Ptychographic coherent diffractive imaging with orthogonal probe relaxation." Optics express 24.8 (2016): 8360-8369
% and/or for multislice:
% E. H. R. Tsai, I. Usov, A. Diaz, A. Menzel, and M. Guizar-Sicairos, X-ray ptychography with extended depth of field, Opt. Express 24, 2908929108 (2016).
% 6. Except for the above-mentioned acknowledgment, LICENSEE shall not use the PROGRAM title or the names or logos of LICENSOR, nor any adaptation thereof, nor the
% names of any of its employees or laboratories, in any advertising, promotional or sales material without prior written consent obtained from LICENSOR in each case.
% 7. Ownership of all rights, including copyright in the PROGRAM and in any material associated therewith, shall at all times remain with LICENSOR, and LICENSEE
% agrees to preserve same. LICENSEE agrees not to use any portion of the PROGRAM or of any IMPROVEMENTS in any machine-readable form outside the PROGRAM, nor to
% make any copies except for its internal use, without prior written consent of LICENSOR. LICENSEE agrees to place the following copyright notice on any such copies:
% © All rights reserved. PAUL SCHERRER INSTITUT, Switzerland, Laboratory for Macromolecules and Bioimaging, 2017.
% 8. The LICENSE shall not be construed to confer any rights upon LICENSEE by implication or otherwise except as specifically set forth herein.
% 9. DISCLAIMER: LICENSEE shall be aware that Phase Focus Limited of Sheffield, UK has an international portfolio of patents and pending applications which relate
% to ptychography and that the PROGRAM may be capable of being used in circumstances which may fall within the claims of one or more of the Phase Focus patents,
% in particular of patent with international application number PCT/GB2005/001464. The LICENSOR explicitly declares not to indemnify the users of the software
% in case Phase Focus or any other third party will open a legal action against the LICENSEE due to the use of the program.
% 10. This Agreement shall be governed by the material laws of Switzerland and any dispute arising out of this Agreement or use of the PROGRAM shall be brought before
% the courts of Zürich, Switzerland.
function self = prepare_flyscan_positions(self, par)
import engines.GPU.GPU_wrapper.*
import math.*
import utils.*
import plotting.*
jumps = diff(self.probe_positions_0);
step = median(jumps,1);
jumps = sum(abs(jumps),2);
% empirical condition
jumps = find(jumps > 10*median(jumps));
%% ADVANCED FLY SCAN - LINE SCAN
% interpolate the other modes into new positions
%pos = self.modes{1}.probe_positions;
pos = self.probe_positions_0; %% modified by YJ, use initial position
%scatter(pos(:,1),pos(:,2),'.'); axis image
%hold on
for ll = 1:par.Nmodes
ratio = par.flyscan_dutycycle*(ll-1)/par.Nmodes;
self.modes{ll}.probe_positions = pos(min((1:self.Npos)+1,self.Npos),:)*ratio + (1-ratio)*pos;
%disp(ll)
%scatter(self.modes{ll}.probe_positions(:,1),self.modes{ll}.probe_positions(:,2),'.'); axis image
if ~isempty(jumps)
% expected step continuation
self.modes{ll}.probe_positions(jumps,:) = bsxfun(@plus, self.modes{ll}.probe_positions(jumps-1,:),step);
end
end
%% PSI code
%{
if length(jumps) < par.Nscans
% assume that smooth path is used
%% ADVANCED FLY SCAN - SPIRAL
for ii = 1:par.Nscans
assert(~any(isfinite(par.probe_position_search)), 'Position refinement and fly scans not suported')
ind = self.reconstruct_ind{ii};
pos = self.probe_positions_0(ind,:);
[ang, rad] = cart2pol(pos(:,1)-pos(1,1), pos(:,2)-pos(1,2));
ang = unwrap(ang);
% get interpolate d positions of the sub probes
ang_all = ang + (par.flyscan_offset -0.5+linspace(0,par.flyscan_dutycycle*(par.Nmodes-1)/par.Nmodes, par.Nmodes) ).*[diff(ang);0];
rad_all = interp1(ang, rad, ang_all, 'pchip');
[X,Y] = pol2cart(ang_all, rad_all);
for ll = 1:par.Nmodes
self.modes{ll}.probe_positions(ind,:) = pos(1,1:2) + [X(:,ll), Y(:,ll)];
%if iter == 1; self.probe{ll} = self.probe{1}; end
%%deleted by YJ. seems a bug
end
end
else
%% ADVANCED FLY SCAN - LINE SCAN
% interpolate the other modes into new positions
pos = self.modes{1}.probe_positions;
for ll = 1:par.Nmodes
ratio = par.flyscan_dutycycle*(ll-1)/par.Nmodes;
self.modes{ll}.probe_positions = pos(min((1:self.Npos)+1,self.Npos),:)*ratio + (1-ratio)*pos;
if ~isempty(jumps)
% expected step continuation
self.modes{ll}.probe_positions(jumps,:) = bsxfun(@plus, self.modes{ll}.probe_positions(jumps-1,:),step);
end
end
end
%}
end
+175
View File
@@ -0,0 +1,175 @@
% propagate_probe.m
% Warning: Currently working only for square pixels
%close all % Recommended if improfile will be used (there is a bug with cursor positioning otherwise)
import utils.*
% Loading reconstruction
scan = 581;
fext = '.h5';
filename=['*_recons' fext];
file = dir(fullfile('~/Data10/analysis/', utils.compile_x12sa_dirname(scan), filename));
if length(file) > 1 ; warning('Multiple files are matching'); end
% load the last reconstruction in the provided scan number
filename = fullfile(file(end).folder, file(end).name);
title_str = file(end).name;
io.load_ptycho_recons(filename);
lambda=p.lambda; % wavelength [m]
dis=p.z; % sample-detector distance [m]
asize=p.asize(1);
pixsize=p.dx_spec(1); % pixel size of final reconstruction [m]
% Axial propagation parameters - Cut through (y,z)
rangez = [-0.7e-3 0.7e-3]; % Range in meters, currently at zero
step_num = 300; % Number of steps
% Propagate to one plane
prop_dis= 1.5e-3; % chosen propagation distance
% Display option
disp = 'hsv'; % Either 'hsv', 'amp', 'phase'
x = [-asize/2 asize/2]*pixsize;
%%%
%%% Code starts
%%%
scrsz = get(0,'ScreenSize');
mask=ones(asize,asize) - (abs(probe)==0);
%probe_corr=rmphaseramp(probe,mask);
probe_corr=remove_linearphase_v2(probe,mask,20);
%probe=probe_corr;
probe_hsv(:,:,3)=abs(probe)/max(max(abs(probe)));
probe_hsv(:,:,2)=ones(asize,asize);
probe_hsv(:,:,1)=angle(probe)/(2*pi)+0.5;
figure(1);
clf
switch disp
case 'hsv'
imagesc(x*1e6,x*1e6,hsv2rgb(probe_hsv));
case 'amp'
imagesc(x*1e6,x*1e6,abs(probe));
colormap bone
case 'phase'
imagesc(x*1e6,x*1e6,angle(probe));
colormap bone
end
axis xy equal tight;
title(['Probe ' title_str], 'interpreter', 'none');
xlabel('x [\mum]')
ylabel('y [\mum]')
set(gcf,'Outerposition',[1 1 500 500])
%
propdists = linspace(rangez(1),rangez(2),step_num);
back_propag_all = prop_free_nf(probe, lambda, propdists, pixsize);
propag=squeeze(back_propag_all(asize/2,:,:));
max_int = max(max(abs(back_propag_all).^2));
propag_hsv=zeros(asize,step_num,3);
propag_hsv(:,:,3)=abs(propag)/max(max(abs(propag)));
propag_hsv(:,:,2)=ones(asize,step_num);
propag_hsv(:,:,1)=angle(propag)/(2*pi)+0.5;
figure(8);
clf
switch disp
case 'hsv'
imagesc(propdists*1e3,x*1e6,hsv2rgb(propag_hsv));
case 'amp'
imagesc(propdists*1e3,x*1e6,abs(propag));
colormap bone
case 'phase'
imagesc(propdists*1e3,x*1e6,angle(propag));
colormap bone
end
title(['Axial propagation ' title_str], 'interpreter', 'none');
xlabel('z [mm]')
ylabel('x [\mum]')
set(gcf,'Outerposition',[1 scrsz(4)-480 1000 480])
back = prop_free_nf(probe, lambda, prop_dis, pixsize);
back_hsv=zeros(asize,asize,3);
back_hsv(:,:,3)=abs(back)/max(max(abs(back)));
back_hsv(:,:,2)=ones(asize,asize);
back_hsv(:,:,1)=angle(back)/(2*pi)+0.5;
figure(2);
clf
switch disp
case 'hsv'
imagesc(x*1e6,x*1e6,hsv2rgb(back_hsv));
case 'amp'
imagesc(x*1e6,x*1e6,abs(back));
colormap bone
case 'phase'
imagesc(x*1e6,x*1e6,angle(back));
colormap bone
end
axis xy equal tight;
title(['Probe propagated to ' num2str(prop_dis*1e3) ' mm ' title_str],'interpreter', 'none');
xlabel('x [\mum]')
ylabel('y [\mum]')
set(gcf,'Outerposition',[501 1 500 500])
utils.verbose(0, '============== Focus positions: %g um =============', 1e6*propdists(math.argmax(max_int)))
%probe=back;
% save('probe_from_S00108_128x128_test_0_recons_00_propag_3_mm.mat','probe');
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for maximum likelihood:
% P. Thibault and M. Guizar-Sicairos, Maximum-likelihood refinement for coherent diffractive imaging, New J. Phys. 14, 063004 (2012).
% (doi: 10.1088/1367-2630/14/6/063004),
% for mixed coherent modes:
% P. Thibault and A. Menzel, Reconstructing state mixtures from diffraction measurements, Nature 494, 6871 (2013). (doi: 10.1038/nature11806),
% and/or for multislice:
% E. H. R. Tsai, I. Usov, A. Diaz, A. Menzel, and M. Guizar-Sicairos, X-ray ptychography with extended depth of field, Opt. Express 24, 2908929108 (2016).
% (doi: 10.1364/OE.24.029089).
% 6. Except for the above-mentioned acknowledgment, LICENSEE shall not use the PROGRAM title or the names or logos of LICENSOR, nor any adaptation thereof, nor the
% names of any of its employees or laboratories, in any advertising, promotional or sales material without prior written consent obtained from LICENSOR in each case.
% 7. Ownership of all rights, including copyright in the PROGRAM and in any material associated therewith, shall at all times remain with LICENSOR, and LICENSEE
% agrees to preserve same. LICENSEE agrees not to use any portion of the PROGRAM or of any IMPROVEMENTS in any machine-readable form outside the PROGRAM, nor to
% make any copies except for its internal use, without prior written consent of LICENSOR. LICENSEE agrees to place the following copyright notice on any such copies:
% © All rights reserved. PAUL SCHERRER INSTITUT, Switzerland, Laboratory for Macromolecules and Bioimaging, 2017.
% 8. The LICENSE shall not be construed to confer any rights upon LICENSEE by implication or otherwise except as specifically set forth herein.
% 9. DISCLAIMER: LICENSEE shall be aware that Phase Focus Limited of Sheffield, UK has an international portfolio of patents and pending applications which relate
% to ptychography and that the PROGRAM may be capable of being used in circumstances which may fall within the claims of one or more of the Phase Focus patents,
% in particular of patent with international application number PCT/GB2005/001464. The LICENSOR explicitly declares not to indemnify the users of the software
% in case Phase Focus or any other third party will open a legal action against the LICENSEE due to the use of the program.
% 10. This Agreement shall be governed by the material laws of Switzerland and any dispute arising out of this Agreement or use of the PROGRAM shall be brought before
% the courts of Zürich, Switzerland.
+79
View File
@@ -0,0 +1,79 @@
import curses
import time
import glob
import os
import numpy as np
from datetime import datetime
def update_max_len(max_len_list, val_list):
for it, val in enumerate(val_list):
if max_len_list[it]< len(val):
max_len_list[it] = len(val)
return max_len_list
def main(sc):
sc.nodelay(1)
header = 'Reconstruction monitor - cSAXS beamline'
curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)
offset_left = 1
offset_min = 5
file_path = os.path.dirname(os.path.realpath(__file__))
while True:
sc.clear()
stdscr = curses.initscr()
ln = curses.LINES
sc.addstr(0,curses.COLS//2-len(header)//2, header, curses.color_pair(2))
#sc.addstr(1, 1, time.strftime("%H:%M:%S"))
fn_list = glob.glob(file_path + '/.tmp_procID/proc_*.dat')
data = []
max_len_data = np.zeros([4])
title_lst = ['Node', 'Scan number', 'Elapsed time', 'Caller']
max_len_data = update_max_len(max_len_data, title_lst)
fn_list.sort(key=lambda x: os.stat(os.path.join('./', x)).st_mtime)
for ii,fn in enumerate(fn_list):
with open(fn, 'r') as f:
for line in f:
tmp_data = line.split()
time_diff = datetime.strptime(time.strftime("%H:%M:%S"), '%H:%M:%S') - datetime.strptime(tmp_data[3], '%H:%M:%S')
tmp_lst = [tmp_data[0], tmp_data[1], str(time_diff), tmp_data[4]]
data.append(tmp_lst)
max_len_data = update_max_len(max_len_data, tmp_lst)
sum_offset = np.zeros([5])
sum_offset[0] = offset_left
for ii,val in enumerate(title_lst):
sc.addstr(3, int(sum_offset[ii] + max_len_data[ii]//2-len(val)//2), val)
sum_offset[ii+1] = offset_min + sum_offset[ii] + max_len_data[ii]
for ii,lst in enumerate(data):
for jj, lst_val in enumerate(lst):
sc.addstr(ii+4,int(sum_offset[jj] + max_len_data[jj]//2-len(lst_val)//2), lst_val)
sc.refresh()
key = sc.getch()
if key == ord('q'):
break
elif key < 0:
time.sleep(1)
if __name__=='__main__': curses.wrapper(main)
+65
View File
@@ -0,0 +1,65 @@
% function p = set_all_engines(p, parameter, value)
% set given parameter to all engines
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for maximum likelihood:
% P. Thibault and M. Guizar-Sicairos, Maximum-likelihood refinement for coherent diffractive imaging, New J. Phys. 14, 063004 (2012).
% (doi: 10.1088/1367-2630/14/6/063004),
% for mixed coherent modes:
% P. Thibault and A. Menzel, Reconstructing state mixtures from diffraction measurements, Nature 494, 6871 (2013). (doi: 10.1038/nature11806),
% and/or for multislice:
% E. H. R. Tsai, I. Usov, A. Diaz, A. Menzel, and M. Guizar-Sicairos, X-ray ptychography with extended depth of field, Opt. Express 24, 2908929108 (2016).
% (doi: 10.1364/OE.24.029089).
% 6. Except for the above-mentioned acknowledgment, LICENSEE shall not use the PROGRAM title or the names or logos of LICENSOR, nor any adaptation thereof, nor the
% names of any of its employees or laboratories, in any advertising, promotional or sales material without prior written consent obtained from LICENSOR in each case.
% 7. Ownership of all rights, including copyright in the PROGRAM and in any material associated therewith, shall at all times remain with LICENSOR, and LICENSEE
% agrees to preserve same. LICENSEE agrees not to use any portion of the PROGRAM or of any IMPROVEMENTS in any machine-readable form outside the PROGRAM, nor to
% make any copies except for its internal use, without prior written consent of LICENSOR. LICENSEE agrees to place the following copyright notice on any such copies:
% © All rights reserved. PAUL SCHERRER INSTITUT, Switzerland, Laboratory for Macromolecules and Bioimaging, 2017.
% 8. The LICENSE shall not be construed to confer any rights upon LICENSEE by implication or otherwise except as specifically set forth herein.
% 9. DISCLAIMER: LICENSEE shall be aware that Phase Focus Limited of Sheffield, UK has an international portfolio of patents and pending applications which relate
% to ptychography and that the PROGRAM may be capable of being used in circumstances which may fall within the claims of one or more of the Phase Focus patents,
% in particular of patent with international application number PCT/GB2005/001464. The LICENSOR explicitly declares not to indemnify the users of the software
% in case Phase Focus or any other third party will open a legal action against the LICENSEE due to the use of the program.
% 10. This Agreement shall be governed by the material laws of Switzerland and any dispute arising out of this Agreement or use of the PROGRAM shall be brought before
% the courts of Zürich, Switzerland.
function p = set_all_engines(p, parameter, value)
for ieng = 1:length(p.engines)
p.engines{ieng}.(parameter) = value;
end
end
+23
View File
@@ -0,0 +1,23 @@
function [ output] = shift( input,dx_x,dx_y,px,py )
%UNTITLED Summary of this function goes here
% Detailed explanation goes here
Ny = size(input,1);
Nx = size(input,2);
dk_y = 1/(dx_y*Ny);
dk_x = 1/(dx_x*Nx);
ky = linspace(-floor(Ny/2),ceil(Ny/2)-1,Ny);
kx = linspace(-floor(Nx/2),ceil(Nx/2)-1,Nx);
[kX,kY] = meshgrid(kx,ky);
kX = kX.*dk_x;
kY = kY.*dk_y;
f = fftshift(fft2(ifftshift(input)));
f = f.*exp(-2*pi*1i*px*kX).*exp(-2*pi*1i*py*kY);
output = fftshift(ifft2(ifftshift(f)));
end
+179
View File
@@ -0,0 +1,179 @@
% show recons.m
% Warning: Currently working only for square pixels
% close all % Recommended if improfile will be used (there is a bug with cursor positioning otherwise)
% Mayor changes, basically rewritten, made on Oct 19, 2015 in order to accomodate waiting for
clear
import utils.*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Show recons parameters %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
base_path='~/Data10/';
addpath '~/Data10/matlab'
addpath ~/Data10/matlab/ptycho/
colorbarphase = [-1 1]*pi; % Give the range, or 'auto'
saveplots = 1; % Saves JPEGs of reconstruction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Parameters to find the file %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Option 1 %%% % Path + name
filefixname = []; % Provide a full path and filename. Leave empty to use the next option.
%%% Option 2 %%% % Range of scan numbers
scans = fliplr([17000:25000]); % Specify a range of scan numbers, the code will try to be smart and find the reconstructions. Leave empty to use the next option.
prefix = ''; % Define a prefix to choose one reconstruction if there are many in the folder. Leave empty to just grab the first one.
suffix = '_recons'; % Alternatively you can define a suffix.
%%% Option 3 %%% Specify an OMNY/flOMNI dat file path. The code will
% keep looking in this folder, it finds the file and moves it to the
% second folder. If the name of second folder is specified, if left
% empty it will not move it
queue_path = ['~/Data10/specES1/recontruct/done/'];
queue_path_out = ['~/Data10/specES1/recontruct/done_shown/']; % If you leave this empty it will not move the files, but then this is pretty useless, eh?
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
continuewithloop = true;
verbose(0); % Change to = 2 in order to have more output on the
varargs{1} = 'PhaseColorBarAxis';
varargs{2} = colorbarphase;
if saveplots
varargs{3} = 'ImageSaveFolder';
varargs{4} = fullfile(base_path,'analysis/online/ptycho/show_recons/');
end
scans_to_do = scans;
scans_plotted = 0;
while(~isempty(scans_to_do))
% while(continuewithloop)
if ~isempty(filefixname) % Just use the fixed name
file = filefixname;
continuewithloop = false;
plotting.ptycho_show_recons(file,varargs);
else
if isempty(scans) % Use OMNY reconstruct dat file
%%% Find file with task to plot
lookforafile = true;
verbose(1,['queue_path is active, looking for files in the queue in ' queue_path]);
while(lookforafile)
files_recons = dir([queue_path 'scan*']);
if ~isempty(files_recons)
file_dat = fullfile(queue_path,files_recons(1).name);
verbose(1,['Found file in queue ' file_dat]);
lookforafile = false;
else
verbose(1,sprintf('Did not find files in the queue: %s, pausing 10 sec',queue_path));
pause(10)
end
end
%%%
p_out = parse_queue_file(file_dat);
scanstoplot = p_out.scan_number;
% Now move the file
if ~exist(queue_path_out,'dir')
warning(sprintf('Creating folder %s',queue_path_out))
mkdir(queue_path_out);
end
verbose(1,sprintf('Moving %s to %s',file_dat,queue_path_out))
movefile(file_dat,queue_path_out)
else % Use the scan numbers provided
continuewithloop = false;
scanstoplot = scans;
end
% Ok, now it knows which scans to plot
num_orig_args = numel(varargs);
for scannum = scans_to_do%scanstoplot
file = find_ptycho_filename(base_path,scannum,prefix,suffix); % Compile name
% waitingforrecons = false;
% while(waitingforrecons)
if iscell(file)
warning('More than one file found, using the 1st one. Consider specific filename.');
file = file{1};
end
if exist(file,'file')
verbose(1,sprintf('Found %s',file));
verbose(1,'Waiting 3 sec to make sure the file is written')
pause(3)
varargs{num_orig_args+1} = 'ScanNumber';
varargs{num_orig_args+2} = scannum;
try
JavaObj = java.lang.Runtime.getRuntime;
fprintf('Free memory: %d\n', JavaObj.freeMemory/1e6)
plotting.ptycho_show_recons(file,varargs);
scans_plotted = scans_plotted+1;
save('debug11.mat','scans_plotted','scans_to_do');
catch
fprintf('failed to open file\n')
end
waitingforrecons = false;
scans_to_do(find(scans_to_do==scannum)) = [];
else
verbose(1,sprintf('Reconstruction %s not found, pausing 10 sec',file));
% pause(10)
end
% end
end
end
% end
end
return
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for maximum likelihood:
% P. Thibault and M. Guizar-Sicairos, Maximum-likelihood refinement for coherent diffractive imaging, New J. Phys. 14, 063004 (2012).
% (doi: 10.1088/1367-2630/14/6/063004),
% for mixed coherent modes:
% P. Thibault and A. Menzel, Reconstructing state mixtures from diffraction measurements, Nature 494, 6871 (2013). (doi: 10.1038/nature11806),
% and/or for multislice:
% E. H. R. Tsai, I. Usov, A. Diaz, A. Menzel, and M. Guizar-Sicairos, X-ray ptychography with extended depth of field, Opt. Express 24, 2908929108 (2016).
% (doi: 10.1364/OE.24.029089).
% 6. Except for the above-mentioned acknowledgment, LICENSEE shall not use the PROGRAM title or the names or logos of LICENSOR, nor any adaptation thereof, nor the
% names of any of its employees or laboratories, in any advertising, promotional or sales material without prior written consent obtained from LICENSOR in each case.
% 7. Ownership of all rights, including copyright in the PROGRAM and in any material associated therewith, shall at all times remain with LICENSOR, and LICENSEE
% agrees to preserve same. LICENSEE agrees not to use any portion of the PROGRAM or of any IMPROVEMENTS in any machine-readable form outside the PROGRAM, nor to
% make any copies except for its internal use, without prior written consent of LICENSOR. LICENSEE agrees to place the following copyright notice on any such copies:
% © All rights reserved. PAUL SCHERRER INSTITUT, Switzerland, Laboratory for Macromolecules and Bioimaging, 2017.
% 8. The LICENSE shall not be construed to confer any rights upon LICENSEE by implication or otherwise except as specifically set forth herein.
% 9. DISCLAIMER: LICENSEE shall be aware that Phase Focus Limited of Sheffield, UK has an international portfolio of patents and pending applications which relate
% to ptychography and that the PROGRAM may be capable of being used in circumstances which may fall within the claims of one or more of the Phase Focus patents,
% in particular of patent with international application number PCT/GB2005/001464. The LICENSOR explicitly declares not to indemnify the users of the software
% in case Phase Focus or any other third party will open a legal action against the LICENSEE due to the use of the program.
% 10. This Agreement shall be governed by the material laws of Switzerland and any dispute arising out of this Agreement or use of the PROGRAM shall be brought before
% the courts of Zürich, Switzerland.
+64
View File
@@ -0,0 +1,64 @@
function [output]=simple_nlm(input,t,f,h1,h2,selfsim)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% input : image to be filtered
% t : radius of search window
% f : radius of similarity window
% h1,h2 : w(i,j) = exp(-||GaussFilter(h1) .* (p(i) - p(j))||_2^2/h2^2)
% selfsim : w(i,i) = selfsim, for all i
%
% Note:
% if selfsim = 0, then w(i,i) = max_{j neq i} w(i,j), for all i
%
% Author: Christian Desrosiers
% Date: 07-07-2015
%
% Reimplementation of the Non-Local Means Filter by Jose Vicente Manjon-Herrera
%
% For details see:
% A. Buades, B. Coll and J.M. Morel, "A non-local algorithm for image denoising"
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[m, n]=size(input);
pixels = input(:);
s = m*n;
psize = 2*f+1;
nsize = 2*t+1;
% Compute patches
padInput = padarray(input,[f f],'symmetric');
filter = fspecial('gaussian',psize,h1);
patches = repmat(sqrt(filter(:))',[s 1]) .* im2col(padInput, [psize psize], 'sliding')';
% Compute list of edges (pixel pairs within the same search window)
indexes = reshape(1:s, m, n);
padIndexes = padarray(indexes, [t t]);
neighbors = im2col(padIndexes, [nsize, nsize], 'sliding');
TT = repmat(1:s, [nsize^2 1]);
edges = [TT(:) neighbors(:)];
RR = find(TT(:) >= neighbors(:));
edges(RR, :) = [];
% Compute weight matrix (using weighted Euclidean distance)
diff = patches(edges(:,1), :) - patches(edges(:,2), :);
V = exp(-sum(diff.*diff,2)/h2^2);
W = sparse(edges(:,1), edges(:,2), V, s, s);
% Make matrix symetric and set diagonal elements
if selfsim > 0
W = W + W' + selfsim*speye(s);
else
maxv = max(W,[],2);
W = W + W' + spdiags(maxv, 0, s, s);
end
% Normalize weights
W = spdiags(1./sum(W,2), 0, s, s)*W;
% Compute denoised image
output = W*pixels;
output = reshape(output, m , n);
+56
View File
@@ -0,0 +1,56 @@
function w = tukeywin(n,r)
%TUKEYWIN Tukey window.
% TUKEYWIN(N) returns an N-point Tukey window in a column vector.
%
% W = TUKEYWIN(N,R) returns an N-point Tukey window in a column vector. A
% Tukey window is also known as the cosine-tapered window. The R
% parameter specifies the ratio of the length of taper section to the
% total length of the window. For a Tukey window, R is normalized to 1
% (i.e., 0 < R < 1). If omitted, R is set to 0.500.
%
% If R is outside the region of (0, 1), the Tukey window degenerates into
% other common windows. Thus when R = 1, it is equivalent to a Hanning
% window. Conversely, for R = 0 the Tukey window is equivalent to a
% boxcar window.
%
% EXAMPLE:
% N = 64;
% w = tukeywin(N,0.5);
% plot(w); title('64-point Tukey window, Ratio = 0.5');
%
% See also CHEBWIN, GAUSSWIN, KAISER, WINDOW.
% Reference:
% [1] fredric j. harris [sic], On the Use of Windows for Harmonic Analysis
% with the Discrete Fourier Transform, Proceedings of the IEEE,
% Vol. 66, No. 1, January 1978, Page 67, Equation 38.
% Author(s): A. Dowd
% Copyright 1988-2005 The MathWorks, Inc.
narginchk(1,2);
% Default value for R parameter.
if nargin < 2 || isempty(r)
r = 0.500;
end
[n,w,trivialwin] = check_order(n);
if trivialwin, return, end
if r <= 0
w = ones(n,1);
elseif r >= 1
w = hann(n);
else
t = linspace(0,1,n)';
% Defines period of the taper as 1/2 period of a sine wave.
per = r/2;
tl = floor(per*(n-1))+1;
th = n-tl+1;
% Window is defined in three sections: taper, constant, taper
w = [ ((1+cos(pi/per*(t(1:tl) - per)))/2); ones(th-tl-1,1); ((1+cos(pi/per*(t(th:end) - 1 + per)))/2)];
end
% [EOF]