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
+49
View File
@@ -0,0 +1,49 @@
% ARGMAX returns coordinates of maximum value in X
%
% varargout = argmax(x)
%
% Inputs:
% **X - Ndim array
% *returns*:
% ++coordinates of the first value equal to maximum
% Example: [i,j] = argmax(randn(10))
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function varargout = argmax(x)
varargout = cell(nargout,1);
[varargout{:}] = find( x == max(x(:)), 1, 'first');
end
+48
View File
@@ -0,0 +1,48 @@
% ARGMIN returns coordinates of minimum value in X
%
% varargout = argmin(x)
%
% Inputs:
% **X - Ndim array
% *returns*:
% ++coordinates of the first value equal to minimum
% Example: [i,j] = argmin(randn(10))
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function varargout = argmin(x)
varargout = cell(nargout,1);
[varargout{:}] = find( x == min(x(:)), 1, 'first');
end
+46
View File
@@ -0,0 +1,46 @@
function [pos_x, pos_y, mass, mu, sigma] = center(X, use_shift)
% -----------------------------------------------------------------------
% This file is part of the PTYCHOMAT Toolbox
% Author: Michal Odstrcil, 2016
% License: Open Source under GPLv3
% Contact: ptychomat@gmail.com
% Website: https://bitbucket.org/michalodstrcil/ptychomat
% -----------------------------------------------------------------------
% Description: find center of mass of matrix X, calculate variance if
% needed
% inputs:
% X 2D stacked images
% use_shift, if true, CoM will be calculated relatively to the center
% of the image, default == true
if nargin < 2
use_shift = true;
end
[N,M,~] = size(X);
mass = sum(sum(X));
xgrid = (1:M);
ygrid = (1:N)';
pos_x = (sum(sum(X,1).*xgrid)./mass);
pos_y = (sum(sum(X,2).*ygrid)./mass);
if nargout > 3
mu = [pos_x, pos_y]';
end
if nargout == 5
pos_xx = (sum(sum(X,1).*((1:M)-pos_x).^2)/mass);
pos_yy = (sum(sum(X,2).*((1:N)-pos_y)'.^2)/mass);
pos_xy = ((X*((1:M)-pos_x)')'*((1:N)-pos_y)'/mass);
pos_yx = ((X*((1:M)-pos_x)')'*((1:N)-pos_y)'/mass);
sigma = [ pos_xx, pos_xy; pos_yx, pos_yy];
end
if use_shift
pos_x = pos_x - M/2-0.5; % defined so that center(ones(N),true) == [0,0]
pos_y = pos_y - N/2-0.5;
end
end
+25
View File
@@ -0,0 +1,25 @@
% COMPOSE_AFFINE_MATRIX calculate affine matrix when provided rotation, shear, asymmetry and scale
%
% affine_mat = compose_affine_matrix(scale, asymmetry, rotation, shear)
%
% Inputs:
% **scale A1 = [scale, 0; 0, scale]
% **asymmetry A2 = [1+asymmetry/2,0; 0,1-asymmetry/2]
% **rotation A3 = [cosd(rotation), sind(rotation); -sind(rotation), cosd(rotation)]
% **shear A4 = [1,0;tand(shear),1];
%
% returns:
% ++ affine_mat affine matrix = A1*A2*A3*A4
function affine_mat = compose_affine_matrix(scale, asymmetry, rotation, shear)
if isscalar(scale) && isscalar(asymmetry) && isscalar(rotation) && isscalar(shear)
affine_mat = scale(1)*[1+asymmetry/2,0; 0,1-asymmetry/2]*[cosd(rotation), sind(rotation); -sind(rotation), cosd(rotation)] * [1,0;tand(shear),1];
else
for ii = 1:max([numel(scale), numel(asymmetry), numel(rotation), numel(shear)])
affine_mat(:,:,ii) = scale(min(ii,end))*...
[1+asymmetry(min(ii,end))/2,0; 0,1-asymmetry(min(ii,end))/2]*...
[cosd(rotation(min(ii,end))), sind(rotation(min(ii,end))); -sind(rotation(min(ii,end))), cosd(rotation(min(ii,end)))] *...
[1,0;tand(shear(min(ii,end))),1];
end
end
end
+58
View File
@@ -0,0 +1,58 @@
% DECOMPOSE_AFFINE_MATRIX calculate rotation, shear, asymmetry and scale from affine matrix
%
% [scale, asymmetry, rotation, shear] = decompose_affine_matrix(affine_mat)
%
% Inputs:
% ** affine_mat affine matrix = A1*A2*A3*A4
%
% returns:
% ++scale A1 = [scale, 0; 0, scale]
% ++asymmetry A2 = [1+asymmetry/2,0; 0,1-asymmetry/2]
% ++rotation A3 = [cosd(rotation), sind(rotation); -sind(rotation), cosd(rotation)]
% ++shear A4 = [1,0;tand(shear),1];
%
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function [scale, asymmetry, rotation, shear] = decompose_affine_matrix(affine_mat)
err_fun = @(x)(affine_mat - x(1)*[1+x(2)/2,0; 0,1-x(2)/2]*[cosd(x(3)), sind(x(3)); -sind(x(3)), cosd(x(3))] * [1,0;tand(x(4)),1]);
options = optimoptions('lsqnonlin','Display','off');
xopt = lsqnonlin( err_fun, [1,0,0,0],[],[],options);
scale = xopt(1);
asymmetry = xopt(2);
rotation = xopt(3);
shear = xopt(4);
end
+90
View File
@@ -0,0 +1,90 @@
%DOUBLE2INT Convert structure values from double to int if precision can be
%preserved.
%
% EXAMPLE:
% p.value1 = 10.25;
% p.value2 = 2;
%
% p_int = double2int(p);
%
% p_int.value1
% ans =
% 10.2500
%
% p_int.value2
% ans =
% uint32
% 2
%
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function [ p ] = double2int( p )
import utils.struc2cell
% convert structure to cell to get all fieldnames
fn = struc2cell(p);
for ii=1:length(fn)
grps = strsplit(fn{ii}, '.');
data_val = getfield(p, grps{:});
if isnumeric(data_val) && isreal(data_val)
try
% check if data can converted to unsigned int
if all(mod(data_val(:),1)==0) && all(all(data_val>=0))
p = setfield(p,grps{:}, uint32(data_val));
% if data is negative, convert it to int
elseif all(mod(data_val(:),1)==0)
p = setfield(p,grps{:}, int32(data_val));
end
catch
keyboard
end
end
end
end
+88
View File
@@ -0,0 +1,88 @@
% FFT2_PARTIAL apply fftn only on smaller blocks (important for GPU)
%
% x = fft2_partial(x,split)
%
% Inputs:
% **x - input array
% *optional*
% **split - number of blocks to split the array before FFT to save the memory
%
% *returns*
% ++x fft2 transformed array
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function x = fft2_partial(x,split, inverse)
if nargin < 3
inverse = false;
end
if nargin < 2 || isempty(split)
%% empirical condition assuming FFT involved, may be too pesimistic
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
mem_req = numel(x)*8 * log2(max(size(x,1),size(x,2)));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if isa(x,'gpuArray')
x = complex(x); % move directly to complex to include the expected memore requirements
gpu = gpuDevice;
split = ceil(mem_req / gpu.AvailableMemory);
else
if mem_req < 50e9
% assume to have at least 50GB ram free ...
split = 1;
else
avail_mem = utils.check_available_memory * 1e6;
split = ceil(mem_req /avail_mem);
end
end
end
if any(split > 1)
Ndims = ndims(x);
for ax = 1:2
x = math.fft_partial(x,ax,1+mod(ax+1,Ndims), split, inverse);
end
else
if ~inverse
x = fft2(x);
else
x = ifft2(x);
end
end
end
+113
View File
@@ -0,0 +1,113 @@
% FFT_PARTIAL apply fft only on smaller blocks (important for GPU)
%
% x = fft_partial(x,fft_axis,split_axis, split, inverse = false)
%
% Inputs:
% **x - input array
% **fft_axis - axis along which is performed FFT
% **split_axis - axis along which is the array split
%
% *optional*
% **split - number of blocks to split the array before FFT to save the memory
% **inverse - if true, use ifft intead of fft
%
% *returns*
% ++x fft transformed array
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function x = fft_partial(x,fft_axis,split_axis, split, inverse)
persistent current_gpu
import math.*
if nargin < 5
inverse = false; % do inverse fft
end
if nargin < 4 || isempty(split)
% auto estimation of the split
mem_req = numel(x)*8 * log2(size(x,fft_axis));
if isa(x,'gpuArray')
% move directly to complex to include the expected memore requirements
x = complex(x);
if isempty(current_gpu) || isnan(current_gpu.AvailableMemory)
current_gpu = gpuDevice;
end
split = ceil(mem_req / current_gpu.AvailableMemory);
else
if mem_req < 50e9
% assume to have at least 50GB ram free ...
split = 1;
else
avail_mem = utils.check_available_memory * 1e6;
split = ceil(mem_req /avail_mem);
end
end
end
if all(split == 1)
if inverse
x = ifft(x,[],fft_axis);
else
x = fft(x,[],fft_axis);
end
return
end
% check GPU memory
Np = size(x);
Nps = Np;
Nps(split_axis) = ceil(Nps(split_axis) / split);
ind = {':', ':',':'};
for i = 1:split
ind{split_axis} = (1+(i-1)*Nps(split_axis)): min(Np(split_axis), i*Nps(split_axis));
x_tmp = x(ind{:});
if ~inverse
x_tmp = fft(x_tmp, [], fft_axis); % avoid additonal memory assignment
else
x_tmp = ifft(x_tmp, [], fft_axis);
end
x(ind{:}) = x_tmp;
end
end
+62
View File
@@ -0,0 +1,62 @@
% FFTN_PARTIAL apply fftn only on smaller blocks (important for GPU)
%
% x = fftn_partial(x,split)
%
% Inputs:
% **x - input array
% *optional*
% **split - number of blocks to split the array before FFT to save the memory
%
% *returns*
% ++x fftn transformed array
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function x = fftn_partial(x,split)
import math.*
% FUNCTION x = fftn_partial(x,split)
% apply fft only on smaller blocks (important for GPU)
if any(split > 1)
Ndims = ndims(x);
for ax = 1:Ndims
x = fft_partial(x,ax,1+mod(ax+1,Ndims), split, false);
end
else
x = fftn(x);
end
end
+27
View File
@@ -0,0 +1,27 @@
function [x,idx] = fftshift_2D(x)
% -----------------------------------------------------------------------
% This file is part of the PTYCHOMAT Toolbox
% Author: Michal Odstrcil, 2016
% License: Open Source under GPLv3
% Contact: ptychomat@gmail.com
% Website: https://bitbucket.org/michalodstrcil/ptychomat
% -----------------------------------------------------------------------
% Description: faster version of matlab fftshift to work for stack of
% 2D images
% Inputs: 2D or stack of 2D images
% Outputs:
% x - 2D or stack of 2D images after fftshift along first 2 dimensions
% idx - precalculated indices for fftshift operation
numDims = 2;
idx = cell(1, numDims);
for k = 1:numDims
m = size(x, k);
p = ceil(m/2);
idx{k} = [p+1:m 1:p];
end
x = x(idx{:},:,:);
end
+109
View File
@@ -0,0 +1,109 @@
function [U,S,V] = fsvd(A, k, i, usePowerMethod)
% FSVD Fast Singular Value Decomposition
%
% [U,S,V] = FSVD(A,k,i,usePowerMethod) computes the truncated singular
% value decomposition of the input matrix A upto rank k using i levels of
% Krylov method as given in [1], p. 3.
%
% If usePowerMethod is given as true, then only exponent i is used (i.e.
% as power method). See [2] p.9, Randomized PCA algorithm for details.
%
% [1] Halko, N., Martinsson, P. G., Shkolnisky, Y., & Tygert, M. (2010).
% An algorithm for the principal component analysis of large data sets.
% Arxiv preprint arXiv:1007.5510, 0526. Retrieved April 1, 2011, from
% http://arxiv.org/abs/1007.5510.
%
% [2] Halko, N., Martinsson, P. G., & Tropp, J. A. (2009). Finding
% structure with randomness: Probabilistic algorithms for constructing
% approximate matrix decompositions. Arxiv preprint arXiv:0909.4061.
% Retrieved April 1, 2011, from http://arxiv.org/abs/0909.4061.
%
% See also SVD.
%
% Copyright 2011 Ismail Ari, http://ismailari.com.
isSparse = issparse(A);
if nargin < 3
i = 1;
end
% Take (conjugate) transpose if necessary. It makes H smaller thus
% leading the computations to be faster
if size(A,1) < size(A,2)
A = A';
isTransposed = true;
else
isTransposed = false;
end
n = size(A,2);
extra_margin = 3; % slighly improve precision
l = k + extra_margin;
% Form a real n×l matrix G whose entries are iid Gaussian r.v.s of zero
% mean and unit variance
G = randn(n,l, 'single');
if nargin >= 4 && usePowerMethod
% Use only the given exponent
H = A*G;
for j = 2:i+1
H = A * (A'*H);
end
else
% Compute the m×l matrices H^{(0)}, ..., H^{(i)}
% Note that this is done implicitly in each iteration below.
if isSparse
H = sparse(size(A,1), l * (i+1) );
else
H = zeros(size(A,1), l * (i+1), 'like', A);
end
H(:,1:l) = A*G;
for j = 2:i+1
H(:,(j-1)*l + (1:l)) = A * (A'*H(: , (j-2)*l + (1:l)));
end
% Form the m×((i+1)l) matrix H
end
% Using the pivoted QR-decomposiion, form a real m×((i+1)l) matrix Q
% whose columns are orthonormal, s.t. there exists a real
% ((i+1)l)×((i+1)l) matrix R for which H = QR.
% XXX: Buradaki column pivoting ile yapılmayan hali.
[Q,~] = qr(H,0);
% Compute the n×((i+1)l) product matrix T = A^T Q
T = A'*Q;
% Form an SVD of T
[Vt, St, W] = svd(T,'econ');
% Compute the m×((i+1)l) product matrix
Ut = Q*W;
% Retrieve the leftmost m×k block U of Ut, the leftmost n×k block V of
% Vt, and the leftmost uppermost k×k block S of St. The product U S V^T
% then approxiamtes A.
if isTransposed
V = Ut(:,1:k);
U = Vt(:,1:k);
else
U = Ut(:,1:k);
V = Vt(:,1:k);
end
S = single(St(1:k,1:k));
end
+70
View File
@@ -0,0 +1,70 @@
% get vertical and horizontal gradient of the image using FFT
%
% [dX, dY] = get_img_grad(img, axis, split)
%
% Inputs:
% **img - stack of images
% **split - split for GPU fft_partial
% **axis - direction of the derivative
% *returns*
% ++[dX, dY] - image gradients
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
%
function [dX, dY] = get_img_grad(img, axis, split)
import math.*
if nargin < 3 || isempty(split)
split = 1;
end
isReal = isreal(img);
Np = size(img);
if nargin < 2 || any(axis == 2)
X = 2i*pi*ifftshift(-fix(Np(2)/2):ceil(Np(2)/2)-1)/Np(2);
dX = bsxfun(@times,fft_partial(img,2,1,split,false),X);
dX = fft_partial(dX,2,1,split,true);
if isReal; dX = real(dX);end
end
if nargout == 2 || (nargin > 1 && any(axis == 1))
Y = 2i*pi*ifftshift(-fix(Np(1)/2):ceil(Np(1)/2)-1)/Np(1);
dY = bsxfun(@times, fft_partial(img,1,2,split,false),Y.');
dY = fft_partial(dY,1,2,split,true);
if isReal; dY = real(dY);end
if nargout == 1; dX = dY; end
end
end
+72
View File
@@ -0,0 +1,72 @@
% GET_IMG_GRAD_CONV get image gradients along all 3 axis using real space convolution
%
% [dX, dY, dZ] = get_img_grad_conv(img, win_size, axis)
%
% Inputs:
% **img - stack of images
% **win_size - size of the window used for approximation of the FFT gradient
% **axis - direction of the derivative
% *returns*
% ++[dX, dY, dZ] - 3D gradients
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
%
function [dX, dY, dZ] = get_img_grad_conv(img, win_size, axis)
%% get vertical and horizontal gradient of the image
if ~isreal(img); error('Not implemented'); end
ker = get_kernel(win_size);
if isa(img, 'gpuArray'); ker = gpuArray(ker); end
if nargin < 3 || any(axis == 2)
dX = convn(img, reshape(ker,1,[],1), 'same');
end
if nargout > 1 || (nargin > 2 && any(axis == 1))
dY = convn(img, reshape(ker,[],1,1), 'same');
if nargout == 1; dX = dY; end
end
if nargout > 2 || (nargin > 2 && any(axis == 3))
dZ = convn(img, reshape(ker,1,1,[]), 'same');
if nargout == 1; dX = dZ; end
end
end
function ker = get_kernel(win_size)
N = max(9,2*win_size +1);
grid = 2i*pi*(fftshift((0:N-1)/(N))-0.5);
ker = -real(fftshift(fft(grid)))/length(grid);
ker = ker( ceil(end/2)+(-ceil(win_size):ceil(win_size)));
ker = utils.Garray(single(ker));
end
+85
View File
@@ -0,0 +1,85 @@
% GET_IMG_INT_1 use FFT to integate the image along selected axis -> can be used for phase
% unwrapping
%
% integer = get_img_int_1D(grad_array, ax)
%
% Inputs:
% **grad_array - phase gradient
% **ax - integration axis
% *returns*
% ++integral - 2D stack scalar arrays that has gradients along "ax" close to "grad_array"
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
%
function integer = get_img_int_1D(grad_array, ax)
if nargin < 2
ax = 1;
end
Np = size(grad_array);
if ax == 2
grad_array = fft(grad_array,[],2);
xgrid = ifftshift(-fix(Np(2)/2):ceil(Np(2)/2)-1)/Np(2);
% not sure why, but it seems to need also shift by 1 pixel to make it
% consistent with gradient
X = exp((2i*pi)*xgrid);
% integration filter
X = X./ (2i*pi*xgrid);
X(1) = 0;
integer = bsxfun(@times, grad_array,X);
integer = ifft(integer,[],2);
elseif ax == 1
grad_array = fft(grad_array,[],1);
ygrid = ifftshift(-fix(Np(1)/2):ceil(Np(1)/2)-1)/Np(1);
% not sure why, but it seems to need also shift by 1 pixel to make it
% consistent with gradient
Y = exp((2i*pi)*ygrid');
% integration filter
Y = Y./(2i*pi*ygrid');
Y(1) = 0;
integer = bsxfun(@times, grad_array,Y);
integer = ifft(integer,[],1);
else
error('Non implemented dimension')
end
end
+68
View File
@@ -0,0 +1,68 @@
% GET_IMG_INT_2D use FFT2 to integate the image along both axis -> can be used for phase
% unwrapping
%
% integral = get_img_int_2D(dX,dY)
%
% Inputs:
% **dX - horizontal phase gradient
% **dY - vertical phase gradient
% *returns*
% ++integral - 2D stack scalar rotation-free arrays that has vertical and horizontal gradients close to dX, dY
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
%
function integral = get_img_int_2D(dX,dY)
Np = size(dX);
fD = math.fft2_partial(dX + 1i*dY);
xgrid = ifftshift(-fix(Np(2)/2):ceil(Np(2)/2)-1)/Np(2);
ygrid = ifftshift(-fix(Np(1)/2):ceil(Np(1)/2)-1)/Np(1);
% not sure why, but it seems to need also shift by 1 pixels to make it
% consistent with gradient
X = exp((2i*pi)*(xgrid+ygrid'));
% apply integration filter
X = X./ (2i*pi*(xgrid+1i*ygrid'));
X(1,1) = 0;
integral = bsxfun(@times, fD,X);
integral = math.ifft2_partial(integral);
end
+91
View File
@@ -0,0 +1,91 @@
% GET_PHASE_GRADIENT_1D get 1D gradient of phase of an image stack.
% Accept either complex image or just phase
%
% [d_img] = get_phase_gradient_1D(img, ax=2, step=0)
%
% Inputs
% **img - stack of complex valued input images
% *optional*
% **ax - axis of derivative, default = 2
% **step - step used to calculate the central difference, default=0 (analytic expression)
%
% *returns*
% ++d_img - phase gradient array
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function d_img = get_phase_gradient_1D(img, ax, step, shift)
import utils.*
import math.*
if isreal(img)
img = exp(1i*img);
end
if nargin < 2
ax = 2;
end
if nargin < 3
step = 0.5; % step of the difference (too small will amplify noise)
end
if nargin < 4
shift = 0; % perform shift and gradient calculation in single step
end
assert(step >= 0, 'Difference step has to be > 0')
% suppress edge issues if phase ramp is not subtracted / there is no
% air around sample
pad_distance = 8;
img = padarray(img,circshift([pad_distance,0,0], ax-1),'symmetric','both');
img = smooth_edges(img, pad_distance, ax);
if step == 0
% analytic formula (sensitive to noise) but faster
img = img ./ (abs(img) + eps);
d_img = get_img_grad(img, ax); % img is assumed to be complex
d_img = imag(conj(img).*d_img);
else
d_img = angle( imshift_fft_ax(img,-step+shift,ax) .* conj( imshift_fft_ax(img,step+shift,ax)))/(2*step);
end
% remove padding
ind = circshift({pad_distance:size(d_img,ax)-pad_distance-1,':', ':'},ax-1);
d_img = d_img(ind{:});
end
+93
View File
@@ -0,0 +1,93 @@
% GET_PHASE_GRADIENT_2D get 2D gradient of phase of image IMG.
% Accept either complex image or just phase
%
% [d_X, d_Y] = get_phase_gradient_2D(img, step=0, padding=8)
%
% Inputs
% **img - stack of complex valued input images
% *optional*
% **step - step used to calculate the central difference, default=0 (analytic expression)
% **padding - padding around edges to prevent periodic boundary artefacts
%
% *returns*
% ++d_X,d_Y - horizontal and vertical phase gradient arrays
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function [d_X, d_Y] = get_phase_gradient_2D(img, step, padding)
import utils.*
import math.*
if isreal(img)
img = exp(1i*img);
end
if nargin < 2
step = 0; % step of the difference (too small will amplify noise)
end
if nargin < 3
padding = 8; % pad arrays to avoid edge issues
end
% suppress edge issues if phase ramp is not subtracted / there is no
% air around sample
if padding > 0
img = padarray(img,[padding, padding],'symmetric','both');
img = smooth_edges(img, padding, [1,2]);
end
if step == 0
% analytic formula (sensitive to noise) but faster
% img = img ./ (abs(img) + eps);
[d_X, d_Y] = get_img_grad(img); % img is assumed to be complex
d_X = imag(conj(img).*d_X);
d_Y = imag(conj(img).*d_Y);
else
% finite difference based method
d_X = angle( imshift_fft_ax(img,-step,2) .* conj( imshift_fft_ax(img,step,2)))/(2*step);
d_Y = angle( imshift_fft_ax(img,-step,1) .* conj( imshift_fft_ax(img,step,1)))/(2*step);
end
if padding > 0
% remove padding
ind = {padding:size(d_X,1)-padding-1,padding:size(d_X,2)-padding-1, ':'};
d_X = d_X(ind{:});
d_Y = d_Y(ind{:});
end
end
+56
View File
@@ -0,0 +1,56 @@
% IFFT2_PARTIAL apply fftn only on smaller blocks (important for GPU)
%
% x = ifft2_partial(x,split)
%
% Inputs:
% **x - input array
% *optional*
% **split - number of blocks to split the array before FFT to save the memory
%
% *returns*
% ++x ifft2 transformed array
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function x = ifft2_partial(x,split)
if nargin < 2
split = [];
end
x = math.fft2_partial(x,split, true);
end
+62
View File
@@ -0,0 +1,62 @@
% IFFT_PARTIAL apply fft only on smaller blocks (important for GPU)
%
% x = ifft_partial(x,fft_axis,split_axis, split)
%
% Inputs:
% **x - input array
% **fft_axis - axis along which is performed FFT
% **split_axis - axis along which is the array split
%
% *optional*
% **split - number of blocks to split the array before FFT to save the memory
%
% *returns*
% ++x ifft transformed array
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function x = ifft_partial(x,fft_axis,split_axis, split)
if nargin < 4
split = [];
end
x = math.fft_partial(x,fft_axis,split_axis, split, true);
end
+59
View File
@@ -0,0 +1,59 @@
% IFFTN_PARTIAL apply fftn only on smaller blocks (important for GPU)
%
% x = ifftn_partial(x,split)
%
% Inputs:
% **x - input array
% *optional*
% **split - number of blocks to split the array before FFT to save the memory
%
% *returns*
% ++x ifftn transformed array
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function x = ifftn_partial(x,split)
import math.*
if any(split > 1)
Ndims = ndims(x);
for ax = 1:Ndims
x = fft_partial(x,ax,1+mod(ax+1,Ndims), split, true);
end
else
x = ifftn(x);
end
end
+27
View File
@@ -0,0 +1,27 @@
function [x,idx] = ifftshift_2D(x)
% -----------------------------------------------------------------------
% This file is part of the PTYCHOMAT Toolbox
% Author: Michal Odstrcil, 2016
% License: Open Source under GPLv3
% Contact: ptychomat@gmail.com
% Website: https://bitbucket.org/michalodstrcil/ptychomat
% -----------------------------------------------------------------------
% Description: faster version of matlab fftshift to work for stack of
% 2D images
% Inputs: 2D or stack of 2D images
% Outputs:
% x - 2D or stack of 2D images after fftshift along first 2 dimensions
% idx - precalculated indices for fftshift operation
numDims = 2;
idx = cell(1, numDims);
for k = 1:numDims
m = size(x, k);
p = floor(m/2);
idx{k} = [p+1:m 1:p];
end
x = x(idx{:},:,:);
end
+50
View File
@@ -0,0 +1,50 @@
% ISINT returns true if all values of X are integers, but class can be arbitrary
% numerical array
%
% Inputs:
% **x - checked array
% *optional*
% **prec - precision threshold used to decide whether the number is still integer, default = 0.01
% *returns*:
% is_integer - scalar bool
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function is_integer = isint(x, prec)
if nargin < 2
prec = 1e-2;
end
is_integer = all(abs(round(x(:)) - x(:)) < prec);
end
+66
View File
@@ -0,0 +1,66 @@
% Generates a 1D orthonormal polynomial base
% polys = legendrepoly1D_2(X,maxorder,w);
% The weighting function has not been tested extensively
% Manuel Guizar - March 10, 2009
% Copyright (c) 2016, Manuel Guizar Sicairos, James R. Fienup, University of Rochester
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:
%
% * Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% * Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in
% the documentation and/or other materials provided with the distribution
% * Neither the name of the University of Rochester nor the names
% of its contributors may be used to endorse or promote products derived
% from this software without specific prior written permission.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.
function polys = legendrepoly1D_2(X,maxorder,w)
if nargin < 3
w = 1;
end
[nc nr] = size(X);
polys = ones(nc,nr);
%%% Generation of polynomials
for ii = 0:maxorder,
polys(:,:,ii+1) = (X.^(ii));
end
%%% Normalization
for ii = 1:length(polys(1,1,:)),
% polys(:,:,ii) = polys(:,:,ii)/sqrt(sum(sum(abs(polys(:,:,ii)).^2)));
polys(:,:,ii) = polys(:,:,ii)/sqrt(sum(sum(w.*abs(polys(:,:,ii)).^2)));
end
%%% Orthonormalization
for ii = 2:length(polys(1,1,:)),
for jj = 1:ii-1,
polys(:,:,ii) = polys(:,:,ii) - sum(sum(polys(:,:,ii).*polys(:,:,jj).*w))*polys(:,:,jj);
end
polys(:,:,ii) = polys(:,:,ii)/sqrt(sum(sum(w.*polys(:,:,ii).^2)));
end
% polys(:,:,3) = polys(:,:,3) - sum(sum(polys(:,:,3).*polys(:,:,1)))*polys(:,:,1);
% polys(:,:,3) = polys(:,:,3)/sum(sum(polys(:,:,3).^2));
+45
View File
@@ -0,0 +1,45 @@
% MAX2 maximum along first two dimensions
%
% Inputs:
% **x Ndim array
% *returns*:
% ++x Ndim-2 array
%
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function x = max2(x)
x = max(max(x,[],1),[],2);
end
+45
View File
@@ -0,0 +1,45 @@
% MEAN2 average along first two dimensions
%
% Inputs:
% **x Ndim array
% *returns*:
% ++x Ndim-2 array
%
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function y = mean2(x)
y = mean(mean(x,1),2);
end
+44
View File
@@ -0,0 +1,44 @@
% MIN2 min along first two dimensions
%
% Inputs:
% **x Ndim array
% *returns*:
% ++x Ndim-2 array
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function x = min2(x)
x = min(min(x,[],1),[],2);
end
+40
View File
@@ -0,0 +1,40 @@
% FUNCTION N = NNORM(a)
% N-Dimensional norm.
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function n = nnorm(a)
n = norm(reshape(a,1,numel(a)));
+45
View File
@@ -0,0 +1,45 @@
% NORM2 1/N * Euclidean norm aling first 2 dims
% Inputs:
% **x Ndim array
% *returns*:
% ++x Ndim-2 array
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function x = norm2(x)
import math.mean2
x = sqrt(mean2(abs(x).^2));
end
+101
View File
@@ -0,0 +1,101 @@
% Find sub-sample location of a global peak within 2D-matrix by applying
% two dimensional polynomial fit & extremum detection.
%
% Sample usage:
% >> M = exp(-((1:30) - 19.5).^2/(2*5^2)); % gauss: center=19.5; sigma=5
% >> P = peakfit2d(M'*M); % find peak in 2D-gauss
% >> disp(P);
% 19.5050 19.5050
%
% Algebraic solution derived with the following steps:
%
% 0.) Define Approximation-Function:
%
% F(x,y) => z = a*x^2+b*x*y+c*x+d+e*y^2+f*y
%
% 1.) Formulate equation for sum of squared differences with
%
% x=-1:1,y=-1:1,z=Z(x,y)
%
% SSD = [ a*(-1)^2+b*(-1)*(-1)+c*(-1)+d+e*(-1)^2+f*(-1) - Z(-1,-1) ]^2 + ...
% ...
% a*(+1)^2+b*(+1)*(+1)+c*(+1)+d+e*(+1)^2+f*(+1) - Z(-1,-1) ]^2
%
% 2.) Differentiate SSD towards each parameter
%
% dSSD / da = ...
% ...
% dSSD / df = ...
%
% 3.) Solve linear system to get [a..f]
%
% 4.) Differentiate F towards x and y and solve linear system for x & y
%
% dF(x,y) / dx = a*... = 0 !
% dF(x,y) / dy = b*... = 0 !
% Copyright (c) 2010, Eric
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:
%
% * Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% * Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in
% the documentation and/or other materials provided with the distribution
% * Neither the name of the HTWK Leipzig nor the names
% of its contributors may be used to endorse or promote products derived
% from this software without specific prior written permission.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE
function P = peakfit2d(Z)
import math.peakfit2d
%% Check input
sZ = size(Z);
if min(sZ)<2
disp('Wrong matrix size. Input matrix should be numerical MxN type.');
P = [0 0];
return;
end
%% peak approximation using 2D polynomial fit within 9 point neighbourship
% find global maximum and extract 9-point neighbourship
[v,p] = max(Z(:));
[yp,xp]=ind2sub(sZ,p);
if (yp==1)||(yp==sZ(1))||(xp==1)||(xp==sZ(2))
disp('Maximum position at matrix border. No subsample approximation possible.');
P = [yp xp];
return;
end
K = Z(yp-1:yp+1,xp-1:xp+1);
% approximate polynomial parameter
a = (K(2,1)+K(1,1)-2*K(1,2)+K(1,3)-2*K(3,2)-2*K(2,2)+K(2,3)+K(3,1)+K(3,3));
b = (K(3,3)+K(1,1)-K(1,3)-K(3,1));
c = (-K(1,1)+K(1,3)-K(2,1)+K(2,3)-K(3,1)+K(3,3));
%d = (2*K(2,1)-K(1,1)+2*K(1,2)-K(1,3)+2*K(3,2)+5*K(2,2)+2*K(2,3)-K(3,1)-K(3,3));
e = (-2*K(2,1)+K(1,1)+K(1,2)+K(1,3)+K(3,2)-2*K(2,2)-2*K(2,3)+K(3,1)+K(3,3));
f = (-K(1,1)-K(1,2)-K(1,3)+K(3,1)+K(3,2)+K(3,3));
% (ys,xs) is subpixel shift of peak location relative to point (2,2)
ys = (6*b*c-8*a*f)/(16*e*a-9*b^2);
xs = (6*b*f-8*e*c)/(16*e*a-9*b^2);
P = [ys+yp xs+xp];
+68
View File
@@ -0,0 +1,68 @@
% Proyects a 1D function onto orthonormalized base, returns residual too
% The weighting function has not been tested extensively
% [coeffs reconstrproj] = projectleg1D_2(input,maxorder,Xext,w);
% March 10, 2009
% Copyright (c) 2016, Manuel Guizar Sicairos, James R. Fienup, University of Rochester
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:
%
% * Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% * Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in
% the documentation and/or other materials provided with the distribution
% * Neither the name of the University of Rochester nor the names
% of its contributors may be used to endorse or promote products derived
% from this software without specific prior written permission.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.
function [coeffs, reconstrproj] = projectleg1D_2(input,maxorder,Xext,w)
import math.legendrepoly1D_2
polys = legendrepoly1D_2(Xext,maxorder,w);
reconstrproj = input;
for ii = 1:length(polys(1,1,:)),
coeffs(ii) = sum(sum(reconstrproj.*polys(:,:,ii).*w));
% end
%
%
% for ii = 1:length(polys(1,1,:)),
reconstrproj = reconstrproj-polys(:,:,ii)*coeffs(ii);
end
% coeffs,
% figure(5);
% imagesc((real(reconstrproj)));
% axis square;
% colorbar;
% colormap gray;
% title('extracted from autocorrelation and projected to legendres')
%
% figure(6);
% % imagesc((real(proj)));
% imagesc((real(reconstrproj-)));
% axis square;
% colorbar;
% colormap gray;
% title('projection to legendres')
+51
View File
@@ -0,0 +1,51 @@
% SP_QUANTILE sparse quantile, just make a fast guess of the quantile value
% on a downsampled array. Useful for estimation of the optimal imagesc
% limits
%
% Qval = sp_quantile(array,quantile,reduce)
%
% Inputs:
% **array - inputs ndim array
% **quantile - number or vector from 0 to 1 denoting quantiles
% **reduce - use every n-th element for calculation
% *returns*:
% ++Q - scalar or vector of quantiles of the reduced array
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function Qval = sp_quantile(x,q,reduce)
x = x(1:reduce:end);
Qval = quantile(x,q);
end
+43
View File
@@ -0,0 +1,43 @@
% SUM2 sum along first two dimensions
% Inputs:
% **x Ndim array
% *returns*:
% ++x Ndim-2 array
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function x = sum2(x)
x = sum(sum(x,1),2);
end
+85
View File
@@ -0,0 +1,85 @@
% UNWRAP2D_FFT simple and very fast 1D phase unwrapping applied for each
% slice of the provided image stack
%
% phase = unwrap2D_fft(img, axis, empty_region, step)
%
% Inputs:
% **img - (2D or 3D image stack) either complex valued image or real valued phase gradient
% **axis - (scalar, int) axis along which the gradient is taken
% *optional*
% **empty_region - 2x1 or 1x1 vector, size of empty region assumed around edges for phase offset removal, default=[]
% **step - used to calculate finite difference gradient, 0 = analytical (default) expression
%
% *returns*
% ++phase - unwrapped phase with phase ramp removed
% ++phase_diff - if img is complex array, phase difference can be also returned
% ++residues - calculated binary map of phase residuas
%
% See also: utils.findresidues, utils.remove_sinogram_ramp
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function [phase, phase_diff, residues] = unwrap2D_fft(phase_diff, axis, empty_region, step)
import math.*
import utils.*
if nargin < 4
step = 0;
end
if nargin < 3
empty_region = [];
end
if nargout > 2 && ~isreal(phase_diff) % if input is complex array
residues = abs(findresidues(phase_diff)) > 0.1;
else
residues = [];
end
if ~isreal(phase_diff)
phase_diff = get_phase_gradient_1D(phase_diff, axis, step);
end
phase = real(get_img_int_1D(phase_diff,axis));
if ~isempty(empty_region) && axis == 2
phase = remove_sinogram_ramp(phase,empty_region,-1);
end
end
+108
View File
@@ -0,0 +1,108 @@
% UNWRAP2D_FFT2 simple and very fast 2D phase unwrapping based on FT
% integration of DIC signal (phase gradient)
%
% [phase, residues] = unwrap2D_fft2(img, empty_region=[], step=0, weights=[], polyfit_order=1)
%
% Inputs:
% **img - either complex valued image or real valued phase gradient
% *optional*
% **empty_region - 2x1 or 1x1 vector, size of empty region assumed around edges for phase offset removal
% **step - used to calculate finite difference gradient, 0 = analytical (default) expression
% **polyfit_order -1 = dont assume anything about the removed phase,
% subtract linear offset from each horizontal line separatelly
% 0 = assume that removed degree of freedom is only a constant offset
% 1 = assume that removed degree of freedom is a 2D plane
% *returns*:
% ++phase - unwrapped phase with subtracted phase ramp / offset
% ++residues - calculated binary map of phase residuas
%
% See also: utils.findresidues, utils.remove_sinogram_ramp
%*-----------------------------------------------------------------------*
%|                                                                       |
%|  Except where otherwise noted, this work is licensed under a          |
%|  Creative Commons Attribution-NonCommercial-ShareAlike 4.0            |
%|  International (CC BY-NC-SA 4.0) license.                             |
%|                                                                       |
%|  Copyright (c) 2017 by Paul Scherrer Institute (http://www.psi.ch)    |
%|                                                                       |
%|      Author: CXS group, PSI  |
%*-----------------------------------------------------------------------*
% You may use this code with the following provisions:
%
% If the code is fully or partially redistributed, or rewritten in another
% computing language this notice should be included in the redistribution.
%
% If this code, or subfunctions or parts of it, is used for research in a
% publication or if it is fully or partially rewritten for another
% computing language the authors and institution should be acknowledged
% in written form in the publication: Data processing was carried out
% using the cSAXS matlab package developed by the CXS group,
% Paul Scherrer Institut, Switzerland.
% Variations on the latter text can be incorporated upon discussion with
% the CXS group if needed to more specifically reflect the use of the package
% for the published work.
%
% A publication that focuses on describing features, or parameters, that
% are already existing in the code should be first discussed with the
% authors.
%
% This code and subroutines are part of a continuous development, they
% are provided as they are without guarantees or liability on part
% of PSI or the authors. It is the user responsibility to ensure its
% proper use and the correctness of the results.
function [phase, residues] = unwrap2D_fft2(img, empty_region, step, weights, polyfit_order)
import utils.*
import math.*
if isreal(img)
error('Complex-valued input array was expected')
end
if nargin < 3 || isempty(step)
step = 0; % use analytical method
end
if nargin < 4 || isempty(weights)
weights = 1;
end
if nargin < 5
polyfit_order = 1; % subtract 2D plane
end
weights = max(0, min(1, single(weights))); % weights are assumed in range [0,1]
img = weights .* img ./ (abs(img)+eps);
clear weights
padding = [64,64]; % padding to avoid periodic boundary artefacts
if any(padding > 0)
img = padarray(img,padding,'symmetric','both');
img = smooth_edges(img, 5, [1,2]);
end
[dX,dY] = get_phase_gradient_2D(img, step, 0);
clear img
phase = real(get_img_int_2D(dX,dY));
if any(padding > 0)
% remove padding
ind = {padding(1):size(phase,1)-padding(1)-1,padding(2):size(phase,2)-padding(2)-1, ':'};
phase = phase(ind{:});
end
if exist('empty_region', 'var') && ~isempty(empty_region)
phase = remove_sinogram_ramp(phase,empty_region, polyfit_order);
end
if nargout > 1
residues = abs(findresidues(img)) > 0.1;
end
end