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,136 @@
% self = align_objects(self )
% align all provided object arrays and apply the same shift on the
% corresponding probe so that the scans can be used for shared object
% reconstructions
%
% Inputs:
% self main data structure
% 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 = align_objects(self)
import engines.GPU.*
import utils.*
import engines.GPU.GPU_wrapper.*
cache.skip_ind = [];
[cache.oROI_s{1},cache.oROI{1}] = shared.find_reconstruction_ROI( self.probe_positions_0,self.Np_o, self.Np_p);
cache.object_ROI = {ceil(self.Np_p(1)/2):self.Np_o(1)-ceil(self.Np_p(1)/2), ...
ceil(self.Np_p(2)/2):self.Np_o(2)-ceil(self.Np_p(2)/2)};
Nobj = size(self.object,1);
shift = [0,0];
obj1 = prod(cat(3,self.object{1,:}),3);
obj1 = Ggather(obj1(cache.object_ROI{:}));
for ll = 1:Nobj
obj2 = prod(cat(3,self.object{ll,:}),3);
obj2 = Ggather(obj2(cache.object_ROI{:}));
[score(ll), object_aligned{ll}] = analysis.fourier_ring_correlation(obj1,obj2,...
'smoothing', 5, 'crop', self.Np_p/4, 'plot_results', false);
shift(ll,:) = score(ll).shift;
end
if any([score(:).AUC] < 0.3)
warning('Alignment of scans %i vs scan %i propably failed, FRC resolution is %3.3g of Nyquist frequency limit', 1, ll, score.resolution)
figure(56476)
subplot(1,Nobj,1)
plotting.imagesc3D(angle(object_aligned{1}{1})); axis off image
grid on
for ll = 1:Nobj
subplot(1,Nobj,ll)
plotting.imagesc3D(angle(object_aligned{ll}{2})); axis off image xy
grid on
end
plotting.suptitle('Objects after alignement, check visually the estimated alignement')
colormap bone
disp('Estimated shifts between the aligned objects')
disp(shift )
end
shift = shift - mean(shift,1);
self.Np_o = self.Np_o + 2*ceil(max(abs(shift(:,[2,1])),[],1));
for layer = 1:size(self.object,2)
for ll = 1:Nobj
% make them all the same size
self.object{ll,layer} = crop_pad(self.object{ll,layer}, self.Np_o, mean(self.object{ll,layer}(:)));
self.object{ll,layer} = utils.imshift_fft(self.object{ll,layer}, shift(ll,:));
end
end
if utils.verbose > -1 && any(max(abs(shift) ./ self.Np_p([2,1])) > 0.25)
warning off backtrace
id = math.argmax(max(abs(shift),[],2));
warning('Alignement of two mirrored scans resulted in maximal probe shift of %3.3g %3.3gpx, \n!! this is more than 50%% of the probe diameter !! \nconsider using better alignement between 0deg and 180deg scans ', -shift(id,1), shift(id,2))
warning on backtrace
end
for ii = 1:length(self.probe)
for ll = 1:Nobj
% apply shift to the probe as well, if needed, replicate the
% probe
probe{ii}(:,:,ll,:) = utils.imshift_fft(self.probe{ii}(:,:,min(end,ll),:), shift(ll,:));
end
end
self.probe = probe ;
end
@@ -0,0 +1,67 @@
% APPLY_PROBE_CONTRAINTS apply support constrains on the probe in the real space, fourier space or any other
% plane if provided, it useds factor in mode.support_back_propagation_factor to perform ASM propagation
%
% probe = apply_probe_contraints(probe, mode)
%
% ** probe complex array with probe / probes
% ** mode structure containing parameters for selected probe mode
%
% returns:
% ** probe complex array with probe / probes
%
%
function probe = apply_probe_contraints(probe, mode)
import math.*
import utils.*
import engines.GPU.shared.*
if ~isempty(mode.probe_support)
% apply support contraint in real space (ir nearfield propagated )
if ~isempty(mode.support_fwd_propagation_factor)
if isscalar(mode.support_fwd_propagation_factor) && isinf(mode.support_fwd_propagation_factor)
probe = fftshift_2D(fft2(fftshift_2D(probe))); % propagate to infinity
else
probe = ifft2(fft2(probe) .* mode.support_propagation_factor);
end
end
%% apply real-space support
probe = probe .* mode.probe_support;
if ~isempty(mode.support_back_propagation_factor)
if isscalar(mode.support_back_propagation_factor) && isinf(mode.support_back_propagation_factor)
probe = fftshift_2D(ifft2(fftshift_2D(probe))); % propagate to infinity
else
probe = ifft2(fft2(probe).* mode.support_back_propagation_factor);
end
end
end
Np_p = size(probe);
if mode.probe_scale_upd(end) > 0 && ~isempty(mode.probe_scale_window)
% apply windowing to avoid boundary issues when subpixel probe
% rescaling is used
probe = probe .* mode.probe_scale_window ;
end
if ~isempty(mode.probe_support_fft) || mode.probe_scale_upd(end) ~= 0
%% apply contraint in the detector plane
% propagate probe on the detector
probe = fwd_fourier_proj(probe, mode);
if ~isempty(mode.probe_support_fft)
probe = probe .* mode.probe_support_fft;
end
if mode.probe_scale_upd(end) < 0 && ~isempty(mode.probe_scale_window)
probe = probe .* mode.probe_scale_window ;
end
% propagate probe back to the sample plane
probe = back_fourier_proj(probe, mode);
end
end
@@ -0,0 +1,111 @@
% APPLY_SUBPX_SHIFT subpixel probe shifting , equivalent just a bit faster than imshift_fft
%
% img = apply_subpx_shift(img, shift)
% apply_subpx_shift() will reset persitent variables that are created on GPU to avoid overhead with CPU / GPU transfer
%
%
% ** img stack images
% ** shift (N,2) array of shifts
% returns
% ++ img shifted image stack
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for maximum likelihood:
% P. Thibault and M. Guizar-Sicairos, Maximum-likelihood refinement for coherent diffractive imaging, New J. Phys. 14, 063004 (2012).
% (doi: 10.1088/1367-2630/14/6/063004),
% for mixed coherent modes:
% P. Thibault and A. Menzel, Reconstructing state mixtures from diffraction measurements, Nature 494, 6871 (2013). (doi: 10.1038/nature11806),
% and/or for multislice:
% E. H. R. Tsai, I. Usov, A. Diaz, A. Menzel, and M. Guizar-Sicairos, X-ray ptychography with extended depth of field, Opt. Express 24, 2908929108 (2016).
% (doi: 10.1364/OE.24.029089).
% 6. Except for the above-mentioned acknowledgment, LICENSEE shall not use the PROGRAM title or the names or logos of LICENSOR, nor any adaptation thereof, nor the
% names of any of its employees or laboratories, in any advertising, promotional or sales material without prior written consent obtained from LICENSOR in each case.
% 7. Ownership of all rights, including copyright in the PROGRAM and in any material associated therewith, shall at all times remain with LICENSOR, and LICENSEE
% agrees to preserve same. LICENSEE agrees not to use any portion of the PROGRAM or of any IMPROVEMENTS in any machine-readable form outside the PROGRAM, nor to
% make any copies except for its internal use, without prior written consent of LICENSOR. LICENSEE agrees to place the following copyright notice on any such copies:
% © All rights reserved. PAUL SCHERRER INSTITUT, Switzerland, Laboratory for Macromolecules and Bioimaging, 2017.
% 8. The LICENSE shall not be construed to confer any rights upon LICENSEE by implication or otherwise except as specifically set forth herein.
% 9. DISCLAIMER: LICENSEE shall be aware that Phase Focus Limited of Sheffield, UK has an international portfolio of patents and pending applications which relate
% to ptychography and that the PROGRAM may be capable of being used in circumstances which may fall within the claims of one or more of the Phase Focus patents,
% in particular of patent with international application number PCT/GB2005/001464. The LICENSOR explicitly declares not to indemnify the users of the software
% in case Phase Focus or any other third party will open a legal action against the LICENSEE due to the use of the program.
% 10. This Agreement shall be governed by the material laws of Switzerland and any dispute arising out of this Agreement or use of the PROGRAM shall be brought before
% the courts of Zürich, Switzerland.
function img = apply_subpx_shift(img, shift)
% subpixel probe shifting
import engines.GPU.shared.*
import engines.GPU.GPU_wrapper.*
persistent xgrid ygrid
if nargin == 0
xgrid = [];
return
end
if all(shift(:) == 0); return ; end
global use_gpu
shift = single(shift);
x = reshape(shift(:,1),1,1,[]);
y = reshape(shift(:,2),1,1,[]);
Np = size(img);
if size(img,3) ~= size(shift,1) && use_gpu
% ugly trick making matlab GPU FFT faster
img = repmat(img,1,1,size(shift,1));
end
img = fft2_safe(img);
if isempty(xgrid)
% matlab seems to need quite a lot of time to generate it -> preallocate
xgrid = Garray(fftshift((0:Np(2)-1)'/Np(2))-0.5)';
ygrid = Garray(fftshift((0:Np(1)-1)'/Np(1))-0.5);
end
if use_gpu
img = Gfun(@apply_shift_Gfun,img,x,y,xgrid, ygrid);
else
img = bsxfun(@times, img, exp((-2i*pi)*bsxfun(@times, x,xgrid)));
img = bsxfun(@times, img, exp((-2i*pi)*bsxfun(@times,y,ygrid)));
end
img = ifft2_safe(img);
end
function img = apply_shift_Gfun(img,x,y,xgrid, ygrid)
img = img .* exp((-2i*pi)*(x*xgrid+y*ygrid));
end
@@ -0,0 +1,98 @@
% APPLY_SUBPX_SHIFT_FFT fast shifting in fourier space (ie apply phase ramp )
%
% img = apply_subpx_shift_fft(img, shift)
%
% ** img stack images
% ** shift (N,2) array of shifts
% returns
% ++ img shifted image stack
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for maximum likelihood:
% P. Thibault and M. Guizar-Sicairos, Maximum-likelihood refinement for coherent diffractive imaging, New J. Phys. 14, 063004 (2012).
% (doi: 10.1088/1367-2630/14/6/063004),
% for mixed coherent modes:
% P. Thibault and A. Menzel, Reconstructing state mixtures from diffraction measurements, Nature 494, 6871 (2013). (doi: 10.1038/nature11806),
% and/or for multislice:
% E. H. R. Tsai, I. Usov, A. Diaz, A. Menzel, and M. Guizar-Sicairos, X-ray ptychography with extended depth of field, Opt. Express 24, 2908929108 (2016).
% (doi: 10.1364/OE.24.029089).
% 6. Except for the above-mentioned acknowledgment, LICENSEE shall not use the PROGRAM title or the names or logos of LICENSOR, nor any adaptation thereof, nor the
% names of any of its employees or laboratories, in any advertising, promotional or sales material without prior written consent obtained from LICENSOR in each case.
% 7. Ownership of all rights, including copyright in the PROGRAM and in any material associated therewith, shall at all times remain with LICENSOR, and LICENSEE
% agrees to preserve same. LICENSEE agrees not to use any portion of the PROGRAM or of any IMPROVEMENTS in any machine-readable form outside the PROGRAM, nor to
% make any copies except for its internal use, without prior written consent of LICENSOR. LICENSEE agrees to place the following copyright notice on any such copies:
% © All rights reserved. PAUL SCHERRER INSTITUT, Switzerland, Laboratory for Macromolecules and Bioimaging, 2017.
% 8. The LICENSE shall not be construed to confer any rights upon LICENSEE by implication or otherwise except as specifically set forth herein.
% 9. DISCLAIMER: LICENSEE shall be aware that Phase Focus Limited of Sheffield, UK has an international portfolio of patents and pending applications which relate
% to ptychography and that the PROGRAM may be capable of being used in circumstances which may fall within the claims of one or more of the Phase Focus patents,
% in particular of patent with international application number PCT/GB2005/001464. The LICENSOR explicitly declares not to indemnify the users of the software
% in case Phase Focus or any other third party will open a legal action against the LICENSEE due to the use of the program.
% 10. This Agreement shall be governed by the material laws of Switzerland and any dispute arising out of this Agreement or use of the PROGRAM shall be brought before
% the courts of Zürich, Switzerland.
function img = apply_subpx_shift_fft(img, shift)
import engines.GPU.GPU_wrapper.*
if all(shift(:) == 0); return ; end
global use_gpu
persistent grid
shift = Garray(shift);
x = reshape(shift(:,1),1,1,[]);
y = reshape(shift(:,2),1,1,[]);
Np = size(img);
if Np(1) ~= Np(2); error('Not implemented'); end
grid = Garray((0:Np(1)-1)'/Np(1)-0.5);
if isempty(grid)
grid = Garray((0:Np(1)-1)'/Np(1)-0.5);
end
if use_gpu
img = Gfun(@apply_shift_Gfun,img,x,y,grid', grid);
else
img = bsxfun(@times, img, exp((-2i*pi)*bsxfun(@times,x,grid')));
img = bsxfun(@times, img, exp((-2i*pi)*bsxfun(@times,y,grid)));
end
end
function img = apply_shift_Gfun(img,x,y,xgrid, ygrid)
img = img .* exp((-2i*pi)*(x*xgrid+y*ygrid));
end
@@ -0,0 +1,111 @@
% BACK_FOURIER_PROJ back propagate to the sample plane
%
% Psi = back_fourier_proj(Psi, mode)
%
% ** Psi [Nx,Ny,N] array, propagated complex valued exit-wave Psi = F(P*O)
% ** mode structure containing parameters for selected probe mode
%
% returns
% ++ psi [Nx,Ny,N] array, back-propagated complex valued exit-wave
% 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 [Psi, fmask] = back_fourier_proj(Psi, mode, ind)
import engines.GPU.shared.*
fmask = [];
try
if mode.distances(end) == 0
% no propagation
elseif mode.distances(end) == inf
Psi = ifft2_safe(Psi); % fully farfield
% Psi = fftshift_2D(ifft2_safe(fftshift_2D(Psi))); % fully farfield
elseif mode.distances(end) == -inf
Psi = fft2_safe(Psi); % fully farfield forward
elseif ~isempty(mode.cFAR_factor) % almost far field
Psi = fftshift_2D(ifft2_safe(fftshift_2D(Psi)));
Psi = bsxfun(@times, Psi, mode.cFAR_factor);
elseif ~isempty(mode.cASM_factor) % near field
Psi = fft2_safe(Psi);
Psi = Psi .* mode.cASM_factor;
Psi = ifft2_safe( Psi );
else
error('Not implemented')
end
if mode.probe_scale_upd(end) ~= 0
% apply scaling to the probe , used for camera distance refinement
Psi = utils.imrescale_frft(Psi,1/(1+mode.probe_scale_upd(end)));
end
if nargin > 2 && any(mode.probe_rotation_all)
% apply rotation to the probe , used for camera angle refinement
Psi = utils.imrotate_ax_fft(Psi,mode.probe_rotation_all(ind),3);
end
if ~isempty(mode.tilted_plane_propagate_fwd)
% propagate to tilted plane of the sample (if provided)
Psi = mode.tilted_plane_propagate_fwd(Psi);
end
catch err
if utils.verbose() > 0
warning(err.message)
keyboard
else
rethrow(err)
end
end
end
@@ -0,0 +1,104 @@
% CLEAN_RESIDUA, try to use 2D FFT unwrapping to remove phase residua
%
% self = clean_residua(self)
%
% ** self structure containing inputs: e.g. current reconstruction results, data, mask, positions, pixel size, ..
% 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 = clean_residua(self, cache)
ker = gausswin(7) .* gausswin(7)';
ker = ker / math.sum2(ker);
for ii = 1:numel(self.object)
object = self.object{ii};
Nresid(ii) = sum(sum(abs(utils.findresidues(object(cache.object_ROI{:}))) > 0.5));
if Nresid(ii) == 0
continue
end
utils.verbose(1,'Detected %i residua, trying to remove', Nresid(ii))
amp = abs(object);
phase = 0;
W = 2*(1-1./(1+cache.illum_sum_0{1}/max(max(cache.illum_sum_0{1}))));
mean_amp = math.sum2(amp .* W) / math.sum2(W);
W = W .* amp / mean_amp;
for jj = 1:2
phase = phase + math.unwrap2D_fft2(object,[],0,W,0);
object = exp(-1i*phase) .* object;
end
phase = convn( phase, ker, 'same');
%plotting.smart_figure(54655);
%imagesc(angle(exp(-1i*phase) .* self.object{ii}))
self.object{ii} = exp(1i*phase)*mean_amp; % remove amplitude information, it is easy to recover
end
if sum(Nresid)
utils.verbose(1,'Removing residua will result in low\n frequency errors in phase and amplitude, \n !! run DM again with current results as initial guess !!')
end
% imagesc(utils.findresidues( self.object{ii} ))
end
@@ -0,0 +1,75 @@
% EXTRACT_PCA Extract N principal compenents of 3D array x using SVD
%
% [X,V] = extract_PCA(x, N)
%
% ** x ND array
% ** N number of SVD modes
% returns:
% ++ X principal components
% ++ V principal weights
% 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,V] = extract_PCA(x, N)
[U,S,V] = fsvd(reshape(x,[],size(x,3)), N);
X = U*S;
X = reshape(X, size(x,1), size(x,2),[]);
end
+94
View File
@@ -0,0 +1,94 @@
% FFT2_SAFE wrapper around fft2, in case of low memory it will try to repeat Ntimes before giving up
%
% x = fft2_safe(x)
%
% ** x input array
% returns:
% ++ x 2D fft 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 = fft2_safe(x)
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'};
N = 5;
for i = 1:N
try
x = fft2(x);
break
catch ME
if ~any(strcmpi(ME.identifier, low_mem_errs))
disp(N)
rethrow(ME)
end
pause(1)
end
warning('FFT was not able to allocate enough memory')
gpuDevice
dbstack
rethrow(ME)
end
end
@@ -0,0 +1,207 @@
% FIND_GEOM_CORRECTION use current probe positions estimates to update geometry model and
% improve the new probe positions
%
% [self] = find_geom_correction(self,cache, par, iter,best_mode_id)
%
%
% ** 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
% ** iter current iteration
% ** best_mode_id strongest mode id
%
% returns:
% ++ self self-like structure with final reconstruction
%
%
function [self] = find_geom_correction(self,cache, par, iter,best_mode_id, update_position_weight)
import engines.GPU.GPU_wrapper.*
import engines.GPU.shared.*
import utils.*
import math.*
mode = self.modes{best_mode_id};
%% constrain the detector rotation
% store only the single update per scan
if iter > par.detector_rotation_search
for ii = 1:length(self.reconstruct_ind)
ind = self.reconstruct_ind{ii};
mrot(ii) = mean(mode.probe_rotation_all(ind));
end
if par.mirror_objects
% enforce zero average rotation if two mirror scans are provided
mrot = mrot - mean(mrot);
end
for ii = 1:length(self.reconstruct_ind)
mode.probe_rotation_all(ind) = mrot(ii) ;
end
mode.probe_rotation(end+1,:) = mrot;
end
if iter <= par.probe_position_search
self.modes{best_mode_id} = mode;
return
end
pos = mode.probe_positions;
pos_0 = mode.probe_positions_0;
%if all(isnan(mode.probe_positions_weight(:))) || all(mode.probe_positions_weight(:)==0)
if update_position_weight %modified by YJ. add this option so users can update poisition weights more than once
%% EMPIRICAL ESTIMATION OF POSITION RELIABILITY
verbose(0,'EMPIRICAL ESTIMATION OF POSITION RELIABILITY\n')
illum = utils.crop_pad(abs(self.probe{1}(:,:,1)).^2, self.Np_p/2);
total_variation = zeros(self.Npos,2, 'single');
for ii = 1:par.Nscans
best_layer = par.Nlayers;
o_tmp = self.object{min(end,ii), best_layer};
o_tmp = o_tmp ./ max2(abs(o_tmp(cache.object_ROI{:})));
% keep it more memory effecient (important for GPU !! )
Npos = length(self.reconstruct_ind{ii});
for jj = 1:ceil(Npos/par.grouping)
ind = 1+(jj-1)*par.grouping:min(Npos, jj*par.grouping);
obj_proj = get_views(o_tmp,[],1,1,self.reconstruct_ind{ii}(ind),cache);
obj_proj = utils.crop_pad(obj_proj, self.Np_p/2);
[nx, ny,~] = size(obj_proj);
[X,Y] = meshgrid(-ny/2:ny/2-1, -nx/2:nx/2-1);
% suppress edge effects of the FFT derivatives
spatial_filter = exp(-(X.^16+Y.^16)/(min(nx,ny)/2.2)^16);
obj_proj = obj_proj.* spatial_filter;
[dX, dY] = get_img_grad(obj_proj);
clear obj_proj
illum_proj = get_views(utils.imgaussfilt2_fft(cache.illum_sum_0{min(ii,end)},self.Np_p/10),[],1,1,self.reconstruct_ind{ii}(ind),cache);
illum_proj = utils.crop_pad(illum_proj, self.Np_p/2);
dX = abs(dX) .* illum_proj.* illum;
dY = abs(dY) .* illum_proj.* illum;
clear illum_proj
total_variation(self.reconstruct_ind{ii}(ind),:) = Ggather(sqrt(squeeze([mean2(dX),mean2(dY)]))');
clear dX dY
end
end
mode.probe_positions_weight = total_variation.^4./mean(total_variation.^4);
end
probe_positions_weight = double(mode.probe_positions_weight);
jj = size(mode.scales,1)+1;
% find geometry for each scan separatelly
for ii = 1:par.Nscans
ind = self.reconstruct_ind{ii};
C0 = mode.affine_matrix(:,:,ii) - eye(2);
C0 = C0(:);
if par.Nscans > 1 && par.share_object
% it the case of multiple scans allow also freedom of coordinates shifts
pos_fun = @(C)(( [1+C(1), C(2); C(3), 1+C(4)]*pos_0(ind,:)')' + C([5,6])' );
if isfield(mode, 'shift_scans' ) && size(mode.shift_scans,2)>=ii
C0(5:6) = mode.shift_scans(:,ii);
else
C0(5:6) = 0;
end
else
pos_fun = @(C)(( [1+C(1), C(2); C(3), 1+C(4)]*pos_0(ind,:)')' );
end
err_fun = @(C)( probe_positions_weight(ind,:) .* (pos(ind,:) - pos_fun(C)));
options = optimoptions('lsqnonlin','Display','off');
%C(:,ii) = lsqnonlin( err_fun, C0,[],[],options) ;
%% modified by YJ to avoid fitting error
try
C(:,ii) = lsqnonlin( err_fun, C0,[],[],options);
catch
disp('Fitting error during geom correction...')
C(:,ii) = [0,0,0,0,0,0];
end
%% restrict the geometry model only to the allowed degreed of freedom
% ===================================================================
M{ii} = reshape(C(1:4,ii),2,2)+eye(2);
M_fit = M; %added by YJ to keep track of estimated affine matrix
[scale, asymmetry, rotation, shear] = decompose_affine_matrix(M{ii});
if ~ismember('scale', par.probe_geometry_model)
scale = 1;
end
if ~ismember('asymmetry', par.probe_geometry_model)
asymmetry = 0;
end
if ~ismember('rotation', par.probe_geometry_model)
rotation = 0;
end
if ~ismember('shear', par.probe_geometry_model)
shear = 0;
end
M{ii} = compose_affine_matrix(scale, asymmetry, rotation, shear);
% ===================================================================
mode.scales(jj,ii) = scale;
mode.asymmetry(jj,ii) = asymmetry;
mode.rotation(jj,ii) = rotation;
mode.shear(jj,ii) = shear;
if par.Nscans > 1 && par.share_object
mode.shift_scans(:,ii) = C(5:6,ii);
else
mode.shift_scans(:,ii) = [0,0];
end
% store initial guess
mode.affine_matrix(:,:,ii) = M{ii};
% calculate ideal model positions
pos_model(ind,:) = pos_fun([reshape(M{ii} - eye(2), [],1); mode.shift_scans(:,ii)]);
end
self.affine_matrix = M;
self.affine_matrix_fit = M_fit; %added by YJ to keep track of estimated affine matrix
verbose(2,['----- Geom. correction ', repmat('%3.3g ', 1,length(C))], C)
% use average
resid_pos= pos - pos_model;
% ignore errors in the global shift of the positions
for ii = 1:par.Nscans
ind = self.reconstruct_ind{ii};
resid_pos(ind,:) = resid_pos(ind,:) - mean(resid_pos(ind,:));
end
err = abs(resid_pos);
max_err = par.probe_position_error_max ./ self.pixel_size .* self.relative_pixel_scale;
verbose(1, '==== AVG position error %3.2g px MAX error %3.2g LIMIT %3.2g px ', mean(err(:)), max(err(:)), max(max_err))
%modified by YJ: add par.apply_relaxed_position_constraint to allow position update without constraints from geometry model.
%Useful if there are big jumps in positions
if par.apply_relaxed_position_constraint
%% apply only relaxed constrain on the probe positions !!!
relax = 0.1;
% constrain more the probes in flat regions
W = relax*(1- (probe_positions_weight./ (1+probe_positions_weight)));
% penalize positions that are further than max_err from origin
W = min(10*relax, W+max(0,err - max_err).^2 ./ max_err.^2 ); % avoid travel larger than max error
else
W=0; %no geom model imposed to regularize positions
end
% allow free movement in depenence on realibility and max allowed error
pos_new = pos .*(1-W)+W.*pos_model;
mode.probe_positions = pos_new;
mode.probe_positions_model = pos_model;
if any(isnan(mode.probe_positions(:)))
keyboard
end
self.modes{best_mode_id} = mode;
end
@@ -0,0 +1,106 @@
% FIND_RECONSTRUCTION_ROI precalculate the reconstruction regions for CPU and GPU
%
% [oROI, oROI_vec, sub_px_shift] = find_reconstruction_ROI( positions,Np_o, Np_p )
%
% ** positions Npox*2 vector of scanning positions
% ** Np_o object size
% ** Np_p probe size
%
% returns:
% ++ oROI cell array contaning range for each view
% ++ oROI_vec cell array contaning range for each view in vector shape
% ++ sub_px_shift subpixel rounding errors, used for subpixel shift
%
%
% 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 [oROI, oROI_vec, sub_px_shift] = find_reconstruction_ROI( positions,Np_o, Np_p )
positions = positions(:,[2,1]);
positions = positions + ceil(Np_o/2-Np_p/2);
sub_px_shift = positions - round(positions);
sub_px_shift = sub_px_shift(:,[2,1]); % return to the original XY coordinates
positions = round(positions);
range = [min(positions), max(positions)+ Np_p];
if any(range(1:2) < 0) || any(range(3:4) > Np_o)
error('Object size is too small, not enough space for probes !! \nposition range: %i %i %i %i, \nobject size: %i %i ', range(1), range(2), range(3), range(4), Np_o(1), Np_o(2))
end
oROI = cell(2,1);
for dim = 1:2
oROI{dim} = [positions(:,dim),positions(:,dim)+ Np_p(dim)-1]-1;
oROI{dim} = uint32(oROI{dim});
end
if nargout > 1
Npos = length(positions);
oROI_vec = cell(Npos,2);
for ii = 1:Npos
for i = 1:2
oROI_vec{ii,i} = oROI{i}(ii,1):oROI{i}(ii,2);
end
end
end
end
@@ -0,0 +1,150 @@
% self = flip_mirror_scan(self, align_objects )
% join two scans obtained at 0 and 180 degrees to get a better estiamte
% of geometry errors
%
% Inputs:
% self main data structure
% align_objects find optimal shifts between the scans to match the 0 and 180 deg scan
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for 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 = flip_mirror_scan(self, align_objects)
import engines.GPU.*
import utils.*
import engines.GPU.GPU_wrapper.*
if nargin < 2
align_objects = true; % find optimal shifts between the scans to match the 0 and 180 deg scan
end
verbose(1,'=== Flipping 2nd scan ==== ')
assert(length(self.reconstruct_ind) == 2, 'Two mirrored (0vs180deg) scans are required')
for layer = 1:size(self.object,2)
self.object{2,layer} = fliplr(self.object{min(end,2),layer});
end
ind = self.reconstruct_ind{2};
%% FLIP THE 2ND SCAN POSITIONS
% keep the position distance from the reconstruction edge
self.probe_positions_0 = flip_positions(self, self.probe_positions_0, ind);
if ~isempty(self.probe_positions)
self.probe_positions = flip_positions(self, self.probe_positions, ind);
end
%% flip other inputs
for ii = 1:length(self.probe)
self.probe{ii}(:,:,2,:) = fliplr(self.probe{ii}(:,:,min(end,2),:));
end
if ~isempty(self.diffraction)
self.diffraction(:,:,ind) = fliplr(self.diffraction(:,:,ind));
end
if ~isempty(self.mask)
if size(self.mask,3) == 1
self.mask = repmat(self.mask, 1, 1, self.Npos);
end
self.mask(:,:,ind) = fliplr(self.mask(:,:,ind));
end
if isfield(self, 'affine_matrix')
% flip nondiagonal terms of the affine matrix for account for the flipping
self.affine_matrix{2} = self.affine_matrix{2} .* [1,-1; -1,1];
end
if align_objects
% using crosscorrelation find optimal shift between objects
self = shared.align_objects(self);
else
% move the probe back to the center of the asize
for ii = 1:2
[cx, cy] = math.center(abs(self.probe{1}(:,:,ii,1)).^2);
self.probe{1}(:,:,ii,:) = utils.imshift_fft(self.probe{1}(:,:,ii,:), -cx, -cy);
self.object{ii} = utils.imshift_fft(self.object{ii}, -cx, -cy);
end
end
end
function pos_0 = flip_positions(self, pos_0, ind)
% flip positions so that the flipped object does not move after
% reconstruction
pos = pos_0(ind,1);
offset = ceil(self.Np_o(2)/2-self.Np_p(2)/2);
pos = -(pos + offset);
left_offset = -max(pos);
right_offset = self.Np_o(2) -max(pos)-self.Np_p(2) ;
pos = pos + right_offset - left_offset;
pos = pos - offset;
pos_0(ind,1) = pos ;
end
@@ -0,0 +1,107 @@
% FWD_FOURIER_PROJ forward propagate to the detector plane
% Psi = fwd_fourier_proj(Psi, mode)
%
% ** psi [Nx,Ny,N] array, back-propagated complex valued exit-wave
% ** mode structure containing parameters for selected probe mode
%
% returns
% ++ Psi [Nx,Ny,N] array, propagated complex valued exit-wave Psi = F(P*O)
% 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 [Psi] = fwd_fourier_proj(Psi, mode, ind)
import engines.GPU.shared.*
try
if ~isempty(mode.tilted_plane_propagate_back)
% propagate from tilted plane of the sample to flat plane of the detector (if provided)
Psi = mode.tilted_plane_propagate_back(Psi);
end
if nargin > 2 && any(mode.probe_rotation_all)
% apply rotation to the probe , used for camera angle refinement
Psi = utils.imrotate_ax_fft(Psi,-mode.probe_rotation_all(ind),3);
end
if mode.probe_scale_upd(end) ~= 0
% apply scaling to the probe , used for camera distance refinement
Psi = utils.imrescale_frft(Psi,1+mode.probe_scale_upd(end));
end
if mode.distances(end) == 0
% no propagation
elseif mode.distances(end) == inf
Psi = fft2_safe(Psi); % fully farfield
% Psi = fftshift_2D(fft2_safe(fftshift_2D(Psi))); % fully farfield
elseif mode.distances(end) == -inf
Psi = ifft2_safe(Psi); % fully farfield backward
elseif ~isempty(mode.FAR_factor) % almost far field
Psi = bsxfun(@times, Psi, mode.FAR_factor);
Psi = fftshift_2D(fft2_safe(fftshift_2D(Psi)));
elseif ~isempty(mode.ASM_factor) % near field transformation
Psi = fft2_safe(Psi);
Psi = Psi .* mode.ASM_factor;
Psi = ifft2_safe(Psi);
else
error('Not implemented')
end
catch err
if utils.verbose()> 0
warning(err.message)
keyboard
else
rethrow(err)
end
end
end
+125
View File
@@ -0,0 +1,125 @@
% GET_ROI find optimal rectange containing the logical mask
%
% ROI = get_ROI(mask, extent = 0, type = 'any')
%
% ** mask logical array
% ** extend (scalar) relative increase of the found range
% ** type (string) odd, even, pow2, any
%
% returns:
% ++ ROI smallest ROI that contains the mask
%
% 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 [ROI] = get_ROI(mask, extent, type)
if all(mask(:) == 0)
error('Empty mask')
end
if nargin < 3
type = 'any';
end
if nargin == 1
extent = 0.25;
end
[W,H] = size(mask);
if ~islogical(mask)
error('Not implemented')
end
x = any(mask,2);
y = any(mask,1);
coord = [find(x, 1,'first'), find(x, 1,'last'), find(y, 1,'first'), find(y, 1,'last')];
w = (coord(2) - coord(1));
h = (coord(4) - coord(3));
Cx = (coord(2) +coord(1))/2;
Cy = (coord(4) + coord(3))/2;
coord(1) = floor(Cx - ceil( (0.5 + extent) *w )) ;
coord(2) = ceil(Cx + ceil((0.5 + extent) * w )) ;
coord(3) = floor(Cy - ceil((0.5 + extent) * h )) ;
coord(4) = ceil(Cy + ceil((0.5 + extent) * h )) ;
switch type
case 'odd'
coord(2) = coord(1) + floor((coord(2) - coord(1))/2)*2;
coord(4) = coord(3) + floor((coord(4) - coord(3))/2)*2;
case 'even'
coord(2) = coord(1) + ceil((coord(2) - coord(1))/2)*2-1;
coord(4) = coord(3) + ceil((coord(4) - coord(3))/2)*2-1;
case 'pow2'
w = 2^(nextpow2( coord(2) - coord(1))-2);
h = 2^(nextpow2( coord(4) - coord(3))-2);
Cx = (coord(2) +coord(1))/2;
Cy = (coord(4) + coord(3))/2;
coord(1) = round(Cx - w) ;
coord(2) = round(Cx + w-1) ;
coord(3) = round(Cy - h) ;
coord(4) = round(Cy + h-1) ;
end
coord(coord < 1) = 1;
if coord(2) > W ; coord(2) = W; end
if coord(4) > H ; coord(4) = H; end
ROI = {coord(1):coord(2), coord(3):coord(4)};
end
+92
View File
@@ -0,0 +1,92 @@
% GET_MASK get mask for current list of indices ind
%
% mask = get_mask(self,mask_indices, ind, damped_mask)
%
% ** self structure containing inputs: e.g. current reconstruction results, data, mask, positions, pixel size, ..
% ** mask_indices indices that determine which mask is needed for each scan position
% ** ind currenly processed indices
% ** damped_mask relaxation constant that push masked values weakly to the measured value, useful for missing pixels when the data were fixed by nearest neighbor
%
% returns:
% ++ mask prepared mask array (true == ignored values)
% 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 mask = get_mask(self,mask_indices, ind, damped_mask)
import engines.GPU.GPU_wrapper.*
mask = [];
if ~isempty(self.mask)
if size(self.mask, 3) == 1
mask = self.mask;
else
mask = self.mask(:,:,mask_indices(ind));
end
end
mask = Garray(mask);
if (isa(mask, 'gpuArray') && strcmpi(classUnderlying(mask), 'uint8')) || isa(mask, 'uint8')
mask = single(mask)/ 255; % convert back to singles from the storage class
end
% push masked regions towards data value (ie towards zero)
if nargin == 4 && damped_mask > 0
mask = mask .* single(1-damped_mask);
end
end
+123
View File
@@ -0,0 +1,123 @@
% GET_MODULUS load and prepare data for current positions ind
%
% modF = get_modulus(self, cache, ind, move_to_gpu = true, bunch_id)
%
%
% ** self structure containing inputs: e.g. current reconstruction results, data, mask, positions, pixel size, ..
% ** cache structure with precalculated values to avoid unnecessary overhead
% ** ind currenly processed indices
% ** move_to_gpu (bool) if the data should be moved on GPU or left on CPU , default == true
% ** bunch_id number of the processed bunch, used only if the positions are stored as a list of cells with data
%
% returns:
% ++ modF prepared modulus data
% 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 modF = get_modulus(self, cache, ind, move_to_gpu, bunch_id)
import engines.GPU.GPU_wrapper.*
import utils.*
if ~iscell(self.diffraction)
% if diffraction is just array, load block ind
modF = self.diffraction(:,:,ind);
else
% load from cell array
modF = self.diffraction{bunch_id};
end
if isa(modF, 'gpuArray')
data_class = classUnderlying(modF);
else
data_class = class(modF);
end
if nargin < 4 || move_to_gpu
% load on GPU if not there yet
modF = Garray(modF);
end
switch data_class
case {'uint16', 'uint8'} % simple sqrt lossy online compression
modF = single(modF)/ cache.C_factor;
verbose(5, 'UINT8/16 lossy compression')
case 'int8'
% lossy compression
modF = single(modF) ;
if size(cache.US_diffraction,2) == 1 && isa(modF, 'gpuArray')
% 1 SVD mode - run merged kernel
modF = Gfun(@decompress_N1,modF, reshape(cache.US_diffraction,self.Np_p),...
reshape(cache.V_diffraction(ind),1,1,[]), cache.C_factor);
else % mode SVD modes
modF = modF + round(reshape(cache.US_diffraction*cache.V_diffraction(ind,:)', size(modF)));
modF = modF / cache.C_factor;
end
verbose(5, 'SVD INT8 lossy compression')
case 'single'
otherwise
error('Not implemented class %s', data_class)
end
end
function modF = decompress_N1(modF, US, V, C)
modF = modF + round(US .* V);
modF = modF / C;
end
+76
View File
@@ -0,0 +1,76 @@
% GET_NOISE load and prepare noise estimate for current positions ind
%
% noise = get_noise(self, par, g_ind)
%
% ** self structure containing inputs: e.g. current reconstruction results, data, mask, positions, pixel size, ..
% ** par structure containing parameters for the engines
% ** g_ind processed indices
%
% returns:
% ++ noise noise intensity for selected frames
% 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 noise = get_noise(self, par, g_ind)
if par.relax_noise && ~isempty(self.noise)
noise = self.noise(:,:,g_ind);
else
noise = [];
end
end
@@ -0,0 +1,85 @@
% GET_OBJECT_EXTENT estimate the minimal area surrounding all the probe positions
%
% Np_o_new = get_object_extent(Np_p, probe_positions, extra_padding)
%
% ** Np_p proeb size
% ** probe_positions (Npos,2) vector of probe positions
% ** extra_padding relative extra padding of the estimated project 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 Np_o_new = get_object_extent(Np_p, probe_positions, extra_padding)
probe = ones(Np_p);
Np_o = [1e5, 1e5];
Npos = size(probe_positions,1);
Np_p = size(probe);
probe_positions = bsxfun(@minus, probe_positions, (max(probe_positions)+min(probe_positions))/2 );
[oROI] = engines.GPU.shared.find_reconstruction_ROI(probe_positions, Np_o, Np_p );
Range = [Np_o, 0,0];
for i = 1:Npos
Range(1) = min(Range(1), oROI{1}(i,1));
Range(2) = min(Range(2), oROI{2}(i,1));
Range(3) = max(Range(3), oROI{1}(i,2));
Range(4) = max(Range(4), oROI{2}(i,2));
end
Np_o_new = [Range(3) - Range(1), Range(4) - Range(2)];
Np_o_new= ceil(Np_o_new*(1+extra_padding));
end
+199
View File
@@ -0,0 +1,199 @@
% GET_VIEWS extract view for each the provided positions and indices
%
% obj_proj = get_views(object, obj_proj,layer_ids,object_id, indices, cache, scan_ids, skip_ind)
%
% ** object [Nx_o, Ny_o] array or cells containing object
% ** obj_proj [Nx_o, Ny_o, N] preallocated array for the views
% ** layer_ids id of the solved layer for multilayer ptycho
% ** object_id id of the object, ie scan or incoherent mode
% ** indices processed positions
% ** cache structure with precalculated values to avoid unnecessary overhead
% ** scan_ids determines to which scan correponds each of the position
% ** skip_ind list of indices to be skipped
%
% returns:
% ++ obj_proj [Nx_p, Ny_p, N] array with the object views
%
% 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 obj_proj = get_views(object, obj_proj,layer_ids,object_id, indices, cache, scan_ids, skip_ind)
import engines.GPU.GPU_wrapper.*
import engines.GPU.shared.*
import utils.verbose
global use_gpu
Np_p = [size(obj_proj,1),size(obj_proj,2)];
if size(obj_proj,3) ~= numel(indices) || isempty(obj_proj)
% in the last iter, number of items may not be equal to grouping
if isempty(obj_proj)
obj_proj = Gzeros([Np_p, numel(indices)], true);
else
% should be tiny bit faster
obj_proj = zeros([Np_p, numel(indices)], 'like', obj_proj);
end
end
if nargin < 8
skip_ind = [];
end
skip_ind = [skip_ind, cache.skip_ind];
if nargin > 6
%% !!! call recursivelly -> wrapper for multiscan version !!!!
% get unique IDs of the scans
if isempty(scan_ids)
unq_scans = [];
elseif all(scan_ids == scan_ids(1))
unq_scans = scan_ids(1);
else
unq_scans = unique(scan_ids);
end
if (length(unq_scans)> 1 || length(object) > 1 ) && iscell(object)
if ~isempty(use_gpu) && use_gpu && isa(object{object_id(1)}, 'gpuArray') && isa(obj_proj, 'gpuArray')
% object_modes > 1 not implemented yet
if size(object,1) == 1
% shared object or single object
ind_ok{1} = uint16(1:length(indices));
else
for kk = 1:size(object,1)
ind_ok{kk} = uint16(find(scan_ids == kk));
end
end
% feed data directly to the GPU mex without splitting
obj_proj = get_views_gpu(object(:,layer_ids),obj_proj,cache.oROI_s{min(end,object_id(1))}, indices, ind_ok);
else
% if GPU not available use this "wrapper" around single
% set_projection function
for kk = unq_scans
ind = scan_ids == kk;
skip_ind = indices(~ind); % avoid going through these indices
obj_proj = get_views(object{kk,layer_ids},obj_proj, 1, object_id, indices, cache, [], skip_ind);
end
end
return
end
end
object_id = object_id(1);
try
if iscell(object)
object = object{object_id, layer_ids};
end
catch
keyboard
end
if ~isempty(cache.skip_ind) && ~isempty(skip_ind)
ind_ok = uint16(find(~ismember(indices, [cache.skip_ind,skip_ind]))); % skip wrong patterns
else
ind_ok = uint16(1:length(indices));
end
if isempty(obj_proj)
Np_p = [length(cache.oROI{min(object_id,end)}{1,1}), length(cache.oROI{min(object_id,end)}{1,2})];
obj_proj = Gzeros([Np_p, length(ind_ok)], true);
end
if isa(object, 'gpuArray')
%% USE CUDA MEX FOR GPU
obj_proj = get_views_gpu(object,obj_proj,cache.oROI_s{min(end,object_id)}, indices, ind_ok);
else
%% USE CPU
positions = int32([cache.oROI_s{min(end,object_id)}{1}(indices,1), cache.oROI_s{min(end,object_id)}{2}(indices,1)]);
obj_proj = utils.get_from_3D_projection(obj_proj,object, positions, ind_ok);
end
end
function obj_proj = get_views_gpu(object, obj_proj, ROI, ind, ind_ok)
% Description: simple method to get GPU based projections from object
import utils.verbose
% mexcuda -output +engines/+GPU/get_views_gpu_mex +engines/+GPU/get_views_gpu_mex.cu
import engines.GPU.GPU_wrapper.*
%% do not return matrices, write directly into obj_proj !!!
x = uint16(ROI{1}(ind,1));
y = uint16(ROI{2}(ind,1));
if ~iscell(object); object = {Garray(complex(object))}; end
if ~iscell(ind_ok); ind_ok = {Garray(uint16(ind_ok))}; end
obj_proj = complex(Garray(obj_proj));
try
get_views_gpu_mex( obj_proj, object,x,y, ind_ok);
catch err
verbose(0, 'Recompilation of MEX functions ... ')
if any(strcmp(err.identifier, { 'MATLAB:UndefinedFunction','MATLAB:mex:ErrInvalidMEXFile'}))
path = replace(mfilename('fullpath'), mfilename, '');
mexcuda('-output', [path,'private/get_views_gpu_mex'], [path, 'private/get_views_gpu_mex.cu'])
get_views_gpu_mex( obj_proj, object,x,y, ind_ok);
else
rethrow(err)
end
end
end
+91
View File
@@ -0,0 +1,91 @@
% IFFT2_SAFE wrapper around fft2, in case of low memory it will try to repeat 5-times before giving up
% ** x input array
%
% x = ifft2_safe(x)
%
% ** x input stacked array
% returns:
% ++ x 2D fft 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 = ifft2_safe(x)
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'};
N = 5;
for i = 1:N
try
x = ifft2(x);
break
catch ME
if ~any(strcmpi(ME.identifier, low_mem_errs))
rethrow(ME)
end
pause(1)
end
warning('FFT was not able to allocate enough memory')
gpuDevice
dbstack
rethrow(ME)
end
end
+78
View File
@@ -0,0 +1,78 @@
% IS_METHOD try if the method match or at least partially match
%
% match = is_method(par, method)
%
% ** par parameter structure
% ** method method name , even partial will work
% returns
% ++ match (bool) if the current method and string "method" at least partialyl match
% 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 match = is_method(par, method)
match = 0;
if ~iscell(method)
method = {method};
end
try
for i = 1:length(method)
match = match || contains(lower(par.method), lower(method{i}));
end
catch
keyboard
end
end
+89
View File
@@ -0,0 +1,89 @@
% IS_USED Check if the extension/extensions is set to be used
%
% used = is_used(param, extension)
% Example: is_used(param, {'ext1', 'ext2'})
%
% ++ param parametrer structure
% ++ extension string or cell of the extension names
% returns:
% ** used bool if method is used
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for mixed coherent modes:
% P. Thibault and A. Menzel, Reconstructing state mixtures from diffraction measurements, Nature 494, 6871 (2013). (doi: 10.1038/nature11806),
% for LSQ-ML method
% M. Odstrcil, A. Menzel, M.G. Sicairos, Iterative least-squares solver for generalized maximum-likelihood ptychography, Optics Express, 2018
% for OPRP method
% M. Odstrcil, P. Baksh, S. A. Boden, R. Card, J. E. Chad, J. G. Frey, W. S. Brocklesby, "Ptychographic coherent diffractive imaging with orthogonal probe relaxation." Optics express 24.8 (2016): 8360-8369
% and/or for multislice:
% E. H. R. Tsai, I. Usov, A. Diaz, A. Menzel, and M. Guizar-Sicairos, X-ray ptychography with extended depth of field, Opt. Express 24, 2908929108 (2016).
% 6. Except for the above-mentioned acknowledgment, LICENSEE shall not use the PROGRAM title or the names or logos of LICENSOR, nor any adaptation thereof, nor the
% names of any of its employees or laboratories, in any advertising, promotional or sales material without prior written consent obtained from LICENSOR in each case.
% 7. Ownership of all rights, including copyright in the PROGRAM and in any material associated therewith, shall at all times remain with LICENSOR, and LICENSEE
% agrees to preserve same. LICENSEE agrees not to use any portion of the PROGRAM or of any IMPROVEMENTS in any machine-readable form outside the PROGRAM, nor to
% make any copies except for its internal use, without prior written consent of LICENSOR. LICENSEE agrees to place the following copyright notice on any such copies:
% © All rights reserved. PAUL SCHERRER INSTITUT, Switzerland, Laboratory for Macromolecules and Bioimaging, 2017.
% 8. The LICENSE shall not be construed to confer any rights upon LICENSEE by implication or otherwise except as specifically set forth herein.
% 9. DISCLAIMER: LICENSEE shall be aware that Phase Focus Limited of Sheffield, UK has an international portfolio of patents and pending applications which relate
% to ptychography and that the PROGRAM may be capable of being used in circumstances which may fall within the claims of one or more of the Phase Focus patents,
% in particular of patent with international application number PCT/GB2005/001464. The LICENSOR explicitly declares not to indemnify the users of the software
% in case Phase Focus or any other third party will open a legal action against the LICENSEE due to the use of the program.
% 10. This Agreement shall be governed by the material laws of Switzerland and any dispute arising out of this Agreement or use of the PROGRAM shall be brought before
% the courts of Zürich, Switzerland.
%
%
function used = is_used(param, extension)
if ~isfield(param, 'extension'); used = false; return ; end
if ~iscell(param.extension) && ~iscell(extension)
used = strcmpi(param.extension, extension);
else
if ~iscell(extension)
extension = {extension};
end
if ~iscell( param.extension)
param.extension = {param.extension};
end
used = false;
for i = 1:length(param.extension)
for j = 1:length(extension)
used = used | strcmpi(param.extension{i}, extension{j});
if used; break; end
end
if used; break; end
end
end
end
@@ -0,0 +1,121 @@
% FUNCTION [u_1, H, h, dH] = near_field_evolution(u_0, z, lambda, extent, use_ASM_only)
% Description: nearfield evolution function, it automatically swithc
% between ASM and Fraunhofer propagation
%
% 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 [u_1, H, h, dH] = near_field_evolution(u_0, z, lambda, extent, use_ASM_only)
H = [];
h = [];
u_1 = [];
dH = [];
if nargin < 5
use_ASM_only = false;
end
extent = extent(:)' .* ones(1,2);
if z == 0
H = 1;
u_1 = u_0;
return
end
if z == inf
return
end
Npix = size(u_0);
xgrid = (0.5+(-Npix(1)/2:Npix(1)/2-1))/Npix(1);
ygrid = (0.5+(-Npix(2)/2:Npix(2)/2-1))/Npix(2);
k = 2 * pi / lambda(1);
% Undesamplling parameter
F = mean( extent.^2 ./ (lambda(1) .* z .* Npix ));
if abs(F) < 1 && ~use_ASM_only
% farfield propagation
warning('Farfield regime, F/Npix=%g', F )
Xrange = xgrid*extent(1);
Yrange = ygrid*extent(2);
[X,Y] = meshgrid(Xrange, Yrange);
h = exp(1i*k*z +1i*k/(2*z) * (X'.^2 + Y'.^2));
% this serves as low pass filter for the far nearfield
H = ifftshift(fft2(fftshift(h)));
H = H / abs(H(end/2+1, end/2+1)); % renormalize to conserve flux in image
else
% standard ASM
kx = 2 * pi .*xgrid / extent(1) * Npix(1) ;
ky = 2 * pi .*ygrid / extent(2) * Npix(2);
[Kx, Ky] = meshgrid(kx, ky);
dH = ( -1i*(Kx'.^2+Ky'.^2)/(2*k) );
H = exp( 1i*z*sqrt( k^2 - Kx'.^2-Ky'.^2)); % it make it a bit more sensitive to z distance
h = [];
end
u_1 = ifft2( bsxfun(@times, ifftshift(H), fft2(u_0)));
end
@@ -0,0 +1,89 @@
% NEAR_FIELD_EVOLUTION_GRADIENT Gradient of the nearfield evolution function, useful for calcualteion of the optimal propagation
% distance
%
% [dH] = near_field_evolution_gradient(Npix, lambda, extent)
%
% ** Npix size of the propagated window
% lambda wavelenght
% extend lateral size of the window
%
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for 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 [dH] = near_field_evolution_gradient(Npix, lambda, extent)
extent = extent(:)' .* ones(1,2);
xgrid = (0.5+(-Npix(1)/2:Npix(1)/2-1))/Npix(1);
ygrid = (0.5+(-Npix(2)/2:Npix(2)/2-1))/Npix(2);
k = 2 * pi / lambda(1);
% standard ASM
kx = 2 * pi .*xgrid / extent(1) * Npix(1) ;
ky = 2 * pi .*ygrid / extent(2) * Npix(2);
[Kx, Ky] = meshgrid(kx, ky);
dH = ( -1i*(Kx'.^2+Ky'.^2)/(2*k) );
end
@@ -0,0 +1,90 @@
% ORTHO_MODES return orthogonal modes, without any normalization , expect cells
%
% x = ortho_modes(x)
%
% ** x cell array with probes to be orthogonalized
%
% returns:
% ++ x orthogonalized set
%
%
%
% 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 = ortho_modes(x)
for i = 1:length(x)
power(i) = sum2(abs( mean(x{i},3)).^2);
for j = 1:i-1
mx_j = mean(x{j},3);
mx_i = mean(x{i},3);
proj = sum2(mx_i .* conj(mx_j)) ...
/ sum2(abs(mx_j).^2);
x{i} = x{i} - proj * mx_j;
end
end
% sort them, should improve convergence
[~,ind]=sort(-power);
x(2:end) = x(ind(2:end));
end
%% added by YJ
function x = sum2(x)
x = sum(sum(x,1),2);
end
@@ -0,0 +1,97 @@
% ORTHO_MODES_EIG orthogonal modes using eigen values
%
% x = ortho_modes_eig(x)
%
% ** x cell array with probes to be orthogonalized
%
% returns:
% ++ x orthogonalized set
%
%
%
% 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 = ortho_modes_eig(x)
N = length(x);
Np = [size(x{1},1),size(x{1},2)];
for i = 1:N
x_tmp{i} = mean(x{i}(:,:,:,1),3);
end
A = zeros(N,N, class(x{1}));
for i = 1:N
for j = 1:N
A(i,j) = (x_tmp{i}(:)'* x_tmp{j}(:));
end
end
[v,d] = eig(A);
[~,di] = sort(-abs(diag(d)));
for j = 1:N
x_new{j} = zeros(Np, class(x{1}));
for i = 1:N
x_new{j} = x_new{j} + x{i}*v(i,j);
end
end
%% sort by energy
x_new = x_new(di);
% dont update the first one (it may interefere with OPR method)
x(2:end) = x_new(2:end);
end
@@ -0,0 +1,85 @@
% PRECALCULATE_ROI precalculate the views areas for given probe_positions for faster calculations
%
% cache = precalculate_ROI(self, cache, probe)
%
% ** self structure containing inputs: e.g. current reconstruction results, data, mask, positions, pixel size, ..
% ** cache structure with precalculated values to avoid unnecessary overhead
% ** probe complex array with the current probe, used to estimate probe smallest support
% returns:
% ++ cache structure with precalculated values to avoid unnecessary overhead
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for mixed coherent 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 cache = precalculate_ROI(self, cache, probe)
import math.*
import utils.*
import engines.GPU.shared.*
object_ROI = {round(self.Np_o(1)/2+(min(self.probe_positions_0(:,2)):max(self.probe_positions_0(:,2)))), ...
round(self.Np_o(2)/2+(min(self.probe_positions_0(:,1)):max(self.probe_positions_0(:,1))))};
Np = size(probe,1);
[~, fftshift_idx] = fftshift_2D(probe);
cache.object_ROI = object_ROI;
cache.fftshift_idx = fftshift_idx;
end
@@ -0,0 +1,168 @@
/*
*
*
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.
*
Compilation from Matlab:
maybe a tiny bit faster code is generated by
mex -O COPTIMFLAGS='-O2' LDOPTIMFLAGS='-O2' CFLAGS="\$CFLAGS -fopenmp" LDFLAGS="\$LDFLAGS -fopenmp" get_views_cpu_mex.cpp
Usage from Matlab:
get_views_cpu_mex(object,obj_proj,positions, ind_ok);
This code in matlab:
asize = size(probe);
for i=ind_ok
Indy = positions(i,1) + (1:asize(1));
Indx = positions(i,2) + (1:asize(2));
ob(Indy,Indx) = ob(Indy,Indx) + probe;
end
*/
#include "mex.h"
#include <math.h>
#include <stdio.h>
#include <omp.h>
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
int i;
/* Check for proper number of arguments. */
if (nrhs != 4)
mexErrMsgTxt("Four input arguments required: get_views_cpu_mex(object,obj_proj,positions,ind_ok)");
else if (nlhs != 0)
mexErrMsgTxt("No output argument has to be specified.");
/* Input must be of type single. */
for (i=0; i < 2; i++) {
if (mxIsSingle(prhs[i]) != 1){
printf(" Input %d is not single\n",i+1);
mexErrMsgIdAndTxt("MexError:ptycho","Inputs must be of correct type.");
}
}
/* Input must be of type int32. */
for (i=2; i<nrhs; i++){
if (mxIsInt32(prhs[i]) != 1){
printf("Input %d is not integer\n",i+1);
mexErrMsgIdAndTxt("MexError:ptycho","Inputs must be of correct type.");
}
}
/* It cannot be one-dimensional */
if(mxGetNumberOfDimensions(prhs[0]) < 2) {
printf("The 1st input argument must have at least two dimensions.");
mexErrMsgIdAndTxt("MexError:ptycho","wrong number of dimensions");
}
/* It cannot be more than 3-dimensional */
if(mxGetNumberOfDimensions(prhs[0]) > 3) {
printf("The 1st input argument must have at most three dimensions.");
mexErrMsgIdAndTxt("MexError:ptycho","wrong number of dimensions");
}
/* Check that arrays are complex */
if(mxIsComplex(prhs[0]) != 1) {
printf("object input argument must be complex-valued.");
mexErrMsgIdAndTxt("MexError:ptycho","Expected complex arrays");
}
if(mxIsComplex(prhs[1]) != 1) {
printf("probe input argument must be complex-valued.");
mexErrMsgIdAndTxt("MexError:ptycho","Expected complex arrays");
}
float *object_r, *object_i, *projection_r,*projection_i;
const int *positions;
positions = (int*)mxGetData(prhs[2]);
object_r = (float*)mxGetData(prhs[0]);
projection_r = (float*)mxGetData(prhs[1]);
/* get pointers to input data */
object_i = (float*)mxGetImagData(prhs[0]);
projection_i = (float*)mxGetImagData(prhs[1]);
/* Get dimension of probe and object */
const mwSize Ndims = mxGetNumberOfDimensions(prhs[1]);
const mwSize * dims = mxGetDimensions(prhs[1]);
const mwSize No_y = mxGetM(prhs[0]);
const mwSize No_x = mxGetN(prhs[0]);
const mwSize Np_y = dims[0];
const mwSize Np_x = dims[1];
const mwSize Npos = mxGetM(prhs[2]);
if((Npos > dims[2])) {
printf("wrong size of update / positions %i", Ndims);
mexErrMsgIdAndTxt("MexError:ptycho","wrong size of update / positions");
}
mwSize id_small, id_large, pos, col, row;
#pragma omp parallel for private(pos,col, row, id_small, id_large)
for (pos=0;pos<Npos;pos++){
for (col=0;col<Np_x;col++) {
for (row=0;row<Np_y;row++) {
id_small = row + col*Np_y + Np_y*Np_x*pos;
id_large = row + positions[pos] + (col+positions[pos+Npos])*No_y;
projection_r[id_small] = object_r[id_large];
projection_i[id_small] = object_i[id_large];
}
}
}
return;
}
@@ -0,0 +1,260 @@
/*
Get complex views from complex object
mexcuda -output +engines/+GPU/+shared/private/get_views_gpu_mex +engines/+GPU/+shared/private/get_views_gpu_mex.cu
*/
#include "mex.h"
#include "gpu/mxGPUArray.h"
#include <math.h>
#include <stdio.h>
typedef const unsigned int cuint;
typedef const uint16_T cuint16;
// unfortunatelly ~10800 is the maximum of const memory
const unsigned int MAX_IND_READ = 10800;
__constant__ uint16_T gC_ind_read[MAX_IND_READ];
__constant__ uint16_T gC_pos_X[MAX_IND_READ];
__constant__ uint16_T gC_pos_Y[MAX_IND_READ];
#define MAX(x,y) (x>y?x:y);
#define MIN(x,y) (x<y?x:y);
#define ABS(x) (x>0?x:-x);
int checkLastError(char * msg)
{
cudaError_t cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
char err[512];
sprintf(err, "getprojection failed \n %s: %s. \n", msg, cudaGetErrorString(cudaStatus));
mexPrintf(err);
return 1;
}
return 0;
}
/*
* Device code
*/
/*********** fast const memory based version ***************/
__global__ void readFromArray_c_fast(float2 * sarray, const float2 * larray,
cuint Np_px,cuint Np_py, cuint Np_pz,cuint Np_ox, cuint Np_oy,
cuint Npos) {
// Location in a 3D matrix
int idx= blockIdx.x * blockDim.x + threadIdx.x;
int idy= blockIdx.y * blockDim.y + threadIdx.y;
int id = blockIdx.z * blockDim.z + threadIdx.z;
if ( idx < Np_px & idy < Np_py & id < Npos)
{
int idz = gC_ind_read[id]-1; // go only through some of the indices
int id_large = gC_pos_X[idz]+idx + Np_ox*(gC_pos_Y[idz]+idy);
int id_small = idx + Np_px*idy + Np_px*Np_py*idz ;
sarray[ id_small ].x = larray[ id_large ].x ;
sarray[ id_small ].y = larray[ id_large ].y ;
}
}
/*********** global memory based version ***************/
__global__ void readFromArray_c(float2 * sarray, const float2 * larray, cuint16* ind_read, cuint16* pos_X, cuint16* posY,
cuint Np_px,cuint Np_py, cuint Np_pz,cuint Np_ox, cuint Np_oy,
cuint Npos) {
// Location in a 3D matrix
int idx= blockIdx.x * blockDim.x + threadIdx.x;
int idy= blockIdx.y * blockDim.y + threadIdx.y;
int id = blockIdx.z * blockDim.z + threadIdx.z;
if ( idx < Np_px & idy < Np_py & id < Npos)
{
int idz = ind_read[id]-1; // go only through some of the indices
int id_large = pos_X[idz]+idx + Np_ox*(posY[idz]+idy);
int id_small = idx + Np_px*idy + Np_px*Np_py*idz ;
sarray[ id_small ].x = larray[ id_large ].x ;
sarray[ id_small ].y = larray[ id_large ].y ;
}
}
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
int i ;
char const * const errId = "parallel:gpu:mexGPUExample:InvalidInput";
char const * const errMsg = "Invalid input to MEX file.";
/* Initialize the MathWorks GPU API. */
//mxInitGPU();
/* Check for proper number of arguments. */
if (nrhs != 5)
mexErrMsgTxt("Five input arguments required");
for (i=0; i < 2; i++) {
if ( !mxIsGPUArray(prhs[i]) && !mxIsCell(prhs[i]) ){
printf("Input %d is not GPU array / cell \n",i+1);
mexErrMsgIdAndTxt("MexError:ptycho","Inputs must be of correct type.");
}
}
// load positions
const mxGPUArray * m_positions_x = mxGPUCreateFromMxArray(prhs[2]);
if ((mxGPUGetClassID(m_positions_x) != mxUINT16_CLASS)) {
mexPrintf("m_positions_x\n");
mexErrMsgIdAndTxt(errId, errMsg);
}
const cuint16 * p_positions_x = (cuint16 *)mxGPUGetDataReadOnly(m_positions_x);
const mxGPUArray * m_positions_y = mxGPUCreateFromMxArray(prhs[3]);
if ((mxGPUGetClassID(m_positions_y) != mxUINT16_CLASS)) {
mexPrintf("m_positions_y\n");
mexErrMsgIdAndTxt(errId, errMsg);
}
const cuint16 * p_positions_y = (cuint16 *)mxGPUGetDataReadOnly(m_positions_y);
/**** copy of the array is the slowest operation *****/
// Now it is writting directly into the input field !!!
//mxGPUArray * m_obj_proj = mxGPUCopyFromMxArray(prhs[0]);
mxGPUArray * m_obj_proj = const_cast<mxGPUArray*>(mxGPUCreateFromMxArray(prhs[0])); //
if ((mxGPUGetClassID(m_obj_proj) != mxSINGLE_CLASS)) {
mexPrintf("m_obj_proj\n");
mexErrMsgIdAndTxt(errId, errMsg);
}
if (mxGPUGetComplexity(m_obj_proj) != mxCOMPLEX) {
mexPrintf("m_obj_proj is not complex \n");
mexErrMsgIdAndTxt(errId, errMsg);
}
float2 * p_obj_proj = (float2 *)mxGPUGetData(m_obj_proj);
if (!mxIsCell(prhs[1]) || !mxIsCell(prhs[4]))
mexErrMsgIdAndTxt("MexError:ptycho","Object and indices has to be in cell/cells !! ");
if (mxGetNumberOfElements(prhs[1]) != mxGetNumberOfElements(prhs[4]))
mexErrMsgIdAndTxt("MexError:ptycho","Number of objects != number of indices ");
/* Get dimension of probe and object */
const unsigned int Ndims = (unsigned int)mxGPUGetNumberOfDimensions(m_obj_proj);
cuint Ncells = mxGetNumberOfElements(prhs[1]);
const unsigned int Np_pp = mxGPUGetNumberOfElements(m_positions_x);
if (Np_pp < MAX_IND_READ) {
cudaMemcpyToSymbol(gC_pos_X, p_positions_x, Np_pp*sizeof(uint16_T), 0, cudaMemcpyHostToDevice);
cudaMemcpyToSymbol(gC_pos_Y, p_positions_y, Np_pp*sizeof(uint16_T), 0, cudaMemcpyHostToDevice);
checkLastError("after cudaMemcpyToSymbol pos");
}
for (int l=0; l<Ncells; l++)
{
// read the cell content
mxArray * mx_object = mxGetCell(prhs[1],l);
mxArray * mx_ind = mxGetCell(prhs[4],l);
int N_ok = mxGetNumberOfElements(mx_ind);
if(N_ok == 0)
continue;
const mxGPUArray * m_object = mxGPUCreateFromMxArray(mx_object);
if ((mxGPUGetClassID(m_object) != mxSINGLE_CLASS)) {
mexPrintf("m_object\n");
mexErrMsgIdAndTxt(errId, errMsg);
}
if (mxGPUGetComplexity(m_object) != mxCOMPLEX) {
mexPrintf("m_object is not complex \n");
mexErrMsgIdAndTxt(errId, errMsg);
}
const float2 * p_object = (float2 *)mxGPUGetDataReadOnly(m_object);
const mxGPUArray * m_ind_ok = mxGPUCreateFromMxArray(mx_ind);
if ((mxGPUGetClassID(m_ind_ok) != mxUINT16_CLASS)) {
mexPrintf("m_ind_ok\n");
mexErrMsgIdAndTxt(errId, errMsg);
}
const cuint16 * p_ind_ok = (cuint16 *)mxGPUGetDataReadOnly(m_ind_ok);
const mwSize * Np_o = mxGPUGetDimensions(m_object);
const mwSize * Np_p = mxGPUGetDimensions(m_obj_proj);
const unsigned int Npos = mxGPUGetNumberOfElements(m_ind_ok);
// mexPrintf("Ndims %i Np_o %i %i Np_p %i %i %i Npos %i \n " ,Ndims,Np_o[0],Np_o[1],Np_p[0],Np_p[1],Np_p[2],Npos);
if (Ndims == 3 && Npos > Np_p[2]) {
printf("wrong size of update / positions %i", Ndims);
mexErrMsgIdAndTxt("MexError:ptycho","wrong size of update / positions");
}
// Choose a reasonably sized number of threads in each dimension for the block.
int const threadsPerBlockEachDim = 32;
// Compute the thread block and grid sizes based on the board dimensions.
int const blocksPerGrid_M = (Np_p[0] + threadsPerBlockEachDim - 1) / threadsPerBlockEachDim;
int const blocksPerGrid_N = (Np_p[1] + threadsPerBlockEachDim - 1) / threadsPerBlockEachDim;
int const blocksPerGrid_O = Npos;
// mexPrintf("Threads %i %i %i \n ", blocksPerGrid_M, blocksPerGrid_N, blocksPerGrid_O);
dim3 const dimBlock(blocksPerGrid_M, blocksPerGrid_N, blocksPerGrid_O);
dim3 const dimThread(threadsPerBlockEachDim, threadsPerBlockEachDim, 1);
checkLastError("after dimThread");
//mexPrintf("Blocks %i %i %i \n ", dimThread.x, dimThread.y, dimThread.z);
if (Np_pp > MAX_IND_READ) {
//mexPrintf( "More than %i positions may be slow \n", MAX_IND_READ);
} else {
cudaMemcpyToSymbol(gC_ind_read, p_ind_ok, Npos*sizeof(uint16_T), 0, cudaMemcpyHostToDevice);
checkLastError("after cudaMemcpyToSymbol pos");
}
checkLastError("after cudaMemcpyToSymbol");
//============= run the kernel ======================
if (Npos < MAX_IND_READ)
readFromArray_c_fast<<<dimBlock, dimThread>>>(p_obj_proj,p_object, Np_p[0],Np_p[1],Np_p[2],Np_o[0],Np_o[1], Npos);
else
readFromArray_c<<<dimBlock, dimThread>>>(p_obj_proj,p_object,p_ind_ok, p_positions_x,p_positions_y,Np_p[0],Np_p[1],Np_p[2],Np_o[0],Np_o[1], Npos);
checkLastError("after kernel");
mxGPUDestroyGPUArray(m_object);
mxGPUDestroyGPUArray(m_ind_ok);
}
cudaThreadSynchronize();
// plhs[0] = mxGPUCreateMxArrayOnGPU(m_obj_proj);
mxGPUDestroyGPUArray(m_obj_proj);
mxGPUDestroyGPUArray(m_positions_x);
mxGPUDestroyGPUArray(m_positions_y);
return;
}
@@ -0,0 +1,193 @@
/*
*
*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.
*
*
Compilation from Matlab:
maybe a tiny bit faster code is generated by
mex -O COPTIMFLAGS='-O2' LDOPTIMFLAGS='-O2' set_views_cpu_mex.c
Usage from Matlab:
set_views_cpu_mex(probe,object,positions, Npos);
This code in matlab:
asize = size(probe);
for i=1:Npos
Indy = positions(i,1) + (1:asize(1));
Indx = positions(i,2) + (1:asize(2));
ob(Indy,Indx) = ob(Indy,Indx) + probe;
end
*/
#include "mex.h"
#include <math.h>
#include <stdio.h>
#include <omp.h>
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
int i;
/* Check for proper number of arguments. */
if (nrhs != 4)
mexErrMsgTxt("Four input arguments required: set_views_cpu_mex(probe,object,positions,Npos)");
else if (nlhs != 0)
mexErrMsgTxt("No output argument has to be specified.");
/* Input must be of type single. */
for (i=0; i < 2; i++) {
if (mxIsSingle(prhs[i]) != 1){
printf("Input %d is not single\n",i+1);
mexErrMsgIdAndTxt("MexError:ptycho","Inputs must be of correct type.");
}
}
/* Input must be of type int32. */
for (i=2; i<nrhs; i++){
if (mxIsInt32(prhs[i]) != 1){
printf("Input %d is not integer\n",i+1);
mexErrMsgIdAndTxt("MexError:ptycho","Inputs must be of correct type.");
}
}
/* It cannot be one-dimensional */
if(mxGetNumberOfDimensions(prhs[0]) < 2) {
printf("The 1st input argument must have at least two dimensions.");
mexErrMsgIdAndTxt("MexError:ptycho","wrong number of dimensions");
}
/* It cannot be more than 3-dimensional */
if(mxGetNumberOfDimensions(prhs[0]) > 3) {
printf("The 1st input argument must have at most three dimensions.");
mexErrMsgIdAndTxt("MexError:ptycho","wrong number of dimensions");
}
// /* Check that arrays are complex */
// if(mxIsComplex(prhs[0]) != 1) {
// printf("object input argument must be complex-valued.");
// mexErrMsgIdAndTxt("MexError:ptycho","Expected complex arrays");
// }
// if(mxIsComplex(prhs[1]) != 1) {
// printf("probe input argument must be complex-valued.");
// mexErrMsgIdAndTxt("MexError:ptycho","Expected complex arrays");
// }
float *object_r, *object_i, *probe_r,*probe_i;
const int *positions, *ind_ok;
bool cprobe, cobject;
cobject = mxIsComplex(prhs[0]);
cprobe = mxIsComplex(prhs[1]);
if( cobject != cobject)
{
printf("probe/object input argument must be complex/real-valued.");
mexErrMsgIdAndTxt("MexError:ptycho","Expected both complex / real arrays");
}
ind_ok = (int*)mxGetData(prhs[3]);
positions = (int*)mxGetData(prhs[2]);
object_r = (float*)mxGetData(prhs[0]);
probe_r = (float*)mxGetData(prhs[1]);
if(cprobe)
{
/* get pointers to input data */
object_i = (float*)mxGetImagData(prhs[0]);
probe_i = (float*)mxGetImagData(prhs[1]);
}
/* Get dimension of probe and object */
const mwSize Ndims = mxGetNumberOfDimensions(prhs[1]);
const mwSize * dims = mxGetDimensions(prhs[1]);
const mwSize No_y = mxGetM(prhs[0]);
const mwSize No_x = mxGetN(prhs[0]);
const mwSize Np_y = dims[0];
const mwSize Np_x = dims[1];
const mwSize Npos = mxGetM(prhs[2]);
if((mxGetM(prhs[2]) != dims[2]) && (Ndims == 3)) {
printf("wrong size of update / positions %i", Ndims);
mexErrMsgIdAndTxt("MexError:ptycho","wrong size of update / positions");
}
mwSize id_small, id_large, pos, col, row, o, p;
bool flat_probe = Ndims == 2;
#pragma omp parallel for private(p,pos, col, row, id_small, id_large)
for (p=0;p<Npos;p++){
pos = ind_ok[p]-1;
for (col=0;col<Np_x;col++) {
for (row=0;row<Np_y;row++) {
if(flat_probe)
id_small = row + col*Np_y;
else
id_small = row + col*Np_y + Np_y*Np_x*pos;
id_large = row + positions[pos] + (col+positions[pos+Npos])*No_y;
#pragma omp atomic
object_r[id_large] += probe_r[id_small];
if(cprobe)
#pragma omp atomic
object_i[id_large] += probe_i[id_small];
}
}
}
return;
}
@@ -0,0 +1,182 @@
/*
*
*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.
*
*
Compilation from Matlab:
maybe a tiny bit faster code is generated by
mex -O COPTIMFLAGS='-O2' LDOPTIMFLAGS='-O2' set_views_cpu_mex_rc.cpp
Usage from Matlab:
set_views_cpu_mex(probe,object,positions, Npos);
This code in matlab:
asize = size(probe);
for i=1:Npos
Indy = positions(i,1) + (1:asize(1));
Indx = positions(i,2) + (1:asize(2));
ob(Indy,Indx) = ob(Indy,Indx) + probe;
end
*/
#include "mex.h"
#include <math.h>
#include <stdio.h>
#include <omp.h>
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
int i;
/* Check for proper number of arguments. */
if (nrhs != 6)
mexErrMsgTxt("Six input arguments required: set_views_cpu_mex_rc(object,obj_upd, illum, illum_upd, positions,ind_ok)");
else if (nlhs != 0)
mexErrMsgTxt("No output argument has to be specified.");
/* Input must be of type single. */
for (i=0; i < 4; i++) {
if (mxIsSingle(prhs[i]) != 1){
printf("Input %d is not single\n",i+1);
mexErrMsgIdAndTxt("MexError:ptycho","Inputs must be of correct type.");
}
}
/* Input must be of type int32. */
for (i=4; i<nrhs; i++){
if (mxIsInt32(prhs[i]) != 1){
printf("Input %d is not integer\n",i+1);
mexErrMsgIdAndTxt("MexError:ptycho","Inputs must be of correct type.");
}
}
/* Check that arrays are complex */
if(mxIsComplex(prhs[0]) != 1) {
printf("first input argument must be complex-valued.");
mexErrMsgIdAndTxt("MexError:ptycho","Expected complex arrays");
}
if(mxIsComplex(prhs[1]) == 1) {
printf("second input argument must be real-valued.");
mexErrMsgIdAndTxt("MexError:ptycho","Expected real arrays");
}
if(mxIsComplex(prhs[2]) != 1) {
printf("third input argument must be complex-valued.");
mexErrMsgIdAndTxt("MexError:ptycho","Expected complex arrays");
}
if(mxIsComplex(prhs[3]) == 1) {
printf("fourth input argument must be real-valued.");
mexErrMsgIdAndTxt("MexError:ptycho","Expected real arrays");
}
float *object_r, *object_i, *probe_r,*probe_i, *illum_r, *illum_upd;
const int *positions, *ind_ok;
bool cprobe, cobject;
positions = (int*)mxGetData(prhs[4]);
ind_ok = (int*)mxGetData(prhs[5]);
object_r = (float*)mxGetData(prhs[0]);
object_i = (float*)mxGetImagData(prhs[0]);
illum_r = (float*)mxGetData(prhs[1]);
probe_r = (float*)mxGetData(prhs[2]);
probe_i = (float*)mxGetImagData(prhs[2]);
illum_upd = (float*)mxGetData(prhs[3]);
/* Get dimension of probe and object */
const mwSize Ndims = mxGetNumberOfDimensions(prhs[2]);
const mwSize * dims = mxGetDimensions(prhs[2]);
const mwSize No_y = mxGetM(prhs[0]);
const mwSize No_x = mxGetN(prhs[0]);
const mwSize Np_y = dims[0];
const mwSize Np_x = dims[1];
const mwSize Npos = mxGetNumberOfElements(prhs[5]);
if(mxGetM(prhs[4]) != dims[2]) {
printf("wrong size of update / positions %i", Ndims);
mexErrMsgIdAndTxt("MexError:ptycho","wrong size of update / positions");
}
// mexPrintf("O %i %i P %i %i N %i \n ", No_y, No_x, Np_y, Np_x, Npos);
mwSize id_small, id_small_3D, id_large, pos, col, row, p;
#pragma omp parallel for private(p,pos, col, row, id_small,id_small_3D, id_large)
for (p=0;p<Npos;p++){
pos = ind_ok[p]-1;
for (col=0;col<Np_x;col++) {
for (row=0;row<Np_y;row++) {
id_small = row + col*Np_y;
id_small_3D = id_small + Np_y*Np_x*pos;
id_large = row + positions[pos] + (col+positions[pos+Npos])*No_y;
#pragma omp atomic
object_r[id_large] += probe_r[id_small_3D];
#pragma omp atomic
object_i[id_large] += probe_i[id_small_3D];
#pragma omp atomic
illum_r[id_large] += illum_upd[id_small];
}
}
}
return;
}
@@ -0,0 +1,303 @@
/*
Set complex views to complex object
mexcuda -output +engines/+GPU/+shared/private/set_views_gpu_mex +engines/+GPU/+shared/private/set_views_gpu_mex.cu
*/
#include "mex.h"
#include "gpu/mxGPUArray.h"
#include <math.h>
#include <stdio.h>
typedef const unsigned int cuint;
typedef const uint16_T cuint16;
// unfortunatelly ~10800 is the maximum of const memory
const unsigned int MAX_IND_READ = 10800;
static const unsigned MAX_IND_READ_DEV = MAX_IND_READ;
__constant__ uint16_T gC_ind_read[MAX_IND_READ_DEV];
__constant__ uint16_T gC_pos_X[MAX_IND_READ_DEV];
__constant__ uint16_T gC_pos_Y[MAX_IND_READ_DEV];
int checkLastError(char * msg)
{
cudaError_t cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
char err[512];
sprintf(err, "setprojection failed \n %s: %s. \n", msg, cudaGetErrorString(cudaStatus));
mexPrintf(err);
return 1;
}
return 0;
}
/*
* Device code
*/
/*********** reduction of object projection array to single object ***************/
template <bool useGlobal>
__global__ void addToArray_r( float const * sarray, float * larray, cuint16* ind_read, cuint16* pos_X, cuint16* posY,
cuint Np_px,cuint Np_py, cuint Np_pz,cuint Np_ox, cuint Np_oy,
cuint Npos, const bool isFlat) {
// Location in a 3D matrix
int idx= blockIdx.x * blockDim.x + threadIdx.x;
int idy= blockIdx.y * blockDim.y + threadIdx.y;
if ( idx < Np_px & idy < Np_py ) {
int idz, id_large;
float sarray_val;
for(int id = 0; id < Npos; id++)
{
if (useGlobal) {
// fast const memory based version
idz = gC_ind_read[id]-1; // go only through some of the indices
id_large = gC_pos_X[idz]+idx + Np_ox*(gC_pos_Y[idz]+idy);
} else {
// slower global memory based version
idz = ind_read[id]-1; // go only through some of the indices
id_large = pos_X[idz]+idx + Np_ox*(posY[idz]+idy);
}
int id_small = idx + Np_px*idy ;
if (!isFlat)
id_small = id_small + Np_px*Np_py*idz ;
// prevent extra memory load
sarray_val = (isFlat && (idz > 0)) ? sarray_val: sarray[ id_small ];
//larray[id_large] += sarray_val;
//__syncthreads();
// slowest step, without atomicAdd it misses some values
atomicAdd(&larray[id_large] ,sarray_val);
}
}
}
template <bool useGlobal>
__global__ void addToArray_c( float2 const * sarray, float2 * larray, cuint16* ind_read, cuint16* pos_X, cuint16* posY,
cuint Np_px,cuint Np_py, cuint Np_pz,cuint Np_ox, cuint Np_oy,
cuint Npos, const bool isFlat) {
// Location in a 3D matrix
int idx= blockIdx.x * blockDim.x + threadIdx.x;
int idy= blockIdx.y * blockDim.y + threadIdx.y;
if ( idx < Np_px & idy < Np_py ) {
int idz, id_large;
float2 sarray_val;
for(int id = 0; id < Npos; id++)
{
if (useGlobal) {
// fast const memory based version
idz = gC_ind_read[id]-1; // go only through some of the indices
id_large = gC_pos_X[idz]+idx + Np_ox*(gC_pos_Y[idz]+idy);
} else {
// slower global memory based version
idz = ind_read[id]-1; // go only through some of the indices
id_large = pos_X[idz]+idx + Np_ox*(posY[idz]+idy);
}
int id_small = idx + Np_px*idy ;
if (!isFlat)
id_small = id_small + Np_px*Np_py*idz ;
// prevent extra memory load
sarray_val = (isFlat && (idz > 0)) ? sarray_val: sarray[ id_small ];
//larray[id_large].x += sarray_val.x;
//larray[id_large].y += sarray_val.y;
//__syncthreads();
// slowest step, without atomicAdd it misses some values
atomicAdd(&larray[id_large].x ,sarray_val.x);
atomicAdd(&larray[id_large].y ,sarray_val.y);
}
}
}
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
int i ;
char const * const errId = "parallel:gpu:mexGPUExample:InvalidInput";
char const * const errMsg = "Invalid input to MEX file.";
// Check for proper number of arguments.
if (nrhs != 5)
mexErrMsgTxt("Five input arguments required");
// Input must be of type single.
for (i=0; i < 2; i++) {
if ( !mxIsGPUArray(prhs[i]) && !mxIsCell(prhs[i]) ){
printf("Input %d is not cell array\n",i+1);
mexErrMsgIdAndTxt("MexError:ptycho","Inputs must be of correct type.");
}
}
// Input must be of type int16.
for (i=2; i<4; i++){
if (mxIsUint16(prhs[i]) != 1){
printf("Input %d is not integer\n",i+1);
mexErrMsgIdAndTxt("MexError:ptycho","Inputs must be of correct type uint16.");
}
}
// It cannot be one-dimensional
if(mxGetNumberOfDimensions(prhs[0]) < 2) {
printf("The 1st input argument must have at least two dimensions.");
mexErrMsgIdAndTxt("MexError:ptycho","wrong number of dimensions");
}
// It cannot be more than 3-dimensional
if(mxGetNumberOfDimensions(prhs[0]) > 3) {
printf("The 1st input argument must have at most three dimensions.");
mexErrMsgIdAndTxt("MexError:ptycho","wrong number of dimensions");
}
// Check that arrays are complex
const mxGPUArray * m_obj_proj = mxGPUCreateFromMxArray(prhs[0]);
if ((mxGPUGetClassID(m_obj_proj) != mxSINGLE_CLASS)) {
mexPrintf("m_obj_proj\n");
mexErrMsgIdAndTxt(errId, errMsg);
}
const mxGPUArray * m_positions_x = mxGPUCreateFromMxArray(prhs[2]);
if ((mxGPUGetClassID(m_positions_x) != mxUINT16_CLASS)) {
mexPrintf("m_positions_x\n");
mexErrMsgIdAndTxt(errId, errMsg);
}
const uint16_T * p_positions_x = (uint16_T *)mxGPUGetDataReadOnly(m_positions_x);
const mxGPUArray * m_positions_y = mxGPUCreateFromMxArray(prhs[3]);
if ((mxGPUGetClassID(m_positions_y) != mxUINT16_CLASS)) {
mexPrintf("m_positions_y\n");
mexErrMsgIdAndTxt(errId, errMsg);
}
const uint16_T * p_positions_y = (uint16_T *)mxGPUGetDataReadOnly(m_positions_y);
if (!mxIsCell(prhs[1]) || !mxIsCell(prhs[4]))
mexErrMsgIdAndTxt("MexError:ptycho","Object and indices has to be in cell/cells !! ");
if (mxGetNumberOfElements(prhs[1]) != mxGetNumberOfElements(prhs[4]))
mexErrMsgIdAndTxt("MexError:ptycho","Number of objects != number of indices ");
cuint Ncells = mxGetNumberOfElements(prhs[1]);
const unsigned int Np_pp = mxGPUGetNumberOfElements(m_positions_y);
if (Np_pp < MAX_IND_READ) {
cudaMemcpyToSymbol(gC_pos_X, p_positions_x, Np_pp*sizeof(uint16_T), 0, cudaMemcpyHostToDevice);
cudaMemcpyToSymbol(gC_pos_Y, p_positions_y, Np_pp*sizeof(uint16_T), 0, cudaMemcpyHostToDevice);
checkLastError("after cudaMemcpyToSymbol pos");
}
for (int l=0; l<Ncells; l++)
{
// read the cell content
mxArray * mx_object = mxGetCell(prhs[1],l);
mxArray * mx_ind = mxGetCell(prhs[4],l);
int N_ok = mxGetNumberOfElements(mx_ind);
if(N_ok == 0)
continue;
mxGPUArray * m_object = const_cast<mxGPUArray*>(mxGPUCreateFromMxArray(mx_object)); // mxGPUCopyFromMxArray(prhs[1]);
if ((mxGPUGetClassID(m_object) != mxSINGLE_CLASS)) {
mexPrintf("m_object\n");
mexErrMsgIdAndTxt(errId, errMsg);
}
if (mxGPUGetComplexity(m_object) != mxGPUGetComplexity(m_obj_proj)) {
mexPrintf("m_object and m_obj_proj complexity has to be the same \n");
mexErrMsgIdAndTxt(errId, errMsg);
}
const mxGPUArray * m_ind_ok = mxGPUCreateFromMxArray(mx_ind);
if ((mxGPUGetClassID(m_ind_ok) != mxUINT16_CLASS)) {
mexPrintf("m_ind_ok\n");
mexErrMsgIdAndTxt(errId, errMsg);
}
const uint16_T * p_ind_ok = (uint16_T *)mxGPUGetDataReadOnly(m_ind_ok);
// Get dimension of probe and object
const unsigned int Ndims = (unsigned int)mxGPUGetNumberOfDimensions(m_obj_proj);
const mwSize * Np_o = mxGPUGetDimensions(m_object);
const mwSize * Np_p = mxGPUGetDimensions(m_obj_proj);
const unsigned int Npos = mxGPUGetNumberOfElements(m_ind_ok);
//mexPrintf("Ndims %i Np_o %i %i Np_p %i %i %i Npos %i \n " ,Ndims,Np_o[0],Np_o[1],Np_p[0],Np_p[1],Np_p[3],Npos);
if (Ndims == 3 && Npos > Np_p[2]) {
printf("wrong size of update / positions %i", Ndims);
mexErrMsgIdAndTxt("MexError:ptycho","wrong size of update / positions");
}
if (Npos > MAX_IND_READ) {
//mexPrintf( "More than %i positions may be slow \n", MAX_IND_READ);
} else {
cudaMemcpyToSymbol(gC_ind_read, p_ind_ok, Npos*sizeof(uint16_T), 0, cudaMemcpyHostToDevice);
checkLastError("after cudaMemcpyToSymbol pos");
}
// Choose a reasonably sized number of threads in each dimension for the block.
int const threadsPerBlockEachDim = 32;
// Compute the thread block and grid sizes based on the board dimensions.
int const blocksPerGrid_M = (Np_p[0] + threadsPerBlockEachDim - 1) / threadsPerBlockEachDim;
int const blocksPerGrid_N = (Np_p[1] + threadsPerBlockEachDim - 1) / threadsPerBlockEachDim;
int const blocksPerGrid_O = 1;
dim3 const dimBlock(blocksPerGrid_M, blocksPerGrid_N, blocksPerGrid_O);
dim3 const dimThread(threadsPerBlockEachDim, threadsPerBlockEachDim, 1);
checkLastError("after dimThread");
checkLastError("after cudaMemcpyToSymbol");
const bool isFlat = (Ndims == 2);
const bool isComplex = mxGPUGetComplexity(m_obj_proj) == mxCOMPLEX;
// ================== call the right kernel ===================
if (isComplex) {
const float2 * p_obj_proj = (float2 *)mxGPUGetDataReadOnly(m_obj_proj);
float2 * p_object = (float2 *)mxGPUGetData(m_object);
if (Np_pp < MAX_IND_READ)
addToArray_c<true><<<dimBlock, dimThread>>>(p_obj_proj,p_object, p_ind_ok, p_positions_x,p_positions_y ,Np_p[0],Np_p[1],Np_p[2],Np_o[0],Np_o[1], Npos, isFlat);
else
addToArray_c<false><<<dimBlock, dimThread>>>(p_obj_proj,p_object, p_ind_ok, p_positions_x,p_positions_y ,Np_p[0],Np_p[1],Np_p[2],Np_o[0],Np_o[1], Npos, isFlat);
} else {
const float * p_obj_proj = (float *)mxGPUGetDataReadOnly(m_obj_proj);
float * p_object = (float *)mxGPUGetData(m_object);
if (Np_pp < MAX_IND_READ)
addToArray_r<true><<<dimBlock, dimThread>>>(p_obj_proj,p_object, p_ind_ok, p_positions_x,p_positions_y ,Np_p[0],Np_p[1],Np_p[2],Np_o[0],Np_o[1], Npos, isFlat);
else
addToArray_r<false><<<dimBlock, dimThread>>>(p_obj_proj,p_object, p_ind_ok, p_positions_x,p_positions_y ,Np_p[0],Np_p[1],Np_p[2],Np_o[0],Np_o[1], Npos, isFlat);
}
checkLastError("after kernel");
mxGPUDestroyGPUArray(m_object);
mxGPUDestroyGPUArray(m_ind_ok);
}
cudaThreadSynchronize();
// plhs[0] = mxGPUCreateMxArrayOnGPU(m_object);
mxGPUDestroyGPUArray(m_obj_proj);
mxGPUDestroyGPUArray(m_positions_x);
mxGPUDestroyGPUArray(m_positions_y);
return;
}
@@ -0,0 +1,73 @@
function [I_phase_grid_rm, f] = remove_grid_artifact(I_phase, dx, step_size, window_size, direction, showFigure)
%REMOVE_GRID_ARTIFACT RemoveS grid artifacts in ptychographic reconstruction
% Inputs:
% I_phase - phase of object
% dx - pixel size
% step_size: (2,1) arrry - scan step size in vertical and horizontal directions
% window_size: (2,1) array - size of Fourier window in vertical and
% horizontal directions. Unit: pixels
% direction: 'x','y' or 'xy' - direction along which the Fourier window is applied
% showFigure - display a figure to show the object and its Fourier transform
% Outputs:
% I_phase_grid_rm - phase image after grid artifacts removal
% f - Fourier transform of I_phase_grid_rm
%
% Written by Yi Jiang. Based on the idead in https://doi.org/10.1063/1.4993744
[Ny,Nx] = size(I_phase);
dk_x = 1/dx/Nx;
dk_y = 1/dx/Ny;
cen_x = floor(Nx/2)+1;
cen_y = floor(Ny/2)+1;
k_max = 1/dx;
f0 = fftshift(fft2(ifftshift(I_phase)));
f = f0;
dk_s_x = 1/step_size(1);
dk_s_y = 1/step_size(2);
switch direction
case 'xy'
x_range = ceil(-k_max/2/dk_s_x):floor(k_max/2/dk_s_x);
y_range = ceil(-k_max/2/dk_s_y):floor(k_max/2/dk_s_y);
case 'x'
x_range = ceil(-k_max/2/dk_s_x):floor(k_max/2/dk_s_x);
y_range = 0;
case 'y'
x_range = 0;
y_range = ceil(-k_max/2/dk_s_y):floor(k_max/2/dk_s_y);
end
for i=1:length(x_range)
for j=1:length(y_range)
if ~(x_range(i)==0 && y_range(j)==0)
window_x_lb = max(round(x_range(i)*dk_s_x/dk_x) + cen_x - window_size(1), 1);
window_x_ub = min(round(x_range(i)*dk_s_x/dk_x) + cen_x + window_size(1), Nx);
window_y_lb = max(round(y_range(j)*dk_s_y/dk_y) + cen_y - window_size(2), 1);
window_y_ub = min(round(y_range(j)*dk_s_y/dk_y) + cen_y + window_size(2), Ny);
f(window_y_lb:window_y_ub,window_x_lb:window_x_ub) = 0;
end
end
end
I_phase_grid_rm = real(fftshift(ifft2(ifftshift(f))));
if showFigure
figure
subplot(2,2,1)
imagesc(I_phase); axis image;
subplot(2,2,2)
imagesc(abs(f0).^0.2); axis image;
subplot(2,2,3)
imagesc(I_phase_grid_rm); axis image;
subplot(2,2,4)
imagesc(abs(f).^0.2); axis image;
colormap jet
end
end
+196
View File
@@ -0,0 +1,196 @@
% SET_VIEWS Reduce stack of projections into one shared object
%
% object = set_views(object, object_update, layer,object_id, indices, cache, scan_ids, skip_ind)
%
% ** obj_update [Nx_o, Ny_o] array or cells containing object
% ** obj_proj [Nx_p, Ny_p, N] preallocated array for the views
% ** layer_ids id of the solved layer for multilayer ptycho
% ** object_id id of the object, ie scan or incoherent mode
% ** indices processed positions
% ** cache structure with precalculated values to avoid unnecessary overhead
% ** scan_ids determines to which scan correponds each of the position
% ** skip_ind list of indices to be skipped
%
% returns:
% ++ object reduced sum of the views
%
% 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 object = set_views(object, object_update, layer,object_id, indices, cache, scan_ids, skip_ind)
import engines.GPU.GPU_wrapper.*
import engines.GPU.shared.*
import utils.verbose
global use_gpu
if nargin < 8
skip_ind = [];
end
if nargin > 6
%% !!! call recursivelly -> wrapper for multiscan version !!!!
% get unique IDs of the scans
if isempty(scan_ids)
unq_scans = [];
elseif all(scan_ids == scan_ids(1))
unq_scans = scan_ids(1);
else
unq_scans = unique(scan_ids);
end
if length(unq_scans)> 1
if ~isempty(use_gpu) && use_gpu && isa(object{1}, 'gpuArray') && isa(object_update, 'gpuArray')
if size(object,1) == 1
% shared object or single object
ind_ok{1} = uint16(1:length(indices));
else
for kk = 1:size(object,1)
%disp(kk)
ind_ok{kk} = uint16(find(scan_ids == kk));
%disp(ind_ok{kk})
end
end
% feed data directly to the GPU mex without splitting
object(:,layer) = set_views_gpu(object(:,layer),object_update,cache.oROI_s{object_id(1)},indices, ind_ok);
else
% ONLY if GPU not available use this "wrapper" around single
% set_projection function
for kk = unq_scans
ind = scan_ids == kk;
skip_ind = indices(~ind); % avoid going through these indices
object{kk,layer} = set_views(object{kk,layer},object_update, object_id, indices, cache,[],skip_ind);
end
end
return
end
end
is_cell = iscell(object);
if is_cell
object_0 = object;
object = object_0{min(end,object_id), layer};
end
if ~isfield(cache,'skip_ind'); cache.skip_ind = []; end
if ~isempty(cache.skip_ind) && ~isempty(skip_ind)
ind_ok = uint16(find(~ismember(indices, [cache.skip_ind,skip_ind]))); % skip wrong patterns
else
ind_ok = uint16(1:length(indices)); %diffraction pattern indicies
end
if isa(object, 'gpuArray')
%% USE CUDA MEX FOR GPU
object = set_views_gpu(object,object_update,cache.oROI_s{min(object_id,end)},indices,ind_ok);
else
%% USE CPU
positions = int32([cache.oROI_s{min(end,object_id)}{1}(indices,1), cache.oROI_s{min(end,object_id)}{2}(indices,1)]);
object = utils.add_to_3D_projection(object_update,object, positions, ind_ok,true);
end
if is_cell
object_0{min(object_id,end), layer}= object;
object = object_0;
end
end
function object = set_views_gpu(object,proj,oROI,ind, ind_ok)
% Description: Set projections to the object function using GPU
% mexcuda -v -output +engines/+GPU/set_views_gpu_mex +engines/+GPU/set_views_gpu_mex.cu
import engines.GPU.GPU_wrapper.*
import utils.verbose
x = uint16(oROI{1}(ind,1));
y = uint16(oROI{2}(ind,1));
return_cell = iscell(object);
if ~iscell(object); object = {Garray(object)}; end
if ~iscell(ind_ok); ind_ok = {Garray(uint16(ind_ok))}; end
for i = 1:length(object)
assert(~isempty(object{i}), 'Input object cannot be empty')
end
for i = 1:length(ind_ok)
assert(~isempty(ind_ok{i}), 'Vector ind_ok cannot be empty')
end
try
set_views_gpu_mex( proj, object,x,y,ind_ok);
catch err
verbose(0, 'Recompilation of MEX functions ... ')
if any(strcmp(err.identifier, { 'MATLAB:UndefinedFunction','MATLAB:mex:ErrInvalidMEXFile'}))
path = replace(mfilename('fullpath'), mfilename, '');
mexcuda('-output', [path,'private/set_views_gpu_mex'], [path, 'private/set_views_gpu_mex.cu'])
set_views_gpu_mex( proj, object,x,y,ind_ok);
else
rethrow(err)
end
end
if ~return_cell
object = object{1};
end
end
+189
View File
@@ -0,0 +1,189 @@
% SET_VIEWS_RC Reduce stack of projections into one shared object
% ! update complex and real object at once
%
% [obj_update,obj_illum] = set_views_rc(obj_update,obj_illum, psi,aprobe2,layer,object_id, indices, cache, scan_ids, skip_ind, object_modes)
%
% ** obj_update [Nx_o, Ny_o] array or cells containing object
% ** obj_illum [Nx_o, Ny_o] array or cells containing illumination sum
% ** obj_proj [Nx_p, Ny_p, N] preallocated array for the views
% ** psi complex valued exit wave (psi ~ P*O)
% ** aprobe2 illumination intensity patch
% ** layer_ids id of the solved layer for multilayer ptycho
% ** object_id id of the object, ie scan or incoherent mode
% ** indices processed positions
% ** cache structure with precalculated values to avoid unnecessary overhead
% ** scan_ids determines to which scan correponds each of the position
% ** skip_ind list of indices to be skipped
% ** object_modes number of incoherent object modes
%
% returns:
% ++ object reduced sum of the views
%
%
% 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 [obj_update,obj_illum] = set_views_rc(obj_update,obj_illum, psi,aprobe2,layer,object_id, indices, cache, scan_ids, skip_ind)
import engines.GPU.GPU_wrapper.*
import engines.GPU.shared.*
import utils.verbose
global use_gpu
if nargin < 10
skip_ind = [];
end
if nargin > 8 && ~isempty(scan_ids)
%% !!! call recursivelly -> wrapper for multiscan version !!!!
% get unique IDs of the scans
if isempty(scan_ids)
unq_scans = [];
elseif all(scan_ids == scan_ids(1))
unq_scans = scan_ids(1);
else
unq_scans = unique(scan_ids);
end
if length(unq_scans)> 1 || (iscell(obj_update) && length(obj_update) > 1)
if ~isempty(use_gpu) && use_gpu && isa(obj_update{1}, 'gpuArray') && isa(psi, 'gpuArray')
if size(obj_update,1) == 1
% shared object or single object
ind_ok{1} = uint16(1:length(indices));
else
for kk = 1:size(obj_update,1)
ind_ok{kk} = uint16(find(scan_ids == kk));
end
end
% feed data directly to the GPU mex without splitting
[obj_update(:,layer),obj_illum(:,layer)] = set_views_gpu_rc(obj_update(:,layer),obj_illum(:,layer),psi, aprobe2,cache.oROI_s{min(object_id,end)},indices, ind_ok );
else
% if GPU not available use this "wrapper" around single
% set_projection function
for kk = unq_scans
ind = scan_ids == kk;
skip_ind = indices(~ind); % avoid going through these indices
[obj_update{kk,layer},obj_illum{kk,layer}] = set_views_rc(obj_update{kk,layer},obj_illum{kk,layer},psi,aprobe2, layer, object_id, indices, cache,[],skip_ind);
end
end
return
end
end
is_cell = iscell(obj_update);
if is_cell
obj_update_0 = obj_update;
obj_illum_0 = obj_illum;
obj_update = obj_update{object_id, min(end,layer)};
obj_illum = obj_illum{object_id, min(end,layer)};
end
if ~isempty(cache.skip_ind) && ~isempty(skip_ind)
ind_ok = uint16(find(~ismember(indices, [cache.skip_ind,skip_ind]))); % skip wrong patterns
else
ind_ok = uint16(1:length(indices));
end
if ~isempty(use_gpu) && use_gpu && isa(obj_update, 'gpuArray') && isa(psi, 'gpuArray')
%% USE CUDA MEX FOR GPU
[obj_update,obj_illum] = set_views_gpu_rc(obj_update,obj_illum, psi,aprobe2,cache.oROI_s{min(object_id,end)},indices, ind_ok);
else
%% USE CPU
obj_illum = set_views(obj_illum , aprobe2, layer, object_id,indices, cache,scan_ids, skip_ind);
obj_update = set_views(complex(obj_update),complex(psi), layer, object_id, indices, cache,scan_ids, skip_ind);
end
if is_cell
obj_update_0{object_id,min(end,layer)} = obj_update;
obj_illum_0{object_id,min(end,layer)} = obj_illum;
obj_update = obj_update_0;
obj_illum = obj_illum_0;
end
end
function [object_c,object_r] = set_views_gpu_rc(object_c,object_r,proj_c, proj_r,oROI,ind, ind_ok )
% Description: update complex and real object at once
import engines.GPU.GPU_wrapper.*
x = uint16(oROI{1}(ind,1));
y = uint16(oROI{2}(ind,1));
return_cell = iscell(object_c);
if ~iscell(object_c); object_c = {Garray(object_c)}; end
if ~iscell(object_r); object_r = {Garray(object_r)}; end
if ~iscell(ind_ok); ind_ok = {Garray(uint16(ind_ok))}; end
proj_c = complex(proj_c);
set_views_gpu_mex( proj_c, object_c,x,y, ind_ok );
set_views_gpu_mex( proj_r, object_r,x,y, ind_ok );
if ~return_cell
object_c = object_c{1};
object_r = object_r{1};
end
end
+109
View File
@@ -0,0 +1,109 @@
% APPLY_SUBPX_SHIFT subpixel probe shifting , equivalet just a bit faster than imshift_fft
%
% img = apply_subpx_shift(img, shift)
%
% ** img stack images
% ** shift (N,2) array of shifts
% returns
% ++ img shifted imaeg stack
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for maximum likelihood:
% P. Thibault and M. Guizar-Sicairos, Maximum-likelihood refinement for coherent diffractive imaging, New J. Phys. 14, 063004 (2012).
% (doi: 10.1088/1367-2630/14/6/063004),
% for mixed coherent modes:
% P. Thibault and A. Menzel, Reconstructing state mixtures from diffraction measurements, Nature 494, 6871 (2013). (doi: 10.1038/nature11806),
% and/or for multislice:
% E. H. R. Tsai, I. Usov, A. Diaz, A. Menzel, and M. Guizar-Sicairos, X-ray ptychography with extended depth of field, Opt. Express 24, 2908929108 (2016).
% (doi: 10.1364/OE.24.029089).
% 6. Except for the above-mentioned acknowledgment, LICENSEE shall not use the PROGRAM title or the names or logos of LICENSOR, nor any adaptation thereof, nor the
% names of any of its employees or laboratories, in any advertising, promotional or sales material without prior written consent obtained from LICENSOR in each case.
% 7. Ownership of all rights, including copyright in the PROGRAM and in any material associated therewith, shall at all times remain with LICENSOR, and LICENSEE
% agrees to preserve same. LICENSEE agrees not to use any portion of the PROGRAM or of any IMPROVEMENTS in any machine-readable form outside the PROGRAM, nor to
% make any copies except for its internal use, without prior written consent of LICENSOR. LICENSEE agrees to place the following copyright notice on any such copies:
% © All rights reserved. PAUL SCHERRER INSTITUT, Switzerland, Laboratory for Macromolecules and Bioimaging, 2017.
% 8. The LICENSE shall not be construed to confer any rights upon LICENSEE by implication or otherwise except as specifically set forth herein.
% 9. DISCLAIMER: LICENSEE shall be aware that Phase Focus Limited of Sheffield, UK has an international portfolio of patents and pending applications which relate
% to ptychography and that the PROGRAM may be capable of being used in circumstances which may fall within the claims of one or more of the Phase Focus patents,
% in particular of patent with international application number PCT/GB2005/001464. The LICENSOR explicitly declares not to indemnify the users of the software
% in case Phase Focus or any other third party will open a legal action against the LICENSEE due to the use of the program.
% 10. This Agreement shall be governed by the material laws of Switzerland and any dispute arising out of this Agreement or use of the PROGRAM shall be brought before
% the courts of Zürich, Switzerland.
function img = apply_subpx_shift(img, shift)
% subpixel probe shifting
import engines.GPU.shared.*
import engines.GPU.GPU_wrapper.*
persistent xgrid ygrid
if nargin == 0
xgrid = [];
return
end
if all(shift(:) == 0); return ; end
global use_gpu
shift = single(shift);
x = reshape(shift(:,1),1,1,[]);
y = reshape(shift(:,2),1,1,[]);
Np = size(img);
if size(img,3) ~= size(shift,1) && use_gpu
% ugly trick making matlab GPU FFT faster
img = repmat(img,1,1,size(shift,1));
end
img = fft2_safe(img);
if isempty(xgrid)
% matlab seems to need quite a lot of time to generate it -> preallocate
xgrid = Garray(fftshift((0:Np(2)-1)'/Np(2))-0.5)';
ygrid = Garray(fftshift((0:Np(1)-1)'/Np(1))-0.5);
end
if use_gpu
img = Gfun(@apply_shift_Gfun,img,x,y,xgrid, ygrid);
else
img = bsxfun(@times, img, exp((-2i*pi)*bsxfun(@times, x,xgrid)));
img = bsxfun(@times, img, exp((-2i*pi)*bsxfun(@times,y,ygrid)));
end
img = ifft2_safe(img);
end
function img = apply_shift_Gfun(img,x,y,xgrid, ygrid)
img = img .* exp((-2i*pi)*(x*xgrid+y*ygrid));
end
@@ -0,0 +1,98 @@
% SHIFT_PROBE_FFT fast shifting in fourier space (ie apply phase ramp )
%
% img = shift_probe_fft(img, shift)
%
% ** img stack images
% ** shift (N,2) array of shifts
% returns
% ++ img shifted image stack
% Academic License Agreement
%
% Source Code
%
% Introduction
% This license agreement sets forth the terms and conditions under which the PAUL SCHERRER INSTITUT (PSI), CH-5232 Villigen-PSI, Switzerland (hereafter "LICENSOR")
% will grant you (hereafter "LICENSEE") a royalty-free, non-exclusive license for academic, non-commercial purposes only (hereafter "LICENSE") to use the cSAXS
% ptychography MATLAB package computer software program and associated documentation furnished hereunder (hereafter "PROGRAM").
%
% Terms and Conditions of the LICENSE
% 1. LICENSOR grants to LICENSEE a royalty-free, non-exclusive license to use the PROGRAM for academic, non-commercial purposes, upon the terms and conditions
% hereinafter set out and until termination of this license as set forth below.
% 2. LICENSEE acknowledges that the PROGRAM is a research tool still in the development stage. The PROGRAM is provided without any related services, improvements
% or warranties from LICENSOR and that the LICENSE is entered into in order to enable others to utilize the PROGRAM in their academic activities. It is the
% LICENSEEs responsibility to ensure its proper use and the correctness of the results.
% 3. THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
% A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. IN NO EVENT SHALL THE LICENSOR, THE AUTHORS OR THE COPYRIGHT
% HOLDERS BE LIABLE FOR ANY CLAIM, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROGRAM OR THE USE
% OF THE PROGRAM OR OTHER DEALINGS IN THE PROGRAM.
% 4. LICENSEE agrees that it will use the PROGRAM and any modifications, improvements, or derivatives of PROGRAM that LICENSEE may create (collectively,
% "IMPROVEMENTS") solely for academic, non-commercial purposes and that any copy of PROGRAM or derivatives thereof shall be distributed only under the same
% license as PROGRAM. The terms "academic, non-commercial", as used in this Agreement, mean academic or other scholarly research which (a) is not undertaken for
% profit, or (b) is not intended to produce works, services, or data for commercial use, or (c) is neither conducted, nor funded, by a person or an entity engaged
% in the commercial use, application or exploitation of works similar to the PROGRAM.
% 5. LICENSEE agrees that it shall make the following acknowledgement in any publication resulting from the use of the PROGRAM or any translation of the code into
% another computing language:
% "Data processing was carried out using the cSAXS ptychography MATLAB package developed by the Science IT and the coherent X-ray scattering (CXS) groups, Paul
% Scherrer Institut, Switzerland."
%
% Additionally, any publication using the package, or any translation of the code into another computing language should cite for difference map:
% P. Thibault, M. Dierolf, A. Menzel, O. Bunk, C. David, F. Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321, 379382 (2008).
% (doi: 10.1126/science.1158573),
% for maximum likelihood:
% P. Thibault and M. Guizar-Sicairos, Maximum-likelihood refinement for coherent diffractive imaging, New J. Phys. 14, 063004 (2012).
% (doi: 10.1088/1367-2630/14/6/063004),
% for mixed coherent modes:
% P. Thibault and A. Menzel, Reconstructing state mixtures from diffraction measurements, Nature 494, 6871 (2013). (doi: 10.1038/nature11806),
% and/or for multislice:
% E. H. R. Tsai, I. Usov, A. Diaz, A. Menzel, and M. Guizar-Sicairos, X-ray ptychography with extended depth of field, Opt. Express 24, 2908929108 (2016).
% (doi: 10.1364/OE.24.029089).
% 6. Except for the above-mentioned acknowledgment, LICENSEE shall not use the PROGRAM title or the names or logos of LICENSOR, nor any adaptation thereof, nor the
% names of any of its employees or laboratories, in any advertising, promotional or sales material without prior written consent obtained from LICENSOR in each case.
% 7. Ownership of all rights, including copyright in the PROGRAM and in any material associated therewith, shall at all times remain with LICENSOR, and LICENSEE
% agrees to preserve same. LICENSEE agrees not to use any portion of the PROGRAM or of any IMPROVEMENTS in any machine-readable form outside the PROGRAM, nor to
% make any copies except for its internal use, without prior written consent of LICENSOR. LICENSEE agrees to place the following copyright notice on any such copies:
% © All rights reserved. PAUL SCHERRER INSTITUT, Switzerland, Laboratory for Macromolecules and Bioimaging, 2017.
% 8. The LICENSE shall not be construed to confer any rights upon LICENSEE by implication or otherwise except as specifically set forth herein.
% 9. DISCLAIMER: LICENSEE shall be aware that Phase Focus Limited of Sheffield, UK has an international portfolio of patents and pending applications which relate
% to ptychography and that the PROGRAM may be capable of being used in circumstances which may fall within the claims of one or more of the Phase Focus patents,
% in particular of patent with international application number PCT/GB2005/001464. The LICENSOR explicitly declares not to indemnify the users of the software
% in case Phase Focus or any other third party will open a legal action against the LICENSEE due to the use of the program.
% 10. This Agreement shall be governed by the material laws of Switzerland and any dispute arising out of this Agreement or use of the PROGRAM shall be brought before
% the courts of Zürich, Switzerland.
function img = shift_probe_fft(img, shift)
import engines.GPU.GPU_wrapper.*
if all(shift(:) == 0); return ; end
global use_gpu
persistent grid
shift = Garray(shift);
x = reshape(shift(:,1),1,1,[]);
y = reshape(shift(:,2),1,1,[]);
Np = size(img);
if Np(1) ~= Np(2); error('Not implemented'); end
grid = Garray((0:Np(1)-1)'/Np(1)-0.5);
if isempty(grid)
grid = Garray((0:Np(1)-1)'/Np(1)-0.5);
end
if use_gpu
img = Gfun(@apply_shift_Gfun,img,x,y,grid', grid);
else
img = bsxfun(@times, img, exp((-2i*pi)*bsxfun(@times,x,grid')));
img = bsxfun(@times, img, exp((-2i*pi)*bsxfun(@times,y,grid)));
end
end
function img = apply_shift_Gfun(img,x,y,xgrid, ygrid)
img = img .* exp((-2i*pi)*(x*xgrid+y*ygrid));
end