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,117 @@
% ACCELERATE_GRADIENTS use the Nesterov's Accelerated Gradient method
%
% cache = accelerate_gradients(self, par, cache, 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
% ** iter number of the current iteration
%
% returns:
% ** self updated structure containing inputs
% ** cache structure with precalculated values - stores the previous accelerated gradients 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 [self,cache] = accelerate_gradients(self, par, cache, iter)
%% accelerated gradients extension, tries to look ahead in direction of the last update
if iter == par.accelerated_gradients_start
cache.object_prev = {self.object, self.object};
cache.probe_prev = {self.probe, self.probe};
for ii = 1:length(cache.illum_sum_0)
cache.update_weights{ii} = cache.illum_sum_0{ii}.^2 ./ (cache.illum_sum_0{ii}.^2 + 0.1*cache.MAX_ILLUM(ii)^2);
end
elseif iter > par.accelerated_gradients_start
object_start = max(par.object_change_start, par.accelerated_gradients_start);
probe_start = max(par.probe_change_start, par.accelerated_gradients_start);
cache.object_prev{1} = cache.object_prev{2};
cache.object_prev{2} = self.object;
cache.probe_prev{1} = cache.probe_prev{2};
cache.probe_prev{2} = self.probe;
% accelerate the object reconstructions
if iter > par.object_change_start
beta = (iter-object_start+1)/(iter-object_start+3);
for ii = 1:size(self.object,1)
for layer = 1:size(self.object,2)
if ii == 1 && utils.verbose() > 3
plotting.smart_figure(555)
update = cache.update_weights{ii}.* (self.object{ii,layer} - cache.object_prev{1}{ii,layer});
plotting.imagesc3D(update)
title('Acceleration step in the Nesterov method')
axis xy off
utils.verbose(0, 'Norm of accelerated gradient = %g', math.norm2(update) )
drawnow
end
self.object{ii,layer} = self.object{ii,layer} + ...
beta*cache.update_weights{ii}.*(self.object{ii,layer} - cache.object_prev{1}{ii,layer});
end
end
end
% accelerate only the first OPR mode of the probe
if iter > par.probe_change_start
beta = (iter-probe_start+1)/(iter-probe_start+3);
for ii = 1:numel(self.probe)
self.probe{ii}(:,:,:,1) = self.probe{ii}(:,:,:,1) + ...
beta.*(self.probe{ii}(:,:,:,1) - cache.probe_prev{1}{ii}(:,:,:,1));
end
end
end
end
@@ -0,0 +1,78 @@
% APPLY_SMOOTHNESS_CONSTRAINT simple weak smoothness constaint by convolution
%
% x = apply_smoothness_constraint(x, alpha)
%
% ** x image stack to be smoothed
% ** alpha relaxation smoothing constant, 0 = no smoothness, 1/8 = maximal smoothness given as conv(x, ones(3)/9)
%
% returns:
% ++ x smoothed array
% 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 x = apply_smoothness_constraint(x, alpha)
assert(alpha < 1/8, 'Too high smoothing')
if alpha > 0
psf = ones(3)*alpha;
psf(2,2) = 1-8*alpha;
if size(x,3) == 1
x = conv2(x, psf, 'same');
else
x = convn(x, psf, 'same');
end
end
end
@@ -0,0 +1,82 @@
% concatenate values from list of cells contaning structures with arrays
%
% array = cat_struct( struct, name, ind)
%
% ** struct list structures
% ** name field name to be ccntatenated
% ** ind which index to take {'last', 'first'}
%
%
% 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 array = cat_struct( struct, name, ind)
array = [];
if nargin < 3
ind = [];
end
for i = 1:length(struct)
s = struct{i}.(name);
if strcmp(ind, 'last')
s = s(end);
elseif strcmp(ind, 'first')
s = s(1);
end
array = [array, s(:)];
end
end
@@ -0,0 +1,126 @@
% GET_FOURIER_ERROR fast calculation of the Fourier plane (at detector) error normalized so that for
% gaussian noise approximation the ideal error should be close to 1
%
% Err = get_fourier_error(modF, aPsi, Noise,Mask, likelihood)
%
% ** modF pre-fftshifted and sqrt-ed data
% ** aPsi reciprocal amplitude model
% ** Noise estimated noise (STD) in each pixel after sqrt transform
% ** Mask masked values, 1 = ignored, 0 = use this pixel
% ** likelihood L1 or poisson
%
% returns:
% ++ Err calculated error for provided positions
% 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 Err = get_fourier_error(modF, aPsi, Noise,Mask, likelihood)
import engines.GPU_MS.GPU_wrapper.*
import utils.*
import math.*
if ~exist('likelihood', 'var'); likelihood = 'L1'; end
likelihood = lower(likelihood);
% USE Gfun IN ORDER TO MAKE IT FASTER ON GPU
if isempty(Mask) && isempty(Noise)
switch likelihood
case 'l1', Err = Gfun(@get_err,modF, aPsi);
case 'poisson', Err = Gfun(@get_loglik,modF, aPsi);
end
elseif ~isempty(Mask) && isempty(Noise)
switch likelihood
case 'l1', Err = Gfun(@get_err_masked,modF, aPsi, Mask);
case 'poisson', Err = Gfun(@get_loglik_masked,modF, aPsi, Mask);
end
elseif isempty(Mask) && ~isempty(Noise)
Err = Gfun(@get_err_noise,modF, aPsi, Noise);
else
Err = Gfun(@get_err_noise_mask, modF, aPsi, Mask, Noise);
end
switch likelihood
case 'l1', Err = sqrt(squeeze(mean2(Err)))';
case 'poisson', Err = squeeze(mean2(Err))';
otherwise, error('Unsupported likelihood')
end
end
function L = get_loglik(modF, aPsi)
modF2 = modF.^2;
aPsi2 = aPsi.^2;
L = -(modF2 .* log(aPsi2+1e-6) - aPsi2) ;
end
function L = get_loglik_masked(modF, aPsi,Mask)
modF2 = modF.^2;
aPsi2 = aPsi.^2;
L = -(1-Mask) .* (modF2 .* log(aPsi2+1e-6) - aPsi2) ;
end
function E = get_err(modF, aPsi)
E = (modF-aPsi).^2 / (0.5)^2; % 0.5 is correction for the Poisson noise (if we expect single photon precision)
end
function E = get_err_masked(modF, aPsi, Mask)
E = (modF-aPsi).^2 .* (1-Mask) / (0.5)^2;
end
function E = get_err_noise(modF, aPsi, Noise)
E = (modF-aPsi).^2 ./ Noise.^2;
end
function E = get_err_noise_mask(modF, aPsi, Mask, Noise)
E = (modF-aPsi).^2 ./ Noise.^2 .* (1-Mask);
end
@@ -0,0 +1,109 @@
% GET_IMG_GRAD get vertical and horizontal gradient of the image, it is slightly faster on GPU than
% the version in math.get_img_grad
%
% [dX, dY] = get_img_grad(img)
%
% ** img stack of complex images
%
% returns:
% ++ dX,dY - directional gradients of the image
%
% 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 [dX, dY] = get_img_grad(img)
import engines.GPU_MS.GPU_wrapper.*
Np = size(img);
if nargout == 1
fX = fft(img,[],2);
X = (fftshift((0:Np(2)-1)/Np(2))-0.5);
dX = bsxfun(@times, fX,2i*pi*X);
dX = ifft(dX,[],2);
return
end
if nargout > 1
X = (fftshift((0:Np(2)-1)/Np(2))-0.5);
Y = (fftshift((0:Np(1)-1)/Np(1))-0.5)';
% use matlab implicite GPU paralelization
if isa(img, 'gpuArray')
% it is much faster to use 2D fft for GPU despite higher
% computational costs
img = fft2(img);
% make it slightly faster with GPU
[dX, dY] = Gfun(@multiply_gfun, img, X, Y);
dX = ifft2(dX);
dY = ifft2(dY);
else
fX = fft(img,[],2);
fY = fft(img,[],1);
dX = bsxfun(@times, fX,2i*pi*X);
dY = bsxfun(@times, fY,2i*pi*Y);
dX = ifft(dX,[],2);
dY = ifft(dY,[],1);
end
end
end
function [dX, dY]=multiply_gfun(img, X,Y)
dX = img .* (2i*pi)* X;
dY = img .* (2i*pi)* Y;
end
@@ -0,0 +1,287 @@
% GET_RECIPROCAL_MODEL get estimate of the measured intensity from given electric field Psi
%
% [aPsi, aPsi2, cache, self] = get_reciprocal_model(self, Psi, modF, mask,iter, g_ind, par, cache)
%
% ** self structure containing inputs: e.g. current reconstruction results, data, mask, positions, pixel size, ..
% ** Psi where Psi is the propagated exitwave
% ** modF pre-fftshifted and sqrt-ed data
% ** mask masked values, 1 = ignored, 0 = use this pixel
% ** iter current iteration number
% ** ind processed indices
% ** par structure containing parameters for the engines
% ** cache structure with precalculated values
%
% returns:
% ++ aPsi reciprocal amplitude model
% ++ aPsi reciprocal intensity model
% ++ cache structure with precalculated values
% ++ 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 [aPsi, aPsi2, cache, self] = get_reciprocal_model(self, Psi, modF, mask,iter, g_ind, par, cache)
import engines.GPU_MS.GPU_wrapper.*
aPsi2 = [];
if par.probe_modes == 1 && isempty(self.background) && self.diff_pattern_blur == 0 ...
&& ~par.background_detection && strcmpi(par.likelihood, 'l1') && par.upsampling_data_factor == 0
% or the simplest and fastest option: just get absolute value
aPsi = abs(Psi{1});
aPsi2 = [];
elseif par.probe_modes == 1 && ~isempty(self.background) && self.diff_pattern_blur == 0 ...
&& ~par.background_detection && strcmpi(par.likelihood, 'l1') && par.upsampling_data_factor == 0
% second simplest option, abs + background
aPsi = Gfun(@modulus_with_background,Psi{1}, self.background , cache.background_profile);
else
% apply corrected model and sum up all coherence modes
aPsi2 = sumsq_cell(Psi);
% assume that the data were upsampled by the utils.unbinning_2D function
if par.upsampling_data_factor
aPsi2 = utils.binning_2D(aPsi2, 2^par.upsampling_data_factor);
end
%%%%%%%%%%%%%%%% linear correction model %%%%%%%%%%%%%%%%%%%%%%%
[aPsi2,cache, self] = get_linear_correction_model(self,par,cache,aPsi2,modF,mask,iter, g_ind );
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
aPsi = sqrt(aPsi2);
end
end
function aPsi = modulus_with_background(Psi, background_value, background_shape)
rPsi = real(Psi);
iPsi = imag(Psi);
aPsi2 = rPsi.^2 + iPsi.^2;
aPsi2 = aPsi2 + background_value .* background_shape;
% sqrt is very slow ...
aPsi = sqrt(aPsi2);
% aPsi = exp(0.5*log(aPsi2)); % log identity has exactly the same calculation time
end
function y = sumsq_cell(x)
% Description: sum incoherently cells x, make it inplace and fast
N = length(x);
if N <= 15 && builtin( 'isa', x{1}, 'gpuArray' )
switch N
case 1, fun = @sum_1;
case 2, fun = @sum_2;
case 3, fun = @sum_3;
case 4, fun = @sum_4;
case 5, fun = @sum_5;
case 6, fun = @sum_6;
case 7, fun = @sum_7;
case 8, fun = @sum_8;
case 9, fun = @sum_9;
case 10, fun = @sum_10;
case 11, fun = @sum_11;
case 12, fun = @sum_12;
case 13, fun = @sum_13;
case 14, fun = @sum_14;
case 15, fun = @sum_15;
end
y = arrayfun(fun, x{:});
else
y = 0;
for i = 1:N
y = y + abs(x{i}).^2;
end
end
end
% !! using sqrt(imag(x)^2 + real(x)^2) is much slower !!!
% merged GPU kernels
function y = sum_1(x)
y = abs(x).^2;
end
function y = sum_2(x1,x2)
y = abs(x1).^2+abs(x2).^2;
end
function y = sum_3(x1,x2,x3)
y = abs(x1).^2+abs(x2).^2+abs(x3).^2;
end
function y = sum_4(x1,x2,x3,x4)
y = abs(x1).^2+abs(x2).^2+abs(x3).^2+abs(x4).^2;
end
function y = sum_5(x1,x2,x3,x4,x5)
y = abs(x1).^2+abs(x2).^2+abs(x3).^2+abs(x4).^2+abs(x5).^2;
end
function y = sum_6(x1,x2,x3,x4,x5,x6)
y = abs(x1).^2+abs(x2).^2+abs(x3).^2+abs(x4).^2+abs(x5).^2+abs(x6).^2;
end
function y = sum_7(x1,x2,x3,x4,x5,x6,x7)
y = abs(x1).^2+abs(x2).^2+abs(x3).^2+abs(x4).^2+abs(x5).^2+abs(x6).^2+abs(x7).^2;
end
function y = sum_8(x1,x2,x3,x4,x5,x6,x7,x8)
y = abs(x1).^2+abs(x2).^2+abs(x3).^2+abs(x4).^2+abs(x5).^2+abs(x6).^2+abs(x7).^2+abs(x8).^2;
end
function y = sum_9(x1,x2,x3,x4,x5,x6,x7,x8,x9)
y = abs(x1).^2+abs(x2).^2+abs(x3).^2+abs(x4).^2+abs(x5).^2+abs(x6).^2+abs(x7).^2+abs(x8).^2+abs(x9).^2;
end
function y = sum_10(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10)
y = abs(x1).^2+abs(x2).^2+abs(x3).^2+abs(x4).^2+abs(x5).^2+abs(x6).^2+abs(x7).^2+abs(x8).^2+abs(x9).^2+abs(x10).^2;
end
function y = sum_11(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11)
y = abs(x1).^2+abs(x2).^2+abs(x3).^2+abs(x4).^2+abs(x5).^2+abs(x6).^2+abs(x7).^2+abs(x8).^2+abs(x9).^2+abs(x10).^2+abs(x11).^2;
end
function y = sum_12(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12)
y = abs(x1).^2+abs(x2).^2+abs(x3).^2+abs(x4).^2+abs(x5).^2+abs(x6).^2+abs(x7).^2+abs(x8).^2+abs(x9).^2+abs(x10).^2+abs(x11).^2+abs(x12).^2;
end
function y = sum_13(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13)
y = abs(x1).^2+abs(x2).^2+abs(x3).^2+abs(x4).^2+abs(x5).^2+abs(x6).^2+abs(x7).^2+abs(x8).^2+abs(x9).^2+abs(x10).^2+abs(x11).^2+abs(x12).^2+abs(x13).^2;
end
function y = sum_14(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14)
y = abs(x1).^2+abs(x2).^2+abs(x3).^2+abs(x4).^2+abs(x5).^2+abs(x6).^2+abs(x7).^2+abs(x8).^2+abs(x9).^2+abs(x10).^2+abs(x11).^2+abs(x12).^2+abs(x13).^2+abs(x14).^2;
end
function y = sum_15(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15)
y = abs(x1).^2+abs(x2).^2+abs(x3).^2+abs(x4).^2+abs(x5).^2+abs(x6).^2+abs(x7).^2+abs(x8).^2+abs(x9).^2+abs(x10).^2+abs(x11).^2+abs(x12).^2+abs(x13).^2+abs(x14).^2+abs(x15).^2;
end
function [aPsi2, cache, self] = get_linear_correction_model(self,par,cache,aPsi2,modF,mask, iter, ii )
import engines.GPU_MS.GPU_wrapper.*
if isempty(self.background) && self.diff_pattern_blur == 0 && strcmp(par.background_detection, 'none')
return % nothing to be done, return
end
%% add background
if ~isempty(self.background)
if ~isfield(cache, 'background_profile') || isscalar(cache.background_profile)
aPsi2 = aPsi2 + self.background;
else
aPsi2 = Gfun(@add_background, aPsi2, self.background, cache.background_profile,modF);
end
end
if self.diff_pattern_blur > 0
%%%%%%%%%%%%%%%%%%%%%%% LINEAR MODEL CORRECTIONS START %%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%
if isempty(self.modes{1}.ASM_factor) % is not nearfield
aPsi2 = aPsi2(cache.fftshift_idx{:},:);
end
% apply blur correction change to Gaussian by ZC
if self.diff_pattern_blur > 0
blur_kernel = fspecial('gaussian',round(self.diff_pattern_blur) *10+1,self.diff_pattern_blur);
aPsi2 = convn(aPsi2, blur_kernel, 'same');
end
% apply blur correction
% if self.diff_pattern_blur > 0
% % generate blurring kernel
% x = [-1, 0,-1]/self.diff_pattern_blur;
% [X,Y] = meshgrid(x,x);
% blur_kernel = exp( -(X.^2 + Y.^2) );
% blur_kernel = blur_kernel / math.sum2( blur_kernel );
% aPsi2 = convn(aPsi2, blur_kernel, 'same');
% end
if isempty(self.modes{1}.ASM_factor) % is not nearfield
aPsi2 = aPsi2(cache.fftshift_idx{:},:);
end
end
% simple estimation of background
if par.background_detection && iter > par.background_detection
if isempty(mask); mask = false; end
% calculate the most optimal background update
[nom,denom] = Gfun(@get_background_estimate,modF, aPsi2, mask, cache.background_profile_weight, cache.background_profile );
update = sum2(nom)./sum2(denom);
if any(ii == 1)
fprintf('Background update: %3.3g curr value:%3.3g \n ', mean(update), self.background);
end
self.background = posit(self.background + (par.grouping/self.Npos)*mean(update));
% %% Check if background is fitted well
% X = (-self.Np_p(1)/2:self.Np_p(1)/2-1);
% Y = (-self.Np_p(2)/2:self.Np_p(2)/2-1);
% [X,Y] = meshgrid(X,Y);
%
% R = (sqrt(X.^2 + Y.^2));
% D = fftshift(single(modF.^2) - aPsi2);
% for i = 1:mean(self.Np_p)/2
% progressbar(i, mean(self.Np_p)/2);
% mask = (R==i);
% mask = mask / sum2(mask);
% B(i) = median(sum2(bsxfun(@times, D, mask)));
% end
% plot(B)
% ylim([-5,5])
% drawnow
%
end
end
function aPsi2 = add_background(aPsi2, background,background_profile,modF)
aPsi2 = aPsi2 + background .* background_profile .* (modF > 0); % leave empty pixels empty
end
function [nom, denom] = get_background_estimate(modF, aPsi2, mask, distribution, background )
W = ~mask .* distribution;
nom = W.* (modF.^2 - aPsi2).*background;
denom = W.*background.^2;
end
@@ -0,0 +1,149 @@
% GRADIENT_NF_PROPAGATION_SOLVER update estimate of the nearfield propagation distance based on the
% current update of the wavefront
%
% self = gradient_NF_propagation_solver(self,psi,chi, cache, ind)
%
% ** self structure containing inputs: e.g. current reconstruction results, data, mask, positions, pixel size, ..
% ** psi exitwave (psi = P*O)
% ** chi [Nx,Ny,N] array, difference between original and updated exit-wave
% ** cache precalculated values
% ** ind indices containg corresponding probe id for each processed position
%
% returns:
% ++ self updated self structure with optimized propagation distance
% ++ cache precalculated values with updated velocity for momentum method
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for mixed coherent modes:
% P. Thibault and A. Menzel, Reconstructing state mixtures from diffraction measurements, Nature 494, 6871 (2013). (doi: 10.1038/nature11806),
% for LSQ-ML method
% M. Odstrcil, A. Menzel, M.G. Sicairos, Iterative least-squares solver for generalized maximum-likelihood ptychography, Optics Express, 2018
% for OPRP method
% M. Odstrcil, P. Baksh, S. A. Boden, R. Card, J. E. Chad, J. G. Frey, W. S. Brocklesby, "Ptychographic coherent diffractive imaging with orthogonal probe relaxation." Optics express 24.8 (2016): 8360-8369
% and/or for multislice:
% E. H. R. Tsai, I. Usov, A. Diaz, A. Menzel, and M. Guizar-Sicairos, X-ray ptychography with extended depth of field, Opt. Express 24, 2908929108 (2016).
% 6. Except for the above-mentioned acknowledgment, LICENSEE shall not use the PROGRAM title or the names or logos of LICENSOR, nor any adaptation thereof, nor the
% names of any of its employees or laboratories, in any advertising, promotional or sales material without prior written consent obtained from LICENSOR in each case.
% 7. Ownership of all rights, including copyright in the PROGRAM and in any material associated therewith, shall at all times remain with LICENSOR, and LICENSEE
% agrees to preserve same. LICENSEE agrees not to use any portion of the PROGRAM or of any IMPROVEMENTS in any machine-readable form outside the PROGRAM, nor to
% make any copies except for its internal use, without prior written consent of LICENSOR. LICENSEE agrees to place the following copyright notice on any such copies:
% © All rights reserved. PAUL SCHERRER INSTITUT, Switzerland, Laboratory for Macromolecules and Bioimaging, 2017.
% 8. The LICENSE shall not be construed to confer any rights upon LICENSEE by implication or otherwise except as specifically set forth herein.
% 9. DISCLAIMER: LICENSEE shall be aware that Phase Focus Limited of Sheffield, UK has an international portfolio of patents and pending applications which relate
% to ptychography and that the PROGRAM may be capable of being used in circumstances which may fall within the claims of one or more of the Phase Focus patents,
% in particular of patent with international application number PCT/GB2005/001464. The LICENSOR explicitly declares not to indemnify the users of the software
% in case Phase Focus or any other third party will open a legal action against the LICENSEE due to the use of the program.
% 10. This Agreement shall be governed by the material laws of Switzerland and any dispute arising out of this Agreement or use of the PROGRAM shall be brought before
% the courts of Zürich, Switzerland.
%
%
function [self, cache] = gradient_NF_propagation_solver(self,psi,chi, cache, ind, layer_id)
% update estimate of the nearfield propagation distance based on the
% current update of the wavefront
import engines.GPU_MS.GPU_wrapper.*
import engines.GPU_MS.shared.*
import math.*
import utils.*
dH = cache.ASM_difference;
% propagate to farfield
Psi_0 = fft2_safe(psi{1});
Psi_1 = fft2_safe(psi{1}+chi{1});
% get phase diffence
Psi_diff = sum(Psi_0 .* conj(Psi_1),3);
aPsi = abs(Psi_diff);
Psi_diff = Psi_diff ./ (aPsi+mean2(aPsi).*1e-6);
% calculate distance that best explains the differences
dz = -Ggather(sum2(real(conj(dH) .* Psi_diff)) ./ sum2(abs(dH).^2));
% %% USE MOMENTUM ACCELERATION TO MAKE THE CONVERGENCE FASTER
% try
% momentum_memory = 10; % compare 10 iterations
% if length(self.modes{1}.distances) > momentum_memory
% if ~isfield(cache, 'velocity_NF_propagation')
% cache.velocity_NF_propagation = 0;
% end
%
% updates = diff(self.modes{1}.distances(end-momentum_memory:end));
% corr_level = corr(updates(1:end-1)', updates(2:end)');
%
% corr_level
%
%
% if all(corr_level > 0 )
% %%%%%%%%%%%% very empritical model %%%
% gain = 1; % smaller -> lower relative speed (less momentum)
% friction = 0.1*max(0, 0.5-corr_level); % smaller -> longer memory, more momentum
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% else
% gain = 0; friction = 0.5;
% end
%
% cache.velocity_NF_propagation = cache.velocity_NF_propagation*(1-friction) + dz;
% %% apply the velocity to the refined positions , if the postition updated are sufficiently small
%
% cache.velocity_NF_propagation
%
% dz = dz + gain*cache.velocity_NF_propagation;
%
%
% end
% catch
% keyboard
% end
% update propagation values
if any(ind==1)
% add new field only when new iteration is started
self.modes{1}.distances = [self.modes{1}.distances,self.modes{1}.distances(end) + dz];
verbose(1, 'Propagation distance: %3.5gum ', self.modes{1}.distances(end)*1e6)
else
self.modes{1}.distances = self.modes{1}.distances + dz;
end
% use the same distance for all positions
for i = 1:length(self.modes)
self.modes{i}.distances = self.modes{1}.distances;
end
end
@@ -0,0 +1,117 @@
% GRADIENT_DESCENT_XI_SOLVER solve optimal update step for the Poisson noise method
%
% [beta_chi, find_xi_step] = gradient_descent_xi_solver(self,modF, aPsi2, R,mask, ind, beta_xi, cache)
%
% ** self structure containing inputs: e.g. current reconstruction results, data, mask, positions, pixel size, ..
% ** modF pre-fftshifted and sqrt-ed data
% ** aPsi2 reciprocal intensity model
% ** R 1- modF / aPsi
% ** mask masked values on detector
% ** ind processed indices
% ** beta_xi previous steps, needed for calculation as initial guess
% ** cache precalculated values
%
% returns:
% ++ beta_xi optimal probe step
% ++ find_xi_step optimal object step
%
% see also: engines.GPU_MS.LSQML, engines.GPU_MS.PIE
% 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 [beta_xi, find_xi_step] = gradient_descent_xi_solver(self,modF, aPsi2, R,mask, ind, beta_xi, cache)
import utils.*
import math.*
import engines.GPU_MS.GPU_wrapper.*
find_xi_step = true;
%% !! use precached values if the change is small
if ~find_xi_step
beta_xi = cache.beta_xi_all(ind,end);
else
if isempty(mask)
mask = 0;
end
for i = 1:2
[nom, denom] = Gfun(@get_coefs, aPsi2,modF,R,mask,beta_xi);
% avoid oscilations of the solution
beta_xi = beta_xi*0.5 + 0.5* Ggather(sum2(nom) ./ sum2(denom));
beta_xi = abs(max(min(beta_xi,1),0));
end
beta_xi = beta_xi + randn(size(beta_xi)) * 1e-2;
end
if any(ind ==1)
verbose(1,'Average xi_alpha %3.2g find_step %i ', mean(beta_xi(:)), find_xi_step)
end
end
function [nom, denom,W] = get_coefs(aPsi2,modF,R,mask,alpha)
modF2 = modF.^2;
chi = 1-R;
W = 1-mask;
nom = -W.*chi.* (modF2./ (1-alpha.*chi) - aPsi2);
denom = W.*aPsi2.*chi.^2;
end
@@ -0,0 +1,110 @@
% FUNCTION mode = gradient_fourier_position_solver(chi,O,P,mode, ind)
% Description: solve position errors in the Fourier space
%
% ** self structure containing inputs: e.g. current reconstruction results, data, mask, positions, pixel size, ..
% ** chi [Nx,Ny,N] array, difference between original and updated exit-wave
% ** O [Nx,Ny,N] array, object views
% ** P [Nx,Ny,1] or [Nx,Ny,N] array, single or variable probe
% ** mode structure with information about each incoherent mode
% ** ind processed indices
%
% returns:
% ++ mode updated mode structure
%
% see also: engines.GPU_MS.LSQML, engines.GPU_MS.PIE
% 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 mode = gradient_fourier_position_solver(chi,O,P,mode, ind)
import engines.GPU_MS.GPU_wrapper.*
import math.*
import utils.*
% use gradinent solver for position correction in fourier space
Np = size(P);
X = linspace(-0.5, 0.5,Np(2)) ;
Y = linspace(-0.5, 0.5,Np(1))' ;
[nom_dx, denom_dx, nom_dy, denom_dy] = Gfun(@get_coefs,chi, P,O,X, Y);
dx = - sum2(nom_dx)./ sum2(denom_dx);
dy = - sum2(nom_dy)./ sum2(denom_dy);
shift = squeeze(Ggather(cat(4,dx, dy)));
shift = min(abs(shift), 0.2) .* sign(shift); % avoid too fast jumps, <0.5px/iter is enough
if any(ind==1)
verbose(1,'Grad fourier pos correction -- AVG step %3.2g px', mean(abs(shift(:))))
end
mode.probe_fourier_shift(ind,:)=mode.probe_fourier_shift(ind,:)+reshape(shift,[],2);
end
function [nom1, denom1, nom2, denom2] = get_coefs(chi, P, O, dX, dY)
dPx = 2i*pi.*dX.*P.*O;
dPy = 2i*pi.*dY.*P.*O;
nom1 = real(conj(dPx) .* chi);
denom1 = abs(dPx).^2;
nom2 = real(conj(dPy) .* chi);
denom2 = abs(dPy).^2;
end
@@ -0,0 +1,196 @@
% GRADIENT_POSITION_SOLVER solve position errors in the real space
%
% [pos_update, cache] = gradient_position_solver(self,xi,O,P,ind, iter, cache)
%
% ** self structure containing inputs: e.g. current reconstruction results, data, mask, positions, pixel size, ..
% ** xi exit wave update vector
% ** O object views
% ** P probe or probes
% ** ind indices of of processed position
% ++ iter current iteration
% ** cache structure with precalculated values to avoid unnecessary overhead
%
% returns:
% ++ pos_update position updates for each of the indices
% ++ cache updated structure with precalculated values
%
% see also: engines.GPU_MS.LSQML, engines.GPU_MS.PIE
function [pos_update, probe_rotation,probe_scale,cache] = gradient_position_solver(self,xi,O,P,ind, iter, cache, par)
import engines.GPU_MS.GPU_wrapper.*
import math.*
import utils.*
% use gradinent solver for position correction
low_mem_errs = {'id:parallel:gpu:array:OOMForOperation',...
'id:MATLAB:LowGPUMem','MATLAB:LowGPUMem',...
'parallel:gpu:array:OOM',...
'parallel:gpu:device:UnknownCUDAError', ...
'parallel:gpu:array:OOMForOperation', ...
'parallel:gpu:array:FFTInternalError'};
% wrapper around get_img_grad, in case of low memory it will try to repeat
% Ntimes before giving up
pos_update = 0; probe_rotation = 0; probe_scale = 0;
N = 5;
for ii = 1:N
try
% reuse dx_O, dy_O to save memory !!
[dx_O,dy_O]=get_img_grad(O);
if iter >= par.detector_rotation_search
%% estimate detector rotation
xgrid = Garray(linspace(-1,1,self.Np_p(1))');
ygrid = Garray(-linspace(-1,1,self.Np_p(2)));
[nom, denom] = Gfun(@get_coefs_mixed,xi, P, dx_O, dy_O, xgrid, ygrid);
probe_rotation = gather(sum2(nom)./ sum2(denom));
end
if iter >= par.detector_scale_search
%% estimate detector scale (ie pixel scale error in farfield mode)
xgrid = Garray(-linspace(-1,1,self.Np_p(2)) .* tukeywin(self.Np_p(2), 0.1)');
ygrid = Garray(-linspace(-1,1,self.Np_p(1))'.* tukeywin(self.Np_p(1), 0.1));
[nom, denom] = Gfun(@get_coefs_mixed,xi, P, dx_O, dy_O, xgrid, ygrid);
probe_scale = gather(sum2(nom)./ sum2(denom));
probe_scale = 0.5*mean(probe_scale) / mean(self.Np_p);
end
if iter >= par.probe_position_search
%% estimate sample shift
[dx_O, denom_dx, dy_O, denom_dy] = Gfun(@get_coefs_shift,xi,P,dx_O, dy_O);
dx = sum2(dx_O)./ sum2(denom_dx);
dy = sum2(dy_O)./ sum2(denom_dy);
end
break
catch ME
warning('Low memory')
if ~any(strcmpi(ME.identifier, low_mem_errs))
rethrow(ME)
end
pause(1)
end
end
if ii == 5
rethrow(ME)
end
if iter < par.probe_position_search
return
end
shift = squeeze(Ggather(cat(4,dx, dy)));
% modified by YJ. allow user to spcify maximum position update
max_shift = min(par.max_pos_update_shift, 10*mad(shift)); %why a factor of 10??
% prevent outliers and too rapid shifts
%max_shift = min(0.1, 10*mad(shift));
shift = min(abs(shift), max_shift) .* sign(shift); % avoid too fast jumps, <0.5px/iter is enough
%old code
%shift = min(abs(shift), 0.2) .* sign(shift); % avoid too fast jumps, <0.5px/iter is enough
pos_update = reshape(shift,[],2);
if ~isfield(cache, 'velocity_map_positions')
cache.velocity_map_positions = zeros(self.Npos,2,'single');
end
if ~isfield(cache, 'position_update_memory')
cache.position_update_memory = {};
end
cache.position_update_memory{iter}(ind,:) = pos_update;
%% USE MOMENTUM ACCELERATION TO MAKE THE CONVERGENCE FASTER
ACC = 0;
if par.probe_position_search_momentum >0
momentum_memory = par.probe_position_search_momentum; %
% only in case far field ptychography
if isinf(self.z_distance) && sum(cellfun(@length, cache.position_update_memory) > 0) > momentum_memory
%corr_level = zeros(momentum_memory,1);
for ii = 1:momentum_memory
corr_level(ii) = mean(diag(corr(cache.position_update_memory{end}(ind,:), cache.position_update_memory{end-ii}(ind,:))));
end
if all(corr_level > 0 )
%estimate optimal friction from previous steps
poly_fit = polyfit(0:momentum_memory,log([1,corr_level]),1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
gain = 0.5; % smaller -> lower relative speed (less momentum)
friction = 0.1*max(-poly_fit(1),0); % smaller -> longer memory, more momentum
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
else
gain = 0; friction = 0.5;
end
cache.velocity_map_positions(ind,:) = cache.velocity_map_positions(ind,:)*(1-friction) + pos_update;
% apply the velocity to the refined positions , if the postition updated are sufficiently small
if max(abs(pos_update)) < 0.1
ACC = norm2(pos_update + gain*cache.velocity_map_positions(ind,:)) / norm2(pos_update);
pos_update = pos_update + gain*cache.velocity_map_positions(ind,:);
end
end
end
% try
%ACC = 0;
% momentum_memory = 5; % remember 5 iterations
%
% % only in case far field ptychography
% if isinf(self.z_distance) && sum(cellfun(@length, cache.position_update_memory) > 0) > momentum_memory
% for ii = 1:momentum_memory
% corr_level(ii) = mean(diag(corr(cache.position_update_memory{end}(ind,:), cache.position_update_memory{end-ii}(ind,:))));
% end
% if all(corr_level > 0 )
% %estimate optimal friction from previous steps
% poly_fit = polyfit(0:momentum_memory,log([1,corr_level]),1);
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% gain = 0.5; % smaller -> lower relative speed (less momentum)
% friction = 0.1*max(-poly_fit(1),0); % smaller -> longer memory, more momentum
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% else
% gain = 0; friction = 0.5;
% end
%
% cache.velocity_map_positions(ind,:) = cache.velocity_map_positions(ind,:)*(1-friction) + pos_update;
% % apply the velocity to the refined positions , if the postition updated are sufficiently small
%
% if max(abs(pos_update)) < 0.1
% ACC = norm2(pos_update + gain*cache.velocity_map_positions(ind,:)) / norm2(pos_update);
% pos_update = pos_update + gain*cache.velocity_map_positions(ind,:);
% end
%
% end
% catch
% keyboard
% end
if any(ind==1)
verbose(1,'Grad pos corr -- AVG step %3.3g px , acceleration = %4.1f', max(abs(pos_update(:))), ACC)
end
end
function [nom1, denom1, nom2, denom2] = get_coefs_shift(xi, P, dx_O, dy_O)
dx_OP = dx_O.*P;
nom1 = real(conj(dx_OP) .* xi);
denom1 = abs(dx_OP).^2;
dy_OP = dy_O.*P;
nom2 = real(conj(dy_OP) .* xi);
denom2 = abs(dy_OP).^2;
end
function [nom, denom] = get_coefs_mixed(xi, P, dx_O, dy_O, xgrid, ygrid)
dm_O = dx_O .* xgrid + dy_O .* ygrid;
dm_OP = dm_O.*P;
nom = real(conj(dm_OP) .* xi);
denom = abs(dm_OP).^2;
end
@@ -0,0 +1,153 @@
% GRADIENT_PROJECTION_SOLVER: 1D search for the optimal step in the gradients descent-like methods
% used in ML and PIE functions
%
% [beta_p, beta_o] = gradient_projection_solver(self,xi,O,P,dO,dP,p_ind,par, cache)
%
%
% ** self structure containing inputs: e.g. current reconstruction results, data, mask, positions, pixel size, ..
% ** chi [Nx,Ny,N] array, difference between original and updated exit-wave
% ** dO [Nx,Ny,N] array, object update direction
% ** dP [Nx,Ny,N] array, probe update direction
% ** O [Nx,Ny,N] array, object views
% ** P [Nx,Ny,1] or [Nx,Ny,N] array, single or variable probe
% ** p_ind indices containg corresponding probe id for each processed position
% ** par structure containing parameters for the engines
% ** cache precalculated values
%
% returns:
% ++ beta_p optimal probe step
% ++ beta_o optimal object step
%
% see also: engines.GPU_MS.LSQML, engines.GPU_MS.PIE
% 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 [beta_p, beta_o] = gradient_projection_solver(self,xi,O,P,dO,dP,p_ind,par, cache)
import engines.GPU_MS.GPU_wrapper.*
import utils.*
import math.*
%% initial setting
beta_o = 0;
beta_p = 0;
find_object_step = numel(dO) > 1;
find_probe_step = numel(dP) > 1;
if ~( par.share_probe || length(unique(p_ind)) == 1 ) && find_probe_step
% in case of multiple scans !!
% replicate the update back to the original probe_update size
dP = dP(:,:,p_ind);
end
dP = mean(dP,3);
% !! reusing dP,dO variables to same GPU memory
if find_probe_step && find_object_step
[dP, denom_p, dO, denom_o] = Gfun(@get_coefs,xi, P,O, dP, dO);
elseif find_probe_step
[dP, denom_p] = Gfun(@get_coef,xi, O, dP);
elseif find_object_step
[dO, denom_o] = Gfun(@get_coef,xi, P, dO);
end
if find_probe_step
beta_p = sum2(dP)./ sum2(denom_p) ; % half of the corrections goes to probe , half to object
end
if find_object_step
beta_o = sum2(dO)./ sum2(denom_o) ; % half of the corrections goes to probe , half to object
end
%% allow matlab GPU paralelization to process the sums while positions corrections are calculated
beta_p = Ggather(beta_p).*par.beta_LSQ * par.beta_probe ;
beta_o = Ggather(beta_o).*par.beta_LSQ * par.beta_object;
beta_o(isnan(beta_o)) = 0;
beta_p(isnan(beta_p)) = 0;
if any(isnan(beta_o)) || any(isnan(beta_p))
%keyboard
error('Convergence failed')
end
end
function [nom1, denom1, nom2, denom2] = get_coefs(xi, P,O, dP, dO)
% projection of dPO in direction of xi, to avoid issues caused by
% correlation between dPO and dOP, the step is divided by 2
dPO = dP.*O;
nom1 = 0.5* real(conj(dPO) .* xi);
denom1 = abs(dPO).^2;
PdO = P.*dO;
nom2 = 0.5* real(conj(PdO) .* xi);
denom2 = abs(PdO).^2;
end
function [nom1, denom1] = get_coef(xi, X, dX)
XdX = X.*dX;
nom1 = 0.5*real(conj(XdX) .* xi);
denom1 = abs(XdX).^2;
end
@@ -0,0 +1,67 @@
% function f = local_TV2D_chambolle(f, lambda, niter)
% apply local total variation usiniter matlab functions, it uses chambolle
% solver -> faster but more memory demanding
% Inputs: x - 2D array to be regularized
% lambda - constant to be tuned
% niter - number of iterations
% Modified from PSI's tomo code. Written by Jonathan Schwartz at U. Mich
function x = local_TV2D_chambolle(x,lambda, niter)
[M,N] = size(x);
if lambda == 0
return
end
x0 = x;
xi = zeros(M,N,2, class(x));
tau=1/8;
%%% INNER LOOP
for iinner = 1:niter
% chambolle step
gdv = grad( div(xi) - x/lambda );
%% isotropic
d = sqrt(sum(gdv.^2,3));
xi = bsxfun(@times, xi + tau*gdv, 1 ./ ( 1+tau*d ));
% reconstruct
x = x - lambda*div( xi );
end
% prevent pushing values to zero by the TV regularization
x = sum(x0(:).* x(:)) / sum(x(:).^2) * x;
end
function fd = div(P)
% div - divergence (backward difference)
%
% fd = div(P);
Px = P(:,:,1);
Py = P(:,:,2);
fx = Px-Px([1 1:end-1],:);
fy = Py-Py(:,[1 1:end-1]);
fd = fx+fy;
end
function f = grad(M)
% grad - gradient, forward differences
% g = grad(M);
fx = M([2:end end],:)-M;
fy = M(:,[2:end end])-M;
f = cat(3,fx,fy);
end
@@ -0,0 +1,169 @@
% MODULUS_CONSTRAINT universal fast relaxed modulus constraint for amplitude and poission likelihood
%
% [chi,R] = modulus_constraint(modF,aPsi ,Psi, mask, noise, relax_noise,likelihood , R_offset)
%
% ** modF pre-fftshifted and sqrt-ed data
% ** aPsi reciprocal amplitude model
% ** Psi where Psi is the propagated exitwave
% ** mask masked values, 1 = ignored, 0 = use this pixel
% ** noise estimated noise (STD) in each pixel after sqrt transform
% ** relax_noise multiplicative constant for the providede noise value
% ** likelihood L1 or poisson
% ** R_offset number to be subtracted from the modF / aPsi ratio
%
% returns:
% ++ chi the updated wavefront or wavefront update, depends on the chosen R_offset
% ++ R modF / aPsi ratio
% 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 [chi,R] = modulus_constraint(modF,aPsi ,Psi, mask, noise, par, R_offset)
import engines.GPU_MS.GPU_wrapper.*
likelihood = lower(par.likelihood);
relax_noise = par.relax_noise;
Nmodes = length(Psi);
R = [];
if par.upsampling_data_factor
% calculate the convolution with delta functions
modF = utils.unbinning_2D(modF, 2^par.upsampling_data_factor );
aPsi = utils.unbinning_2D(aPsi, 2^par.upsampling_data_factor );
if ~isempty(mask) && ~isscalar(mask)
mask = utils.unbinning_2D(mask, 2^par.upsampling_data_factor );
end
end
%% write the most common cases as merged kernels
if nargout == 1
if isempty(mask) && isempty(noise) && relax_noise == 0 && strcmpi(likelihood, 'l1') && Nmodes == 1 % common modulus constraint
chi{1} = Gfun(@modulus_non_relaxed,Psi{1},modF, aPsi, R_offset);
return
end
if ~isempty(mask) && isempty(noise) && strcmpi(likelihood, 'l1') && Nmodes == 1 % common modulus constraint
chi{1} = Gfun(@modulus_weight_relaxed,Psi{1},modF, aPsi,mask, R_offset);
return
end
end
if isempty(mask) && isempty(noise) && relax_noise == 0 % common modulus constraint
switch likelihood
case 'l1', R = Gfun(@non_relaxed, modF, aPsi, R_offset);
case 'poisson', R = Gfun(@poisson_noise_relaxed,modF, aPsi, R_offset);
end
elseif isempty(mask) && isempty(noise) && relax_noise > 0 % common modulus constraint
switch likelihood
case 'l1', R = Gfun(@weight_relaxed, modF, aPsi, relax_noise, R_offset );
case 'poisson', R = Gfun(@poisson_noise_weight_relaxed,modF, aPsi,relax_noise, R_offset);
end
elseif ~isempty(mask) && isempty(noise)
switch likelihood
case 'l1', R = Gfun(@weight_relaxed, modF, aPsi, max(mask, relax_noise), R_offset );
case 'poisson', R = Gfun(@poisson_noise_weight_relaxed,modF, aPsi, max(mask, relax_noise), R_offset);
end
elseif isempty(mask) && ~isempty(noise)
R = Gfun(@noise_relaxed, modF, aPsi, noise, relax_noise, R_offset);
else
R = Gfun(@noise_weight_relaxed, modF, aPsi, noise,relax_noise, mask, R_offset);
end
for i = 1:Nmodes
chi{i} = Psi{i} .* R; % apply the constraint to the currect estimation
end
end
% classical modulus
function chi = modulus_non_relaxed(Psi,modF, aPsi, R_offset)
R = (modF./(aPsi+1e-9)- R_offset);
chi = R .* Psi;
end
function chi = modulus_weight_relaxed(Psi,modF, aPsi,W, R_offset)
R = (W+(1-W).*modF./(aPsi+1e-9))- R_offset;
chi = R .* Psi;
end
function R = non_relaxed(modF, aPsi, R_offset)
R = modF./(aPsi+1e-9)- R_offset;
end
% modulus for noisy data with relaxation
function R = weight_relaxed(modF, aPsi, W, R_offset)
R = (W+(1-W).*modF./(aPsi+1e-9))- R_offset;
end
function R = noise_relaxed(modF, aPsi, noise, relax_noise, R_offset)
W = 1 ./ (1+ ((aPsi - modF)./(noise .* relax_noise)).^2 );
R = (W+(1-W).*modF./(aPsi+1e-9))- R_offset;
end
function R = noise_weight_relaxed(modF, aPsi, noise,relax_noise, W0, R_offset)
% if mask == 1 then W has to be 0
W = 1-(1-W0) .* (1-1./ (1+ ((aPsi - modF)./(noise .* relax_noise) ).^2 ));
R = (W+(1-W).*modF./(aPsi+1e-9))- R_offset;
end
function R = poisson_noise_weight_relaxed(modF, aPsi, W, R_offset)
% if mask == 1 then W has to be 0
% Maximum-likelihood refinement for coherent diffractive imaging
R = (W+(1-W).*modF.^2 ./(aPsi.^2+1e-3))- R_offset;
end
function [R] = poisson_noise_relaxed(modF, aPsi, R_offset)
% if mask == 1 then W has to be 0
% Maximum-likelihood refinement for coherent diffractive imaging
R = modF.^2 ./(aPsi.^2+1e-3)- R_offset;
end
@@ -0,0 +1,74 @@
% REGULATION_MULTILAYERS try to avoid ambiguity in the multilayer reconstruction by weakly forcing missing cone
% values towards zero
%
% self = regulation_multilayers(self, par, cache)
%
% ** 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
%
% returns:
% ++ self self-like structure with final reconstruction
%
function self = regulation_multilayers(self, par, cache)
import engines.GPU_MS.GPU_wrapper.*
%% Added by ZC. Use CPU is object size is too big
% par.obj_size_limit_on_gpu is maximum object size (in MB) allowed on gpu.
% Automatically use cpu if exceed the limit.
Obj_size_limit = par.obj_size_limit_on_gpu / 8 * 2^20 ;
%%
Npix = [self.Np_o, par.Nlayers]; % -1, Not last inf layer, by Zhen Chen
for i = 1:3
grid{i} = ifftshift((-fix(Npix(i)/2):ceil(Npix(i)/2)-1))'/Npix(i);
grid{i} = shiftdim(grid{i},1-i);
end
% calculate force of regularization based on the idea that DoF = resolution^2/lambda
W = 1-atan(( par.regularize_layers * abs(grid{3}) ./ sqrt(grid{1}.^2+grid{2}.^2+1e-3)).^2) / (pi/2);
relax = 1;
alpha = 1;
Wa = W.*exp(-alpha*(grid{1}.^2 + grid{2}.^2));
for kk = 1:size(self.object,1) % par.Nscans
%% Added by ZC. use CPU to save GPU memory if object is too big
if numel(self.object{kk,1}) * size(self.object,2) > Obj_size_limit && par.use_gpu
object=cellfun(@gather, self.object(kk,:),'UniformOutput',false);
obj = cat(3, object{:});
else
obj = cat(3, self.object{kk,:});
end
% Note: size(obj) = [self.Np_o, par.Nlayers]
%%
% find correction for amplitude
aobj = abs(obj);
fobj = fftn(aobj);
fobj = fobj .* Wa;
aobj_upd = ifftn(fobj);
% push towards zero
aobj_upd = 1+0.9*(aobj_upd-1);
% find correction for phase
Wphase = min(1, 10*(cache.illum_sum_0{kk}/cache.MAX_ILLUM(kk)));
if numel(obj) > Obj_size_limit && par.use_gpu % Added by ZC to save memory
Wphase=gather(Wphase);
end
pobj = math.unwrap2D_fft2(obj,[],0,Wphase,-1);
fobj = (fftn((pobj)));
fobj = fobj .* Wa;
pobj_upd = ifftn(fobj);
if numel(obj) > Obj_size_limit && par.use_gpu % Added by ZC to save memory
obj_upd = regulation_multilayers_kernel(obj, aobj,aobj_upd, pobj, pobj_upd, Wphase, relax);
else
obj_upd = Gfun(@regulation_multilayers_kernel,obj, aobj,aobj_upd, pobj, pobj_upd, Wphase, relax);
end
for ii = 1:par.Nlayers % -1, Not last inf layer, by Zhen Chen
self.object{kk,ii} = Garray(obj_upd(:,:,ii));
end
end
end
function [obj,corr] = regulation_multilayers_kernel(obj, aobj,aobj_upd, pobj, pobj_upd, weights, relax)
aobj_upd = (real(aobj_upd) - aobj);
pobj_upd = weights.*(real(pobj_upd) - pobj);
corr = (1+relax*aobj_upd) .* exp(1i*relax*pobj_upd);
obj = obj .* corr;
end
@@ -0,0 +1,112 @@
% REGULATION_MULTILAYERS try to avoid ambiguity in the multilayer reconstruction by weakly forcing missing cone
% values towards zero
%
% self = regulation_multilayers(self, par, cache)
%
% ** 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
%
% returns:
% ++ self self-like structure with final reconstruction
%
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for mixed coherent modes:
% P. Thibault and A. Menzel, Reconstructing state mixtures from diffraction measurements, Nature 494, 6871 (2013). (doi: 10.1038/nature11806),
% for LSQ-ML method
% M. Odstrcil, A. Menzel, M.G. Sicairos, Iterative least-squares solver for generalized maximum-likelihood ptychography, Optics Express, 2018
% for OPRP method
% M. Odstrcil, P. Baksh, S. A. Boden, R. Card, J. E. Chad, J. G. Frey, W. S. Brocklesby, "Ptychographic coherent diffractive imaging with orthogonal probe relaxation." Optics express 24.8 (2016): 8360-8369
% and/or for multislice:
% E. H. R. Tsai, I. Usov, A. Diaz, A. Menzel, and M. Guizar-Sicairos, X-ray ptychography with extended depth of field, Opt. Express 24, 2908929108 (2016).
% 6. Except for the above-mentioned acknowledgment, LICENSEE shall not use the PROGRAM title or the names or logos of LICENSOR, nor any adaptation thereof, nor the
% names of any of its employees or laboratories, in any advertising, promotional or sales material without prior written consent obtained from LICENSOR in each case.
% 7. Ownership of all rights, including copyright in the PROGRAM and in any material associated therewith, shall at all times remain with LICENSOR, and LICENSEE
% agrees to preserve same. LICENSEE agrees not to use any portion of the PROGRAM or of any IMPROVEMENTS in any machine-readable form outside the PROGRAM, nor to
% make any copies except for its internal use, without prior written consent of LICENSOR. LICENSEE agrees to place the following copyright notice on any such copies:
% © All rights reserved. PAUL SCHERRER INSTITUT, Switzerland, Laboratory for Macromolecules and Bioimaging, 2017.
% 8. The LICENSE shall not be construed to confer any rights upon LICENSEE by implication or otherwise except as specifically set forth herein.
% 9. DISCLAIMER: LICENSEE shall be aware that Phase Focus Limited of Sheffield, UK has an international portfolio of patents and pending applications which relate
% to ptychography and that the PROGRAM may be capable of being used in circumstances which may fall within the claims of one or more of the Phase Focus patents,
% in particular of patent with international application number PCT/GB2005/001464. The LICENSOR explicitly declares not to indemnify the users of the software
% in case Phase Focus or any other third party will open a legal action against the LICENSEE due to the use of the program.
% 10. This Agreement shall be governed by the material laws of Switzerland and any dispute arising out of this Agreement or use of the PROGRAM shall be brought before
% the courts of Zürich, Switzerland.
%
function self = regulation_multilayers(self, par, cache)
import engines.GPU_MS.GPU_wrapper.*
Npix = [self.Np_o, par.Nlayers - 1 ]; % -1, Not last inf layer, by Zhen Chen
for i = 1:3
grid{i} = ifftshift((-fix(Npix(i)/2):ceil(Npix(i)/2)-1))'/Npix(i);
grid{i} = shiftdim(grid{i},1-i);
end
% calculate force of regularization based on the idea that DoF = resolution^2/lambda
W = 1-atan(( par.regularize_layers * abs(grid{3}) ./ sqrt(grid{1}.^2+grid{2}.^2+1e-3)).^2) / (pi/2);
relax = 1;
alpha = 1;
Wa = W.*exp(-alpha*(grid{1}.^2 + grid{2}.^2));
for kk = 1:size(self.object,1)
obj = cat(3, self.object{kk,:});
obj = obj(:,:,end-1); % leave last inf layer, by Zhen Chen
% find correction for amplitude
aobj = abs(obj);
fobj = fftn(aobj);
fobj = fobj .* Wa;
aobj_upd = ifftn(fobj);
% push towards zero
aobj_upd = 1+0.9*(aobj_upd-1);
% find correction for phase
Wphase = min(1, 10*(cache.illum_sum_0{kk}/cache.MAX_ILLUM(kk)));
pobj = math.unwrap2D_fft2(obj,[],0,Wphase,-1);
fobj = (fftn((pobj)));
fobj = fobj .* Wa;
pobj_upd = ifftn(fobj);
obj_upd = Gfun(@regulation_multilayers_kernel,obj, aobj,aobj_upd, pobj, pobj_upd, Wphase, relax);
for ii = 1:par.Nlayers - 1 % -1, Not last inf layer, by Zhen Chen
self.object{kk,ii} = obj_upd(:,:,ii);
end
end
end
function [obj,corr] = regulation_multilayers_kernel(obj, aobj,aobj_upd, pobj, pobj_upd, weights, relax)
aobj_upd = (real(aobj_upd) - aobj);
pobj_upd = weights.*(real(pobj_upd) - pobj);
corr = (1+relax*aobj_upd) .* exp(1i*relax*pobj_upd);
obj = obj .* corr;
end
@@ -0,0 +1,90 @@
% REMOVE_OBJECT_AMBIGUITY remove normalization ambiguity of ptychography by optimal normalization
% of the object
%
% self = remove_object_ambiguity(self, cache, par)
%
% ** 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
%
% returns:
% ++ self self-like structure with final reconstruction
%
%
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for mixed coherent modes:
% P. Thibault and A. Menzel, Reconstructing state mixtures from diffraction measurements, Nature 494, 6871 (2013). (doi: 10.1038/nature11806),
% for LSQ-ML method
% M. Odstrcil, A. Menzel, M.G. Sicairos, Iterative least-squares solver for generalized maximum-likelihood ptychography, Optics Express, 2018
% for OPRP method
% M. Odstrcil, P. Baksh, S. A. Boden, R. Card, J. E. Chad, J. G. Frey, W. S. Brocklesby, "Ptychographic coherent diffractive imaging with orthogonal probe relaxation." Optics express 24.8 (2016): 8360-8369
% and/or for multislice:
% E. H. R. Tsai, I. Usov, A. Diaz, A. Menzel, and M. Guizar-Sicairos, X-ray ptychography with extended depth of field, Opt. Express 24, 2908929108 (2016).
% 6. Except for the above-mentioned acknowledgment, LICENSEE shall not use the PROGRAM title or the names or logos of LICENSOR, nor any adaptation thereof, nor the
% names of any of its employees or laboratories, in any advertising, promotional or sales material without prior written consent obtained from LICENSOR in each case.
% 7. Ownership of all rights, including copyright in the PROGRAM and in any material associated therewith, shall at all times remain with LICENSOR, and LICENSEE
% agrees to preserve same. LICENSEE agrees not to use any portion of the PROGRAM or of any IMPROVEMENTS in any machine-readable form outside the PROGRAM, nor to
% make any copies except for its internal use, without prior written consent of LICENSOR. LICENSEE agrees to place the following copyright notice on any such copies:
% © All rights reserved. PAUL SCHERRER INSTITUT, Switzerland, Laboratory for Macromolecules and Bioimaging, 2017.
% 8. The LICENSE shall not be construed to confer any rights upon LICENSEE by implication or otherwise except as specifically set forth herein.
% 9. DISCLAIMER: LICENSEE shall be aware that Phase Focus Limited of Sheffield, UK has an international portfolio of patents and pending applications which relate
% to ptychography and that the PROGRAM may be capable of being used in circumstances which may fall within the claims of one or more of the Phase Focus patents,
% in particular of patent with international application number PCT/GB2005/001464. The LICENSOR explicitly declares not to indemnify the users of the software
% in case Phase Focus or any other third party will open a legal action against the LICENSEE due to the use of the program.
% 10. This Agreement shall be governed by the material laws of Switzerland and any dispute arising out of this Agreement or use of the PROGRAM shall be brought before
% the courts of Zürich, Switzerland.
%
function self = remove_object_ambiguity(self, cache, par)
for kk = 1:size(self.object,1)
W = cache.illum_sum_0{min(kk,end)}(cache.object_ROI{:});
W = W ./ math.norm2(W);
for layer = 1:par.Nlayers
object_norm(kk, layer) = sqrt(mean2(abs(self.object{kk,layer}(cache.object_ROI{:})).^2.* W));
end
end
if par.share_probe
object_norm = mean(object_norm,1);
end
for kk = 1:size(self.object,1)
for layer = 1:par.Nlayers
% it can be quite slow for variable probe method
self.object{kk,layer} = self.object{kk,layer} / object_norm(min(kk,end),layer) ; % should avoid abiguity ,
end
end
for ll = 1:length(self.probe)
self.probe{ll} = self.probe{ll} .* reshape(prod(object_norm,2),1,1,[]); % should avoid abiguity ,
end
end
@@ -0,0 +1,152 @@
% REMOVE_VARIABLE_PROBE_AMBIGUITIES remove ambiguities in when the variable probe methods is used
% -> normalize the OPR modes
% -> make sue that the modes are orthogonal
%
% self = remove_variable_probe_ambiguities(self,par)
%
% ** self structure containing inputs: e.g. current reconstruction results, data, mask, positions, pixel size, ..
% ** par structure containing parameters for the engines
%
% returns:
% ++ self self-like structure with final reconstruction
%
%
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for mixed coherent modes:
% P. Thibault and A. Menzel, Reconstructing state mixtures from diffraction measurements, Nature 494, 6871 (2013). (doi: 10.1038/nature11806),
% for LSQ-ML method
% M. Odstrcil, A. Menzel, M.G. Sicairos, Iterative least-squares solver for generalized maximum-likelihood ptychography, Optics Express, 2018
% for OPRP method
% M. Odstrcil, P. Baksh, S. A. Boden, R. Card, J. E. Chad, J. G. Frey, W. S. Brocklesby, "Ptychographic coherent diffractive imaging with orthogonal probe relaxation." Optics express 24.8 (2016): 8360-8369
% and/or for multislice:
% E. H. R. Tsai, I. Usov, A. Diaz, A. Menzel, and M. Guizar-Sicairos, X-ray ptychography with extended depth of field, Opt. Express 24, 2908929108 (2016).
% 6. Except for the above-mentioned acknowledgment, LICENSEE shall not use the PROGRAM title or the names or logos of LICENSOR, nor any adaptation thereof, nor the
% names of any of its employees or laboratories, in any advertising, promotional or sales material without prior written consent obtained from LICENSOR in each case.
% 7. Ownership of all rights, including copyright in the PROGRAM and in any material associated therewith, shall at all times remain with LICENSOR, and LICENSEE
% agrees to preserve same. LICENSEE agrees not to use any portion of the PROGRAM or of any IMPROVEMENTS in any machine-readable form outside the PROGRAM, nor to
% make any copies except for its internal use, without prior written consent of LICENSOR. LICENSEE agrees to place the following copyright notice on any such copies:
% © All rights reserved. PAUL SCHERRER INSTITUT, Switzerland, Laboratory for Macromolecules and Bioimaging, 2017.
% 8. The LICENSE shall not be construed to confer any rights upon LICENSEE by implication or otherwise except as specifically set forth herein.
% 9. DISCLAIMER: LICENSEE shall be aware that Phase Focus Limited of Sheffield, UK has an international portfolio of patents and pending applications which relate
% to ptychography and that the PROGRAM may be capable of being used in circumstances which may fall within the claims of one or more of the Phase Focus patents,
% in particular of patent with international application number PCT/GB2005/001464. The LICENSOR explicitly declares not to indemnify the users of the software
% in case Phase Focus or any other third party will open a legal action against the LICENSEE due to the use of the program.
% 10. This Agreement shall be governed by the material laws of Switzerland and any dispute arising out of this Agreement or use of the PROGRAM shall be brought before
% the courts of Zürich, Switzerland.
%
function self = remove_variable_probe_ambiguities(self,par)
% apply normalization and orthogonalize the variable probe modes
import math.*
import engines.GPU_MS.GPU_wrapper.*
Nmodes = par.variable_probe_modes;
if par.share_probe
inds = {[self.reconstruct_ind{:}]};
else
inds = self.reconstruct_ind;
end
probe_modes = length(inds); % number of independend probes
probe = self.probe{1};
for kk = 1:probe_modes
ind = inds{kk};
if par.variable_probe_smooth > 0
% relaxed regularization , restrict the probe evolution to slow
% changes with polynomial order given by par.variable_probe_smooth
for ll = 2:Nmodes
self.probe_evolution(ind,ll) = self.probe_evolution(ind,ll) * 0.5 + 0.5*polyval(polyfit(ind,self.probe_evolution(ind,ll)',round(par.variable_probe_smooth)), ind)';
end
end
% remove degrees of freedom (orthogonalize the first mode)
% self.probe_evolution(ind,:) = self.probe_evolution(ind,:) - mean(self.probe_evolution(ind,:),1);
% self.probe_evolution(ind,1) = self.probe_evolution(ind,1)*0.99 + 1;
end
%% apply normalization on the coherence modes
vprobe_norm = Ggather(norm2(probe(:,:,:,2:end)));
probe(:,:,:,2:end) = probe(:,:,:,2:end) ./ vprobe_norm;
for kk = 1:probe_modes
ind = inds{kk};
self.probe_evolution(ind,2:end) = self.probe_evolution(ind,2:end) .* reshape(vprobe_norm(1,1,kk,:),1,[]);
end
%% orthogonalize the variable modes
for i = 1:(1+Nmodes)
for j = 1:i-1
mx_j = probe(:,:,:,j);
mx_i = probe(:,:,:,i);
proj = sum2(mx_i .* conj(mx_j)) ...
./ sum2(abs(mx_j).^2);
probe(:,:,:,i) = probe(:,:,:,i) - proj .* mx_j;
for kk = 1:probe_modes
ind = inds{kk};
p_j = self.probe_evolution(ind,j);
p_i = self.probe_evolution(ind,i);
proj = sum2(p_i .* conj(p_j)) ...
./ sum2(abs(p_j).^2);
self.probe_evolution(ind,i) = self.probe_evolution(ind,i) - proj .* p_j;
end
end
end
%% sort the modes by their energy
Energy = zeros(probe_modes, Nmodes);
for kk = 1:probe_modes
for ii = 1:Nmodes
ind = inds{kk};
Energy(kk,ii) = norm(self.probe_evolution(ind,ii+1));
end
end
[~,ind] = sort(Energy,2, 'descend');
for kk = 1:probe_modes
swap = [1,1+ind(kk,:)];
probe(:,:,kk,:) = probe(:,:,kk,swap);
self.probe_evolution(inds{kk},:) = self.probe_evolution(inds{kk},swap);
end
%% remove outliers
aevol = abs(self.probe_evolution);
self.probe_evolution = min(aevol, 1.5*quantile(aevol,0.95)) .* sign(self.probe_evolution);
% store the results
self.probe{1} = probe;
end