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,204 @@
%ALIGNED_FSC_TEMPLATE
% Script to align images and compute FSC
%
% 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).
%
addpath ../base/
% clear;
% close all;
params = struct;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Reconstruction files %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
openwithGUI = 1; % Use GUI for choosing files, otherwise specify parameters below
scan1 = [89]; % Scan number of first image
scan2 = [90]; % Scan number of second image
sample_name = ''; % File prefix
suffix = 'test_1_recons.h5'; % File suffix
analysis_folder = '../../analysis/'; % /mnt/das-gpfs/work/p12345/analysis/ % /sls/X12SA/Data10/e12345/analysis/
filenamewithpath1 = ['image1.tif']; % Give the full filename and path - Overrides the parameters above; Can be in .mat or any format supported by 'imread'
filenamewithpath2 = ['image2.tif']; % Give the full filename and path - Overrides the parameters above; Can be in .mat or any format supported by 'imread'
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Alignment parameters %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
params.verbose_level = 3; % adjust output level
params.plotting = 2; % (3) show everything, (2) show aligned images + FSC, (1) show FSC, (0) none
params.remove_ramp = 1; % Try to remove ramp from whole image before initial alignment
params.image_prop = 'phasor'; % = 'complex' or = 'phasor' (phase with unit amplitude) or = 'phase' (Note: phase should not be used if there is phase wrapping)
params.crop = 'manual';
% '' 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.flipped_images = 0; % If images are taken with a horizontal flip, e.g. 0 & 180 for tomography
params.GUIguess = 0; % To click for an initial alignment guess, ignores the values below
params.guessx = []; % Some initial guess for x alignment
params.guessy = [];
%%%%%%%%%%%%%%%%%%%%%%
%%% FSC parameters %%%
%%%%%%%%%%%%%%%%%%%%%%
params.taper = 20; % Pixels of image tapering (smoothing at edges) - Increase until the FSC does not change anymore
params.SNRt = 0.5; % 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
params.thickring = 10; % Thickness of Fourier domain ring for FSC in pixels
params.freq_thr = 0.05; % (default 0.05) To ignore the crossings before freq_thr for determining resolution
%%%%%%%%%%%%
%%% misc %%%
%%%%%%%%%%%%
params.prop_obj = false; % propagation distance at the sample plane; leave empty to use the value from the reconstruction p structure; set to "false" for no propagation
params.apod = []; % if true, applies an apodization before propagating by params.prop_obj, the apodization border is around the valid reconstruction region; leave empty to use the value from the reconstruction p structure
params.lambda = []; % wavelength; needed for propagating the object; leave empty to use the value from the reconstruction p structure
params.pixel_size = []; % pixel size at the object plane; leave empty to use the value from the reconstruction p structure
%%%%%%%%%%%%%%%%%%%%
%%% FP parameter %%%
%%%%%%%%%%%%%%%%%%%%
%%% the following parameters are ignored, unless p.fourier_ptycho==true %%%
params.filter_FFT = true; % apply a circular mask to the reconstructed spectrum (needs p.plot_maskdim)
params.crop_factor = 0.9; % crop final image by the given factor
params.crop_asize = [800 800]; % crop object before applying the FFT
params.z_lens = 49.456e-3; % FZP focal distance
%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Do not modify below %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%
caller = dbstack;
if length(caller)==1
addpath('utils')
scanfolder1 = utils.compile_x12sa_dirname(scan1(1)); % Looks for the file in this folder, I leave a variable so that the folder can be overriden
scanfolder2 = utils.compile_x12sa_dirname(scan2(1));
%%% Opening file %%%
if openwithGUI
disp('Using GUI open mode')
if exist([analysis_folder scanfolder1],'dir')
uipath1 = [analysis_folder scanfolder1];
else
uipath1 = [];
end
if exist([analysis_folder scanfolder2],'dir')
uipath2 = [analysis_folder scanfolder2];
else
uipath2 = [];
end
filetypes = {'*.h5;*.mat','Reconstruction files (*.h5,*.mat)'; '*.*', 'All Files (*.*)'};
[filename, pathname] = uigetfile(filetypes,'Open first reconstruction', uipath1);
file{1} = fullfile(pathname,filename);
[filename, pathname] = uigetfile(filetypes,'Open second reconstruction', uipath2);
file{2} = fullfile(pathname,filename);
else
% Checking recons 1 %
if ~isempty(filenamewithpath1)
file{1} = filenamewithpath1;
else
file{1} = fullfile(analysis_folder,scanfolder1,[sample_name '*' suffix]);
D = dir(file{1});
if numel(D) == 0
error(['I did not find any file: ' file{1}])
elseif numel(D) > 1
warning(['I found many files with the mask: ' file{1}]);
warning(['I selected ' D(1).name]);
end
file{1} = fullfile(analysis_folder,scanfolder1,D(1).name);
end
% Checking recons 2 %
if ~isempty(filenamewithpath2)
file{2} = filenamewithpath2;
else
file{2} = fullfile(analysis_folder,scanfolder2,[sample_name '*' suffix]);
D = dir(file{2});
if numel(D) == 0
error(['I did not find any file: ' file{2}])
elseif numel(D) > 1
warning(['I found many files with the mask: ' file{2}]);
warning(['I selected ' D(1).name]);
end
file{2} = fullfile(analysis_folder,scanfolder2,D(1).name);
end
end
% Making a JPEG of FSC
[~,filename] = fileparts(file{1});
params.out_fn = sprintf('%sonline/ptycho/%s_FSC.jpg', analysis_folder, filename);
[resolution] = aligned_FSC(file{1}, file{2}, params);
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 PtychoShelves
% 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 PtychoShelves 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
% K. Wakonig, H.-C. Stadler, M. Odstrčil, E.H.R. Tsai, A. Diaz, M. Holler, I. Usov, J. Raabe, A. Menzel, M. Guizar-Sicairos, PtychoShelves, a versatile
% high-level framework for high-performance analysis of ptychographic data, J. Appl. Cryst. 53(2) (2020). (doi: 10.1107/S1600576720001776)
% and 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 LSQ-ML:
% M. Odstrčil, A. Menzel, and M. Guizar-Sicairos, Iterative least-squares solver for generalized maximum-likelihood ptychography, Opt. Express 26(3), 3108 (2018).
% (doi: 10.1364/OE.26.003108),
% 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),
% and/or for OPRP:
% 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.
% Opt. Express 24.8 (8360-8369) 2016. (doi: 10.1364/OE.24.008360).
% 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.
+121
View File
@@ -0,0 +1,121 @@
%CALC_FSC calculate the FRC for the reconstructed scans
% ** p p structure
%
% returns:
% ++ p updated p structure
% ++ resolution FSC resolution
%
% 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 [p, resolution] = calc_FSC(p)
% get parameters from template
run('aligned_FSC_template')
crop = round(p.object_size(1,:)*0.1);
ob_good_range = {p.asize(1)/2+crop(1):p.object_size(1,1)-p.asize(1)/2-crop(1), p.asize(2)/2+crop(2):p.object_size(1,2)-p.asize(2)/2-crop(2)};
% store verbose level
verbose_lvl = utils.verbose;
% adjust structure
params.plotting = (p.plot.show_FSC+max(utils.verbose-2, 0))*p.use_display;
params.crop = ob_good_range;
params.pixel_size = p.dx_spec;
params.asize = p.asize;
params.apod = p.plot.obj_apod;
params.thickring = ceil(min(min(p.object_size-p.asize))/100); % 100 rings should be enough
params.show_summary = utils.verbose > 2;
params.image_prop = 'variation'; %% seems to provide better alignement stability then the original phasor option
utils.verbose(struct('prefix', {'analysis'}))
utils.verbose(0, 'Calculating FSC ...')
% if the original object is available, use it for comparison
if isfield(p, 'simulation') && isfield(p.simulation, 'obj')
params.fname{1} = 'Reconstruction';
params.fname{2} = 'Model';
obj{1} = prod(p.object{1}(:,:,1,:),4);
obj{2} = prod(p.simulation.obj{1}(:,:,1,:),4);
else
params.fname{1} = sprintf('S%05u', p.scan_number(1));
params.fname{2} = sprintf('S%05u', p.scan_number(2));
for ii=1:p.numobjs
obj{ii} = prod(p.object{ii}(:,:,1,:),4);
end
end
if verbose_lvl < 3
params.verbose_level = 1;
end
% update params if needed
if isfield(p, 'FSC')
params = utils.update_param(params, p.FSC);
end
resolution = aligned_FSC(obj{1}, obj{2}, params);
% restore verbose level
utils.verbose(verbose_lvl);
utils.verbose(struct('prefix', {'saving'}))
p.FSC.resolution = resolution;
p.FSC.params = params;
end
+184
View File
@@ -0,0 +1,184 @@
%PLOT_ERROR_METRIC plot evolution of the provided error metric
% ** p p structure
% ** final bool - indicates if it is final plot
% ** use_display if false, do not open figures to plot the results
%
% *returns*
% ++fig - image handle
% 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 fig4 = plot_error_metric(p, final, use_display)
if ~use_display
fig4 = plotting.smart_figure('Visible', 'off');
else
if p.plot.windowautopos && ~ishandle(4) && isfield(p.plot, 'scrsz') % position it only if the window does not exist
fig4 = plotting.smart_figure(4);
set(gcf,'Outerposition',[1 1 ceil(p.plot.scrsz(4)/p.plot.horz_fact) ceil(p.plot.scrsz(4)/2)]) %[left, bottom, width, height
else
fig4 = plotting.smart_figure(4);
end
end
% if p.numobjs==1; clf; end
Neng = length(p.engines);
Nrows = 1+p.plot.positions;
if final
eng_id = 0;
err_final = [];
for ieng=1:Neng
eng = p.engines{ieng};
if ~isfield(eng, 'error_metric_final'); continue; end
iieng = 1;
if ~iscell(eng.error_metric_final)
err_final(eng_id+1).iteration = eng.error_metric_final.iteration;
err_final(eng_id+1).value = eng.error_metric_final.value;
err_final(eng_id+1).method = eng.error_metric_final.method;
err_final(eng_id+1).err_metric = eng.error_metric_final.err_metric;
else
for iieng=1:length(eng.error_metric_final)
err_final(eng_id+iieng).iteration = eng.error_metric_final{iieng}.iteration;
err_final(eng_id+iieng).value = eng.error_metric_final{iieng}.value;
err_final(eng_id+iieng).method = eng.error_metric_final{iieng}.method;
err_final(eng_id+iieng).err_metric = eng.error_metric_final{iieng}.err_metric;
end
end
eng_id = eng_id + iieng;
end
for ieng = 1:length(err_final)
subplot(Nrows,length(err_final),ieng);
cla()
plot(err_final(ieng).iteration,err_final(ieng).value);
if ~isvector(err_final(ieng).value) % error values for each position -> plot also average
hold on
plot(err_final(ieng).iteration, mean(err_final(ieng).value,2), '-k', 'LineWidth',2)
hold off
end
title(err_final(ieng).method,'interpreter','none');
legend(err_final(ieng).err_metric)
grid on
axis tight
xlabel('Iteration')
if p.plot.log_scale(1)
set(gca, 'xscale', 'log')
end
if p.plot.log_scale(2)
if all(err_final(ieng).value > 0); set(gca, 'yscale', 'log'); end
end
if ~isempty(err_final(ieng).iteration)
xlim([0, err_final(ieng).iteration(end)])
end
end
plotting.suptitle(replace(sprintf('error: %s %s', p.plot.errtitlestring, p.plot.extratitlestring),'_', '-'), ...
'Interpreter', 'none');
elseif isfield(p, 'error_metric') && ~isempty(p.error_metric)
err = p.error_metric;
if p.plot.positions
subplot(2,1,1);
end
cla()
if iscell(err)
err = cell2mat(err);
end
if ~isempty(err(1).iteration)&&size(err,1)==2
try
subplot(2,2,1);
plot(err(1).iteration, err(1).value); grid on; title(sprintf('error\n'),'interpreter','none');
if p.plot.log_scale(1)
set(gca, 'xscale', 'log')
end
if p.plot.log_scale(2)
if all(err > 0); set(gca, 'yscale', 'log'); end
end
subplot(2,2,2);
plot(err(1).iteration(end)+err(2).iteration, log10(err(2).value),'r'); grid on
if p.plot.log_scale(1)
set(gca, 'xscale', 'log')
end
if p.plot.log_scale(2)
if all(err > 0); set(gca, 'yscale', 'log'); end
end
catch
end
else
subplot(2,2,[1 2]);
plot(err(1).iteration,err(1).value,'r'); grid on
if p.plot.log_scale(1)
set(gca, 'xscale', 'log')
end
if p.plot.log_scale(2)
if all(err(1).value > 0); set(gca, 'yscale', 'log'); end
end
axis tight
end
plotting.suptitle(sprintf('error: %s %s\n', p.plot.errtitlestring, p.plot.extratitlestring), 'Interpreter', 'none');
end
end
@@ -0,0 +1,127 @@
%PLOT_OBJECT_SPECTRUM
% plot fourier transformation of the reconstructed object
%
% ** p p structure
% ** use_display if false, dont plot results on screen
%
% *returns*
% ++fig - image handle
% 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 fig6 = plot_object_spectrum(p, use_display)
count_plotobj = 1;
[objpix] = get_object_pixel_size(p);
for obnum = 1:p.numobjs
for obmode = 1:p.object_modes
ob_plot = p.object{obnum}(:,:,obmode,:);
ob_plot = prod(ob_plot,4); % make one eDoF image
if ~p.fourier_ptycho
ob_plot = fftshift(fft2(ob_plot));
end
absob = abs(ob_plot);
if ~use_display && count_plotobj == 1
fig6 = plotting.smart_figure('Visible', 'off');
else
if count_plotobj == 1
if p.plot.windowautopos && ~ishandle(6) % position it only if the window does not exist
fig6 = plotting.smart_figure(6);
set(gcf,'Outerposition',[ceil(p.plot.scrsz(4)*2/p.plot.horz_fact)+1 ceil(p.plot.scrsz(4)/2) ceil(p.plot.scrsz(4)/p.plot.horz_fact) ceil(p.plot.scrsz(4)/2)]) %[left, bottom, width, height
else
fig6 = plotting.smart_figure(6);
end
else
set(groot,'CurrentFigure',fig6);
end
end
ax_abs(count_plotobj)=subplot(p.plot.subplwinobj(1),p.plot.subplwinobj(2),count_plotobj);
good_fov(1) = (p.object_size(obnum,1)/2 - p.asize(1)/2) .*p.dx_spec(1)*1e6;
good_fov(2) = (p.object_size(obnum,2)/2 - p.asize(2)/2) .*p.dx_spec(2)*1e6;
if ~p.plot.realaxes
imagesc(log10(absob));
else
obj_ax = {([1 p.object_size(obnum,2)]-floor(p.object_size(obnum,2)/2)+1)*objpix(2)*1e6,([1 p.object_size(obnum,1)]-floor(p.object_size(obnum,1)/2)+1)*objpix(1)*1e6};
imagesc(obj_ax{:},log10(absob));
xlabel('\mum')
ylabel('\mum')
end
colorbar
axis image xy tight
if p.share_object
title(sprintf('log10 object spectrum: %s %s', p.plot.obtitlestring, p.plot.extratitlestring),'interpreter','none');
else
title(sprintf('log10 object spectrum: %s %s', p.scan_str{obnum}, p.plot.extratitlestring),'interpreter','none');
end
count_plotobj = count_plotobj + 1;
end
end
end
+350
View File
@@ -0,0 +1,350 @@
%PLOT_OBJECTS plot reconstructed objects and layers
% ** p p structure
% ** use_display if false, dont plot results on screen
% *returns*
% ++fig - image handle
% 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 [fig1, fig2] = plot_objects(p, use_display)
import math.*
import utils.*
% prepare quadratic phase for FP backpropagation and calculate the pixel
% size
[objpix, FP_pre_phase_factor] = get_object_pixel_size(p);
% mask for backpropagation (FP only)
if p.fourier_ptycho && p.plot.filt
for ii=1:p.numobjs
ob_mask{ii} = ifftshift(filt2d_pad(p.object_size(ii,:), round(p.plot.FP_maskdim/p.dx_spec(1)*1.2), round(p.plot.FP_maskdim/p.dx_spec(1)), 'circ'));
end
end
if length(unique(p.share_object_ID)) ~= length(p.object)
% the GPU engine allows to modify the sharing within the engine and it
% can cause inconsitencies during plotting
utils.verbose(0,'Number of object does not correspond to the number of share_object_ID, resetting ... ')
if length(p.object) == 1
% assume shared scans
p.share_object_ID(:) = 1;
elseif length(p.object) == length(p.share_object_ID)
% assume unshared scans
p.share_object_ID(:) = 1:length(p.object);
else
error('Correct settings of the shared objects could not be determined')
end
end
count_plotobj = 1;
%modified by YJ for electron pty
if isfield(p,'beam_source') && strcmp(p.beam_source, 'electron')
unitFactor = 0.1;
unitLabel = 'nm';
else %X-ray
unitFactor = 1e6;
unitLabel = '\mum';
end
for obmode = 1:p.object_modes
for obnum = 1:p.numobjs
% number of layers for multilayer object reconstruction
Nlayers = size(p.object{obnum},4);
% get the new object - 2D or 3D array
ob_plot = p.object{obnum}(:,:,obmode,:);
% enforce update of the object_size
object_size(obnum,:) = [size(ob_plot,1), size(ob_plot,2)];
% get the actual reconstructed area and calculate the corresponding
% mask
ob_good_range = {p.asize(1)/2:object_size(obnum,1)-p.asize(1)/2, p.asize(2)/2:object_size(obnum,2)-p.asize(2)/2};
plot_mask = false(object_size(obnum,:));
plot_mask(ob_good_range{:},:) = true;
% remove phase offset and phase ramp (if requested)
ob_plot = utils.stabilize_phase(ob_plot, 'weight', plot_mask, ...
'remove_ramp', p.plot.remove_phase_ramp);
if p.fourier_ptycho
% propagate from lens plane to object plane
ob_plot = ifft2(ifftshift(ob_plot.*ob_mask{obnum}))*p.object_size(obnum,1).*ifftshift(FP_pre_phase_factor{obnum});
else
if p.plot.show_layers
if ~p.plot.show_layers_stack
% plot multiple layers next to each other
ob_plot = reshape(ob_plot,object_size(obnum,1), object_size(obnum,2)* Nlayers);
object_size(obnum,:) = size(ob_plot);
plot_mask = repmat(plot_mask,1,Nlayers);
else
% 3D object for imagesc3D
ob_plot = squeeze(ob_plot);
end
else
% plot single eDOF image
ob_plot = prod(ob_plot,4); % show extended depth of focus images
end
end
% apply apodization
if p.plot.obj_apod
try
filt_size = [size(ob_good_range{1},2) size(ob_good_range{2},2)];
ob_plot_size = [size(ob_plot,1),size(ob_plot,2)];
ob_plot = ob_plot.*fftshift(utils.filt2d_pad(ob_plot_size, max(1,filt_size), max(1,filt_size-min(floor(filt_size.*0.05)))));
catch
utils.verbose(2, 'Failed to apply apodization.')
end
end
% propagate object
if p.plot.prop_obj ~= 0
ob_plot = utils.prop_free_nf(ob_plot, p.lambda, p.plot.prop_obj, objpix);
end
% get complex conjugate
if p.plot.conjugate
ob_plot = conj(ob_plot);
end
% precalculate absorption and phase
absob = abs(ob_plot);
phob = angle(ob_plot);
%%%%%%%%%%%%%%%%%
%%% AMPLITUDE %%%
%%%%%%%%%%%%%%%%%
% prepare figure handle for absorption images
if ~use_display && count_plotobj == 1
fig1 = plotting.smart_figure('Visible', 'off');
else
if count_plotobj == 1
if p.plot.windowautopos && ~ishandle(1) % position it only if the window does not exist
fig1 = plotting.smart_figure(1);
set(gcf,'Outerposition',[ceil(p.plot.scrsz(4)/p.plot.horz_fact)+1 ceil(p.plot.scrsz(4)/2) ceil(p.plot.scrsz(4)/p.plot.horz_fact) ceil(p.plot.scrsz(4)/2)]) %[left, bottom, width, height
else
fig1 = plotting.smart_figure(1);
end
clf;
else
set(groot,'CurrentFigure',fig1);
end
end
ax_abs(count_plotobj)=subplot(p.plot.subplwinobj(1),p.plot.subplwinobj(2),count_plotobj);
range = [min(p.positions([p.scanidxs{p.share_object_ID == obnum}],:)), ...
max(p.positions([p.scanidxs{p.share_object_ID == obnum}],:))];
% FOV [xmin, ymin, xmax, ymax]
good_fov(1) = -(p.object_size(obnum,1)/2 - p.asize(1)/2-range(1));
good_fov(2) = -(p.object_size(obnum,2)/2 - p.asize(2)/2-range(2));
good_fov(3) = good_fov(1) + range(3)-range(1);
good_fov(4) = good_fov(2) + range(4)-range(2);
good_fov = good_fov.*p.dx_spec([1,2,1,2])*unitFactor;
fov_box = [good_fov(2),good_fov(1),good_fov(4)-good_fov(2), good_fov(3)-good_fov(1)]; % [xmin, ymin, W, H] coordinates of the FOV box
% plot the absorption
if ~p.plot.realaxes
plotting.imagesc3D(absob);
if p.plot.fov_box && ~(p.plot.show_layers && ~p.plot.show_layers_stack && Nlayers > 1)
rectangle('Position',[p.asize([2,1])/2 , p.object_size([2,1]) - p.asize([2,1])], 'EdgeColor', p.plot.fov_box_color)
end
else
obj_ax = {([1 object_size(obnum,2)]-floor(object_size(obnum,2)/2)+1)*objpix(2)*unitFactor,([1 object_size(obnum,1)]-floor(object_size(obnum,1)/2)+1)*objpix(1)*unitFactor};
plotting.imagesc3D(obj_ax{:},absob);
xlabel(unitLabel)
ylabel(unitLabel)
if p.plot.fov_box && p.plot.show_layers && ~p.plot.show_layers_stack && Nlayers > 1
% plot bar around each layer
for layer = 1:Nlayers
rectangle('Position', [good_fov(2) + (layer-(Nlayers+1)/2)*p.object_size(obnum,2).*p.dx_spec(1)*unitFactor ,good_fov(1), good_fov(4)-good_fov(2),good_fov(3)-good_fov(1)], 'EdgeColor', p.plot.fov_box_color)
end
elseif p.plot.fov_box
rectangle('Position',fov_box, 'EdgeColor', p.plot.fov_box_color)
end
end
% calculate a proper colorbar range
try
amp_range = sp_quantile(absob(plot_mask),[1e-4,1-1e-4], 10);
catch
keyboard
end
if amp_range(1) < amp_range(2)
caxis(amp_range);
end
colormap(bone(256)); colorbar
axis image xy tight
if check_option(p, 'show_only_FOV') && p.plot.realaxes
axis([good_fov(2) good_fov(4) good_fov(1) good_fov(3)])
elseif check_option(p, 'show_only_FOV') && ~p.plot.realaxes
axis([p.asize(2)/2, object_size(obnum,2) - p.asize(2)/2, p.asize(1)/2, object_size(obnum,1) - p.asize(1)/2, ])
end
% prepare title strings
if p.share_object
title(sprintf('amplitude: %s %s', p.plot.obtitlestring, p.plot.extratitlestring),'interpreter','none');
else
title(sprintf('amplitude: %s %s', p.scan_str{obnum}, p.plot.extratitlestring),'interpreter','none');
end
%%%%%%%%%%%%%%%%%%%
%%%%%% PHASE %%%%%%
%%%%%%%%%%%%%%%%%%%
% prepare figure handle for phase images
if ~use_display && count_plotobj == 1
fig2 = plotting.smart_figure('Visible', 'off');
else
if count_plotobj == 1
if p.plot.windowautopos && ~ishandle(2) % position it only if the window does not exist
fig2 = plotting.smart_figure(2);
set(gcf,'Outerposition',[1 ceil(p.plot.scrsz(4)/2) ceil(p.plot.scrsz(4)/p.plot.horz_fact) ceil(p.plot.scrsz(4)/2)]) %[left, bottom, width, height
else
fig2 = plotting.smart_figure(2);
end
clf;
else
set(groot,'CurrentFigure',fig2);
end
end
if check_option(p.plot, 'residua') && ~check_option(p, 'fourier_ptycho')
% find residua to plot and avoid plotting residua in not illuminated regions
residues = plot_mask(2:end, 2:end) & (abs(utils.findresidues(ob_plot)) > 0.1);
[residues_ind{1}, residues_ind{2}] = find(residues);
end
ax_phase(count_plotobj)=subplot(p.plot.subplwinobj(1),p.plot.subplwinobj(2),count_plotobj);
% plot the phase
if ~p.plot.realaxes
plotting.imagesc3D(phob);
if p.plot.fov_box && ~(p.plot.show_layers && ~p.plot.show_layers_stack && Nlayers > 1)
rectangle('Position',[p.asize([2,1])/2 , p.object_size([2,1]) - p.asize([2,1])], 'EdgeColor', p.plot.fov_box_color)
end
if check_option(p.plot, 'residua')
hold all
plot(residues_ind{[2,1]},'or')
hold off
end
else
plotting.imagesc3D(obj_ax{:},phob);
xlabel(unitLabel)
ylabel(unitLabel)
if p.plot.fov_box && p.plot.show_layers && ~p.plot.show_layers_stack && Nlayers > 1
% plot bar around each layer
for layer = 1:Nlayers
rectangle('Position', [good_fov(2) + (layer-(Nlayers+1)/2)*p.object_size(obnum,2).*p.dx_spec(1)*unitFactor ,good_fov(1), good_fov(4)-good_fov(2),good_fov(3)-good_fov(1)], 'EdgeColor', p.plot.fov_box_color)
end
elseif p.plot.fov_box
rectangle('Position',fov_box, 'EdgeColor', p.plot.fov_box_color)
end
if check_option(p.plot, 'residua')
hold all
plot((residues_ind{2}-size(ob_plot,2)/2)*objpix(2)*unitFactor,(residues_ind{1}-size(ob_plot,1)/2)*objpix(1)*unitFactor,'or')
hold off
end
end
p_range = sp_quantile(phob(plot_mask),[1e-4,1-1e-4], 10);
if p_range(1) < p_range(2)
caxis(p_range);
end
colormap(bone(256));colorbar
if p.share_object
title(sprintf('phase: %s %s', p.plot.obtitlestring, p.plot.extratitlestring),'interpreter','none');
else
title(sprintf('phase: %s %s', p.scan_str{obnum}, p.plot.extratitlestring),'interpreter','none');
end
axis image xy tight
if check_option(p, 'show_only_FOV') && p.plot.realaxes
axis([-good_fov(2) good_fov(2) -good_fov(1) good_fov(1)])
elseif check_option(p, 'show_only_FOV') && ~p.plot.realaxes
axis([p.asize(2)/2, object_size(obnum,2) - p.asize(2)/2, p.asize(1)/2, object_size(obnum,1) - p.asize(1)/2, ])
end
count_plotobj = count_plotobj + 1;
end
if use_display
% link axes in case of zooming
try linkaxes([ax_abs, ax_phase], 'xy'); end
end
end
end
+66
View File
@@ -0,0 +1,66 @@
% PLOT_POSITIONS
% plot positions of the illumination with respect to the object
%
% ** p p structure
%
%
%
%
function plot_positions(p)
%modified by YJ for electron pty
if isfield(p,'beam_source') && strcmp(p.beam_source, 'electron')
unitFactor = 0.1;
unitLabel = 'nm';
else %X-ray
unitFactor = 1e6;
unitLabel = '\mum';
end
% NOTE: the positions are appended to fig 4 (cf. plot_error_metric)
numscans = length(p.scan_number);
scanfirstindex = [1 cumsum(p.numpts)+1]; % First index for scan number
for ii = 1:numscans
p.scanidxs{ii} = scanfirstindex(ii):(scanfirstindex(ii+1)-1);
end
subplot(2,2,[3 4]);
for ii = 1:numscans
idx = min(ii,p.numobjs);
positions_centered(p.scanidxs{ii},:) = p.positions(p.scanidxs{ii},:) - p.object_size(idx,:)/2 + p.asize/2;
end
cla()
if p.plot.realaxes
scale = p.dx_spec*unitFactor;
else
% plot positions in pixels, useful for grazing incidence ptycho
scale = [1,1];
end
hold all
for ii = 1:numscans
plot(positions_centered(p.scanidxs{ii},2).*scale(2), ...
positions_centered(p.scanidxs{ii},1).*scale(1),...
'x:','markersize',4);
end
grid on;
if numscans==1
title('positions','interpreter','none');
else
title('positions (red 1st, blue 2nd)','interpreter','none');
end
if p.plot.realaxes
xlabel(unitLabel);
ylabel(unitLabel);
else
xlabel('pixels');
ylabel('pixels');
end
axis tight equal;
end
+73
View File
@@ -0,0 +1,73 @@
%PLOT_PROBES plot reconstructed probes
% ** p p structure
% ** use_display if false, dont plot results on screen
%
% *returns*
% fig - image handle
function fig3 = plot_probes(p, use_display)
import utils.rmphaseramp
import plotting.c2image
%modified by YJ for electron pty
if isfield(p,'beam_source') && strcmp(p.beam_source, 'electron')
unitFactor = 0.1;
unitLabel = 'nm';
else %X-ray
unitFactor = 1e6;
unitLabel = '\mum';
end
count_plotprb = 1;
for prmode = 1:p.probe_modes
for prnum = 1:p.numprobs
aux = p.probes(:,:,prnum,:);
E = sum(abs(aux(:)).^2);
if ~use_display && count_plotprb == 1
fig3 = plotting.smart_figure('Visible', 'off');
else
if count_plotprb == 1
if p.plot.windowautopos && ~ishandle(3) % position it only if the window does not exist
fig3 = plotting.smart_figure(3);
set(gcf,'Outerposition',[ceil(p.plot.scrsz(4)/p.plot.horz_fact) 1 ceil(p.plot.scrsz(4)/p.plot.horz_fact) ceil(p.plot.scrsz(4)/2)]) %[left, bottom, width, height
else
fig3 = plotting.smart_figure(3);
end
clf;
else
set(groot,'CurrentFigure',fig3);
end
end
probe = p.probes(:,:,prnum,prmode);
if p.plot.remove_phase_ramp
probe = rmphaseramp(rmphaseramp(probe,'abs'),'abs');
end
subplot(p.plot.subplwinprob(1),p.plot.subplwinprob(2),count_plotprb)
if ~p.plot.realaxes
imagesc(c2image(probe));
else
iaxis{1} = ([1 p.asize(2)]-floor(p.asize(2)/2)+1)*p.dx_spec(2)*unitFactor;
iaxis{2} = ([1 p.asize(1)]-floor(p.asize(1)/2)+1)*p.dx_spec(1)*unitFactor;
imagesc(iaxis{:},c2image(probe));
xlabel(unitLabel)
ylabel(unitLabel)
end
if p.share_probe
titlestring = sprintf('probe: %s %s', p.plot.prtitlestring, p.plot.extratitlestring);
else
titlestring = sprintf('probe: %s %s',p.scan_str{prnum}, p.plot.extratitlestring);
end
if p.probe_modes > 1
Ethis = sum(sum(abs(p.probes(:,:,prnum,prmode)).^2));
Ethis = Ethis/E;
titlestring = [titlestring sprintf(' %.1f%%',Ethis*100)];
end
title(titlestring,'interpreter','none');
axis image xy tight
count_plotprb = count_plotprb + 1;
end
end
end
@@ -0,0 +1,66 @@
% PLOT_PROBES_AT_DETECTOR
% plot reconstructed probes propagated to the detector
%
% ** p p structure
% ** use_display if false, do now show plots
%
% *returns*
% ++fig - image handle
%
%
function fig5 = plot_probes_at_detector(p, use_display)
count_plotprb = 1;
for prmode = 1:p.probe_modes
for prnum = 1:p.numprobs
aux = p.probes(:,:,prnum,:);
E = sum(abs(aux(:)).^2);
if ~use_display && count_plotprb == 1
fig5 = plotting.smart_figure('Visible', 'off');
else
if count_plotprb == 1
if p.plot.windowautopos && ~ishandle(5) % position it only if the window does not exist
fig5 = plotting.smart_figure(5);
set(gcf,'Outerposition',[ceil(p.plot.scrsz(4)*2/p.plot.horz_fact) 1 ceil(p.plot.scrsz(4)/p.plot.horz_fact) ceil(p.plot.scrsz(4)/2)]) %[left, bottom, width, height
else
fig5 = plotting.smart_figure(5);
end
clf;
else
set(groot,'CurrentFigure',fig5);
end
end
subplot(p.plot.subplwinprob(1),p.plot.subplwinprob(2),count_plotprb)
af_probe = abs(fftshift(fft2(p.probes(:,:,prnum,prmode)))).^2;
max_af_probe = max(af_probe(:));
if isfield(p, 'renorm')
af_probe = af_probe / single(p.renorm).^2;
end
if ~p.plot.realaxes
imagesc(log10(1e-2*max_af_probe+af_probe));
else
imagesc(([1 p.asize(2)]-floor(p.asize(2)/2)+1)*p.ds*1e3,([1 p.asize(1)]-floor(p.asize(1)/2)+1)*p.ds*1e3,log10(1e-2*max_af_probe+af_probe));
xlabel('mm')
ylabel('mm')
end
if p.share_probe
titlestring = sprintf('log10 FFT probe: %s %s', p.plot.prtitlestring, p.plot.extratitlestring);
else
titlestring = sprintf('log10 FFT probe: %s %s',p.scan_str{prnum}, p.plot.extratitlestring);
end
if p.probe_modes > 1
Ethis = sum(sum(abs(p.probes(:,:,prnum,prmode)).^2));
Ethis = Ethis/E;
titlestring = [titlestring sprintf(' %.1f%%',Ethis*100)];
end
title(titlestring,'interpreter','none');
axis image xy tight
colormap(plotting.franzmap)
colorbar
count_plotprb = count_plotprb + 1;
end
end
end
+60
View File
@@ -0,0 +1,60 @@
%PLOT_RAW_DATA Simple plotting routine for masked raw data
%
% ** p p structure
%
% see also: core.initialize_ptycho
function plot_raw_data(p)
import utils.verbose
magnitude = p.fmag .* p.fmask;
max_intensity = (max(max(magnitude))/p.renorm).^2;
verbose(1, 'Plotting prepared data.')
kk = 1;
title_list = cell(1,size(p.fmag,3));
for jj=1:p.numscans
for ii = p.scanidxs{jj}
title_list{kk} = sprintf('Scan S%0.5d - Point (%d) maximal intensity:%.4g',p.scan_number(jj), ii, max_intensity(kk));
kk = kk +1 ;
end
end
% really enforce popup of this figure, it gets very annoying when running somewhere in background
if ishandle(10)
close(10);
end
fig = figure(10);
if ~p.fourier_ptycho
plt_fnct = @(x)(log10(0.1+math.fftshift_2D(x / p.renorm).^2));
else
plt_fnct = @(x)((x / p.renorm).^2);
end
plotting.imagesc3D(magnitude, 'title_list', title_list, 'fnct', plt_fnct);
if ~p.fourier_ptycho
caxis([-1, log10(max(max_intensity))])
else
caxis(math.sp_quantile((magnitude/p.renorm).^2, [1e-6 1-1e-6], 10))
end
c = colorbar;
ylabel(c, 'log10 counts')
ax = fig.CurrentAxes;
axis(ax, 'xy', 'equal', 'image')
colormap(ax, 'plotting.franzmap')
if p.plot.windowautopos
horiz_fact = 2.5;
if check_option(p.plot, 'object_spectrum')
pos = 3;
else
pos = 2;
end
set(gcf,'Outerposition',[ceil(min(p.plot.scrsz(3)-ceil(p.plot.scrsz(4)/2), ceil(p.plot.scrsz(4)*pos/horiz_fact))) ceil(p.plot.scrsz(4)/2) ceil(p.plot.scrsz(4)/horiz_fact) ceil(p.plot.scrsz(4)/2)]) %[left, bottom, width, height
end
ax.play(ax);
end
+322
View File
@@ -0,0 +1,322 @@
%%% PLOT_RESULTS plotting routine for ptychographic reconstructions
% ** p p structure from a ptychographic reconstruction
%
% *optional*
% ** use_display show plots (default: true)
% ** store_images write images to disk (default: false)
% ** final show all error metrics for a final plot (default: false)
% ** save_path change default save_path (p.save_path) for saving jpgs
%
% EXAMPLES:
% core.analysis.plot_results(p);
% core.analysis.plot_results(p, 'store_images', true);
% core.analysis.plot_results(p, 'use_display', false, 'store_images', true);
%
%
% see also: plotting.ptycho_show_recons
%
% 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 plot_results(p, varargin)
import plotting.*
import utils.*
import math.sp_quantile
% parse p.plot inputs
check_input = @(x) islogical(x) || isnumeric(x);
parse_p = inputParser;
parse_p.KeepUnmatched = true;
parse_p.addParameter('fourier_ptycho', false, check_input)
parse_p.addParameter('object_spectrum', [], check_input)
parse_p.addParameter('filt', true, check_input)
parse_p.addParameter('plot_layers', true, check_input)
parse_p.addParameter('plot_layers_stack', true, check_input)
parse_p.addParameter('remove_phase_ramp', false, check_input)
parse_p.addParameter('prop_obj',0, check_input)
parse_p.addParameter('plot_conj', false, check_input)
parse_p.addParameter('obj_apod', false, check_input)
parse_p.parse(p.plot);
p.plot = utils.update_param(p.plot, parse_p.Results);
% parse p.save
parse_p = inputParser;
parse_p.KeepUnmatched = true;
parse_p.addParameter('store_images_format', 'png', @(x)ismember(x, {'png', 'jpg'}))
parse_p.addParameter('store_images_dpi', 150, @math.isint)
parse_p.parse(p.save);
p.save = utils.update_param(p.save, parse_p.Results);
if isempty(varargin) || ischar(varargin{1})
par = inputParser;
par.addParameter('use_display', true, check_input)
par.addParameter('store_images', false, check_input)
par.addParameter('final', false, check_input)
par.addParameter('save_path',[], @ischar)
par.parse(varargin{:})
vars = par.Results;
end
if p.fourier_ptycho
p.plot.fov_box = false;
end
if isempty(p.plot.object_spectrum)
p.plot.object_spectrum = (utils.verbose>=3);
end
if ~isfield(p.plot, 'log_scale')
p.plot.log_scale = [false false];
elseif isscalar(p.plot.log_scale)
p.plot.log_scale = repmat(p.plot.log_scale,1,2);
end
% Subplot geometry
% p.subplwin = [floor(sqrt(p.numscans)) ceil(p.numscans/floor(sqrt(p.numscans)))];
numwinobj = p.numobjs*p.object_modes;
p.plot.subplwinobj = [floor(sqrt(numwinobj)) ceil(numwinobj/floor(sqrt(numwinobj)))];
if p.numprobs == 1 || p.probe_modes == 1
% distribute as efficiently as possible
numwinprob = p.numprobs*p.probe_modes;
p.plot.subplwinprob = [floor(sqrt(numwinprob)) ceil(numwinprob/floor(sqrt(numwinprob)))];
else
% show scans in columns and probe modes in rows
p.plot.subplwinprob = [p.probe_modes, p.numprobs];
end
if check_option(p.plot, 'subplwinobj_dir', 'vertical') || (p.plot.show_layers && size(p.object{1},4) > 1)
% prefer to stack the object verticaly , useful for multilayer object plotting
p.plot.subplwinobj = sort(p.plot.subplwinobj, 'descend');
end
%%%%%%%%%%%%%%%%%%%%
%%%%%% OBJECTS %%%%%
%%%%%%%%%%%%%%%%%%%%
[fig1, fig2] = core.analysis.plot_objects(p, vars.use_display);
%%%%%%%%%%%%%%%%%%%%
%%%%%% PROBES %%%%%%
%%%%%%%%%%%%%%%%%%%%
fig3 = core.analysis.plot_probes(p, vars.use_display);
%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%% ERROR METRIC %%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%
try
fig4 = core.analysis.plot_error_metric(p, vars.final, vars.use_display);
catch ME
warning('Failed to plot error metrics.')
disp([ME.getReport]);
fig4 = plotting.smart_figure(4);
end
%%%%%%%%%%%%%%%%%%%%%%%
%%%%%% POSITIONS %%%%%%
%%%%%%%%%%%%%%%%%%%%%%%
if p.plot.positions
core.analysis.plot_positions(p);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%% PROBES @ DETECTOR %%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if p.plot.probe_spectrum
fig5 = core.analysis.plot_probes_at_detector(p, vars.use_display);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%% OBJECT SPECTRUM %%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if p.plot.object_spectrum
fig6 = core.analysis.plot_object_spectrum(p, vars.use_display);
end
drawnow;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Write in figures folder %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% If you configured to dump it also saves the figures in
% analysis/online/ptycho
if vars.store_images
if isempty(vars.save_path)
% split the save_path and find the last occurrence of 'analysis'
tmpPath = strsplit(p.save_path{1}, '/');
analysisPos = find(strcmpi(tmpPath, 'analysis'));
save_path_online = strjoin(tmpPath(1:max(1,analysisPos(end)-1)),'/');
if ~isfield(p, 'datasetID')
p.datasetID = 0;
end
% load sample name if provided in .dat files and append it to the
% save name suffix
if isfield(p, 'samplename')
suffix = sprintf('dset_%s_%05d', p.samplename, p.datasetID);
else
suffix = sprintf('dset_%05d', p.datasetID);
end
subdir = fullfile(save_path_online,'analysis/online/ptycho/', suffix);
gallery = fullfile(save_path_online,'analysis/online/ptycho/gallery/');
else
subdir = vars.save_path;
gallery = fullfile(subdir,'/gallery/');
end
if ~exist(gallery,'dir')
mkdir(gallery);
end
if ~exist(subdir,'dir')
mkdir(subdir);
end
utils.verbose(0, 'Saving images to %s', subdir)
% ignore prefix in the run name -> make sorting by name equivalent to
% sorting by scan number -> easier preview and browsing through image
% gallery
image_name = p.run_name(1+length(p.prefix):end);
width = 6*p.plot.subplwinobj(2);
height = 4*p.plot.subplwinobj(1);
if any(p.save.store_images_ids == 1)
fig1.PaperPosition = [3 3 width height]; % adjust size of the resulting image
save_figs(fig1, '%s_amplitude.%s', image_name, subdir, gallery, p.save);
end
if any(p.save.store_images_ids == 2)
fig2.PaperPosition = [3 3 width height]; % adjust size of the resulting image
save_figs(fig2, '%s_phase.%s', image_name, subdir, gallery, p.save);
end
if any(p.save.store_images_ids == 6)
fig6.PaperPosition = [3 3 width height]; % adjust size of the resulting image
save_figs(fig6, '%s_object_spectrum.%s', image_name, subdir, gallery, p.save);
end
width = 4*p.plot.subplwinprob(2);
height = 4*p.plot.subplwinprob(1);
if any(p.save.store_images_ids == 3)
fig3.PaperPosition = [3 3 width height]; % adjust size of the resulting image
save_figs(fig3, '%s_probe.%s', image_name, subdir, gallery, p.save);
end
if any(p.save.store_images_ids == 4)
save_figs(fig4, '%s_err.%s', image_name, subdir, gallery, p.save);
end
if any(p.save.store_images_ids == 5)
fig5.PaperPosition = [3 3 width height]; % adjust size of the resulting image
save_figs(fig5, '%s_probe_spectrum.%s', image_name, subdir, gallery, p.save);
end
end
end
function save_figs(fig_handle, fname,run_name, subdir, gallery, params)
try
fname = sprintf(fname,run_name, params.store_images_format);
utils.verbose(3, 'saving %s',fullfile(subdir,fname));
switch params.store_images_format
case 'png' , printer = '-dpng';
case 'jpg' , printer = '-djpeg';
otherwise, error('Unsupported image extension')
end
print(fig_handle, printer,['-r', num2str(params.store_images_dpi)],fullfile(subdir,fname));
% trim borders around the images
system(sprintf('convert -trim %s %s', fullfile(subdir,fname), fullfile(subdir,fname)));
% make a symbolic link to a gallery folder
system(sprintf('ln -sf %s %s', fullfile(subdir,fname), fullfile(gallery, fname)));
catch err
warning('Saving plot handle fig%i failed: %s',fig_handle.Number, err.message)
end
end
@@ -0,0 +1,80 @@
%GET_OBJECT_PIXEL_SIZE
% calculate object pixel size, for conventional ptycho it is p.dx_spec
%
% ** p p structure
%
% Outputs:
% ++
%
% 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 [objpix, FP_pre_phase_factor] = get_object_pixel_size(p)
import utils.get_grid
if p.fourier_ptycho
k = 2*pi/p.lambda;
objpix = p.lambda*p.z_lens./(p.object_size.*p.dx_spec);
for ii=1:p.numobjs
[Xp,Yp] = get_grid(p.object_size(ii,:), objpix(1));
FP_pre_phase_factor{ii} = exp(1i*k*((Xp).^2+(Yp).^2)/(2*p.z_lens));
end
else
objpix = p.dx_spec;
FP_pre_phase_factor = [];
end
end