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,329 @@
% FOURIER_RING_CORRELATION simplified but faster version of the FRC code
%
% [score, object] = fourier_ring_correlation(object_1, object_2, varargin)
%
% ** object_1 array reconstructed object
% ** object_2 array reconstructed object from an independend scan
% ** varargin see code for more details
%
% 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 [score, object] = fourier_ring_correlation(object_1, object_2, varargin)
import engines.GPU.shared.*
import engines.GPU.GPU_wrapper.*
import math.*
import utils.*
import plotting.*
par = inputParser;
par.addParameter('px_scale', 1 , @isnumeric )
par.addParameter('auto_crop', false, @islogical )
par.addParameter('plot_results', true , @islogical ) % use white background
par.addParameter('smoothing', 0 , @isnumeric ) % smooth over N pixels
par.addParameter('Nrings', 20 , @isnumeric ) % smooth over N pixels
par.addParameter('crop', 0 , @isnumeric ) % crop image by N pixels
par.addParameter('flip_horizontal', false , @islogical ) % flip second image horizontally
par.addParameter('fft_phase_removal_guess', false , @islogical ) % flip second image horizontally
par.addParameter('weights', {} , @iscell ) % cell array of weights
par.addParameter('find_shift', true, @islogical ) % cell array of weights
par.parse(varargin{:})
r = par.Results;
if r.flip_horizontal
object_2 = fliplr(object_2);
end
Npix = min(size(object_1), size(object_2));
object = {object_1, object_2};
if r.crop > 0
for ii = 1:2
object{ii} = crop_pad(object{ii}, Npix-r.crop);
end
if ~isempty(r.weights)
for ii = 1:2
r.weights{ii} = crop_pad(r.weights{ii}, Npix-r.crop);
end
end
end
Npix = min(size(object{1}), size(object{2}));
for ii = 1:2
object{ii} = object{ii} / mean(abs(object{1}(:)) );
W{ii} = tukeywin(Npix(1), 0.2) .* tukeywin(Npix(2),0.2)';
if ~isempty(r.weights)
W{ii} = W{ii} .* single(r.weights{ii});
end
end
score.shift = [0,0];
if r.find_shift
for kk = 1:4
Npix = size(object{1});
[X,Y] = meshgrid(-Npix(2)/2+1:Npix(2)/2,-Npix(1)/2+1:Npix(1)/2);
object{1} = utils.stabilize_phase(object{1}, object{2}, 'fourier_guess', r.fft_phase_removal_guess);
for ii = 1:2
phasor{ii} = object{ii} ./ (abs(object{ii}) + 1e-3*mean(abs(object{ii}(:))));
fobject{ii} = fft2(single(W{ii}.*(phasor{ii}-mean(phasor{ii}(:)))));
end
% high pass filter
Wf = Garray(fftshift(exp(- 1./ ((X.^2+Y.^2)/(Npix(1)/50)^2))));
[output] = utils.dftregistration( Wf.* fobject{1}, Wf.* fobject{2},100);
object{2} = imshift_fft(object{2}, output(4), output(3));
ROI = { (1+max(0,ceil(output(3)))):(Npix(1)+min(0, floor(output(3)))) , ...
(1+max(0,ceil(output(4)))):(Npix(2)+min(0, floor(output(4))))};
object{1} = object{1}(ROI{:});
object{2} = object{2}(ROI{:});
for j = 1:2
W{j} = W{j}(ROI{:});
end
verbose(3,'Image shifted by %g %g px', output([4,3]))
score.shift = score.shift + Ggather([output(4), output(3)]);
% subplot(1,2,1)
% plotting.imagesc3D(object{1}); axis off image
% subplot(1,2,2)
% plotting.imagesc3D(object{2}); axis off image
% drawnow
if all(abs(output(3:4)) < 0.5)
break
end
end
end
Npix = size(object{1});
[object{1}] = utils.stabilize_phase(object{1}, object{2}, abs(object{2}), 'binning', 4 , 'fourier_guess', r.fft_phase_removal_guess);
if r.flip_horizontal
score.shift(1) = -score.shift(1);
end
for ii = 1:2
object{ii} = object{ii} ./ mean(abs(object{ii}(:)));
end
W = sqrt(W{1} .* W{2});
ROI_compare = get_ROI(W>0.1*max(W(:))); % compare only the reliable ROIs
W = tukeywin(length(ROI_compare{1}),0.2) .* tukeywin(length(ROI_compare{2}),0.2)';
for ii = 1:2
fobject{ii} = fft2(W.*object{ii}(ROI_compare{:}));
end
for ii = 1:2
fobject{ii} = fftshift(fobject{ii});
fobject_norm{ii} = abs(fobject{ii}).^2;
end
fcorr = fobject{1} .* conj(fobject{2});
binning = ceil(Npix/2 / r.Nrings);
fcorr = conv2(fcorr, ones(binning) / prod(binning), 'same');
fcorr = fcorr(1:binning(1):end, 1:binning(2):end);
for ii = 1:2
fobject_norm{ii} = conv2(fobject_norm{ii}, ones(binning) / prod(binning), 'same');
fobject_norm{ii} = fobject_norm{ii}(1:binning(1):end, 1:binning(2):end);
end
Npix= size(fcorr);
x = single(-Npix(2)/2+0.5:Npix(2)/2-0.5)/(Npix(2)/2);
y = single(-Npix(1)/2+0.5:Npix(1)/2-0.5)/(Npix(1)/2);
if length(r.px_scale) > 1 && r.px_scale(1) > r.px_scale(2)
y = y .* r.px_scale(2) / r.px_scale(1);
elseif length(r.px_scale) > 1 && r.px_scale(1) < r.px_scale(2)
x = x .* r.px_scale(1) / r.px_scale(2);
end
[X,Y] = meshgrid(x, y);
R_mat = sqrt(X.^2 + Y.^2);
Rmax = 0.98;
R0 = 0.01;
R_all = linspace(R0, Rmax, min(r.Nrings, min(Npix)));
for ii = 1:(length(R_all)-1)
R = R_all(ii);
ring = find((R_mat > R_all(ii)) & (R_mat < R_all(ii+1)));
fcorr_values{1}(ii) = abs(sum(fcorr(ring)) ./ sqrt(sum(fobject_norm{1}(ring)) .* sum(fobject_norm{2}(ring))));
n_values(ii) = length(ring); % sum(ring(:));
end
spatial_freq = R_all(1:end-1);
n_values = n_values .* prod(binning);
% 1-bit curve
T = (0.5+2.41./sqrt(n_values)) ./ (1.5+1.41./sqrt(n_values));
% 1/2 bit curve
% T = (0.21+1.91 ./sqrt(n_values)) ./ (1.21+0.91./sqrt(n_values));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fcorr_values{1} = Ggather(fcorr_values{1});
AUC = nanmean(fcorr_values{1}); % area undear curve criterion
score.AUC = AUC;
score.thresh = T;
score.FRC = fcorr_values{1};
score.spatial_freq = spatial_freq;
score.SSNR = 2 * score.FRC ./ (1-score.FRC);
score.SNR_avg = nansum(score.SSNR .* spatial_freq) / sum(spatial_freq);
Ts = smooth(T);
if r.smoothing > 0
score.FRC = imgaussfilt(score.FRC,r.smoothing);
end
[x0,y0,iout,jout] = intersections(spatial_freq,score.FRC,spatial_freq, Ts,false);
if all(score.FRC >= Ts')
score.resolution = 1;
elseif all(score.FRC <= Ts')
score.resolution = 0;
elseif any(x0 > 0.1)
score.resolution = min(x0(x0 > 0.1));
else
score.resolution = min(x0);
end
if r.plot_results
subplot(1,2,1)
hold all
b = plot(spatial_freq,score.FRC+randn*0.1,'LineWidth', 2);
h = plot(spatial_freq, Ts, 'k--', 'LineWidth', 2);
plot(x0, y0, 'o')
xlabel('Spatial frequency / Nyquist')
% ylabel('FRC')
ylabel(sprintf('Fourier ring correlation, AUC=%3.3g', AUC))
hold off
ylim([0,1])
xlim([0,1])
% r = vline(resolution, '-k');
legend([b, h], 'FRC', '1 bit threshold','Location','Best');
grid on
subplot(1,2,2)
hold all
plot(score.spatial_freq, score.SSNR);
try; vline(score.resolution); end
hline(1)
set(gca, 'yscale', 'log')
hold off
grid on
ylabel(sprintf('Spectral SNR, SNR_{avg}=%3.3g', score.SNR_avg))
% width = 10;
% aspect_ratio=4/3;
% height = width / aspect_ratio;
% % set size of the resulting image
% set(gcf, 'PaperPosition', [1.5 1.5 width height]);
plotting.suptitle(sprintf('Resolution=%.3gnm AuC=%.3g', min(r.px_scale) / score.resolution * 1e9,AUC))
end
verbose(3,'AUC %g', score.AUC)
verbose(3,'SNR %g', score.SNR_avg)
verbose(3,'resolution %g (%g nm)', score.resolution, min(r.px_scale) / score.resolution*1e9)
try
verbose('SSNR 0.1 %g 0.5 %g, 0.9 %g \n', log10(quantile(score.SSNR, [0.1, 0.5, 0.9] )))
end
end
@@ -0,0 +1,214 @@
% ONLINE_FSC_ESTIMATE online estimation of the fourier shell correlation curve to estimation of optimal convergence
% compare two scans and estimate FSC and other statistics
%
% score = online_FSC_estimate(self, par, cache, score_0, iter)
%
%
% ** self structure containing inputs: e.g. current reconstruction results, data, mask, positions, pixel size, ..
% ** par structure containing parameters for the engines
% ** cache structure with precalculated values to avoid unnecessary overhead
% ** score_0 [] or a structure with outputs from previous online estimation of FSC curve
%
% returns:
% ++ score structure with outputs from online estimation of FSC curve
% 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 score = online_FSC_estimate(self, par, cache, score_0, iter)
import engines.GPU.GPU_wrapper.*
import math.*
import utils.*
import plotting.*
import engines.GPU.*
if check_option(self, 'object_orig')
self.object{end+1,1} = cat(3,self.object_orig{1,:});
end
compared_indices = (2:size(self.object,1))-1;
% take product of the reconstructed images, eDOF
%% refererene image
selected_ROI = cache.object_ROI;
selected_ROI{2} = selected_ROI{2}(ceil(end/10):floor(end*9/10));
obj{1} = cat(3, self.object{1,:});
obj{1} = Garray(obj{1});
for ll = compared_indices
%% compared image
% take product of the reconstructed images, eDOF
obj_compared = cat(3,self.object{ll+1,:});
if ~isempty(score_0) && ~isempty(score_0{ll})
obj_compared = imshift_fft(obj_compared, score_0{ll}.shift);
end
obj{2} = Garray(obj_compared);
%% get at least some empirical esitmation of reliability -> for selection of compared ROI
for kk = 1:2
ind = [1,min(ll+1, length(cache.illum_sum_0))];
W{kk} = cache.illum_sum_0{ind(kk)}(selected_ROI{:});
W{kk} = W{kk} > 0.5*mean(W{kk});
% W{kk} = imfill(W{kk}, 'holes');
if any(W{kk}(:)==0)
Npix = size(W{kk});
downscale = 10;
W{kk} = real(utils.interpolateFT(W{kk}, ceil(Npix / downscale)));
try; W{kk} = Garray(imerode( Ggather(W{kk})>0.1, strel('disk', ceil(self.Np_p(1)/8/downscale)))); end
W{kk} = (utils.imgaussfilt3_conv(W{kk}, mean(self.Np_p)/8/downscale));
W{kk} = max(0,real(utils.interpolateFT(W{kk},Npix)));
end
end
clear obj_0
Wshared = sqrt(W{1}.*W{2});
for kk = 1:2
W{kk} = Wshared;
end
if size(obj{1},3) > 1 ||size(obj{2},3) > 1
Nl_shifts = 4;
else
Nl_shifts = 1;
end
for kk = 1:Nl_shifts
for ii = 1:2
Nlayers = size(obj{ii},3);
horiz_shifts = linspace(-(kk-1), (kk-1), Nlayers)';
shift = [horiz_shifts, zeros(Nlayers,1)];
if kk > 1 && ii == 1
shift = shift - score{ll,kk-1}.shift;
end
% apply different shift on each layer -> minic rotation
obj_tmp{ii} = prod(imshift_fft(obj{ii}, shift),3);
obj_tmp{ii} = obj_tmp{ii}(selected_ROI{:});
end
[score{ll,kk},obj_out] = analysis.fourier_ring_correlation(obj_tmp{:},...
'smoothing', 1, 'crop', ceil(self.Np_p / 4) , 'plot_results', false, 'px_scale', self.pixel_size, 'weights', W);
if ~isempty(score_0) && ~isempty(score_0{ll})
score{ll,kk}.shift = score{ll,kk}.shift + score_0{ll}.shift ;
end
if ll == compared_indices(end) && verbose > 2
plotting.smart_figure(2121)
img = angle(cat(3,obj_out{:}));
plotting.imagesc3D(img); axis off image xy ;
caxis(Ggather(math.sp_quantile(img, [0.01, 0.99],10)))
title('Aligned frames used for FSC estimation')
drawnow
end
% fprintf('========== total object shift ====== %g %g\n', score{end}.shift)
score{ll,kk}.iter = iter;
score{ll,kk}.positions = self.modes{1}.probe_positions;
score{ll,kk}.positions_0 = self.modes{1}.probe_positions_0;
%score{ll,kk}.intensity = self.modes{1}.weights;
score{ll,kk}.probe_fourier_shift = self.modes{1}.probe_fourier_shift;
end
end
plotting.smart_figure(4554)
clf
subplot(1,2,1)
linestyle = {'-','--',':'};
hold all
for kk = 1:Nl_shifts
for ll = compared_indices
if isempty(score{ll,kk}); continue; end
b(ll) = plot(score{ll,kk}.spatial_freq,score{ll,kk}.FRC,linestyle{1+mod(ll-1,end)},'LineWidth', 2);
legend_names{ll} = sprintf('FRC scans 1 vs %i', ll+1);
end
h = plot(score{ll,1}.spatial_freq, score{ll,1}.thresh, 'k--', 'LineWidth', 2);
end
xlabel('Spatial frequency / Nyquist')
ylabel(sprintf('Fourier ring correlation, AUC=%3.3g', score{ll,1}.AUC))
hold off
ylim([0,1])
xlim([0,1])
legend([b, h], legend_names{:}, '1 bit threshold','Location','Best');
grid on
subplot(1,2,2)
hold all
for kk = 1:Nl_shifts
for ll = compared_indices
if isempty(score{ll,kk}); continue; end
score{ll,kk}.SSNR(~isfinite(score{ll}.SSNR) | score{ll,kk}.SSNR <= 0) = nan;
plot(score{ll,kk}.spatial_freq, score{ll,kk}.SSNR);
end
end
hline(1)
set(gca, 'yscale', 'log')
hold off
grid on
ylabel(sprintf('Spectral SNR, SNR_{avg}=%3.3g', score{ll,1}.SNR_avg))
%modified by YJ for electron pty
if isfield(par,'beam_source') && strcmp(par.beam_source, 'electron')
plotting.suptitle(sprintf('Resolution %3.3g angstrom', mean(self.pixel_size) / score{ll,1}.resolution))
else
plotting.suptitle(sprintf('Resolution %3.3gnm', mean(self.pixel_size) / score{ll,1}.resolution * 1e9))
end
end
@@ -0,0 +1,77 @@
% PLOT_BACKGROUND_INTENSITY plot estiamtion of background for each of the scan positions
%
% plot_background_intensity(self,probe, background)
%
% ** self structure containing inputs: e.g. current reconstruction results, data, mask, positions, pixel size, ..
% ** probe structure containing parameters for the engines
% ** probe [Nx,Ny,variable_modes] complex array with probe
% ** background [Npos,1] array with background intensity
% 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 plot_background_intensity(self,probe, background)
plotting.smart_figure(11231)
subplot(1,2,1)
show_spatial_distribution(self.probe_positions_0, background, false, false)
axis off image
colorbar
title('Background distribution')
subplot(1,2,2)
imagesc(abs(probe))
axis off image
end
@@ -0,0 +1,97 @@
% PLOT_FRC_ANALYSIS plot evolution of the resolution and SNR estimated from the FRC
%
% plot_frc_analysis(score, par)
%
% ** score structure with outputs from online estimation of FSC curve
% ** par structure containing parameters for the 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 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 plot_frc_analysis(score, par)
N = size(score,1)-1;
resolution = nan(N,1);
for i = 1:N
iteration(i) = score{i+1,1}.iter;
try; resolution(i) = score{i+1,1}.resolution; end
SNR(i) = score{i+1,1}.SNR_avg;
AUC(i) = score{i+1,1}.AUC;
end
plotting.smart_figure(123132)
subplot(1,3,1)
semilogx(iteration, medfilt1(resolution, 'truncate'))
xlim([1, par.number_iterations])
xlabel('Iteration')
ylabel('Spatial frequency/Nyquist')
title('FRC resolution')
grid on
subplot(1,3,2)
semilogx(iteration, medfilt1(SNR, 'truncate' ))
xlim([1, par.number_iterations])
xlabel('Iteration')
ylabel('SNR')
title('Average signal to noise ratio')
grid on
subplot(1,3,3)
semilogx(iteration, medfilt1(AUC, 'truncate' ))
xlim([1, par.number_iterations])
xlabel('Iteration')
ylabel('AUC')
title('Area under FRC curve')
grid on
plotting.suptitle('Fourier ring resolution analysis')
end
@@ -0,0 +1,292 @@
% PLOT_GEOM_CORRECTIONS plot position refinement statistics - position errors, directions and weights
%
% plot_geom_corrections(self, mode, object, iter, par, cache)
%
% ** self structure containing inputs: e.g. current reconstruction results, data, mask, positions, pixel size, ..
% ** mode structure containing reconstruction parameters related to the selected incoherent mode
% ** object cell of arrays, reconstructed object
% ** iter current iteration number
% ** par structure containing parameters for the engines
% ** cache structure with precalculated values to avoid unnecessary overhead
%
% FUNCTION plot_geom_corrections(self, mode, object, iter, par, cache)
% plot positiones updates
% 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 plot_geom_corrections(self, mode, object, iter, par, cache)
import engines.GPU.GPU_wrapper.*
import math.*
import plotting.*
import utils.*
pos = mode.probe_positions;
pos_0 = self.probe_positions_0;
Nplots = 4*(iter >= par.probe_position_search && ~isempty(par.probe_geometry_model)) ...
+ (iter >= par.estimate_NF_distance) + ...
(iter >= par.detector_rotation_search) + ...
(iter >= par.detector_scale_search);
if ~ishandle(16165)
plotting.smart_figure(16165)
set(gcf,'Outerposition',[100 100 Nplots*330 400]) %[left, bottom, width, height
else
plotting.smart_figure(16165)
end
plot_id = 0;
if iter >= par.probe_position_search && ~isempty(par.probe_geometry_model)
clf()
x_iters=[par.probe_position_search:iter]; % correction of iteration index in x-axis by ZC
subplot(1,Nplots,1)
hold all
plot(x_iters,mode.scales , '-'); axis tight
ylabel('Relative pixel scaling correction [-]')
xlabel('Iteration')
hold off
grid on
title('Scales')
subplot(1,Nplots,2)
plot(x_iters,mode.rotation , '-'); axis tight
ylabel('Rotation [deg]')
title('Rotation')
xlabel('Iteration')
grid on
subplot(1,Nplots,3)
plot(x_iters,mode.shear , '-'); axis tight
ylabel('Shear [deg]')
title('Shear')
xlabel('Iteration')
grid on
subplot(1,Nplots,4)
plot(x_iters,mode.asymmetry*100 , '-'); axis tight
ylabel('Asymmetry [%]')
title('Asymmetry')
xlabel('Iteration')
grid on
plot_id = 4;
end
if iter >= par.estimate_NF_distance
subplot(1,Nplots,plot_id+1)
plot(mode.distances * 1e6 , '-');
axis tight
grid on
ylabel('Propagation distance [um]')
title('Nearfield propagation distance')
xlabel('Iteration')
plot_id = plot_id + 1;
end
if iter >= par.detector_rotation_search
subplot(1,Nplots,plot_id+1)
plot(mode.probe_rotation,'-');
axis tight
grid on
ylabel('Detector rotation angle [deg]')
title('Detector rotation')
xlabel('Iteration')
plot_id = plot_id + 1;
end
if iter >= par.detector_scale_search
subplot(1,Nplots,plot_id+1)
plot((1+mode.probe_scale_upd),'-');
axis tight
grid on
ylabel('Detector optimal scaling [-]')
title('Relative pixel scale')
xlabel('Iteration')
plot_id = plot_id + 1;
end
plotting.suptitle('Evolution of geometry parameters')
%modified by YJ: remove check_option(par, 'probe_geometry_model') to
%plot position correction even without geom refinement
%if iter >= par.probe_position_search && check_option(par, 'probe_geometry_model')
if iter >= par.probe_position_search
%modified by YJ for electron pty
if isfield(par,'beam_source') && strcmp(par.beam_source, 'electron')
unitFactor = 1;
scaleFactor = 0.1;
unitLabel = 'A';
else %X-ray
unitFactor = 1e9;
scaleFactor = 1e6;
unitLabel = 'nm';
end
% substract the geometry model to show only residuum
pos_err = pos - mode.probe_positions_model ;
% subtract average error per scan
for kk = 1:par.Nscans
ind = self.reconstruct_ind{kk};
pos_err(ind,:) = pos_err(ind,:) - mean(pos_err(ind,:));
end
pos = pos+ self.Np_o([2,1])/2;
marker_colors = {'r', 'b', 'g', 'k'};
scale = self.pixel_size*scaleFactor;
plotting.smart_figure(455454)
clf()
subplot(2,2,1)
aobject = angle(object);
range = sp_quantile(aobject(cache.object_ROI{:}), [1e-3, 1-1e-3],10);
aobject = (aobject - range(1)) / (range(2) - range(1));
grids = {(-ceil(self.Np_o(2)/2):ceil(self.Np_o(2)/2)-1)*scale(2), ...
(-ceil(self.Np_o(1)/2):ceil(self.Np_o(1)/2)-1)*scale(1)};
imagesc(grids{:}, aobject, [-2, 1]); % reduce contrast
colormap bone
axis xy
hold on
if isfield(par,'beam_source') && strcmp(par.beam_source, 'electron')
ylabel('Position [nm]')
else
ylabel('Position [\mum]')
end
pos_scales = (pos-self.Np_o([2,1])/2) .* scale([2,1]);
for i = 1:length(self.reconstruct_ind)
id = self.reconstruct_ind{i};
if any(mode.probe_positions_weight)
% plot importance
scatter(pos_scales(id,1), pos_scales(id,2), max(mode.probe_positions_weight(id,:),[],2)*20, marker_colors{1+mod(i,4)})
end
mean_err = mean(std(pos_err));
range = max(pos) - min(pos);
up = 0.02 * min(range) / mean_err;
rounding_order = 10^floor(log10(up));
up = ceil(up / rounding_order)*rounding_order;
quiver( pos_scales(id,1), pos_scales(id,2), scale(1)*pos_err(id,1)*up, scale(2)*pos_err(id,2)*up, 0, marker_colors{1+mod(i,4)})
end
hold off
axis equal xy tight
range = [min(pos_scales(:,1)), max(pos_scales(:,1)), min(pos_scales(:,2)), max(pos_scales(:,2))];
axis(range)
title(sprintf('Position errors, upscaled %ix', up))
subplot(2,2,3)
plot(mean(mode.probe_positions_weight,2), 'b.-')
ylim([0, max(mean(mode.probe_positions_weight,2))])
hold all
for i = 1:length(self.reconstruct_ind)
vline(self.reconstruct_ind{i}(end), '-r')
end
hold off
axis tight
ylabel('Importance weights')
xlabel('Position #')
title('Relative importance weights for geometry model')
subplot(2,2,2)
yyaxis left
h = plot(pos_err(:,1), 'w.');
axis tight
ylabel('Position error [px]')
yyaxis right
plot(pos_err(:,1)*self.pixel_size(2)*unitFactor, 'b.-')
axis tight
xlabel('Position #')
ylabel(strcat('Position error [',unitLabel,']'))
hold all
for i = 1:length(self.reconstruct_ind)
vline(self.reconstruct_ind{i}(end), '-r')
end
hold off
title( 'Horizontal')
grid on
%legend({sprintf('STD=%3.2g nm', std(pos_err(:,1)*self.pixel_size(2)*unitFactor) )})
legend({sprintf(strcat('STD=%3.2g ',unitLabel), std(pos_err(:,1)*self.pixel_size(2)*unitFactor) )})
subplot(2,2,4)
yyaxis left
h = plot(pos_err(:,2), 'w.');
ylabel('Position error [px]')
axis tight
yyaxis right
plot(pos_err(:,2)*self.pixel_size(1)*unitFactor, 'b.-')
axis tight
%ylabel('Position error [nm]')
ylabel(strcat('Position error [',unitLabel,']'))
xlabel('Position #')
hold all
title( 'Vertical')
legend({sprintf(strcat('STD=%3.2g ',unitLabel), std(pos_err(:,2)*self.pixel_size(1)*unitFactor) )})
grid on
for i = 1:length(self.reconstruct_ind)
vline(self.reconstruct_ind{i}(end), '-r')
end
hold off
plotting.suptitle('Random position errors after subtraction of geometry model')
try
if length(self.reconstruct_ind) == 2 && verbose() > 1 && length(self.reconstruct_ind{1}) == length(self.reconstruct_ind{2})
disp('Correlation between two scans')
corr( pos_err(self.reconstruct_ind{1},:), pos_err(self.reconstruct_ind{2},:) )
end
end
end
end
@@ -0,0 +1,81 @@
% PLOT_GEOM_CORRECTIONS plot evolution of intensity correction
%
% plot_geom_corrections(self)
%
% ** 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 plot_intensity_corr(self)
plotting.smart_figure(131231)
subplot(1,2,1)
corr = abs(self.intensity_corr/median(self.intensity_corr));
plot(corr)
axis([1,self.Npos, 0, max(corr)])
title('Intensity evolution')
subplot(1,2,2)
show_spatial_distribution(self.probe_positions_0, abs( self.intensity_corr), false, false)
axis off image
colorbar
title('Intensity distribution')
end
@@ -0,0 +1,145 @@
% PLOT_OBJECT_MODES incoherent object modes / layers / objects belonging to multiple scans
%
% plot_object_modes(self, cache)
%
% ** self structure containing inputs: e.g. current reconstruction results, data, mask, positions, pixel size, ..
% ** cache structure with precalculated values to avoid unnecessary overhead
%
% 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 object{ii}:
% 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 plot_object_modes(self, cache)
import engines.GPU.GPU_wrapper.*
import engines.GPU.shared.*
import utils.*
import math.*
import plotting.*
[Nscans,Nlayers] = size(self.object);
ROI = cache.object_ROI;
for ii = 1:Nscans
object{ii} = cat(3,self.object{ii,:});
object{ii} = Ggather(object{ii}(ROI{:},:));
illum{ii} = cache.illum_sum_0{ii}(ROI{:});
end
plotting.smart_figure(302809)
kk = 1;
scale = self.pixel_size;
Np_o = [size(object{1},1),size(object{1},2)];
Np_o(2) = Np_o(2) * Nlayers;
for ii = 1:Nscans
grids = {(-ceil(Np_o(2)/2):ceil(Np_o(2)/2)-1)*scale(2), ...
(-ceil(Np_o(1)/2):ceil(Np_o(1)/2)-1)*scale(1)};
amp_obj = abs(object{ii});
% consider only the illuminated region
ROI_mask = illum{ii} >= 0.5*quantile(illum{ii}(:), 0.9);
[ROI] = get_ROI(ROI_mask);
ROI_mask = repmat(ROI_mask,1,1,size(amp_obj,3));
RANGE_amp = sp_quantile(amp_obj(ROI_mask),[5e-3,1-5e-3], 4)';
RANGE_amp(2) = max(RANGE_amp(2), RANGE_amp(1)+1e-6);
[~, gamma] = stabilize_phase(object{ii}(ROI{:},:));
ang_object = -angle(object{ii}.*gamma);
RANGE_angle = sp_quantile(ang_object(ROI_mask),[1e-3,1-1e-3], 4)';
for jj = 1:Nlayers
% avoid plotting residua in not illuminated regions for object{ii}
resid_mask = cache.illum_sum_0{ii}(ROI{:})/ cache.MAX_ILLUM(ii) > 0.1;
resid_mask = imfill(gather(resid_mask), 'holes'); % gpuArray and imfill seems to be very unstable
residues = resid_mask(2:end,2:end) & (abs(utils.findresidues(object{ii}(:,:,jj))) > 0.1);
[X,Y] = find(residues);
end
ax(2*kk-1)=subplot(2,Nscans,ii);
imagesc(grids{:},reshape(amp_obj, Np_o))
if diff(RANGE_amp)>0;caxis(RANGE_amp); end
title(sprintf('Scan %i (L:%i)', ii, jj))
ylabel(sprintf('Amplitude - <%3.2g ; %3.2g>', RANGE_amp))
axis xy tight image
colormap bone
set(gca,'TickLength',[0 0])
set(gca,'XTick',[],'YTick',[])
ax(2*kk)=subplot(2,Nscans,Nscans+kk);
imagesc(grids{:},reshape(ang_object, Np_o))
hold all
plot(Y,X,'or')
hold off
if diff(RANGE_angle)>0; caxis((RANGE_angle')); end
ylabel(sprintf('Phase - <%3.2g ; %3.2g>', RANGE_angle))
axis xy tight image
colormap bone
set(gca,'TickLength',[0 0])
set(gca,'XTick',[],'YTick',[])
kk = kk + 1 ;
end
linkaxes(ax, 'xy')
end
@@ -0,0 +1,142 @@
% PLOT_PROBE_MODES plot incoherent probe modes
%
% plot_probe_modes(self, cache)
%
% ** self structure containing inputs: e.g. current reconstruction results, data, mask, positions, pixel size, ..
% ** cache structure with precalculated values to avoid unnecessary overhead
%
% 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 probe:
% 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 plot_probe_modes(self, par)
import engines.GPU.GPU_wrapper.*
import utils.*
import math.*
import plotting.*
for i = 1:par.probe_modes
power(i) = Ggather(mean2(abs(self.probe{i}(:,:,1)).^2));
end
power = power / sum(power);
grids = {(-ceil(self.Np_p(2)/2):ceil(self.Np_p(2)/2)-1)*self.pixel_size(2), ...
(-ceil(self.Np_p(1)/2):ceil(self.Np_p(1)/2)-1)*self.pixel_size(1)};
plotting.smart_figure(46456)
for i = 1:par.probe_modes
mode = Ggather(mean(mean(self.probe{i},3),4));
ax(2*i-1)=subplot(2,par.probe_modes,i);
RANGE = sp_quantile(abs(mode),[1e-3,1-5e-3], 4)';
RANGE(2) = max(RANGE(2), RANGE(1)+1e-6);
amode = abs(mode);
imagesc3D(grids{:},amode)
if diff(RANGE)>0;caxis(RANGE); end
title(sprintf('Mode %i, P:%3.2g', i, power(i)))
ylabel(sprintf('Amplitude - <%3.2g ; %3.2g>', RANGE))
axis image xy
colormap bone
set(gca,'TickLength',[0 0])
set(gca,'XTick',[],'YTick',[])
ax(2*i)=subplot(2,par.probe_modes,par.probe_modes+i);
arg = -angle(utils.stabilize_phase(mode));
RANGE_arg = sp_quantile(arg,[1e-3,1-1e-3], 4)';
imagesc3D(grids{:},arg )
if diff(RANGE_arg)>0; caxis((RANGE_arg')); end
ylabel(sprintf('Phase - <%3.2g ; %3.2g>', RANGE_arg))
axis image xy
colormap bone
set(gca,'TickLength',[0 0])
set(gca,'XTick',[],'YTick',[])
end
linkaxes(ax, 'xy')
%{
if par.probe_modes > par.Nscans % dont run for multiscan
reconstruct_ind = [self.reconstruct_ind{:}];
if par.variable_probe
%plotting.smart_figure(id+1) %a bug?
plotting.smart_figure(46457) %modified by YJ
clf
power = power / sum(power);
for i = 1:length(self.probe)
%pos = self.probe{i}.probe_positions;
pos = self.probe_positions_0;
pos = pos(:,[2,1]);
pos(:,1) = -pos(:,1);
subplot(2,1,1)
hold all
plot(power(i))
hold off
title('Variable incoherent probe')
xlabel('Normalized mode power')
subplot(2,par.probe_modes,par.probe_modes+i)
scatter(pos(reconstruct_ind,:),gather(W(reconstruct_ind)), 20); %what is W?
axis off image
end
end
end
%}
end
@@ -0,0 +1,181 @@
% PLOT_RESULTS show current reconstruction and errors during ptychography
%
% plot_results(self, cache, par, fourier_error,probe_positions)
%
% ** self structure containing inputs: e.g. current reconstruction results, data, mask, positions, pixel size, ..
% ** cache structure with precalculated values to avoid unnecessary overhead
% ** par structure containing parameters for the engines
% ** fourier_error array [Npos,1] containing evolution of reconstruction error
% ** probe_positions array [Npos,2] with probe positions for the main coherence mode
%
% 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 plot_results(self, cache, par, fourier_error,probe_positions)
import engines.GPU.GPU_wrapper.*
import utils.*
import math.*
import plotting.*
likelihood = lower(par.likelihood);
try
verbose(1,'Plotting ... ')
Np_o = self.Np_o;
Npos = length(probe_positions);
reconstruct_ind = [self.reconstruct_ind{:}];
ind = find(any(~isnan(fourier_error),2));
probe = Ggather(self.probe{1}(:,:,1,1));
% show extended DoF projection through layers of first scan
object = prod(cat(3,self.object{1,:}),3);
if par.fourier_ptycho
object = fft2(fftshift(object));
end
object = object(cache.object_ROI{:});
plotting.smart_figure(10)
clf()
number_iterations = size(fourier_error,1);
ha = tight_subplot(2,2,[.01 .01],[.01 .01],[.01 .01]);
axes(ha(1))
pixel_size = self.pixel_size .* cosd(par.sample_rotation_angles([1,2]));
params = {'scale', pixel_size,'enhance_contrast', true};
probe_positions = probe_positions - repmat([mean(cache.object_ROI{2})-Np_o(2)/2, mean(cache.object_ROI{1})-Np_o(1)/2],Npos,1);
imagesc_hsv(object ,params{:});
if ~par.fourier_ptycho
% avoid plotting residua in not illuminated regions
resid_mask = cache.illum_sum_0{1}(cache.object_ROI{:})/ cache.MAX_ILLUM(1) > 0.1;
% find residua to plot
residues = resid_mask(2:end, 2:end) & (abs(utils.findresidues(object)) > 0.1);
[X,Y] = find(residues);
if length(probe_positions) < 2e3
points = probe_positions(reconstruct_ind, :);
hold all
plot(points(:,1)*pixel_size(2)*1e6, points(:,2)*pixel_size(1)*1e6, '.w')
plot((Y-size(object,2)/2)*pixel_size(2)*1e6,(X-size(object,1)/2)*pixel_size(1)*1e6,'ow')
hold off
end
end
axis xy
ylabel('Reconstruction in fake colors')
axes(ha(3))
probe = utils.prop_free_nf(probe, self.lambda, sum(self.z_distance(1:end-1))/2, self.pixel_size);
imagesc_hsv(probe, params{:} );
axis xy
ylabel('Contrast enhanced probe')
subplot(2,2,2)
fourier_error(fourier_error == 0) = nan;
if strcmpi(likelihood, 'poisson')
fourier_error = (bsxfun(@minus, fourier_error, fourier_error(1,:)));
end
if ~isempty(ind) %if there is somethign to plot
hold all
plot(ind, fourier_error(ind,reconstruct_ind), '-')
ind_missing = ~ismember(1:self.Npos, reconstruct_ind);
if any(ind_missing)
plot(ind, fourier_error(ind,ind_missing), '--')
end
plot(ind, nanmean(fourier_error(ind,~ind_missing)'),'k', 'LineWidth', 3)
plot(ind, nanmedian(fourier_error(ind,~ind_missing)'),'k--', 'LineWidth', 3)
hold off
grid on
set(gca, 'xscale', 'log')
if strcmpi(likelihood, 'L1')
set(gca, 'yscale', 'log')
end
xlim([1, number_iterations])
% ignore the first iteration error in plotting
try ylim([min2(fourier_error(2:end,:)), max2(fourier_error(2:end,:))]); end
switch likelihood
case 'poisson', title('Relative neg-likelihood change');
case 'l1', title('Fourier error');
end
end
subplot(2,2,4)
if length(ind) > 1
err = fourier_error(ind(end) , reconstruct_ind) ;
pos = pixel_size([2,1]).*probe_positions(reconstruct_ind,:);
%% compatibility with the CPU code
pos(:,2) = -pos(:,2);
show_spatial_distribution(Ggather(pos), Ggather(err), false, length(probe_positions) < 2e3)
axis off equal
end
title('Spatial distribution of error')
catch err
warning('Error during plotting: %s', err.message)
keyboard
disp('plotting failed')
end
end
@@ -0,0 +1,111 @@
% PLOT_VARIABLE_PROBE plot SVD decomposition of the probes to show their differences
%
% plot_variable_probe(self, par)
%
% ** self structure containing inputs: e.g. current reconstruction results, data, mask, positions, pixel size, ..
% ** par structure containing parameters for the 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 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 plot_variable_probe(self, par)
import engines.GPU.GPU_wrapper.*
import plotting.*
import math.*
probe = self.probe{1}; %the FIRST probe mode in mixed-states
% probe = fftshift_2D(fft2( fftshift_2D( self.probe{1})));
%Note by YJ: is ploting real part enough? Seems they are all real, why?
probe_evolution= real(self.probe_evolution);
plotting.smart_figure(12131)
ax(1)=subplot(2,1+par.variable_probe_modes,1);
imagesc_hsv(probe(:,:,:,1))
axis xy off
title('Constant mode')
for ii = 1:par.variable_probe_modes
ax(ii+1)=subplot(2,1+par.variable_probe_modes,1+ii);
imagesc_hsv(probe(:,:,:,1+ii))
axis xy off
title(sprintf('Variable mode %i', ii))
end
subplot(2,1,2)
plot( probe_evolution(:,1)-1 , 'k' );
hold on
plot( probe_evolution(:,2:end))
hold off
for kk = 1:length(self.reconstruct_ind)
vline(self.reconstruct_ind{kk}(end),'r--')
end
hold off
axis tight
if par.variable_probe && par.variable_intensity
legend({'Intensity correction', 'Variable mode evol'}, 'Location', 'best')
elseif par.variable_intensity
legend({'Intensity correction'}, 'Location', 'best')
else
legend({'Variable mode evol'}, 'Location', 'best')
end
xlabel('Position #')
ylabel('Relative mode importance')
title('Evolution of each variable probe mode')
linkaxes(ax, 'xy');
end
@@ -0,0 +1,202 @@
% IMAGESC_HSV for plotting complex valued arrays , similar to imagesc3D but with more options
% imagesc_hsv(varargin)
%
% ** varargin see the code
%
% 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 imagesc_hsv(varargin)
import utils.*
import math.*
par = inputParser;
par.addOptional('data', [])
par.addParameter('scale', nan , @isnumeric )
par.addParameter('clim', [] , @isnumeric )
par.addParameter('inverse', false , @islogical ) % use white background
par.addParameter('show_ROI', false , @islogical ) % show only intersting area
par.addParameter('points', [] , @isnumeric ) % plot dots
par.addParameter('enhance_contrast', false , @islogical ) % plot dots
par.addParameter('axis', [] , @isnumeric ) % plot dots
par.addParameter('stabilize_phase', true , @islogical ) % plot dots
par.addParameter('show', true , @islogical ) % plot dots
par.parse(varargin{:})
r = par.Results;
data = r.data;
clim = r.clim;
if all(data(:) == 0)
warning('Empty data to plot')
return
end
[W,H] = size(data);
if ~isempty(r.axis)
X = linspace(r.axis(1),r.axis(2),W)*1e6;
Y = linspace(r.axis(3),r.axis(4),H)*1e6;
else
if ~isnan(r.scale)
scale = ones(2,1).*r.scale(:);
X = [-W/2:W/2-1]* scale(1)*1e6;
Y = [-H/2:H/2-1]* scale(2)*1e6;
else
X = 1:W; Y = 1:H;
end
end
if r.show_ROI
asum = abs(sum(data,3));
try
T1 = (graythresh_new((sum(asum,1))));
T2 = (graythresh_new((sum(asum,2))));
asum(:,sum(asum,1) < T1) = 0;
asum(sum(asum,2) < T2,:) = 0;
[ROI] = get_ROI(asum > 0.01*quantile(asum(:), 0.99), 0);
data = data(ROI{:});
X = X(ROI{1});
Y = Y(ROI{2});
catch
warning('ROI estimation failed')
end
end
[W,H] = size(data);
if ~isempty(clim)
ind_min = abs(data) < clim(1);
ind_max = abs(data) > clim(2);
data(ind_min) = data(ind_min) ./ abs(data(ind_min)) * clim(1);
data(ind_max) = data(ind_max) ./ abs(data(ind_max)) * clim(2);
end
adata = abs(data);
alpha = 1e-3;
tmp= sort(adata(:));
MAX = tmp(ceil(end*(1-alpha)));
ind = adata > MAX;
data(ind) = MAX * data(ind) ./ abs(data(ind));
if r.enhance_contrast
data = data ./ sqrt(alpha+abs(data));
clim = sqrt(clim);
end
if r.stabilize_phase
data = stabilize_phase(data, abs(data), abs(data), 'remove_ramp', false);
end
adata = abs(data);
if isempty(clim)
range = sp_quantile(adata(:), [1e-2, 1-1e-2],10);
else
range = clim;
end
adata = (adata - range(1) ) ./ ( range(2) - range(1) );
ang_data = angle(data);
if r.enhance_contrast && r.stabilize_phase
ang_range = max(abs(sp_quantile(ang_data(:), [1e-2, 1-1e-2],10)));
ang_range = max(1e-3, ang_range);
ang_data = 2*pi*ang_data ./ (2* ang_range);
end
if r.inverse
hue = mod(ang_data+1.5*pi, 2*pi)/(2*pi);
hsv_data = [ hue(:) , adata(:), ones(W*H,1) ];
else
hue = mod(ang_data+2.5*pi, 2*pi)/(2*pi);
hsv_data = [ hue(:) , ones(W*H,1), adata(:) ];
end
hsv_data = min(max(0, hsv_data),1);
rgb_data = hsv2rgb(hsv_data);
rgb_data = reshape(rgb_data, W,H,3);
rgb_data = min(1,rgb_data);
if r.show
hh = imagesc(Y,X, rgb_data );
axis image
end
if r.show
% Get the parent Axes of the image
axis image
if ~isempty(r.points) && ~any(isnan(r.scale))
hold on
points = r.scale.*1e6.*r.points;
plot( points(:,1),points(:,2), '.w')
hold off
end
end
end
@@ -0,0 +1,369 @@
function [x0,y0,iout,jout] = intersections(x1,y1,x2,y2,robust)
%INTERSECTIONS Intersections of curves.
% Computes the (x,y) locations where two curves intersect. The curves
% can be broken with NaNs or have vertical segments.
%
% Example:
% [X0,Y0] = intersections(X1,Y1,X2,Y2,ROBUST);
%
% where X1 and Y1 are equal-length vectors of at least two points and
% represent curve 1. Similarly, X2 and Y2 represent curve 2.
% X0 and Y0 are column vectors containing the points at which the two
% curves intersect.
%
% ROBUST (optional) set to 1 or true means to use a slight variation of the
% algorithm that might return duplicates of some intersection points, and
% then remove those duplicates. The default is true, but since the
% algorithm is slightly slower you can set it to false if you know that
% your curves don't intersect at any segment boundaries. Also, the robust
% version properly handles parallel and overlapping segments.
%
% The algorithm can return two additional vectors that indicate which
% segment pairs contain intersections and where they are:
%
% [X0,Y0,I,J] = intersections(X1,Y1,X2,Y2,ROBUST);
%
% For each element of the vector I, I(k) = (segment number of (X1,Y1)) +
% (how far along this segment the intersection is). For example, if I(k) =
% 45.25 then the intersection lies a quarter of the way between the line
% segment connecting (X1(45),Y1(45)) and (X1(46),Y1(46)). Similarly for
% the vector J and the segments in (X2,Y2).
%
% You can also get intersections of a curve with itself. Simply pass in
% only one curve, i.e.,
%
% [X0,Y0] = intersections(X1,Y1,ROBUST);
%
% where, as before, ROBUST is optional.
% Version: 2.0, 25 May 2017
% Author: Douglas M. Schwarz
% Email: dmschwarz=ieee*org, dmschwarz=urgrad*rochester*edu
% Real_email = regexprep(Email,{'=','*'},{'@','.'})
% Theory of operation:
%
% Given two line segments, L1 and L2,
%
% L1 endpoints: (x1(1),y1(1)) and (x1(2),y1(2))
% L2 endpoints: (x2(1),y2(1)) and (x2(2),y2(2))
%
% we can write four equations with four unknowns and then solve them. The
% four unknowns are t1, t2, x0 and y0, where (x0,y0) is the intersection of
% L1 and L2, t1 is the distance from the starting point of L1 to the
% intersection relative to the length of L1 and t2 is the distance from the
% starting point of L2 to the intersection relative to the length of L2.
%
% So, the four equations are
%
% (x1(2) - x1(1))*t1 = x0 - x1(1)
% (x2(2) - x2(1))*t2 = x0 - x2(1)
% (y1(2) - y1(1))*t1 = y0 - y1(1)
% (y2(2) - y2(1))*t2 = y0 - y2(1)
%
% Rearranging and writing in matrix form,
%
% [x1(2)-x1(1) 0 -1 0; [t1; [-x1(1);
% 0 x2(2)-x2(1) -1 0; * t2; = -x2(1);
% y1(2)-y1(1) 0 0 -1; x0; -y1(1);
% 0 y2(2)-y2(1) 0 -1] y0] -y2(1)]
%
% Let's call that A*T = B. We can solve for T with T = A\B.
%
% Once we have our solution we just have to look at t1 and t2 to determine
% whether L1 and L2 intersect. If 0 <= t1 < 1 and 0 <= t2 < 1 then the two
% line segments cross and we can include (x0,y0) in the output.
%
% In principle, we have to perform this computation on every pair of line
% segments in the input data. This can be quite a large number of pairs so
% we will reduce it by doing a simple preliminary check to eliminate line
% segment pairs that could not possibly cross. The check is to look at the
% smallest enclosing rectangles (with sides parallel to the axes) for each
% line segment pair and see if they overlap. If they do then we have to
% compute t1 and t2 (via the A\B computation) to see if the line segments
% cross, but if they don't then the line segments cannot cross. In a
% typical application, this technique will eliminate most of the potential
% line segment pairs.
%
%
% Copyright (c) 2017, Douglas M. Schwarz
% 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.
%
%
% Input checks.
if verLessThan('matlab','7.13')
error(nargchk(2,5,nargin)) %#ok<NCHKN>
else
narginchk(2,5)
end
% Adjustments based on number of arguments.
switch nargin
case 2
robust = true;
x2 = x1;
y2 = y1;
self_intersect = true;
case 3
robust = x2;
x2 = x1;
y2 = y1;
self_intersect = true;
case 4
robust = true;
self_intersect = false;
case 5
self_intersect = false;
end
% x1 and y1 must be vectors with same number of points (at least 2).
if sum(size(x1) > 1) ~= 1 || sum(size(y1) > 1) ~= 1 || ...
length(x1) ~= length(y1)
error('X1 and Y1 must be equal-length vectors of at least 2 points.')
end
% x2 and y2 must be vectors with same number of points (at least 2).
if sum(size(x2) > 1) ~= 1 || sum(size(y2) > 1) ~= 1 || ...
length(x2) ~= length(y2)
error('X2 and Y2 must be equal-length vectors of at least 2 points.')
end
% Force all inputs to be column vectors.
x1 = x1(:);
y1 = y1(:);
x2 = x2(:);
y2 = y2(:);
% Compute number of line segments in each curve and some differences we'll
% need later.
n1 = length(x1) - 1;
n2 = length(x2) - 1;
xy1 = [x1 y1];
xy2 = [x2 y2];
dxy1 = diff(xy1);
dxy2 = diff(xy2);
% Determine the combinations of i and j where the rectangle enclosing the
% i'th line segment of curve 1 overlaps with the rectangle enclosing the
% j'th line segment of curve 2.
% Original method that works in old MATLAB versions, but is slower than
% using binary singleton expansion (explicit or implicit).
% [i,j] = find( ...
% repmat(mvmin(x1),1,n2) <= repmat(mvmax(x2).',n1,1) & ...
% repmat(mvmax(x1),1,n2) >= repmat(mvmin(x2).',n1,1) & ...
% repmat(mvmin(y1),1,n2) <= repmat(mvmax(y2).',n1,1) & ...
% repmat(mvmax(y1),1,n2) >= repmat(mvmin(y2).',n1,1));
% Select an algorithm based on MATLAB version and number of line
% segments in each curve. We want to avoid forming large matrices for
% large numbers of line segments. If the matrices are not too large,
% choose the best method available for the MATLAB version.
if n1 > 1000 || n2 > 1000 || verLessThan('matlab','7.4')
% Determine which curve has the most line segments.
if n1 >= n2
% Curve 1 has more segments, loop over segments of curve 2.
ijc = cell(1,n2);
min_x1 = mvmin(x1);
max_x1 = mvmax(x1);
min_y1 = mvmin(y1);
max_y1 = mvmax(y1);
for k = 1:n2
k1 = k + 1;
ijc{k} = find( ...
min_x1 <= max(x2(k),x2(k1)) & max_x1 >= min(x2(k),x2(k1)) & ...
min_y1 <= max(y2(k),y2(k1)) & max_y1 >= min(y2(k),y2(k1)));
ijc{k}(:,2) = k;
end
ij = vertcat(ijc{:});
i = ij(:,1);
j = ij(:,2);
else
% Curve 2 has more segments, loop over segments of curve 1.
ijc = cell(1,n1);
min_x2 = mvmin(x2);
max_x2 = mvmax(x2);
min_y2 = mvmin(y2);
max_y2 = mvmax(y2);
for k = 1:n1
k1 = k + 1;
ijc{k}(:,2) = find( ...
min_x2 <= max(x1(k),x1(k1)) & max_x2 >= min(x1(k),x1(k1)) & ...
min_y2 <= max(y1(k),y1(k1)) & max_y2 >= min(y1(k),y1(k1)));
ijc{k}(:,1) = k;
end
ij = vertcat(ijc{:});
i = ij(:,1);
j = ij(:,2);
end
elseif verLessThan('matlab','9.1')
% Use bsxfun.
[i,j] = find( ...
bsxfun(@le,mvmin(x1),mvmax(x2).') & ...
bsxfun(@ge,mvmax(x1),mvmin(x2).') & ...
bsxfun(@le,mvmin(y1),mvmax(y2).') & ...
bsxfun(@ge,mvmax(y1),mvmin(y2).'));
else
% Use implicit expansion.
[i,j] = find( ...
mvmin(x1) <= mvmax(x2).' & mvmax(x1) >= mvmin(x2).' & ...
mvmin(y1) <= mvmax(y2).' & mvmax(y1) >= mvmin(y2).');
end
% Find segments pairs which have at least one vertex = NaN and remove them.
% This line is a fast way of finding such segment pairs. We take
% advantage of the fact that NaNs propagate through calculations, in
% particular subtraction (in the calculation of dxy1 and dxy2, which we
% need anyway) and addition.
% At the same time we can remove redundant combinations of i and j in the
% case of finding intersections of a line with itself.
if self_intersect
remove = isnan(sum(dxy1(i,:) + dxy2(j,:),2)) | j <= i + 1;
else
remove = isnan(sum(dxy1(i,:) + dxy2(j,:),2));
end
i(remove) = [];
j(remove) = [];
% Initialize matrices. We'll put the T's and B's in matrices and use them
% one column at a time. AA is a 3-D extension of A where we'll use one
% plane at a time.
n = length(i);
T = zeros(4,n);
AA = zeros(4,4,n);
AA([1 2],3,:) = -1;
AA([3 4],4,:) = -1;
AA([1 3],1,:) = dxy1(i,:).';
AA([2 4],2,:) = dxy2(j,:).';
B = -[x1(i) x2(j) y1(i) y2(j)].';
% Loop through possibilities. Trap singularity warning and then use
% lastwarn to see if that plane of AA is near singular. Process any such
% segment pairs to determine if they are colinear (overlap) or merely
% parallel. That test consists of checking to see if one of the endpoints
% of the curve 2 segment lies on the curve 1 segment. This is done by
% checking the cross product
%
% (x1(2),y1(2)) - (x1(1),y1(1)) x (x2(2),y2(2)) - (x1(1),y1(1)).
%
% If this is close to zero then the segments overlap.
% If the robust option is false then we assume no two segment pairs are
% parallel and just go ahead and do the computation. If A is ever singular
% a warning will appear. This is faster and obviously you should use it
% only when you know you will never have overlapping or parallel segment
% pairs.
if robust
overlap = false(n,1);
warning_state = warning('off','MATLAB:singularMatrix');
% Use try-catch to guarantee original warning state is restored.
try
lastwarn('')
for k = 1:n
T(:,k) = AA(:,:,k)\B(:,k);
[unused,last_warn] = lastwarn; %#ok<ASGLU>
lastwarn('')
if strcmp(last_warn,'MATLAB:singularMatrix')
% Force in_range(k) to be false.
T(1,k) = NaN;
% Determine if these segments overlap or are just parallel.
overlap(k) = rcond([dxy1(i(k),:);xy2(j(k),:) - xy1(i(k),:)]) < eps;
end
end
warning(warning_state)
catch err
warning(warning_state)
rethrow(err)
end
% Find where t1 and t2 are between 0 and 1 and return the corresponding
% x0 and y0 values.
in_range = (T(1,:) >= 0 & T(2,:) >= 0 & T(1,:) <= 1 & T(2,:) <= 1).';
% For overlapping segment pairs the algorithm will return an
% intersection point that is at the center of the overlapping region.
if any(overlap)
ia = i(overlap);
ja = j(overlap);
% set x0 and y0 to middle of overlapping region.
T(3,overlap) = (max(min(x1(ia),x1(ia+1)),min(x2(ja),x2(ja+1))) + ...
min(max(x1(ia),x1(ia+1)),max(x2(ja),x2(ja+1)))).'/2;
T(4,overlap) = (max(min(y1(ia),y1(ia+1)),min(y2(ja),y2(ja+1))) + ...
min(max(y1(ia),y1(ia+1)),max(y2(ja),y2(ja+1)))).'/2;
selected = in_range | overlap;
else
selected = in_range;
end
xy0 = T(3:4,selected).';
% Remove duplicate intersection points.
[xy0,index] = unique(xy0,'rows');
x0 = xy0(:,1);
y0 = xy0(:,2);
% Compute how far along each line segment the intersections are.
if nargout > 2
sel_index = find(selected);
sel = sel_index(index);
iout = i(sel) + T(1,sel).';
jout = j(sel) + T(2,sel).';
end
else % non-robust option
for k = 1:n
[L,U] = lu(AA(:,:,k));
T(:,k) = U\(L\B(:,k));
end
% Find where t1 and t2 are between 0 and 1 and return the corresponding
% x0 and y0 values.
in_range = (T(1,:) >= 0 & T(2,:) >= 0 & T(1,:) < 1 & T(2,:) < 1).';
x0 = T(3,in_range).';
y0 = T(4,in_range).';
% Compute how far along each line segment the intersections are.
if nargout > 2
iout = i(in_range) + T(1,in_range).';
jout = j(in_range) + T(2,in_range).';
end
end
% Plot the results (useful for debugging).
% plot(x1,y1,x2,y2,x0,y0,'ok');
function y = mvmin(x)
% Faster implementation of movmin(x,k) when k = 1.
y = min(x(1:end-1),x(2:end));
function y = mvmax(x)
% Faster implementation of movmax(x,k) when k = 1.
y = max(x(1:end-1),x(2:end));
@@ -0,0 +1,115 @@
% SHOW_SPATIAL_DISTRIBUTION plot distribution of a variable, you can also use scatter or scatter_hsv
%
% show_spatial_distribution(pos, values, symmetrize, plot_points, range, px_scale )
%
% ** pos positions for each value
% ** val plotted values
% ** symmetrize (bool) if true make the caxis symmetric around 0
% ** plot_points (bool) if true plot the positions where are provided values located
% ** range array 2x1 of min / max range
% ** px_scale size of a single pixel
%
%
% 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 show_spatial_distribution(pos, values, symmetrize, plot_points, range, px_scale )
pos = double(pos);
values = squeeze(double(values));
if nargin < 3; symmetrize = false; end
if nargin < 4; plot_points = true; end
if nargin < 5 || isempty(range); range = [min(values(:)), max(values(:))]; end
if nargin < 6; px_scale = 1; end
if range(1) == range(2)
range(1) = 0;
range(2) = max(range(1),1);
range = sort(range);
end
% remove missing data
missing = isnan(values);
pos(missing,:) = [];
values(missing) = [];
ax = [min(pos(:,1)), max(pos(:,1)), min(pos(:,2)), max(pos(:,2))];
N = max(100, 4*sqrt(length(pos)));
XI = linspace(ax(1), ax(2), N);
YI = linspace(ax(3), ax(4), N)';
warning('off','all')
Z = griddata(pos(:,1),pos(:,2),real(values),XI,YI,'linear');
if ~isreal(values)
Z = Z + 1i*griddata(pos(:,1),pos(:,2),imag(values),XI,YI,'linear');
end
warning('on','all')
if isreal(Z)
imagesc(px_scale*XI, px_scale*YI, Z, range)
colormap gray
else
imagesc_hsv(Z)
end
if plot_points
hold on
plot(px_scale*pos(:,1), px_scale*pos(:,2), 'wo')
hold off
axis equal tight
end
end
@@ -0,0 +1,129 @@
% PTYCHO_PLOT_WRAPPER wrapper around the default ptychoshelves plotting routine
%
% ptycho_plot_wrapper(self, par, fourier_error)
%
% ** self structure containing inputs: e.g. current reconstruction results, data, mask, positions, pixel size, ..
% ** par structure containing parameters for the engines
% ** fourier_error array [Npos,1] containing evolution of reconstruction error
% 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.
%
%% PLOTTING
function ptycho_plot_wrapper(self, par, fourier_error)
%% wrapper to the cSAXS default plotting function
import engines.GPU.GPU_wrapper.*
p = par.p;
p.object_size = ceil(p.object_size .* ( self.Np_p ./ p.asize)); % modify the size in case of presolver with different probe size
p.asize = self.Np_p;
p.numobjs = size(self.object,1);
Nlayers = size(self.object,2);
p.object = {};
for ii = 1:p.numobjs
p.object_size(ii,:) = self.Np_o;
p.object{ii} = [];
for jj = 1:Nlayers
p.object{ii}(:,:,1,jj) = Ggather(utils.crop_pad(self.object{ii,jj}, p.object_size));
end
end
p.object_modes = par.object_modes;
p.probe_modes = par.probe_modes;
p.probes = [];
for ii = 1:p.probe_modes
p.probes(:,:,:,ii) = Ggather(self.probe{ii}(:,:,:,1));
end
p.dx_spec=[self.pixel_size]/self.relative_pixel_scale;
p.engines = {struct()};
iterations = Ggather(find(any(~isnan(fourier_error),2)));
p.engines{1}.error_metric_final = struct();
p.engines{1}.error_metric_final.iteration=iterations;
p.engines{1}.error_metric_final.value = Ggather(fourier_error( iterations,:));
p.engines{1}.error_metric_final.method = par.method;
p.engines{1}.error_metric_final.err_metric = par.likelihood;
position_offset = 1+floor((p.object_size-self.Np_p)/2);
for ii = 1:p.numscans
ind = p.scanidxs{ii};
p.positions(ind,:) = self.modes{1}.probe_positions(ind,[2,1]) + position_offset(p.share_object_ID(ii),:);
end
p.plot.extratitlestring = '';
p.plot.show_only_FOV = true;
p.plot.mask_bool = false;
p.plot.log_scale = [1 1];
p.plot.subplwinobj_dir = 'vertical';
p.plot.show_layers = true;
p.plot.residua = true;
if isempty(p.plot.obtitlestring)
p.plot.obtitlestring = [core.generate_scan_name(p) ' '];
end
if isempty(p.plot.prtitlestring)
p.plot.prtitlestring = [core.generate_scan_name(p) ' '];
end
if par.share_object
p.share_object_ID = ones(p.numobjs,1);
else
p.share_object_ID = 1:p.numobjs;
end
core.analysis.plot_results(p, 'final', true)
end
@@ -0,0 +1,186 @@
% REPORT_REFINED_GEOMETRY report results of the geometry refinenement in a readable way
%
% p = report_refined_geometry(self, param, p)
%
%
% ** self structure containing inputs: e.g. current reconstruction results, data, mask, positions, pixel size, ..
% ** param structure containing parameters for the engines
% ** p ptychoshelves p structure
%
% returns:
% ** p updated ptychoshelves p structure
function p = report_refined_geometry(self, param, p)
import utils.*
scale = 1;
%% GENERATE REPORT ABOUT GEOMETRY REFINEMENT
if isempty(p.affine_matrix)
p.affine_matrix = diag([1,1]);
end
% aux function for printing results
mat2str=@(matrix)sprintf(' [%.4g , %.4g ; %.4g , %.4g ] ', reshape(matrix',[],1));
if ~isempty(self.affine_matrix) && param.probe_position_search < param.number_iterations && ~isempty(param.probe_geometry_model)
for ii = 1:length(self.affine_matrix)
%switch diagonal elements
self.affine_matrix{ii} = rot90(self.affine_matrix{ii},2)'; % rotation is important to match the coordinates with other engines
end
for ii = 1:length(self.affine_matrix)
p.affine_matrix_refined{ii} = p.affine_matrix * self.affine_matrix{ii};
end
if param.Nscans == 2 && param.share_object && param.mirror_objects
%% use mirrored scans to refine scanning geometry
verbose(0, '========================================================= ')
verbose(0, '==== Geometry parameters for shared 0/180 deg scans ===== ')
verbose(0, '========================================================= ')
verbose(0, '')
% find difference between 0 and 180 ,
affine_mat_relative = sqrtm(self.affine_matrix{1} * self.affine_matrix{2})*p.affine_matrix;
% keep only nondiagonal terms
affine_mat_relative = eye(2) + (1-eye(2)).*affine_mat_relative;
verbose(0, '=============== RELATIVE (0vs180deg) GEOMETRY REFINEMENT ===============')
verbose(0, '(apply p.affine_matrix manually to your template)')
verbose(0, 'p.affine_matrix = %s ', mat2str(affine_mat_relative))
[~, ~, rotation, shear] = math.decompose_affine_matrix(affine_mat_relative);
verbose(0, 'This correponds to the following parameters: [rotation=%.3fdeg , shear=%.3fdeg] ', [rotation, shear])
% find affine matrix that stays contant when moving from 0 to
% 180 deg, include also the diagonal terms from original affine
% matrix
affine_mat_global = sqrtm(self.affine_matrix{1} * ( [1,-1;-1,1] .* self.affine_matrix{2}));
affine_mat_global = affine_mat_global* diag(diag(p.affine_matrix));
verbose(0, '====================================================================================')
verbose(0, '')
scale = mean(diag(affine_mat_global));
else
%% use conventional scans to refine scanning geometry
median_affine_matrix = median(cat(3,p.affine_matrix_refined{:}),3);
verbose(0, '')
verbose(0, '========= 2D PTYCHO GEOMETRY REFINEMENT, apply manually to your template ===========')
verbose(0, 'p.affine_matrix = %s' , mat2str(median_affine_matrix))
verbose(0, '====================================================================================')
verbose(0, '')
verbose(0, 'Advanced: ======================== AFFINE CORRECTION OF SCANNER AXIS ====================')
verbose(0, 'Advanced: (for control system of piezo scanner, important for calibration of cSAXS fast FZP scanner)')
verbose(0, 'Advanced: correction_matrix = inv(p.affine_matrix) = %s ', mat2str(inv(median_affine_matrix)))
verbose(0, 'Advanced: ===============================================================================')
verbose(0, 'Note: Use scans at 0 and 180 deg with eng.share_object == true && eng.mirror_objects == true to get estimation of the 0vs180deg affine matrix requied for ptychotomography')
verbose(0, '')
verbose(0, '')
verbose(0, '==== Geometry parameters for each scan===== ')
for ii = 1:length(p.affine_matrix_refined)
[scale, asymmetry, rotation, shear] = math.decompose_affine_matrix(p.affine_matrix_refined{ii});
verbose(0, 'Scan #%i: [scale=%.4f , asymmetry=%.3f , rotation=%.3fdeg , shear=%.3fdeg, shift = %.1f %.1fpx ] ', [p.scan_number(ii), scale, asymmetry, rotation, shear, self.shift_scans(:,ii)'])
end
scale = mean(diag(median_affine_matrix));
end
%% evaluate results if the simulated geometry
if isfield(p,'simulation') && check_option(p.simulation,'affine_matrix')
% report for simulation
verbose(-2, '')
verbose(-2, '========== IDEAL AFFINE MATRIX vs RECONSTRUCTED AFFINE MATRIX ====')
verbose(-2, 'ideal_affine_matrix = %s ', mat2str(p.simulation.affine_matrix))
if param.Nscans == 2 && param.share_object && param.mirror_objects
affine_mat = diag(diag(affine_mat_global)) + affine_mat_relative - eye(2);
else
affine_mat = median_affine_matrix;
end
verbose(-2, 'refined_affine_matrix = %s ', mat2str(affine_mat))
verbose(-2, '==================================================================')
verbose(-2, '')
end
end
if param.number_iterations > param.detector_rotation_search && ~isempty(param.probe_geometry_model)
if isfield(p,'simulation') && check_option(p.simulation,'sample_rotation_angles')
% report for simulation
verbose(-2, '')
verbose(-2, '==== SIMULATION: IDEAL vs RECONSTRUCTED DETECTOR ROTATION CORRECTION =======')
verbose(-2, 'ideal camera rotation = %.3f deg reconstructed camera rotation = %.3f deg', p.simulation.sample_rotation_angles(3), self.detector_rotation(1))
verbose(-2, '=============================================================================')
verbose(-2, '')
else
% report for real data
verbose(0, '')
verbose(0, '========== RECONSTRUCTED DETECTOR ROTATION CORRECTION =====================')
verbose(0, '(misalignement between detector and the rotation axis, correct by camera rotation)')
verbose(0, 'Reconstructed camera rotation = %.3f deg', self.detector_rotation(1) + param.sample_rotation_angles(3))
verbose(0, '=============================================================================')
verbose(0, '')
end
end
if param.number_iterations > param.detector_scale_search && ~isempty(param.probe_geometry_model)
if isfield(p,'simulation') && isfield(p.simulation, 'affine_matrix') && param.detector_scale_search
% report for simulation
verbose(-2, '')
verbose(-2, '============ SIMULATION: IDEAL vs RECONSTRUCTED DETECTOR SCALE =============')
if check_option(p.simulation, 'z')
scale_z = p.z / p.simulation.z;
else
scale_z = 1;
end
verbose(-2, 'ideal scale = %.3f reconstructed scale = %.3f ', 1/(mean(diag(p.simulation.affine_matrix)) * scale_z), scale/self.detector_scale)
verbose(-2, '=============================================================================')
verbose(-2, '')
else
% report for real data
verbose(0, '')
verbose(0, '========== RECONSTRUCTED DETECTOR SCALE CORRECTION ========================')
verbose(0, '(relative scaling error of the provided reconstruction pixel p.dx_spec )')
verbose(0, 'reconstructed scale = %.3f ', scale/self.detector_scale)
verbose(0, '=============================================================================')
verbose(0, '')
end
end
if isinf(self.z_distance) && ...
((param.detector_scale_search < param.number_iterations) ...
|| (param.probe_position_search < param.number_iterations && any(ismember(param.probe_geometry_model, 'scale'))))
verbose(-2, '')
verbose(-2, '========== RECONSTRUCTED DETECTOR DISTANCE CORRECTION =====================')
if isfield(p,'simulation') && check_option(p.simulation, 'z')
% report for simulation
verbose(-2, '==== Compare ideal (simulated) distance and distance refined by ptychography')
if isfield(p.simulation, 'affine_matrix')
aff_corr_scale = mean(diag(p.simulation.affine_matrix));
else
aff_corr_scale = 1;
end
verbose(-2, 'ideal camera distance = %.4f estimated camera distance = %.4f', p.simulation.z/aff_corr_scale, p.z / (scale * self.detector_scale))
else
% report for measurements
verbose(-2, '(needs to be corrected by adjusting p.z parameter in the template)')
verbose(-2, '==== Scale error corresponds to the following p.z value')
verbose(-2, 'p.z = %.4f (error=%.2g%%)', p.z/(scale*self.detector_scale), 100*(1/(scale*self.detector_scale)-1))
if param.probe_position_search < param.number_iterations && ~isempty(param.probe_geometry_model)
verbose(0, '(corrected p.affine_matrix to be used with the new p.z value, add manually to your template)')
if exist('median_affine_matrix', 'var')
affine_mat = median_affine_matrix;
else
affine_mat = affine_mat_relative;
end
verbose(0, 'p.affine_matrix = %s ', mat2str(affine_mat / (scale/self.detector_scale) ))
end
end
verbose(-2, '=============================================================================')
end
end