plateform
stringclasses 1
value | repo_name
stringlengths 13
113
| name
stringlengths 3
74
| ext
stringclasses 1
value | path
stringlengths 12
229
| size
int64 23
843k
| source_encoding
stringclasses 9
values | md5
stringlengths 32
32
| text
stringlengths 23
843k
|
---|---|---|---|---|---|---|---|---|
github
|
andreafarina/SOLUS-master
|
fix_lines.m
|
.m
|
SOLUS-master/src/util/export_fig/fix_lines.m
| 6,441 |
utf_8
|
ffda929ebad8144b1e72d528fa5d9460
|
%FIX_LINES Improves the line style of eps files generated by print
%
% Examples:
% fix_lines fname
% fix_lines fname fname2
% fstrm_out = fixlines(fstrm_in)
%
% This function improves the style of lines in eps files generated by
% MATLAB's print function, making them more similar to those seen on
% screen. Grid lines are also changed from a dashed style to a dotted
% style, for greater differentiation from dashed lines.
%
% The function also places embedded fonts after the postscript header, in
% versions of MATLAB which place the fonts first (R2006b and earlier), in
% order to allow programs such as Ghostscript to find the bounding box
% information.
%
%IN:
% fname - Name or path of source eps file.
% fname2 - Name or path of destination eps file. Default: same as fname.
% fstrm_in - File contents of a MATLAB-generated eps file.
%
%OUT:
% fstrm_out - Contents of the eps file with line styles fixed.
% Copyright: (C) Oliver Woodford, 2008-2014
% The idea of editing the EPS file to change line styles comes from Jiro
% Doke's FIXPSLINESTYLE (fex id: 17928)
% The idea of changing dash length with line width came from comments on
% fex id: 5743, but the implementation is mine :)
% Thank you to Sylvain Favrot for bringing the embedded font/bounding box
% interaction in older versions of MATLAB to my attention.
% Thank you to D Ko for bringing an error with eps files with tiff previews
% to my attention.
% Thank you to Laurence K for suggesting the check to see if the file was
% opened.
% 01/03/15: Issue #20: warn users if using this function in HG2 (R2014b+)
% 27/03/15: Fixed out of memory issue with enormous EPS files (generated by print() with OpenGL renderer), related to issue #39
function fstrm = fix_lines(fstrm, fname2)
% Issue #20: warn users if using this function in HG2 (R2014b+)
if using_hg2
warning('export_fig:hg2','The fix_lines function should not be used in this Matlab version.');
end
if nargout == 0 || nargin > 1
if nargin < 2
% Overwrite the input file
fname2 = fstrm;
end
% Read in the file
fstrm = read_write_entire_textfile(fstrm);
end
% Move any embedded fonts after the postscript header
if strcmp(fstrm(1:15), '%!PS-AdobeFont-')
% Find the start and end of the header
ind = regexp(fstrm, '[\n\r]%!PS-Adobe-');
[ind2, ind2] = regexp(fstrm, '[\n\r]%%EndComments[\n\r]+');
% Put the header first
if ~isempty(ind) && ~isempty(ind2) && ind(1) < ind2(1)
fstrm = fstrm([ind(1)+1:ind2(1) 1:ind(1) ind2(1)+1:end]);
end
end
% Make sure all line width commands come before the line style definitions,
% so that dash lengths can be based on the correct widths
% Find all line style sections
ind = [regexp(fstrm, '[\n\r]SO[\n\r]'),... % This needs to be here even though it doesn't have dots/dashes!
regexp(fstrm, '[\n\r]DO[\n\r]'),...
regexp(fstrm, '[\n\r]DA[\n\r]'),...
regexp(fstrm, '[\n\r]DD[\n\r]')];
ind = sort(ind);
% Find line width commands
[ind2, ind3] = regexp(fstrm, '[\n\r]\d* w[\n\r]');
% Go through each line style section and swap with any line width commands
% near by
b = 1;
m = numel(ind);
n = numel(ind2);
for a = 1:m
% Go forwards width commands until we pass the current line style
while b <= n && ind2(b) < ind(a)
b = b + 1;
end
if b > n
% No more width commands
break;
end
% Check we haven't gone past another line style (including SO!)
if a < m && ind2(b) > ind(a+1)
continue;
end
% Are the commands close enough to be confident we can swap them?
if (ind2(b) - ind(a)) > 8
continue;
end
% Move the line style command below the line width command
fstrm(ind(a)+1:ind3(b)) = [fstrm(ind(a)+4:ind3(b)) fstrm(ind(a)+1:ind(a)+3)];
b = b + 1;
end
% Find any grid line definitions and change to GR format
% Find the DO sections again as they may have moved
ind = int32(regexp(fstrm, '[\n\r]DO[\n\r]'));
if ~isempty(ind)
% Find all occurrences of what are believed to be axes and grid lines
ind2 = int32(regexp(fstrm, '[\n\r] *\d* *\d* *mt *\d* *\d* *L[\n\r]'));
if ~isempty(ind2)
% Now see which DO sections come just before axes and grid lines
ind2 = repmat(ind2', [1 numel(ind)]) - repmat(ind, [numel(ind2) 1]);
ind2 = any(ind2 > 0 & ind2 < 12); % 12 chars seems about right
ind = ind(ind2);
% Change any regions we believe to be grid lines to GR
fstrm(ind+1) = 'G';
fstrm(ind+2) = 'R';
end
end
% Define the new styles, including the new GR format
% Dot and dash lengths have two parts: a constant amount plus a line width
% variable amount. The constant amount comes after dpi2point, and the
% variable amount comes after currentlinewidth. If you want to change
% dot/dash lengths for a one particular line style only, edit the numbers
% in the /DO (dotted lines), /DA (dashed lines), /DD (dot dash lines) and
% /GR (grid lines) lines for the style you want to change.
new_style = {'/dom { dpi2point 1 currentlinewidth 0.08 mul add mul mul } bdef',... % Dot length macro based on line width
'/dam { dpi2point 2 currentlinewidth 0.04 mul add mul mul } bdef',... % Dash length macro based on line width
'/SO { [] 0 setdash 0 setlinecap } bdef',... % Solid lines
'/DO { [1 dom 1.2 dom] 0 setdash 0 setlinecap } bdef',... % Dotted lines
'/DA { [4 dam 1.5 dam] 0 setdash 0 setlinecap } bdef',... % Dashed lines
'/DD { [1 dom 1.2 dom 4 dam 1.2 dom] 0 setdash 0 setlinecap } bdef',... % Dot dash lines
'/GR { [0 dpi2point mul 4 dpi2point mul] 0 setdash 1 setlinecap } bdef'}; % Grid lines - dot spacing remains constant
% Construct the output
% This is the original (memory-intensive) code:
%first_sec = strfind(fstrm, '% line types:'); % Isolate line style definition section
%[second_sec, remaining] = strtok(fstrm(first_sec+1:end), '/');
%[remaining, remaining] = strtok(remaining, '%');
%fstrm = [fstrm(1:first_sec) second_sec sprintf('%s\r', new_style{:}) remaining];
fstrm = regexprep(fstrm,'(% line types:.+?)/.+?%',['$1',sprintf('%s\r',new_style{:}),'%']);
% Write the output file
if nargout == 0 || nargin > 1
read_write_entire_textfile(fname2, fstrm);
end
end
|
github
|
andreafarina/SOLUS-master
|
splsqr.m
|
.m
|
SOLUS-master/src/util/regu/splsqr.m
| 4,613 |
utf_8
|
0181a37f320874537246273fe4ae9b3a
|
function x = splsqr(A,b,lambda,Vsp,maxit,tol,reorth)
%SPLSQR Subspace preconditioned LSQR for discrete ill-posed problems.
%
% x = splsqr(A,b,lambda,Vsp,maxit,tol,reorth)
%
% Subspace preconditioned LSQR (SP-LSQR) for solving the Tikhonov problem
% min { || A x - b ||^2 + lambda^2 || x ||^2 }
% with a preconditioner based on the subspace defined by the columns of
% the matrix Vsp. While not necessary, we recommend to use a matrix Vsp
% with orthonormal columns.
%
% The output x holds all the solution iterates as columns, and the last
% iterate x(:,end) is the best approximation to x_lambda.
%
% The parameter maxit is the maximum allowed number of iterations (default
% value is maxit = 300). The parameter tol is used a stopping criterion
% for the norm of the least squares residual relative to the norm of the
% right-hand side (default value is tol = 1e-12).
%
% A seventh input parameter reorth ~= 0 enforces MGS reorthogonalization
% of the Lanczos vectors.
% This is a model implementation of SP-LSQR. In a real implementation the
% Householder transformations should use LAPACK routines, only the final
% iterate should be returned, and reorthogonalization is not used. Also,
% if Vsp represents a fast transformation (such as the DCT) then explicit
% storage of Vsp should be avoided. See the reference for details.
% Reference: M. Jacobsen, P. C. Hansen and M. A. Saunders, "Subspace pre-
% conditioned LSQR for discrete ill-posed problems", BIT 43 (2003), 975-989.
% Per Christian Hansen and Michael Jacobsen, IMM, July 29, 2007.
% Input check.
if nargin < 5, maxit = 300; end
if nargin < 6, tol = 1e-12; end
if nargin < 7, reorth = 0; end
if maxit < 1, error('Number of iterations must be positive'); end;
% Prepare for SP-LSQR algorithm.
[m,n] = size(A);
k = size(Vsp,2);
z = zeros(n,1);
if reorth
UU = zeros(m+n,maxit);
VV = zeros(n,maxit);
end
% Initial QR factorization of [A;lamnda*eye(n)]*Vsp;
QQ = qr([A*Vsp;lambda*Vsp]);
% Prepare for LSQR iterations.
u = app_house_t(QQ,[b;z]);
u(1:k) = 0;
beta = norm(u);
u = u/beta;
v = app_house(QQ,u);
v = A'*v(1:m) + lambda*v(m+1:end);
alpha = norm(v);
v = v/alpha;
w = v;
Wxw = zeros(n,1);
phi_bar = beta;
rho_bar = alpha;
if reorth, UU(:,1) = u; VV(:,1) = v; end;
for i=1:maxit
% beta*u = A*v - alpha*u;
uu = [A*v;lambda*v];
uu = app_house_t(QQ,uu);
uu(1:k) = 0;
u = uu - alpha*u;
if reorth
for j=1:i-1, u = u - (UU(:,j)'*u)*UU(:,j); end
end
beta = norm(u);
u = u/beta;
% alpha * v = A'*u - beta*v;
vv = app_house(QQ,u);
v = A'*vv(1:m) + lambda*vv(m+1:end) - beta*v;
if reorth
for j=1:i-1, v = v - (VV(:,j)'*v)*VV(:,j); end
end
alpha = norm(v);
v = v/alpha;
if reorth, UU(:,i) = u; VV(:,i) = v; end;
% Update LSQR parameters.
rho = norm([rho_bar beta]);
c = rho_bar/rho;
s = beta/rho;
theta = s*alpha;
rho_bar = -c*alpha;
phi = c*phi_bar;
phi_bar = s*phi_bar;
% Update the LSQR solution.
Wxw = Wxw + (phi/rho)*w;
w = v - (theta/rho)*w;
% Compute residual and update the SP-LSQR iterate.
r = [b - A*Wxw ; -lambda*Wxw];
r = app_house_t(QQ,r);
r = r(1:k);
xv = triu(QQ(1:k,:))\r;
x(:,i) = Vsp*xv + Wxw;
% Stopping criterion.
if phi_bar*alpha*abs(c) < tol*norm(b), break, end
end
%-----------------------------------------------------------------
function Y = app_house(H,X)
% Y = app_house(H,X)
% Input: H = matrix containing the necessary information of the
% Householder vectors v in the lower triangle and R in
% the upper triangle; e.g., computed as H = qr(A).
% X = matrix to be multiplied with orthogonal matrix.
% Output: Y = Q*X
[n,p] = size(H);
Y = X;
for k = p:-1:1
v = ones(n+1-k,1);
v(2:n+1-k) = H(k+1:n,k);
beta = 2/(v'*v);
Y(k:n,:) = Y(k:n,:) - beta*v*(v'*Y(k:n,:));
end
%-----------------------------------------------------------------
function Y = app_house_t(H,X)
% Y = app_house_t(H,X)
% Input: H = matrix containing the necessary information of the
% Householder vectors v in the lower triangle and R in
% the upper triangle; e.g., computed as H = qr(A).
% X = matrix to be multiplied with transposed orthogonal matrix.
% Output: Y = Q'*X
[n,p] = size(H);
Y = X;
for k = 1:p
v = ones(n+1-k,1);
v(2:n+1-k) = H(k+1:n,k);
beta = 2/(v'*v);
Y(k:n,:) = Y(k:n,:) - beta*v*(v'*Y(k:n,:));
end
|
github
|
andreafarina/SOLUS-master
|
discrep.m
|
.m
|
SOLUS-master/src/util/regu/discrep.m
| 5,823 |
utf_8
|
a520d1bf79c0055419bc02e05bebc36e
|
function [x_delta,lambda] = discrep(U,s,V,b,delta,x_0)
%DISCREP Discrepancy principle criterion for choosing the reg. parameter.
%
% [x_delta,lambda] = discrep(U,s,V,b,delta,x_0)
% [x_delta,lambda] = discrep(U,sm,X,b,delta,x_0) , sm = [sigma,mu]
%
% Least squares minimization with a quadratic inequality constraint:
% min || x - x_0 || subject to || A x - b || <= delta
% min || L (x - x_0) || subject to || A x - b || <= delta
% where x_0 is an initial guess of the solution, and delta is a
% positive constant. Requires either the compact SVD of A saved as
% U, s, and V, or part of the GSVD of (A,L) saved as U, sm, and X.
% The regularization parameter lambda is also returned.
%
% If delta is a vector, then x_delta is a matrix such that
% x_delta = [ x_delta(1), x_delta(2), ... ] .
%
% If x_0 is not specified, x_0 = 0 is used.
% Reference: V. A. Morozov, "Methods for Solving Incorrectly Posed
% Problems", Springer, 1984; Chapter 26.
% Per Christian Hansen, IMM, August 6, 2007.
% Initialization.
m = size(U,1); n = size(V,1);
[p,ps] = size(s); ld = length(delta);
x_delta = zeros(n,ld); lambda = zeros(ld,1); rho = zeros(p,1);
if (min(delta)<0)
error('Illegal inequality constraint delta')
end
if (nargin==5), x_0 = zeros(n,1); end
if (ps == 1), omega = V'*x_0; else omega = V\x_0; end
% Compute residual norms corresponding to TSVD/TGSVD.
beta = U'*b;
if (ps == 1)
delta_0 = norm(b - U*beta);
rho(p) = delta_0^2;
for i=p:-1:2
rho(i-1) = rho(i) + (beta(i) - s(i)*omega(i))^2;
end
else
delta_0 = norm(b - U*beta);
rho(1) = delta_0^2;
for i=1:p-1
rho(i+1) = rho(i) + (beta(i) - s(i,1)*omega(i))^2;
end
end
% Check input.
if (min(delta) < delta_0)
error('Irrelevant delta < || (I - U*U'')*b ||')
end
% Determine the initial guess via rho-vector, then solve the nonlinear
% equation || b - A x ||^2 - delta_0^2 = 0 via Newton's method.
if (ps == 1)
% The standard-form case.
s2 = s.^2;
for k=1:ld
if (delta(k)^2 >= norm(beta - s.*omega)^2 + delta_0^2)
x_delta(:,k) = x_0;
else
[dummy,kmin] = min(abs(rho - delta(k)^2));
lambda_0 = s(kmin);
lambda(k) = newton(lambda_0,delta(k),s,beta,omega,delta_0);
e = s./(s2 + lambda(k)^2); f = s.*e;
x_delta(:,k) = V(:,1:p)*(e.*beta + (1-f).*omega);
end
end
elseif (m>=n)
% The overdetermined or square genera-form case.
omega = omega(1:p); gamma = s(:,1)./s(:,2);
x_u = V(:,p+1:n)*beta(p+1:n);
for k=1:ld
if (delta(k)^2 >= norm(beta(1:p) - s(:,1).*omega)^2 + delta_0^2)
x_delta(:,k) = V*[omega;U(:,p+1:n)'*b];
else
[dummy,kmin] = min(abs(rho - delta(k)^2));
lambda_0 = gamma(kmin);
lambda(k) = newton(lambda_0,delta(k),s,beta(1:p),omega,delta_0);
e = gamma./(gamma.^2 + lambda(k)^2); f = gamma.*e;
x_delta(:,k) = V(:,1:p)*(e.*beta(1:p)./s(:,2) + ...
(1-f).*s(:,2).*omega) + x_u;
end
end
else
% The underdetermined general-form case.
omega = omega(1:p); gamma = s(:,1)./s(:,2);
x_u = V(:,p+1:m)*beta(p+1:m);
for k=1:ld
if (delta(k)^2 >= norm(beta(1:p) - s(:,1).*omega)^2 + delta_0^2)
x_delta(:,k) = V*[omega;U(:,p+1:m)'*b];
else
[dummy,kmin] = min(abs(rho - delta(k)^2));
lambda_0 = gamma(kmin);
lambda(k) = newton(lambda_0,delta(k),s,beta(1:p),omega,delta_0);
e = gamma./(gamma.^2 + lambda(k)^2); f = gamma.*e;
x_delta(:,k) = V(:,1:p)*(e.*beta(1:p)./s(:,2) + ...
(1-f).*s(:,2).*omega) + x_u;
end
end
end
%-------------------------------------------------------------------
function lambda = newton(lambda_0,delta,s,beta,omega,delta_0)
%NEWTON Newton iteration (utility routine for DISCREP).
%
% lambda = newton(lambda_0,delta,s,beta,omega,delta_0)
%
% Uses Newton iteration to find the solution lambda to the equation
% || A x_lambda - b || = delta ,
% where x_lambda is the solution defined by Tikhonov regularization.
%
% The initial guess is lambda_0.
%
% The norm || A x_lambda - b || is computed via s, beta, omega and
% delta_0. Here, s holds either the singular values of A, if L = I,
% or the c,s-pairs of the GSVD of (A,L), if L ~= I. Moreover,
% beta = U'*b and omega is either V'*x_0 or the first p elements of
% inv(X)*x_0. Finally, delta_0 is the incompatibility measure.
% Reference: V. A. Morozov, "Methods for Solving Incorrectly Posed
% Problems", Springer, 1984; Chapter 26.
% Per Christian Hansen, IMM, 12/29/97.
% Set defaults.
thr = sqrt(eps); % Relative stopping criterion.
it_max = 50; % Max number of iterations.
% Initialization.
if (lambda_0 < 0)
error('Initial guess lambda_0 must be nonnegative')
end
[p,ps] = size(s);
if (ps==2), sigma = s(:,1); s = s(:,1)./s(:,2); end
s2 = s.^2;
% Use Newton's method to solve || b - A x ||^2 - delta^2 = 0.
% It was found experimentally, that this formulation is superior
% to the formulation || b - A x ||^(-2) - delta^(-2) = 0.
lambda = lambda_0; step = 1; it = 0;
while (abs(step) > thr*lambda & abs(step) > thr & it < it_max), it = it+1;
f = s2./(s2 + lambda^2);
if (ps==1)
r = (1-f).*(beta - s.*omega);
z = f.*r;
else
r = (1-f).*(beta - sigma.*omega);
z = f.*r;
end
step = (lambda/4)*(r'*r + (delta_0+delta)*(delta_0-delta))/(z'*r);
lambda = lambda - step;
% If lambda < 0 then restart with smaller initial guess.
if (lambda < 0), lambda = 0.5*lambda_0; lambda_0 = 0.5*lambda_0; end
end
% Terminate with an error if too many iterations.
if (abs(step) > thr*lambda & abs(step) > thr)
error(['Max. number of iterations (',num2str(it_max),') reached'])
end
|
github
|
andreafarina/SOLUS-master
|
corner.m
|
.m
|
SOLUS-master/src/util/regu/corner.m
| 8,640 |
utf_8
|
1fc59ce57e9ede542069ef7b1fce444d
|
function [k_corner,info] = corner(rho,eta,fig)
%CORNER Find corner of discrete L-curve via adaptive pruning algorithm.
%
% [k_corner,info] = corner(rho,eta,fig)
%
% Returns the integer k_corner such that the corner of the log-log
% L-curve is located at ( log(rho(k_corner)) , log(eta(k_corner)) ).
%
% The vectors rho and eta must contain corresponding values of the
% residual norm || A x - b || and the solution's (semi)norm || x ||
% or || L x || for a sequence of regularized solutions, ordered such
% that rho and eta are monotonic and such that the amount of
% regularization decreases as k increases.
%
% The second output argument describes possible warnings.
% Any combination of zeros and ones is possible.
% info = 000 : No warnings - rho and eta describe a discrete
% L-curve with a corner.
% info = 001 : Bad data - some elements of rho and/or eta are
% Inf, NaN, or zero.
% info = 010 : Lack of monotonicity - rho and/or eta are not
% strictly monotonic.
% info = 100 : Lack of convexity - the L-curve described by rho
% and eta is concave and has no corner.
%
% The warnings described above will also result in text warnings on the
% command line. Type 'warning off Corner:warnings' to disable all
% command line warnings from this function.
%
% If a third input argument is present, then a figure will show the discrete
% L-curve in log-log scale and also indicate the found corner.
% Reference: P. C. Hansen, T. K. Jensen and G. Rodriguez, "An adaptive
% pruning algorithm for the discrete L-curve criterion," J. Comp. Appl.
% Math., 198 (2007), 483-492.
% Per Christian Hansen and Toke Koldborg Jensen, IMM, DTU;
% Giuseppe Rodriguez, University of Cagliari, Italy; March 22, 2006.
% Initialization of data
rho = rho(:); % Make rho and eta column vectors.
eta = eta(:);
if (nargin < 3) | isempty(fig)
fig = 0; % Default is no figure.
elseif fig < 0,
fig = 0;
end
info = 0;
fin = isfinite(rho+eta); % NaN or Inf will cause trouble.
nzr = rho.*eta~=0; % A zero will cause trouble.
kept = find(fin & nzr);
if isempty(kept)
error('Too many Inf/NaN/zeros found in data')
end
if length(kept) < length(rho)
info = info + 1;
warning('Corner:warnings', ...
['Bad data - Inf, NaN or zeros found in data\n' ...
' Continuing with the remaining data'])
end
rho = rho(kept); % rho and eta with bad data removed.
eta = eta(kept);
if any(rho(1:end-1)<rho(2:end)) | any(eta(1:end-1)>eta(2:end))
info = info + 10;
warning('Corner:warnings', 'Lack of monotonicity')
end
% Prepare for adaptive algorithm.
nP = length(rho); % Number of points.
P = log10([rho eta]); % Coordinates of the loglog L-curve.
V = P(2:nP,:)-P(1:nP-1,:); % The vectors defined by these coordinates.
v = sqrt(sum(V.^2,2)); % The length of the vectors.
W = V./repmat(v,1,2); % Normalized vectors.
clist = []; % List of candidates.
p = min(5, nP-1); % Number of vectors in pruned L-curve.
convex = 0; % Are the pruned L-curves convex?
% Sort the vectors according to the length, the longest first.
[Y,I] = sort(v);
I = flipud(I);
% Main loop -- use a series of pruned L-curves. The two functions
% 'Angles' and 'Global_Behavior' are used to locate corners of the
% pruned L-curves. Put all the corner candidates in the clist vector.
while p < (nP-1)*2
elmts = sort(I(1:min(p, nP-1)));
% First corner location algorithm
candidate = Angles( W(elmts,:), elmts);
if candidate>0,
convex = 1;
end
if candidate & ~any(clist==candidate)
clist = [clist;candidate];
end
% Second corner location algorithm
candidate = Global_Behavior(P, W(elmts,:), elmts);
if ~any(clist==candidate)
clist = [clist; candidate];
end
p = p*2;
end
% Issue a warning and return if none of the pruned L-curves are convex.
if convex==0
k_corner = [];
info = info + 100;
warning('Corner:warnings', 'Lack of convexity')
return
end
% Put rightmost L-curve point in clist if not already there; this is
% used below to select the corner among the corner candidates.
if sum(clist==1) == 0
clist = [1;clist];
end
% Sort the corner candidates in increasing order.
clist = sort(clist);
% Select the best corner among the corner candidates in clist.
% The philosophy is: select the corner as the rightmost corner candidate
% in the sorted list for which going to the next corner candidate yields
% a larger increase in solution (semi)norm than decrease in residual norm,
% provided that the L-curve is convex in the given point. If this is never
% the case, then select the leftmost corner candidate in clist.
vz = find(diff(P(clist,2)) ... % Points where the increase in solution
>= abs(diff(P(clist,1)))); % (semi)norm is larger than or equal
% to the decrease in residual norm.
if length(vz)>1
if(vz(1) == 1), vz = vz(2:end); end
elseif length(vz)==1
if(vz(1) == 1), vz = []; end
end
if isempty(vz)
% No large increase in solution (semi)norm is found and the
% leftmost corner candidate in clist is selected.
index = clist(end);
else
% The corner is selected as described above.
vects = [P(clist(2:end),1)-P(clist(1:end-1),1) ...
P(clist(2:end),2)-P(clist(1:end-1),2)];
vects = sparse(diag(1./sqrt(sum(vects.^2,2)))) * vects;
delta = vects(1:end-1,1).*vects(2:end,2) ...
- vects(2:end,1).*vects(1:end-1,2);
vv = find(delta(vz-1)<=0);
if isempty(vv)
index = clist(vz(end));
else
index = clist(vz(vv(1)));
end
end
% Corner according to original vectors without Inf, NaN, and zeros removed.
k_corner = kept(index);
if fig % Show log-log L-curve and indicate the found corner.
figure(fig); clf
diffrho2 = (max(P(:,1))-min(P(:,1)))/2;
diffeta2 = (max(P(:,2))-min(P(:,2)))/2;
loglog(rho, eta, 'k--o'); hold on; axis square;
% Mark the corner.
loglog([min(rho)/100,rho(index)],[eta(index),eta(index)],':r',...
[rho(index),rho(index)],[min(eta)/100,eta(index)],':r')
% Scale axes to same number of decades.
if abs(diffrho2)>abs(diffeta2),
ax(1) = min(P(:,1)); ax(2) = max(P(:,1));
mid = min(P(:,2)) + (max(P(:,2))-min(P(:,2)))/2;
ax(3) = mid-diffrho2; ax(4) = mid+diffrho2;
else
ax(3) = min(P(:,2)); ax(4) = max(P(:,2));
mid = min(P(:,1)) + (max(P(:,1))-min(P(:,1)))/2;
ax(1) = mid-diffeta2; ax(2) = mid+diffeta2;
end
ax = 10.^ax; ax(1) = ax(1)/2; axis(ax);
xlabel('residual norm || A x - b ||_2')
ylabel('solution (semi)norm || L x ||_2');
title(sprintf('Discrete L-curve, corner at %d', k_corner));
end
% =========================================================================
% First corner finding routine -- based on angles
function index = Angles( W, kv)
% Wedge products
delta = W(1:end-1,1).*W(2:end,2) - W(2:end,1).*W(1:end-1,2);
[mm kk] = min(delta);
if mm < 0 % Is it really a corner?
index = kv(kk) + 1;
else % If there is no corner, return 0.
index = 0;
end
% =========================================================================
% Second corner finding routine -- based on global behavior of the L-curve
function index = Global_Behavior(P, vects, elmts)
hwedge = abs(vects(:,2)); % Abs of wedge products between
% normalized vectors and horizontal,
% i.e., angle of vectors with horizontal.
[An, In] = sort(hwedge); % Sort angles in increasing order.
% Locate vectors for describing horizontal and vertical part of L-curve.
count = 1;
ln = length(In);
mn = In(1);
mx = In(ln);
while(mn>=mx)
mx = max([mx In(ln-count)]);
count = count + 1;
mn = min([mn In(count)]);
end
if count > 1
I = 0; J = 0;
for i=1:count
for j=ln:-1:ln-count+1
if(In(i) < In(j))
I = In(i); J = In(j); break
end
end
if I>0, break; end
end
else
I = In(1); J = In(ln);
end
% Find intersection that describes the "origin".
x3 = P(elmts(J)+1,1)+(P(elmts(I),2)-P(elmts(J)+1,2))/(P(elmts(J)+1,2) ...
-P(elmts(J),2))*(P(elmts(J)+1,1)-P(elmts(J),1));
origin = [x3 P(elmts(I),2)];
% Find distances from the original L-curve to the "origin". The corner
% is the point with the smallest Euclidian distance to the "origin".
dists = (origin(1)-P(:,1)).^2+(origin(2)-P(:,2)).^2;
[Y,index] = min(dists);
|
github
|
andreafarina/SOLUS-master
|
splsqrL.m
|
.m
|
SOLUS-master/src/util/regu/splsqrL.m
| 5,128 |
utf_8
|
1e24aa441349e75e253fbc2c5296364f
|
function x = splsqr(A,L,b,lambda,Vsp,maxit,tol,reorth)
%SPLSQR Subspace preconditioned LSQR for discrete ill-posed problems.
%
% x = splsqr(A,L,b,lambda,Vsp,maxit,tol,reorth)
%
% Subspace preconditioned LSQR (SP-LSQR) for solving the Tikhonov problem
% min { || A x - b ||^2 + lambda^2 || L x ||^2 }
% with a preconditioner based on the subspace defined by the columns of
% the matrix Vsp. While not necessary, we recommend to use a matrix Vsp
% with orthonormal columns.
%
% If L is the identity matrix, use L = [] for efficiency reasons.
%
% The output x holds all the solution iterates as columns, and the last
% iterate x(:,end) is the best approximation to x_lambda.
%
% The parameter maxit is the maximum allowed number of iterations (default
% value is maxit = 300). The parameter tol is used a stopping criterion
% for the norm of the least squares residual relative to the norm of the
% right-hand side (default value is tol = 1e-12).
%
% A eighth input parameter reorth ~= 0 enforces MGS reorthogonalization
% of the Lanczos vectors.
% This is a model implementation of SP-LSQR. In a real implementation the
% Householder transformations should use LAPACK routines, only the final
% iterate should be returned, and reorthogonalization is not used. Also,
% if Vsp represents a fast transformation (such as the DCT) then explicit
% storage of Vsp should be avoided. See the reference for details.
% Reference: M. Jacobsen, P. C. Hansen and M. A. Saunders, "Subspace pre-
% conditioned LSQR for discrete ill-posed problems", BIT 43 (2003), 975-989.
% Per Christian Hansen and Michael Jacobsen, IMM, July 30, 2007.
% Input check.
if nargin < 6, maxit = 300; end
if nargin < 7, tol = 1e-12; end
if nargin < 8, reorth = 0; end
if maxit < 1, error('Number of iterations must be positive'); end;
% Prepare for SP-LSQR algorithm.
[m,n] = size(A);
k = size(Vsp,2);
isI = isempty(L);
if isI, p = n; else p = size(L,1); end
z = zeros(p,1);
if reorth
UU = zeros(m+p,maxit);
VV = zeros(n,maxit);
end
% Initial QR factorization of [A;lambda*L]*Vsp;
if isI
QQ = qr([A*Vsp;lambda*Vsp]);
else
QQ = qr([A*Vsp;lambda*L*Vsp]);
end
% Prepare for LSQR iterations.
u = app_house_t(QQ,[b;z]);
u(1:k) = 0;
beta = norm(u);
u = u/beta;
v = app_house(QQ,u);
if isI
v = A'*v(1:m) + lambda*v(m+1:end);
else
v =A'*v(1:m) + lambda*L'*v(m+1:end);
end
alpha = norm(v);
v = v/alpha;
w = v;
Wxw = zeros(n,1);
phi_bar = beta;
rho_bar = alpha;
if reorth, UU(:,1) = u; VV(:,1) = v; end;
for i=1:maxit
% beta*u = [A;lambda*L]*v - alpha*u;
if isI
uu = [A*v;lambda*v];
else
uu = [A*v;lambda*L*v];
end
uu = app_house_t(QQ,uu);
uu(1:k) = 0;
u = uu - alpha*u;
if reorth
for j=1:i-1, u = u - (UU(:,j)'*u)*UU(:,j); end
end
beta = norm(u);
u = u/beta;
% alpha * v = [A;lambda*L]'*u - beta*v;
vv = app_house(QQ,u);
if isI
v = A'*vv(1:m) + lambda*vv(m+1:end) - beta*v;
else
v = A'*vv(1:m) + lambda*L'*vv(m+1:end) - beta*v;
end
if reorth
for j=1:i-1, v = v - (VV(:,j)'*v)*VV(:,j); end
end
alpha = norm(v);
v = v/alpha;
if reorth, UU(:,i) = u; VV(:,i) = v; end;
% Update LSQR parameters.
rho = norm([rho_bar beta]);
c = rho_bar/rho;
s = beta/rho;
theta = s*alpha;
rho_bar = -c*alpha;
phi = c*phi_bar;
phi_bar = s*phi_bar;
% Update the LSQR solution.
Wxw = Wxw + (phi/rho)*w;
w = v - (theta/rho)*w;
% Compute residual and update the SP-LSQR iterate.
if isI
r = [b - A*Wxw ; -lambda*Wxw];
else
r = [b - A*Wxw ; -lambda*L*Wxw];
end
r = app_house_t(QQ,r);
r = r(1:k);
xv = triu(QQ(1:k,:))\r;
x(:,i) = Vsp*xv + Wxw;
% Stopping criterion.
if phi_bar*alpha*abs(c) < tol*norm(b), break, end
end
%-----------------------------------------------------------------
function Y = app_house(H,X)
% Y = app_house(H,X)
% Input: H = matrix containing the necessary information of the
% Householder vectors v in the lower triangle and R in
% the upper triangle; e.g., computed as H = qr(A).
% X = matrix to be multiplied with orthogonal matrix.
% Output: Y = Q*X
[n,p] = size(H);
Y = X;
for k = p:-1:1
v = ones(n+1-k,1);
v(2:n+1-k) = H(k+1:n,k);
beta = 2/(v'*v);
Y(k:n,:) = Y(k:n,:) - beta*v*(v'*Y(k:n,:));
end
%-----------------------------------------------------------------
function Y = app_house_t(H,X)
% Y = app_house_t(H,X)
% Input: H = matrix containing the necessary information of the
% Householder vectors v in the lower triangle and R in
% the upper triangle; e.g., computed as H = qr(A).
% X = matrix to be multiplied with transposed orthogonal matrix.
% Output: Y = Q'*X
[n,p] = size(H);
Y = X;
for k = 1:p
v = ones(n+1-k,1);
v(2:n+1-k) = H(k+1:n,k);
beta = 2/(v'*v);
Y(k:n,:) = Y(k:n,:) - beta*v*(v'*Y(k:n,:));
end
|
github
|
andreafarina/SOLUS-master
|
RecSolverTK0_TD.m
|
.m
|
SOLUS-master/src/solvers/RecSolverTK0_TD.m
| 5,808 |
utf_8
|
d062281845b0da893711d62f1f5c8a01
|
%==========================================================================
% This function contains solvers for DOT or fDOT.
% To have available all the functionalty install REGU toolbox
% Andrea Farina 12/16
% Andrea Farina 11/2020: simplified normalizations of X, Jac, Data, dphi
%==========================================================================
function [bmua,bmus,reg_par] = RecSolverTK0_TD(solver,grid,mua0,mus0, n, A,...
Spos,Dpos,dmask, dt, nstep, twin, self_norm, data, irf, ref, sd, type_fwd, lambda)
%% Jacobain options
LOAD_JACOBIAN = solver.prejacobian.load; % Load a precomputed Jacobian
geom = 'semi-inf';
xtransf = '(x/x0)'; %log(x),x,log(x/x0)
type_ratio = 'gauss'; % 'gauss', 'born', 'rytov';
type_ref = 'theor'; % 'theor', 'meas', 'area'
%% REGULARIZATION PARAMETER CRITERION
%REGU = 'external'; % 'lcurve', 'gcv', 'external'
REGU = 'lcurve';
BACKSOLVER = 'tikh'; % 'tikh', 'tsvd', 'discrep','simon', 'gmres', 'pcg', 'lsqr'
% -------------------------------------------------------------------------
[~,type] = ExtractVariables(solver.variables);
% if rytov and born jacobian is normalized to proj
if strcmpi(type_ratio,'rytov')||strcmpi(type_ratio,'born')
logdata = true;
else
logdata = false;
end
Jacobian = @(mua, mus) JacobianTD (grid, Spos, Dpos, dmask, mua, mus, n, A, ...
dt, nstep, twin, irf, geom,type,type_fwd,self_norm,logdata);
% homogeneous forward model
[proj, ~] = ForwardTD(grid,Spos, Dpos, dmask, mua0, mus0, n, ...
[],[], A, dt, nstep, 0, geom, 'linear', irf);
proj = WindowTPSF(proj,twin);
if self_norm
proj = NormalizeTPSF(proj);
end
% ref = proj;
[dphi,sd] = PrepareDataFitting(data,ref,sd,type_ratio,type_ref,proj);
% creat mask for nan, ising
mask = (isnan(dphi(:))) | (isinf(dphi(:)));
dphi(mask) = [];
% solution vector
[x0,x] = PrepareX([mua0,1./(3*mus0)],grid.N,type,xtransf);
% ---------------------- Construct the Jacobian ---------------------------
if LOAD_JACOBIAN == true
fprintf (1,'Loading Jacobian\n');
tic;
%load([jacdir,jacfile])
load(solver.prejacobian.path);
toc;
else
%fprintf (1,'Calculating Jacobian\n');
tic;
J = Jacobian ( mua0, mus0);
[jpath,~,~] = fileparts(solver.prejacobian.path);
if ~exist(jpath,'dir')
mkdir(jpath)
end
save(solver.prejacobian.path,'J');
toc;
end
if ~isempty(solver.prior.refimage)
%d1 = (solver.prior(:) > 0 )&(solver.prior(:)==min(solver.prior(:)));
d1 = solver.prior.refimage(:) > mean(solver.prior.refimage(:));
d2 = ~d1;
if mean(solver.prior.refimage(d1))<mean(solver.prior.refimage(d2))
d1 = ~d1;
d2 = ~d2;
end
%(solver.prior(:) > min(solver.prior(:)))&(solver.prior(:)==max(solver.prior(:)));
D = [d1(:),d2(:)];
J = J * D;
end
% sd jacobian normalization
J = spdiags(1./sd(:),0,numel(sd),numel(sd)) * J;
nsol = size(J,2);
% parameter normalisation (scale x0)
if ~strcmpi(xtransf,'x')
J = J * spdiags(x0,0,length(x0),length(x0));
end
J(mask,:) = [];
%% ====== Solver =======
disp('Calculating singolar values');
%if ~strcmpi((BACKSOLVER),'simon')
[U,s,V]=csvd(J); % compact SVD (Regu toolbox)
figure(402);
picard(U,s,dphi); % Picard plot (Regu toolbox)
%end
if (~strcmpi(REGU,'lcurve')&&(~strcmpi(REGU,'gcv')))
alpha = solver.tau * s(1);
end
if ~exist('alpha','var')
fig = figure(403);
fig.Name = ['Lambda' num2str(lambda)];
if strcmpi(REGU,'lcurve')
alpha = l_curve(U,s,dphi);%,BACKSOLVER); % L-curve (Regu toolbox)
elseif strcmpi(REGU,'gcv')
alpha = gcv(U,s,dphi);%,BACKSOLVER)
end
end
disp(['tau = ' num2str(alpha/s(1))]);
disp('Solving...')
switch lower(BACKSOLVER)
case 'tikh'
disp('Tikhonov');
[dx,~] = tikhonov(U,s,V,dphi,alpha);
case 'tsvd'
disp('TSVD');
[dx,~] = tsvd(U,s,V,dphi,alpha);
case 'discrep'
disc_value = norm(sd(~mask))*10;
disp(['Discrepancy principle with value=' num2str(disc_value)]);
dx = discrep(U,s,V,dphi,disc_value);
case 'simon'
disp('Simon');
% tic;
% s1 = svds(J,1);
% toc;
% alpha = solver.tau * s1;
dx = [J;sqrt(alpha)*speye(nsol)]\[dphi;zeros(nsol,1)];
%dx = [dx;zeros(nsol,1)];
%rho
%cond(J)
%dx = [dx;zeros(nsol,1)];
%dx = [J;alpha*eye(2*nsol)]\[dphi;zeros(2*nsol,1)];
%dx = lsqr(J,dphi,1e-4,100);
%dx = pcg(@(x)JTJH(x,J,eye(2*nsol),alpha),J'*dphi,1e-4,100);
case 'gmres'
disp('gmres')
if strcmpi(REGU,'external')
lambda = sum(sum(J.^2));
alpha = lambda * alpha;
end
dx = gmres(@(x)JTJH(x,J,eye(nsol),alpha),J'*dphi,[],1e-6,100);
case 'pcg'
disp('pcg')
tic;
if strcmpi(REGU,'external')
lambda = sum(sum(J.^2));
alpha = alpha * lambda;
disp(['alpha=' num2str(alpha)]);
end
%dx = pcg(J'*J + alpha*speye(nsol),J'*dphi,1e-6,100);
dx = pcg(@(x)JTJH(x, J, speye(nsol),alpha),J'*dphi,1e-6,1000);
case 'lsqr'
disp('lsqr');
tic;
if strcmpi(REGU,'external')
lambda = sum(sum(J.^2));
alpha = alpha * lambda;
disp(['alpha=' num2str(alpha)]);
end
dx = lsqr([J;alpha*speye(nsol)],[dphi;zeros(nsol,1)],1e-6,200);
toc;
%dx = J' * ((J*J' + alpha*eye(length(data)))\dphi);
end
%==========================================================================
%% Add update to solution
%==========================================================================
if ~isempty(solver.prior.refimage)
dx = D * dx;
end
x = x + dx;
x = BackTransfX(x,x0,xtransf);
[bmua,bmus] = XtoMuaMus(x,mua0,mus0,type);
reg_par = alpha;
end
|
github
|
andreafarina/SOLUS-master
|
RecSolverL1_TD_.m
|
.m
|
SOLUS-master/src/solvers/RecSolverL1_TD_.m
| 4,567 |
utf_8
|
71ec8697b0a2f9804c46ee57893e22bf
|
%==========================================================================
% This function contains solvers for DOT or fDOT.
% To have available all the functionalty install REGU toolbox
% Andrea Farina 12/16
%==========================================================================
function [bmua,bmus] = RecSolverL1_TD(solver,grid,mua0,mus0, n, A,...
Spos,Dpos,dmask, dt, nstep, twin, self_norm, data, irf, ref, sd, ~)
%% Jacobain options
LOAD_JACOBIAN = false; % Load a precomputed Jacobian
geom = 'semi-inf';
%% SOLVER PARAMETER CRITERION
LSQRit = 40; % solve LSQR with small number of iterations
LSQRtol = 1e-6; % tolerence of LSQR
% ISTA FLAGS
ISTA_FLAGS.FISTA= true;
ISTA_FLAGS.pos = true;
ISTA_FLAGS.Wavelets =true;
ISTA_FLAGS.Iterates = true;
%% path
%rdir = ['../results/test/precomputed_jacobians/'];
jacdir = ['../results/test/precomputed_jacobians/'];
jacfile = 'J';
%mkdir(rdir);
%disp(['Intermediate results will be stored in: ' rdir])
%save([rdir 'REC'], '-v7.3','REC'); %save REC structure which describes the experiment
% -------------------------------------------------------------------------
bdim = (grid.dim);
nQM = sum(dmask(:));
nwin = size(twin,1);
Jacobian = @(mua, mus) JacobianTD (grid, Spos, Dpos, dmask, mua, mus, n, A, ...
dt, nstep, twin, irf, geom);
%% Inverse solver
[proj, Aproj] = ForwardTD(grid,Spos, Dpos, dmask, mua0, mus0, n, ...
[],[], A, dt, nstep, self_norm,...
geom, 'homo');
if numel(irf)>1
for i = 1:nQM
z(:,i) = conv(proj(:,i),irf);
end
proj = z(1:numel(irf),:);
if self_norm == true
proj = proj * spdiags(1./sum(proj)',0,nQM,nQM);
end
clear z
end
proj = WindowTPSF(proj,twin);
proj = proj(:);
ref = ref(:);
data = data(:);
factor = proj./ref;
data = data .* factor;
ref = ref .* factor;
%% data scaling
sd = sd(:).*sqrt(factor);
%sd = proj(:);
%sd = ones(size(proj(:)));
%% mask for excluding zeros
mask = ((ref(:).*data(:)) == 0) | ...
(isnan(ref(:))) | (isnan(data(:)));
%mask = false(size(mask));
if ref == 0
ref = proj(:);
end
ref(mask) = [];
data(mask) = [];
%sd(mask) = [];
% solution vector
x = ones(grid.N,1) * mua0;
x0 = x;
p = length(x);
dphi = (data(:)-ref(:))./sd(~mask);%./ref(:);
%dphi = log(data(:)) - log(ref(:));
%save('dphi','dphi');
% ---------------------- Construct the Jacobian ---------------------------
if LOAD_JACOBIAN == true
fprintf (1,'Loading Jacobian\n');
tic;
load([jacdir,jacfile])
toc;
else
fprintf (1,'Calculating Jacobian\n');
tic;
J = Jacobian ( mua0, mus0);
save([jacdir,jacfile],'J');
toc;
end
if ~isempty(solver.prior)
d1 = (solver.prior(:) > 0 )&(solver.prior(:)==min(solver.prior(:)));
d2 = (solver.prior(:) > min(solver.prior(:)))&(solver.prior(:)==max(solver.prior(:)));
D = [d1(:),d2(:)];
J = J * D;
end
if self_norm == true
for i=1:nQM
sJ = sum(J((1:nwin)+(i-1)*nwin,:));
sJ = repmat(sJ,nwin,1);
sJ = spdiags(proj((1:nwin)+(i-1)*nwin),0,nwin,nwin) * sJ;
J((1:nwin)+(i-1)*nwin,:) = (J((1:nwin)+(i-1)*nwin,:) - sJ)./Aproj(i);
end
end
J = spdiags(1./sd(:),0,numel(sd),numel(sd)) * J; % data normalisation
nsol = size(J,2);
% parameter normalisation (map to log)
% for i = 1:p
% J(:,i) = J(:,i) * x(i);
% end
% ------- to solve only for mua uncomment the following sentence ----------
%J(:,nsol+(1:nsol)) = 0;
proj(mask) = [];
J(mask,:) = [];
%% now ISTA (slow!)
lambda = sum(sum(J.^2));
xista = zeros(size(x0));
Niter = 5000/1;
tau = 2/lambda;
T = 1e-5;
tic
h = waitbar(0,'ISTA iterations');
for k = 1:Niter
xista = SoftThresh(xista + tau*J'*(dphi - J*xista),T);
waitbar(k/Niter);
end
toc;
disp('solved using ISTA');
dx = xista;
%% Let's try shrinkage-Newton
% xsn = zeros(size(x0));
% NSNit = ceil(5000/4);
% T = 1e-5;%0.02;
% alpha = 0;
% tic;
% h = waitbar(0,'iteration');
% for k = 1:NSNit
% % xsn = SoftThresh(xsn + lsqr([J; alpha*lambda*speye(nsol)],[dphi-J*xsn;zeros(nsol,1)],1e-1,5),T );
% % xsn = SoftThresh(xsn + (J'*a + alpha*lambda*speye(nsol))\J'*(dphi-J*xsn),T );
% %xsn = SoftThresh(xsn + pcg(J'*J + alpha*lambda*speye(nsol),J'*(dphi-J*xsn),1e-6,100),T);
% waitbar(k/NSNit);
% end
%toc;
%disp('solved using shrinkage-Newton');
%% update solution
x = x + dx;
%logx = logx + dx;
%x = exp(logx);
bmua = x;
bmus = ones(size(bmua)) * mus0;
end
|
github
|
andreafarina/SOLUS-master
|
FitVoxel.m
|
.m
|
SOLUS-master/src/solvers/FitVoxel.m
| 1,246 |
utf_8
|
814d3aee178f4f2b0dcc28baf8428dea
|
function [fbmua,fbmus,fbConc,fbA,fbbB]=FitVoxel(bmua,bmus,spe)
nL = spe.nLambda;
nV = size(bmua,1);
opts = optimoptions('lsqcurvefit',...
'Jacobian','off',...
...'Algorithm','levenberg-marquardt',...
'DerivativeCheck','off',...
'MaxIter',100,'Display','none','FinDiffRelStep',repmat(1e-5,2,1));%,'TolFun',1e-10,'TolX',1e-10)
fbmua = zeros(nV,nL); fbmus = zeros(nV,nL);
fbConc = zeros(nV,spe.nCromo); fbA = zeros(nV,1); fbbB = zeros(nV,1);
for iv = 1:nV
fbConc(iv,:) = spe.ext_coeff0\bmua(iv,:)';
x = lsqcurvefit(@forward,ones(2,1),[],bmus(iv,:),[],[],opts);% x0 = x;
fbA(iv) = x(1);fbbB(iv) = x(2);
fbmus(iv,:) = x(1).*(spe.lambda./spe.lambda0).^(-x(2));
fbmua(iv,:) = spe.ext_coeff0*fbConc(iv,:)';
if rem(iv,1000)==0, display(['Voxel : ' num2str(iv) '/' num2str(nV)]); end
end
err_mus = (fbmus-bmus)./bmus *100;
err_mua = (fbmua-bmua)./bmua *100;
display(mean(err_mus,1));
display(mean(err_mua,1));
function [mus] = forward(x,~)
mus = x(1).*(spe.lambda./spe.lambda0).^(-x(2));
% mus = mus';
% figure(345)
% subplot(1,2,1),plot(spe.lambda,[data(1:nL) mua]), legend('data_mua','fit_mua')
% subplot(1,2,2),plot(spe.lambda,[data(nL+1:end) mus]), legend('data_mus','fit_mus')
% display(x')
end
end
|
github
|
andreafarina/SOLUS-master
|
SpectralFitConcAB_TD.m
|
.m
|
SOLUS-master/src/solvers/SpectralFitConcAB_TD.m
| 12,999 |
utf_8
|
bd7e1ac5ac742c497e6277031ba22e18
|
%==========================================================================
% This function contains a solver for fitting optical properties of
% homogeneous phantom using routines in Matlab Optimization Toolbox
%
% Andrea Farina 10/15
%==========================================================================
function [bMua, bMusp, bConc,bB, bA] = SpectralFitConcAB_TD(solver,grid, conc0,a0,b0, n, A,...
Spos,Dpos,dmask, dt, nstep, twin, self_norm, data, irf, ref, sd,TYPE_FWD,radiometry,spe,geometry)
BULK = 1;% set to 1 if wanting to fit the bulk.
INCL = 1;% set to 1 if wanting to fit the inclusion defined by refimage
% set to INCL = 0 and BULK = 1 to make a homogenous fit
geom = geometry;
refimage = solver.prior.refimage;
self_norm = true;
if strcmpi(TYPE_FWD, 'linear')
warning('TYPE_FWD set to linear but it should be fem instead. TYPE_FWD set to fem')
TYPE_FWD = 'fem';
end
weight_type = 'none';%'none'
min_func = 'lsqrfit';%'lsqrcurvefit'
first_lim = 0.1; last_lim = 0.1;
ForceConstitSolution = spe.ForceConstitSolution;
nQM = sum(dmask(:));
nwin = size(twin,1);
%% Inverse solver
mua0 = (spe.ext_coeff0*conc0)';
mus0 = (a0 .* (spe.lambda./spe.lambda0).^(-b0));
[proj, Aproj] = ForwardTD_multi_wave(grid,Spos, Dpos, dmask, mua0, mus0, n, ...
[],[], A, dt, nstep, self_norm,...
geom,TYPE_FWD,radiometry);
if numel(irf)>1
for inl = 1:radiometry.nL
meas_set = (1:nQM)+(inl-1)*nQM;
proj_single = proj(:,meas_set);
z = convn(proj_single,irf(:,inl));
nmax = max(nstep,numel(irf(:,inl)));
proj_single = z(1:nmax,:);
clear nmax
if self_norm == true
proj_single = proj_single * spdiags(1./sum(proj_single,'omitnan')',0,nQM,nQM);
end
clear z
if inl == 1
proj(1:size(proj_single),meas_set) = proj_single;
proj(size(proj_single,1)+1:end,:) = [];
else
proj(1:size(proj_single,1),meas_set) = proj_single;
end
end
end
if self_norm == true
for inl = 1:radiometry.nL
meas_set = (1:nQM)+(inl-1)*nQM;
data_single = data(:,meas_set);
data_single = data_single * spdiags(1./sum(data_single,'omitnan')',0,nQM,nQM);
ref_single = ref(:,meas_set);
ref_single = ref_single * spdiags(1./sum(ref_single,'omitnan')',0,nQM,nQM);
data(:,meas_set) = data_single;
ref(:,meas_set) = ref_single;
end
end
dummy_proj = zeros(size(twin,1),nQM*radiometry.nL);
for inl = 1:radiometry.nL
meas_set =(1:nQM)+(inl-1)*nQM; twin_set = (1:2)+(inl-1)*2;
proj_single = proj(:,meas_set);
proj_single = WindowTPSF(proj_single,twin(:,twin_set));
if self_norm == true
proj_single = proj_single * spdiags(1./sum(proj_single,'omitnan')',0,nQM,nQM);
end
dummy_proj(:,meas_set) = proj_single;
end
weight = ones(nwin,nQM*radiometry.nL);
if ~strcmpi(weight_type,'none')
weight = zeros(nwin,nQM*radiometry.nL);
interval = zeros(2,nQM*radiometry.nL);
for im = 1:nQM*radiometry.nL
idx1 = find(ref(:,im)>max(ref(:,im)*first_lim),1,'first');
idx2 = find(ref(:,im)>max(ref(:,im)*last_lim),1,'last');
weight(idx1:idx2,im) = 1;
interval(1,im) = idx1+(im-1)*nwin;
interval(2,im) = idx2+(im-1)*nwin;
end
weight = weight(:);
figure, semilogy(ref(:)), vline(interval(:),'r');
ref =ref(:).*weight;
end
proj = dummy_proj;
proj = proj(:);
data = data(:);
ref = ref(:);
%factor = proj./ref;
%data = data .* factor;
%ref = ref .* factor;
%% data scaling
%sd = sd(:).*(factor);
%% mask for excluding zeros
mask = ((ref(:).*data(:)) == 0) | ...
(isnan(ref(:))) | (isnan(data(:)));
%mask = false(size(mask));
if ref == 0
ref = proj(:);
end
ref(mask) = [];
data(mask) = [];
proj(mask) = [];
%weight(mask) = [];
figure(1002);semilogy([proj,data]),legend('proj','ref')
sd = sqrt(ref);%%ones(size(proj));%proj(:);
%sd = ones(size(data));
data = data./sd;
%% solution vector
% x = [mua0;mus0;-0]; % [mua0,mus0,t0]
%% Setup optimization for lsqcurvefit
if spe.SPECTRA == 0 && ForceConstitSolution == false
FinDiffRelStep = 10*repmat(1e-3,spe.nLambda*2,INCL+BULK);
else
FinDiffRelStep = 10*repmat(1e-3,spe.nCromo+2,INCL+BULK);
end
%% Setup optimization for lsqnonlin
% opts = optimoptions('lsqnonlin',...
% 'Jacobian','off',...
% ...'Algorithm','levenberg-marquardt',...
% 'DerivativeCheck','off',...
% 'MaxIter',20,'Display','iter-detailed')
%% Setup optimization for fminunc
% opts = optimoptions('fminunc','GradObj','on','Algorithm','quasi-newton','MaxIter',2,...
% 'Display','iter')
%% initialise solution vector
if (BULK == 1) && (INCL == 1)
x0 = [[conc0', a0, b0];[conc0', a0, b0]];
elseif ( (BULK == 0) && (INCL == 1) )|| ((BULK == 1) && (INCL == 0))
x0 = [conc0', a0, b0];
xB = x0;
else
disp('No region to fit has been selected')
return;
end
%% Solve
%x = fminsearch(@objective,x0);
if spe.SPECTRA == 0 && ForceConstitSolution == false
% x0 = {mua0 mus0};
low_bound = zeros(INCL + BULK,numel([x0{:}]));
else
if ForceConstitSolution
spe.opt.conc0 = ones(spe.nCromo,1).*spe.active_cromo';
spe.opt.a0 = 1; spe.opt.b0 = 1;
end
% x0 = {spe.opt.conc0',[spe.opt.a0 spe.opt.b0]};
low_bound = zeros(INCL + BULK,spe.nCromo+2);
end
if strcmpi(min_func,'lsqrfit')
opts = optimoptions('lsqcurvefit',...
'Jacobian','off',...
'Algorithm','trust-region-reflective',...
'DerivativeCheck','off',...
'MaxIter',200*radiometry.nL,'Display','iter-detailed',...
'FinDiffRelStep', FinDiffRelStep,'TolFun',1e-10,'TolX',1e-10);
[x,res] = lsqcurvefit(@comp_forward,x0,[],data,low_bound,[],opts);
elseif strcmpi(min_func,'fminunc')
opts = optimoptions('fminunc',...
'Algorithm','quasi-newton',...
'Display','iter-detailed',...
'GradObj','off',...
'MaxIter',200 * radiometry.nL);
[x, res] = fminunc(@Loss_func,x0, opts);
end
%x0 = [t0 x0{:}];
%[x,res] = lsqcurvefit(@forward,x0,[],data,low_bound,[],opts);
%x = lsqnonlin(@objective2,x0,[],[],opts);
%% display fit result
disp(['Residual: ' num2str(res)])
% chromofores, b & a
if ((BULK == 1) && (INCL == 1))
bConc = x(1,1:end-2) .* ~refimage(:) + x(2,1:end-2) .* refimage(:);
bA = x(1,end-1) * ~refimage(:) + x(2,end-1) * refimage(:);
bB = x(1,end) * ~refimage(:) + x(2,end) * refimage(:);
elseif ((BULK == 1) && (INCL == 0))
bConc = x(1,1:end-2)' .* ones(size(refimage(:)));
bA = x(1,end-1) * ones(size(refimage(:))) ;
bB = x(1,end) * ones(size(refimage(:)));
elseif (BULK == 0) && (INCL == 1 )
bConc = xB(1,1:end-2) .* ~refimage(:) + x(2,1:end-2) .* refimage(:);
bA = xB(1,end-1) * ~refimage(:) + x(2,end-1) * refimage(:);
bB = xB(1,end) * ~refimage(:) + x(2,end) * refimage(:);
end
% Optical Coefficients from chromofores, b & a
bMua = (spe.ext_coeff0 * bConc(:,:)')' ;
bMusp = bA.*(spe.lambda./spe.lambda0).^(-bB);
return
%% extract the amplitude area
self_norm = 0;
mask = true(nwin*nQM,1);
[proj_fit, Aproj_fit] = ForwardTD_multi_wave(grid,Spos, Dpos, dmask, bmua, bmus, n, ...
[],[], A, dt, nstep, self_norm,...
geom, TYPE_FWD,radiometry);
% proj_fit = circshift(proj_fit,round(x(3)/dt));
if numel(irf)>1
z = convn(proj_fit,irf);
nmax = max(nstep,numel(irf));
proj_fit = z(1:nmax,:);
clear nmax
end
proj_fit = WindowTPSF(proj_fit,twin);
Aproj_fit = sum(proj_fit);
A_data = sum(data2);
factor = Aproj_fit./A_data;
save('factor_ref.mat','factor');
%% Callback function OBJECTIVE for forward problem
function [proj,J] =comp_forward(x,~)
%xx = [x(1)*ones(nsol,1);x(2)*ones(nsol,1)];
if spe.SPECTRA == 0 && ForceConstitSolution == false
mua = x(2:spe.nLambda+1);
mus = x(spe.nLambda+2:end);
else
if (BULK == 1) && (INCL == 1)
b_out = x(1,end); a_out = x(1,end-1); conc_out = x(1,1:end-2).*spe.active_cromo;
b_in = x(2,end); a_in = x(2,end-1); conc_in = x(2,1:end-2).*spe.active_cromo;
mua_out = (spe.ext_coeff0*conc_out');
mus_out = a_out.*(spe.lambda./spe.lambda0).^(-b_out);
mua_in = (spe.ext_coeff0*conc_in');
mus_in = (a_in.*(spe.lambda./spe.lambda0).^(-b_in));
mua = zeros([size(refimage), radiometry.nL]);
mus = zeros([size(refimage), radiometry.nL]);
for inL = 1: radiometry.nL
mua(:,:,:, inL) = mua_out(inL) * (1 -refimage) + mua_in(inL) * refimage;
mus(:,:,:, inL) = mus_out(inL) * (1 -refimage) + mus_in(inL) * refimage;
end
elseif (BULK == 1) && (INCL == 0)
b_out = x(1,end); a_out = x(1,end-1); conc_out = x(1,1:end-2).*spe.active_cromo;
mua_out = (spe.ext_coeff0*conc_out');
mus_out = a_out.*(spe.lambda./spe.lambda0).^(-b_out);
mua = zeros([size(refimage), radiometry.nL]);
mus = zeros([size(refimage), radiometry.nL]);
for inL = 1: radiometry.nL
mua(:,:,:, inL) = mua_out(inL) * ones(size(refimage));
mus(:,:,:, inL) = mus_out(inL) * ones(size(refimage));
end
elseif (BULK == 0) && (INCL == 1 )
b_out = xB(1,end); a_out = xB(1,end-1); conc_out = xB(1,1:end-2).*spe.active_cromo;
b_in = x(1,end); a_in = x(1,end-1); conc_in = x(1,1:end-2).*spe.active_cromo;
mua_out = (spe.ext_coeff0*conc_out');
mus_out = a_out.*(spe.lambda./spe.lambda0).^(-b_out);
mua_in = (spe.ext_coeff0*conc_in');
mus_in = (a_in.*(spe.lambda./spe.lambda0).^(-b_in));
mua = zeros([size(refimage), radiometry.nL]);
mus = zeros([size(refimage), radiometry.nL]);
for inL = 1: radiometry.nL
mua(:,:,:, inL) = mua_out(inL) * ~(refimage) + mua_in(inL) * refimage;
mus(:,:,:, inL) = mus_out(inL) * ~(refimage) + mus_in(inL) * refimage;
end
end
end
[proj, Aproj] = ForwardTD_multi_wave(grid,Spos, Dpos, dmask, mua_out, mus_out, n, ...
mua,mus, A, dt, nstep, self_norm,...
geom,TYPE_FWD,radiometry);
if spe.SPECTRA == 0 && ForceConstitSolution == false
display(['mua = ',num2str(mua)]);
display(['musp = ',num2str(mus)]);
else
if BULK == 1
disp('bulk:');disp(spe.cromo_label); disp(conc_out); disp({'a','b'}); disp([a_out b_out]);
end
if INCL == 1
disp('inclusion:');disp(spe.cromo_label); disp(conc_in); disp({'a','b'}); disp([a_in b_in]);
end
end
% [~,proj] = Contini1997(0,(1:nstep)*dt/1000,20,mua(1),mus(1),1,n(1),'slab','Dmus',200);
% proj = proj';%./sum(proj);
if numel(irf)>1
for inl_ = 1:radiometry.nL
meas_set_ = (1:nQM)+(inl_-1)*nQM;
proj_single_ = proj(:,meas_set_);
z = convn(proj_single_,irf(:,inl_));
nmax = max(nstep,numel(irf(:,inl_)));
proj_single_ = z(1:nmax,:);
clear nmax
if self_norm == true
proj_single_ = proj_single_ * spdiags(1./sum(proj_single_,'omitnan')',0,nQM,nQM);
end
clear z
if inl_ == 1
proj(1:size(proj_single_,1),meas_set_) = proj_single_;
proj(size(proj_single_,1)+1:end,:) = [];
else
proj(1:size(proj_single_,1),meas_set_) = proj_single_;
end
end
end
clear meas_set_
dummy_proj_ = zeros(size(twin,1),sum(dmask(:))*radiometry.nL);
for inl_ = 1:radiometry.nL
meas_set_ = (1:nQM)+(inl_-1)*nQM;twin_set_ = (1:2)+(inl_-1)*2;
proj_single_ = proj(:,meas_set_);
proj_single_ = WindowTPSF(proj_single_,twin(:,twin_set_));
if self_norm == true
proj_single_ = proj_single_ * spdiags(1./sum(proj_single_,'omitnan')',0,nQM,nQM);
end
dummy_proj_(:,meas_set_) = proj_single_;
end
proj = dummy_proj_(:);
if ~strcmpi(weight_type,'none')
proj = proj.*weight;
end
proj(mask) = [];
proj = proj(:)./sd;
% plot forward
t = (1:numel(data)) * dt;
figure(1003);
semilogy(t,proj,'-',t,data,'.'),ylim([1e-3 1])
% semilogy([proj data]),ylim([1e-3 1])
% vline(sum(dmask(:))*size(twin,1)*(1:radiometry.nL),repmat({'r'},radiometry.nL,1))
drawnow;
nwin = size(twin,1);
end
function L = Loss_func(x,~)
out = comp_forward(x);
L = sum((out(:) - data(:)).^2);
end
end
|
github
|
andreafarina/SOLUS-master
|
SpectralFitMuaMus_TD.m
|
.m
|
SOLUS-master/src/solvers/SpectralFitMuaMus_TD.m
| 8,682 |
utf_8
|
ccd66ec5f1e92daf914cde29ebd9337d
|
%==========================================================================
% This function contains a solver for fitting optical properties of
% homogeneous phantom using routines in Matlab Optimization Toolbox
%
% Andrea Farina 10/15
%==========================================================================
function [bMua,bMus,bmua,bmus] = SpectralFitMuaMus_TD(~,grid,mua0,mus0, n, A,...
Spos,Dpos,dmask, dt, nstep, twin, self_norm, data, irf, ref, sd,~,radiometry,spe)
geom = 'semi-inf';
weight_type = 'none'; %'rect';
first_lim = 0.1; last_lim = 0.1;
ForceConstitSolution = spe.ForceConstitSolution;
% mua0 = 0.01;
% mus0 = 1.0;
nQM = sum(dmask(:));
nwin = size(twin,1);
%% Inverse solver
[proj, Aproj] = ForwardTD_multi_wave(grid,Spos, Dpos, dmask, mua0, mus0, n, ...
[],[], A, dt, nstep, self_norm,...
geom,'linear',radiometry,irf);
if self_norm == true
data = NormalizeTPSF(data);
ref = NormalizeTPSF(ref);
end
dummy_proj = zeros(size(twin,1),nQM*radiometry.nL);
for inl = 1:radiometry.nL
meas_set =(1:nQM)+(inl-1)*nQM; twin_set = (1:2)+(inl-1)*2;
proj_single = proj(:,meas_set);
proj_single = WindowTPSF(proj_single,twin(:,twin_set));
if self_norm == true
proj_single = NormalizeTPSF(proj_single);
end
dummy_proj(:,meas_set) = proj_single;
end
weight = ones(nwin,nQM*radiometry.nL);
if ~strcmpi(weight_type,'none')
weight = zeros(nwin,nQM*radiometry.nL);
interval = zeros(2,nQM*radiometry.nL);
for im = 1:nQM*radiometry.nL
idx1 = find(ref(:,im)>max(ref(:,im)*first_lim),1,'first');
idx2 = find(ref(:,im)>max(ref(:,im)*last_lim),1,'last');
weight(idx1:idx2,im) = 1;
interval(1,im) = idx1+(im-1)*nwin;
interval(2,im) = idx2+(im-1)*nwin;
end
weight = weight(:);
figure, semilogy(ref(:)), vline(interval(:),'r');
ref =ref(:).*weight;
end
proj = dummy_proj;
proj = proj(:);
data = data(:);
ref = ref(:);
%factor = proj./ref;
%data = data .* factor;
%ref = ref .* factor;
%% data scaling
%sd = sd(:).*(factor);
%% mask for excluding zeros
mask = ((ref(:).*data(:)) == 0) | ...
(isnan(ref(:))) | (isnan(data(:)));
%mask = false(size(mask));
if ref == 0
ref = proj(:);
end
ref(mask) = [];
data(mask) = [];
proj(mask) = [];
%weight(mask) = [];
figure(1002);semilogy([proj,data]),legend('proj','ref')
sd = sqrt(ref);%%ones(size(proj));%proj(:);
%sd = ones(size(data));
data = ref./sd;
%% solution vector
% x = [mua0;mus0;-0]; % [mua0,mus0,t0]
%% Setup optimization for lsqcurvefit
if spe.SPECTRA == 0 && ForceConstitSolution == false
FinDiffRelStep = [2; repmat(1e-3,spe.nLambda*2,1)];
else
FinDiffRelStep = [2; repmat(1e-3,spe.nCromo+2,1)];
end
opts = optimoptions('lsqcurvefit',...
'Jacobian','off',...
...'Algorithm','levenberg-marquardt',...
'DerivativeCheck','off',...
'MaxIter',200,'Display','iter-detailed','FinDiffRelStep',FinDiffRelStep);%,'TolFun',1e-10,'TolX',1e-10)
%% Setup optimization for lsqnonlin
% opts = optimoptions('lsqnonlin',...
% 'Jacobian','off',...
% ...'Algorithm','levenberg-marquardt',...
% 'DerivativeCheck','off',...
% 'MaxIter',20,'Display','iter-detailed')
%% Setup optimization for fminunc
%opts = optimoptions('fminunc','GradObj','on','Algorithm','quasi-newton','MaxIter',2,...
% 'Display','iter')
% opts = optimoptions('fminunc',...
% 'Algorithm','quasi-newton',...
% 'Display','iter-detailed',...
% 'GradObj','off',...
% 'MaxIter',20)
%% Solve
%x = fminunc(@objective,x0,opts);
%x = fminsearch(@objective,x0);
if spe.SPECTRA == 0 && ForceConstitSolution == false
x0 = {mua0 mus0};
low_bound = [-100 zeros(1,numel([x0{:}]))];
else
if ForceConstitSolution
spe.opt.conc0 = ones(spe.nCromo,1).*spe.active_cromo';
spe.opt.a0 = 1; spe.opt.b0 = 1;
end
x0 = {spe.opt.conc0',[spe.opt.a0 spe.opt.b0]};
low_bound = [-100 zeros(1,spe.nCromo+2)];
end
t0 = 0;
x0 = [t0 x0{:}];
[x,res] = lsqcurvefit(@forward,x0,[],data,low_bound,[],opts);
%x = lsqnonlin(@objective2,x0,[],[],opts);
%% display fit result
disp(['Residual: ' num2str(res)])
if spe.SPECTRA == 0 && ForceConstitSolution == false
bmua = x(2:spe.nLambda+1);
bmus = x(spe.nLambda+2:end);
else
if isrow(x), x = x'; end
bmua = spe.ext_coeffB*x(2:end-2);
bmus = x(end-1).*(spe.lambda/spe.lambda0).^(-x(end));
if iscolumn(bmua), bmua = bmua'; end
if iscolumn(bmus), bmus = bmus'; end
display(['a = ' num2str(x(end-1))]); display(['b =' num2str(x(end))]);
display([char(spe.cromo_label) repmat('=',spe.nCromo,1) num2str(x(2:end-2))]);
disp([char(spe.cromo_label) repmat('=',spe.nCromo,1) num2str(x(2:end-2)) repmat(' ',spe.nCromo,1) char(spe.cromo_units)]);
end
fprintf(['<strong>mua = ',num2str(bmua),'</strong>\n']);
fprintf(['<strong>musp = ',num2str(bmus),'</strong>\n']);
display(['t0 = ',num2str(x(1))]);
% display(['MuaErr= ',num2str(bmua-mua0)])
% display(['MusErr= ',num2str(bmus-mus0)])
% display(['MuaErr%= ',num2str(((bmua-mua0)./mua0).*100)])
% display(['MusErr%= ',num2str(((bmus-mus0)./mus0).*100)])
%% Map parameters back to mesh
bMua = bmua.*ones(grid.N,1);
bMus = bmus.*ones(grid.N,1);
return
%% extract the amplitude area
self_norm = 0;
mask = true(nwin*nQM,1);
[proj_fit, Aproj_fit] = ForwardTD_multi_wave(grid,Spos, Dpos, dmask, bmua, bmus, n, ...
[],[], A, dt, nstep, self_norm,...
geom, 'linear',radiometry);
% proj_fit = circshift(proj_fit,round(x(3)/dt));
if numel(irf)>1
z = convn(proj_fit,irf);
nmax = max(nstep,numel(irf));
proj_fit = z(1:nmax,:);
clear nmax
end
proj_fit = WindowTPSF(proj_fit,twin);
Aproj_fit = sum(proj_fit);
A_data = sum(data2);
factor = Aproj_fit./A_data;
save('factor_ref.mat','factor');
%% Callback function for forward problem
function [proj,J] = forward(x,~)
%xx = [x(1)*ones(nsol,1);x(2)*ones(nsol,1)];
t0_ = x(1);
if spe.SPECTRA == 0 && ForceConstitSolution == false
mua = x(2:spe.nLambda+1);
mus = x(spe.nLambda+2:end);
else
b_ = x(end); a_ = x(end-1); conc_ = x(2:end-2).*spe.active_cromo;
if isrow(conc_), conc_ = conc_'; end
mua = (spe.ext_coeff0*conc_)';
mus = a_.*(spe.lambda./spe.lambda0).^(-b_);
end
[proj, Aproj] = ForwardTD_multi_wave(grid,Spos, Dpos, dmask, mua, mus, n, ...
[],[], A, dt, nstep, self_norm,...
geom,'linear',radiometry,irf);
% if spe.SPECTRA == 0 && ForceConstitSolution == false
% display(['mua = ',num2str(mua)]);
% display(['musp = ',num2str(mus)]);
% else
% disp(spe.cromo_label); disp(conc_'); disp({'a','b'}); disp([a_ b_]);
% end
% [~,proj] = Contini1997(0,(1:nstep)*dt/1000,20,mua(1),mus(1),1,n(1),'slab','Dmus',200);
% proj = proj';%./sum(proj);
clear meas_set_
dummy_proj_ = zeros(size(twin,1),sum(dmask(:))*radiometry.nL);
for inl_ = 1:radiometry.nL
meas_set_ = (1:nQM)+(inl_-1)*nQM;twin_set_ = (1:2)+(inl_-1)*2;
proj_single_ = proj(:,meas_set_);
proj_single_ = circshift(proj_single_,round(t0_/dt));
proj_single_ = WindowTPSF(proj_single_,twin(:,twin_set_));
if self_norm == true
proj_single_ = NormalizeTPSF(proj_single_);
end
dummy_proj_(:,meas_set_) = proj_single_;
end
proj = dummy_proj_(:);
if ~strcmpi(weight_type,'none')
proj = proj.*weight;
end
proj(mask) = [];
proj = proj(:)./sd;
% plot forward
t = (1:numel(data)) * dt;
figure(1003);
semilogy(t,proj,'-',t,data,'.'),ylim([1e-3 1])
% semilogy([proj data]),ylim([1e-3 1])
% vline(sum(dmask(:))*size(twin,1)*(1:radiometry.nL),repmat({'r'},radiometry.nL,1))
drawnow;
nwin = size(twin,1);
if nargout>1
JJ = Jacobian (mua, mus, qvec, mvec);
%save('J1','JJ');
njac = size(JJ,2)/2;
% Normalized measruements
if self_norm == true
for i=1:nQM
sJ = sum(JJ((1:nwin)+(i-1)*nwin,:),'omitnan');
sJ = repmat(sJ,nwin,1);
sJ = spdiags(proj((1:nwin)+(i-1)*nwin),0,nwin,nwin) * sJ;
JJ((1:nwin)+(i-1)*nwin,:) = (JJ((1:nwin)+(i-1)*nwin,:) - sJ)./Aproj(i);
end
end
J(:,1) = sum(JJ(:,1:njac),2);% * 0.3;
J(:,2) = sum(JJ(:,njac + (1:njac)),2);% * 0.3;
% J = spdiags(1./proj,0,nQM*nwin,nQM*nwin) * J;
end
end
end
|
github
|
andreafarina/SOLUS-master
|
FitMuaMus_TD_weighted.m
|
.m
|
SOLUS-master/src/solvers/FitMuaMus_TD_weighted.m
| 10,607 |
utf_8
|
07f0b1aacd410d6c21dee2788a9f6667
|
%==========================================================================
% This function contains a solver for fitting optical properties of
% homogeneous phantom using routines in Matlab Optimization Toolbox
%
% Andrea Farina 10/15
%==========================================================================
function [bmua,bmus] = FitMuaMus_TD_weighted(~,grid,mua0,mus0, n, A,...
Spos,Dpos,dmask, dt, nstep, twin, self_norm, data, irf, ref, sd,verbosity)
geom = 'semi-inf';
weight_type = 'rect';
self_norm = true;
mua0 = 0.01;
mus0 = 1.0;
data2 = data;%data;%ref;%data;%ref;
nQM = sum(dmask(:));
nwin = size(twin,1);
Jacobian = @(mua, mus) JacobianTD (grid, Spos, Dpos, dmask, mua, mus, n, A, ...
dt, nstep, twin, irf, geom);
%% Inverse solver
[proj, Aproj] = ForwardTD(grid,Spos, Dpos, dmask, mua0, mus0, n, ...
[],[], A, dt, nstep, self_norm,...
geom,'linear');
if numel(irf)>1
z = convn(proj,irf);
nmax = max(nstep,numel(irf));
proj = z(1:nmax,:);
clear nmax
if self_norm == true
proj = proj * spdiags(1./sum(proj)',0,nQM,nQM);
end
clear z
end
if self_norm == true
data = data * spdiags(1./sum(data)',0,nQM,nQM);
ref = ref * spdiags(1./sum(ref)',0,nQM,nQM);
end
proj = WindowTPSF(proj,twin);
if self_norm == true
proj = proj * spdiags(1./sum(proj)',0,nQM,nQM);
end
proj = proj(:);
data = data(:);
ref = ref(:);
%factor = proj./ref;
%data = data .* factor;
%ref = ref .* factor;
%% data scaling
%sd = sd(:).*(factor);
%% mask for excluding zeros
mask = ((ref(:).*data(:)) == 0) | ...
(isnan(ref(:))) | (isnan(data(:)));
%mask = false(size(mask));
if ref == 0
ref = proj(:);
end
ref(mask) = []; %#ok<NASGU>
data(mask) = [];
proj(mask) = [];
figure(1002);semilogy([proj,data]),legend('proj','ref')
sd = sqrt(ref);%%ones(size(proj));%proj(:);
%sd = ones(size(data));
data = ref./sd;
%% solution vector
x = [mua0;mus0;0]; % [mua0,mus0,t0]
%% Setup optimization for lsqcurvefit
opts = optimoptions('lsqcurvefit',...
'Jacobian','off',...
...'Algorithm','levenberg-marquardt',...
'DerivativeCheck','off',...
'MaxIter',100,'Display','iter-detailed','FinDiffRelStep',[1e-3,1e-2,2]);%,'TolFun',1e-10,'TolX',1e-10)
%% Setup optimization for lsqnonlin
% opts = optimoptions('lsqnonlin',...
% 'Jacobian','off',...
% ...'Algorithm','levenberg-marquardt',...
% 'DerivativeCheck','off',...
% 'MaxIter',20,'Display','iter-detailed')
%% Setup optimization for fminunc
%opts = optimoptions('fminunc','GradObj','on','Algorithm','quasi-newton','MaxIter',2,...
% 'Display','iter')
% opts = optimoptions('fminunc',...
% 'Algorithm','quasi-newton',...
% 'Display','iter-detailed',...
% 'GradObj','off',...
% 'MaxIter',20)
%% Solve
%x = fminunc(@objective,x0,opts);
%x = fminsearch(@objective,x0);
x0 = x;
% x = lsqcurvefit(@forward,x0,[],data,[],[],opts);
% x = lsqcurvefit(@Loss_func,x0,[],0,[],[],opts);
x = fminunc(@Loss_func,x0);
%x = lsqnonlin(@objective2,x0,[],[],opts);
%% Map parameters back to mesh
bmua = x(1)*ones(grid.N,1);
bmus = x(2)*ones(grid.N,1);
%% display fit result
display(['mua = ',num2str(bmua(1))]);
display(['musp = ',num2str(bmus(1))]);
display(['t0 = ',num2str(x(3))]);
%% extract the amplitude area
self_norm = 0;
mask = true(nwin*nQM,1);
[proj_fit, Aproj_fit] = ForwardTD(grid,Spos, Dpos, dmask, x(1), x(2), n, ...
[],[], A, dt, nstep, self_norm,...
geom, 'linear');
proj_fit = circshift(proj_fit,round(x(3)/dt));
if numel(irf)>1
z = convn(proj_fit,irf);
nmax = max(nstep,numel(irf));
proj_fit = z(1:nmax,:);
clear nmax
end
proj_fit = WindowTPSF(proj_fit,twin);
Aproj_fit = sum(proj_fit);
A_data = sum(data2);
factor = Aproj_fit./A_data;
save('factor_ref.mat','factor');
%% Callback function for objective evaluation
function [p,g] = objective(x,~)
verbosity = 1;
xx = [x(1)*ones(nsol,1);x(2)*ones(nsol,1)];
[mua,mus] = toastDotXToMuaMus(hBasis,xx,refind);
mua(notroi) = mua0;
mus(notroi) = mus0;
%mua(mua<0) = 1e-4;
%mus(mus<0) = 0.2;
% for j = 1:length(mua) % ensure positivity
% mua(j) = max(1e-4,mua(j));
% mus(j) = max(0.2,mus(j));
% end
%
[proj,Aproj] = ProjectFieldTD(hMesh,qvec,mvec,dmask,...
mua,mus,conc,tau,n,dt,nstep, 0,self_norm,'diff',0);
if numel(irf)>1
for i = 1:nQM
z(:,i) = conv(full(proj(:,i)),irf);
end
nmax = max(nstep,numel(irf));
proj = z(1:nmax,:);
clear nmax
if self_norm == true
proj = proj * spdiags(1./sum(proj)',0,nQM,nQM);
end
clear z
end
proj = WindowTPSF(proj,twin);
proj = proj(:);
%proj = privProject (hMesh, hBasis, x, ref, freq, qvec, mvec);
[p, p_data, p_prior] = privObjective (proj, data, sd);
if verbosity > 0
fprintf (1, ' [LH: %f, PR: %f]\n', p_data, p_prior);
end
nwin = size(twin,1);
if nargout>1
JJ = Jacobian (mua, mus, qvec, mvec);
% Normalized measruements
if self_norm == true
for i=1:nQM
sJ = sum(JJ((1:nwin)+(i-1)*nwin,:));
sJ = repmat(sJ,nwin,1);
sJ = spdiags(proj((1:nwin)+(i-1)*nwin),0,nwin,nwin) * sJ;
JJ((1:nwin)+(i-1)*nwin,:) = (JJ((1:nwin)+(i-1)*nwin,:) - sJ)./Aproj(i);
end
end
J(:,1) = sum(JJ(:,1:nsol),2);
J(:,2) = sum(JJ(:,nsol + (1:nsol)),2);
g = - 2 * J' * ((data-proj)./sd);
end
end
%% Callback function for objective evaluation
function [p,J] = objective2(x,~)
xx = [x(1)*ones(nsol,1);x(2)*ones(nsol,1)];
[mua,mus] = toastDotXToMuaMus(hBasis,xx,refind);
mua(notroi) = mua0;
mus(notroi) = mus0;
%mua(mua<0) = 1e-4;
%mus(mus<0) = 0.2;
% for j = 1:length(mua) % ensure positivity
% mua(j) = max(1e-4,mua(j));
% mus(j) = max(0.2,mus(j));
% end
%
[proj,Aproj] = ProjectFieldTD(hMesh,qvec,mvec,dmask,...
mua,mus,conc,tau,n,dt,nstep, 0,self_norm,'diff',0);
if numel(irf)>1
for i = 1:nQM
z(:,i) = conv(full(proj(:,i)),irf);
end
proj = z(1:nstep,:);
if self_norm == true
proj = proj * spdiags(1./sum(proj)',0,nQM,nQM);
end
clear z
end
proj = WindowTPSF(proj,twin);
proj = proj(:);
p = (data - proj)./sd;
nwin = size(twin,1);
if nargout>1
JJ = Jacobian (mua, mus, qvec, mvec);
JJ = spdiags(1./sd,0,nQM*nwin,nQM*nwin) * JJ;
% Normalized measruements
if self_norm == true
for i=1:nQM
sJ = sum(JJ((1:nwin)+(i-1)*nwin,:));
sJ = repmat(sJ,nwin,1);
sJ = spdiags(proj((1:nwin)+(i-1)*nwin),0,nwin,nwin) * sJ;
JJ((1:nwin)+(i-1)*nwin,:) = (JJ((1:nwin)+(i-1)*nwin,:) - sJ)./Aproj(i);
end
end
J(:,1) = - sum(JJ(:,1:nsol),2);
J(:,2) = - sum(JJ(:,nsol + (1:nsol)),2);
end
end
%% Callback function for forward problem
function [proj,J] = forward(x,~)
%xx = [x(1)*ones(nsol,1);x(2)*ones(nsol,1)];
t0 = x(3);
[proj, Aproj] = ForwardTD(grid,Spos, Dpos, dmask, x(1), x(2), n, ...
[],[], A, dt, nstep, self_norm,...
geom, 'linear');
% [~,proj] = Contini1997(0,(1:nstep)*dt/1000,20,mua(1),mus(1),1,n(1),'slab','Dmus',200);
% proj = proj';%./sum(proj);
if numel(irf)>1
z = convn(proj,irf);
nmax = max(nstep,numel(irf));
proj = z(1:nmax,:);
clear nmax
if self_norm == true
proj = proj * spdiags(1./sum(proj)',0,nQM,nQM);
end
clear z
end
proj = circshift(proj,round(t0/dt));
proj = WindowTPSF(proj,twin);
if self_norm == true
proj = proj * spdiags(1./sum(proj)',0,nQM,nQM);
end
proj(mask) = [];
proj = proj(:)./sd;
% plot forward
t = (1:numel(data)) * dt;
figure(1003);
semilogy(t,proj,'-',t,data,'.'),ylim([1e-3 1])
drawnow;
nwin = size(twin,1);
if nargout>1
JJ = Jacobian (mua, mus, qvec, mvec);
%save('J1','JJ');
njac = size(JJ,2)/2;
% Normalized measruements
if self_norm == true
for i=1:nQM
sJ = sum(JJ((1:nwin)+(i-1)*nwin,:));
sJ = repmat(sJ,nwin,1);
sJ = spdiags(proj((1:nwin)+(i-1)*nwin),0,nwin,nwin) * sJ;
JJ((1:nwin)+(i-1)*nwin,:) = (JJ((1:nwin)+(i-1)*nwin,:) - sJ)./Aproj(i);
end
end
J(:,1) = sum(JJ(:,1:njac),2);% * 0.3;
J(:,2) = sum(JJ(:,njac + (1:njac)),2);% * 0.3;
% J = spdiags(1./proj,0,nQM*nwin,nQM*nwin) * J;
end
end
function L = Loss_func(coeff,~)
fwd = forward(coeff);
err_square = (fwd-data).^2;
data_=reshape(data,numel(fwd)/nQM,nQM);
first_lim = 0.7; last_lim = 0.1;
switch lower(weight_type)
case 'rect'
weight = zeros(numel(fwd)/nQM,nQM);
for im = 1:nQM
idx1 = find(data_(:,im)>max(data_(:,im))*first_lim,1,'first');
idx2 = find(data_(:,im)>max(data_(:,im))*last_lim,1,'last');
weight([idx1:idx2],im) = 1;
interval(1,im) = idx1+(im-1)*numel(fwd)/nQM; interval(2,im)= idx2+(im-1)*numel(fwd)/nQM;
end
L=sum(weight(:).*err_square);
vline(dt*interval(:),'r');
case 'abba'
weight = data;
L=sum(weight(:).*err_square);
case 'abba2'
weight = zeros(numel(fwd)/nQM,nQM);
for im = 1:nQM
idx1 = find(data_(:,im)>max(data_(:,im))*first_lim,1,'first');
idx2 = find(data_(:,im)>max(data_(:,im))*last_lim,1,'last');
weight([idx1:idx2],im) = 1;
interval(1,im) = idx1+(im-1)*numel(fwd)/nQM; interval(2,im)= idx2+(im-1)*numel(fwd)/nQM;
end
vline(dt*interval(:),'r');
weight = weight.* data;
L=sum(weight(:).*err_square);
case 'var'
weight = 1./sd(:);
L=sum(weight(:).*err_square);
end
end
end
|
github
|
andreafarina/SOLUS-master
|
FitMuaMus_TD.m
|
.m
|
SOLUS-master/src/solvers/FitMuaMus_TD.m
| 9,595 |
utf_8
|
6828e8f9c41383ef887ca557ec1099f3
|
%==========================================================================
% This function contains a solver for fitting optical properties of
% homogeneous phantom using routines in Matlab Optimization Toolbox
%
% Andrea Farina 10/15
% Andrea Farina 11/20 fixed error arising by fitting with fraction
%==========================================================================
function [bmua,bmus] = FitMuaMus_TD(~,grid,mua0,mus0, n, A,...
Spos,Dpos,dmask, dt, nstep, twin, self_norm, data, irf, ref, sd, type_fwd)
geom = 'semi-inf';
weight_type = 'none';%rect';%'none'; % 'none','rect'
fract_first = 0.5; fract_last = 0.01;
data = data;%ref;%data;%ref;
data2 = data;
nQM = sum(dmask(:));
nwin = size(twin,1);
Jacobian = @(mua, mus) JacobianTD (grid, Spos, Dpos, dmask, mua, mus, n, A, ...
dt, nstep, twin, irf, geom, 'muaD', type_fwd, self_norm,0);
%% Inverse solver
[proj, Aproj] = ForwardTD(grid,Spos, Dpos, dmask, mua0, mus0, n, ...
[],[], A, dt, nstep, self_norm,...
geom,'linear',irf);
proj = WindowTPSF(proj,twin);
switch lower(weight_type)
case 'none'
if self_norm == true
proj = NormalizeTPSF(proj);
end
case 'rect'
[ROI,ROI_d] = ThresholdTPSF(data,fract_first,fract_last);
data = NormalizeTPSF(data.*ROI_d);
data = data(ROI);
sd = sd(ROI);
ref = ref(ROI);
if self_norm == true
proj = NormalizeTPSF(proj.*ROI_d);
end
proj = proj(ROI);
end
proj = proj(:);
data = data(:);
ref = ref(:);
%factor = proj./ref;
%data = data .* factor;
%ref = ref .* factor;
%% data scaling
%sd = sd(:).*(factor);
%% mask for excluding zeros
mask = ((ref(:).*data(:)) == 0) | ...
(isnan(ref(:))) | (isnan(data(:)));
%mask = false(size(mask));
if ref == 0
ref = proj(:);
end
ref(mask) = [];
data(mask) = [];
proj(mask) = [];
figure(1002);semilogy([proj,data]),legend('proj','ref')
%sd = sqrt(ref);
data = ref(:);
data = data./sd;
%% solution vector
x = [mua0;mus0;-0]; % [mua0,mus0,t0]
%% Setup optimization for lsqcurvefit
opts = optimoptions('lsqcurvefit',...
'Jacobian','off',...
...'Algorithm','levenberg-marquardt',...
'DerivativeCheck','off',...
'MaxIter',100,'Display','final-detailed','FinDiffRelStep',[1e-3,1e-2,2]);%,'TolFun',1e-10,'TolX',1e-10)
%% Setup optimization for lsqnonlin
% opts = optimoptions('lsqnonlin',...
% 'Jacobian','off',...
% ...'Algorithm','levenberg-marquardt',...
% 'DerivativeCheck','off',...
% 'MaxIter',20,'Display','iter-detailed')
%% Setup optimization for fminunc
%opts = optimoptions('fminunc','GradObj','on','Algorithm','quasi-newton','MaxIter',2,...
% 'Display','iter')
% opts = optimoptions('fminunc',...
% 'Algorithm','quasi-newton',...
% 'Display','iter-detailed',...
% 'GradObj','off',...
% 'MaxIter',20)
%% Solve
%x = fminunc(@objective,x0,opts);
%x = fminsearch(@objective,x0);
x0 = x;
%if strcmpi(weight_type,'none')
x = lsqcurvefit(@forward,x0,[],data,[],[],opts);
%else
% x = fminunc(@Loss_func,x0);
%end
%x = lsqnonlin(@objective2,x0,[],[],opts);
%% Map parameters back to mesh
bmua = x(1)*ones(grid.N,1);
bmus = x(2)*ones(grid.N,1);
%% display fit result
% AF: occhio che mua0 e mus0 sono i valori da cui parte il fit e non quelli
% simulati. Non ha senso calcolare l'errore su quei dati.
fprintf(['<strong>mua = ',num2str(bmua(1)),'</strong>\n']);
fprintf(['<strong>musp = ',num2str(bmus(1)),'</strong>\n']);
fprintf(['<strong>t0 = ',num2str(x(3)),'</strong>\n']);
% display(['MuaErr= ',num2str(bmua(1)-mua0)])
% display(['MusErr= ',num2str(bmus(1)-mus0)])
% display(['MuaErr%= ',num2str(((bmua(1)-mua0)./mua0).*100)])
% display(['MusErr%= ',num2str(((bmus(1)-mus0)./mus0).*100)])
%% extract the amplitude area
self_norm = 0;
mask = true(nwin*nQM,1);
[~, Aproj_fit] = ForwardTD(grid,Spos, Dpos, dmask, x(1), x(2), n, ...
[],[], A, dt, nstep, self_norm,...
geom, 'linear',irf);
%proj_fit = circshift(proj_fit,round(x(3)/dt));
%proj_fit = WindowTPSF(proj_fit,twin);
A_data = sum(data2);
factor = Aproj_fit./A_data;
save('factor_ref.mat','factor');
%% ===================== OBJECTIVE FUNCTIONS=============================
%% Callback function for objective evaluation
function [p,g] = objective(x,~) %#ok<DEFNU>
verbosity = 1;
xx = [x(1)*ones(nsol,1);x(2)*ones(nsol,1)];
[mua,mus] = toastDotXToMuaMus(hBasis,xx,refind);
mua(notroi) = mua0;
mus(notroi) = mus0;
%mua(mua<0) = 1e-4;
%mus(mus<0) = 0.2;
% for j = 1:length(mua) % ensure positivity
% mua(j) = max(1e-4,mua(j));
% mus(j) = max(0.2,mus(j));
% end
%
[proj,Aproj] = ProjectFieldTD(hMesh,qvec,mvec,dmask,...
mua,mus,conc,tau,n,dt,nstep, 0,self_norm,'diff',0);
if numel(irf)>1
for i = 1:nQM
z(:,i) = conv(full(proj(:,i)),irf);
end
nmax = max(nstep,numel(irf));
proj = z(1:nmax,:);
clear nmax
if self_norm == true
proj = proj * spdiags(1./sum(proj,'omitnan')',0,nQM,nQM);
end
clear z
end
proj = WindowTPSF(proj,twin);
proj = proj(:);
%proj = privProject (hMesh, hBasis, x, ref, freq, qvec, mvec);
[p, p_data, p_prior] = privObjective (proj, data, sd);
if verbosity > 0
fprintf (1, ' [LH: %f, PR: %f]\n', p_data, p_prior);
end
nwin = size(twin,1);
if nargout>1
JJ = Jacobian (mua, mus, qvec, mvec);
% Normalized measruements
if self_norm == true
for i=1:nQM
sJ = sum(JJ((1:nwin)+(i-1)*nwin,:),'omitnan');
sJ = repmat(sJ,nwin,1);
sJ = spdiags(proj((1:nwin)+(i-1)*nwin),0,nwin,nwin) * sJ;
JJ((1:nwin)+(i-1)*nwin,:) = (JJ((1:nwin)+(i-1)*nwin,:) - sJ)./Aproj(i);
end
end
J(:,1) = sum(JJ(:,1:nsol),2);
J(:,2) = sum(JJ(:,nsol + (1:nsol)),2);
g = - 2 * J' * ((data-proj)./sd);
end
end
%% Callback function for objective evaluation
function [p,J] = objective2(x,~) %#ok<DEFNU>
xx = [x(1)*ones(nsol,1);x(2)*ones(nsol,1)];
[mua,mus] = toastDotXToMuaMus(hBasis,xx,refind);
mua(notroi) = mua0;
mus(notroi) = mus0;
%mua(mua<0) = 1e-4;
%mus(mus<0) = 0.2;
% for j = 1:length(mua) % ensure positivity
% mua(j) = max(1e-4,mua(j));
% mus(j) = max(0.2,mus(j));
% end
%
[proj,Aproj] = ProjectFieldTD(hMesh,qvec,mvec,dmask,...
mua,mus,conc,tau,n,dt,nstep, 0,self_norm,'diff',0);
if numel(irf)>1
for i = 1:nQM
z(:,i) = conv(full(proj(:,i)),irf);
end
proj = z(1:nstep,:);
if self_norm == true
proj = proj * spdiags(1./sum(proj,'omitnan')',0,nQM,nQM);
end
clear z
end
proj = WindowTPSF(proj,twin);
proj = proj(:);
p = (data - proj)./sd;
nwin = size(twin,1);
if nargout>1
JJ = Jacobian (mua, mus, qvec, mvec);
JJ = spdiags(1./sd,0,nQM*nwin,nQM*nwin) * JJ;
% Normalized measruements
J(:,1) = - sum(JJ(:,1:nsol),2);
J(:,2) = - sum(JJ(:,nsol + (1:nsol)),2);
end
end
%% Callback function for forward problem
function [proj,J] = forward(x,~)
%xx = [x(1)*ones(nsol,1);x(2)*ones(nsol,1)];
t0 = x(3);
[proj, Aproj] = ForwardTD(grid,Spos, Dpos, dmask, x(1), x(2), n, ...
[],[], A, dt, nstep, self_norm,...
geom, 'linear',irf);
proj = circshift(proj,round(t0/dt));
proj = WindowTPSF(proj,twin);
switch lower(weight_type)
case 'none'
if self_norm == true
proj = NormalizeTPSF(proj);
end
case 'rect'
if self_norm == true
proj = NormalizeTPSF(proj.*ROI_d);
end
proj = proj(ROI);
end
proj(mask) = [];
proj = proj(:)./sd;
% plot forward
t = (1:numel(data)) * dt;
figure(1003);
semilogy(t,proj,'-',t,data,'.'),ylim([1e-3 1])
drawnow;
nwin = size(twin,1);
if nargout>1
JJ = Jacobian (x(1), x(2));
%save('J1','JJ');
njac = size(JJ,2)/2;
% Normalized measruements
J(:,1) = sum(JJ(:,1:njac),2);% * 0.3;
J(:,2) = sum(JJ(:,njac + (1:njac)),2);% * 0.3;
% J = spdiags(1./proj,0,nQM*nwin,nQM*nwin) * J;
end
end
function L = Loss_func(coeff,~) %#ok<DEFNU>
fwd = forward(coeff);
err_square = (fwd-data).^2;
data_=reshape(data,numel(fwd)/nQM,nQM);
switch lower(weight_type)
case 'rect'
weight = zeros(numel(fwd)/nQM,nQM);
for im = 1:nQM
idx1 = find(data_(:,im)>max(data_(:,im))*fract_first,1,'first');
idx2 = find(data_(:,im)>max(data_(:,im))*fract_last,1,'last');
weight(idx1:idx2,im) = 1;
interval(1,im) = idx1+(im-1)*numel(fwd)/nQM; interval(2,im)= idx2+(im-1)*numel(fwd)/nQM;
end
L=sum(weight(:).*err_square);
vline(dt*interval(:),'r');
end
end
end
|
github
|
andreafarina/SOLUS-master
|
RecSolverTK0_spectra_TD.m
|
.m
|
SOLUS-master/src/solvers/RecSolverTK0_spectra_TD.m
| 6,653 |
utf_8
|
5841b7f325397ee3e0718a2305ef93f2
|
%==========================================================================
% This function contains solvers for DOT or fDOT.
% To have available all the functionalty install REGU toolbox
% Andrea Farina 12/16
%==========================================================================
function [bmua,bmus,bconc,bA,bB] = RecSolverTK0_spectral_TD(solver,grid,mua0,mus0, n, A,...
Spos,Dpos,dmask, dt, nstep, twin, self_norm, data, irf, ref, sd, fwd_type,radiometry,spe,conc0,a0,b0)
%global factor
%ref = 0;
%% Jacobain options
LOAD_JACOBIAN = solver.prejacobian.load; % Load a precomputed Jacobian
geom = 'semi-inf';
xtransf = '(x/x0)'; %log(x),x,log(x/x0)
type_ratio = 'gauss'; % 'gauss', 'born', 'rytov';
type_ref = 'theor'; % 'theor', 'meas', 'area'
%% REGULARIZATION PARAMETER CRITERION
NORMDIFF = 'sd'; % 'ref', 'sd'
REGU = 'lcurve'; % 'lcurve', 'gcv', 'external'
BACKSOLVER = 'tikh'; % 'tikh', 'tsvd', 'discrep','simon', 'gmres', 'pcg', 'lsqr'
% -------------------------------------------------------------------------
nQM = sum(dmask(:));
nwin = size(twin,1);
% -------------------------------------------------------------------------
[p,type_jac] = ExtractVariables_spectral(solver.variables,spe);
% if rytov and born jacobian is normalized to proj
if strcmpi(type_ratio,'rytov')||strcmpi(type_ratio,'born')
logdata = true;
else
logdata = false;
end
Jacobian = @(mua, mus) JacobianTD_multiwave_spectral (grid, Spos, Dpos, dmask, mua, mus, n, A, ...
dt, nstep, twin, irf, geom,type_jac,fwd_type,radiometry,spe,self_norm,logdata);
% homogeneous forward model
[proj, ~] = ForwardTD_multi_wave(grid,Spos, Dpos, dmask, mua0, mus0, n, ...
[],[], A, dt, nstep, 0,...
geom, fwd_type,radiometry,irf);
%% Window TPSF for each wavelength
dummy_proj = zeros(size(twin,1),nQM*radiometry.nL);
for inl = 1:radiometry.nL
meas_set = (1:nQM)+(inl-1)*nQM; twin_set = (1:2)+(inl-1)*2;
proj_single = proj(:,meas_set);
proj_single = WindowTPSF(proj_single,twin(:,twin_set));
dummy_proj(:,meas_set) = proj_single;
end
proj = dummy_proj;
clear dummy_proj
if self_norm
proj = NormalizeTPSF(proj);
end
[dphi,sd] = PrepareDataFitting(data,ref,sd,type_ratio,type_ref,proj);
% creat mask for nan, isinf
mask = (isnan(dphi(:))) | (isinf(dphi(:)));
dphi(mask) = [];
% solution vector
[x0,x] = PrepareX_spectral(spe,grid.N,type_jac,xtransf);
% ---------------------- Construct the Jacobian ---------------------------
if LOAD_JACOBIAN == true
fprintf (1,'Loading Jacobian\n');
tic;
%load([jacdir,jacfile])
load(solver.prejacobian.path);
toc;
else
%fprintf (1,'Calculating Jacobian\n');
tic;
J = Jacobian ( mua0, mus0);
[jpath,jname,jext] = fileparts(solver.prejacobian.path);
if ~exist(jpath,'dir')
mkdir(jpath)
end
save(solver.prejacobian.path,'J','-v7.3');
toc;
end
if ~isempty(solver.prior.refimage)
%d1 = (solver.prior(:) > 0 )&(solver.prior(:)==min(solver.prior(:)));
d1 = solver.prior.refimage(:) > mean(solver.prior.refimage(:));
d2 = ~d1;
if mean(solver.prior.refimage(d1))<mean(solver.prior.refimage(d2))
d1 = ~d1;
d2 = ~d2;
end
%(solver.prior(:) > min(solver.prior(:)))&(solver.prior(:)==max(solver.prior(:)));
D = [d1(:),d2(:)];
J = J * D;
end
% sd jacobian normalization
J = spdiags(1./sd(:),0,numel(sd),numel(sd)) * J;
nsol = size(J,2);
% parameter normalisation (scale x0)
if ~strcmpi(xtransf,'x')
J = J * spdiags(x0,0,length(x0),length(x0));
end
J(mask,:) = [];
%% Solver
%if ~strcmpi((BACKSOLVER),'simon')
if (~strcmpi(REGU,'lcurve')&&(~strcmpi(REGU,'gcv')))
disp('Calculating larger singular value');
s = svds(J,1)
alpha = solver.tau * s;
end
if (strcmpi(BACKSOLVER,'tikh'))
disp('Calculating compact SVD');
[U,s,V]=csvd(J); % compact SVD (Regu toolbox)
figure(402);
picard(U,s,dphi); % Picard plot (Regu toolbox)
end
if ~exist('alpha','var')
fh = figure(403);
fh.NumberTitle = 'off'; fh.Name = 'L-curve';
if strcmpi(REGU,'lcurve')
alpha = l_curve(U,s,dphi);%,BACKSOLVER); % L-curve (Regu toolbox)
elseif strcmpi(REGU,'gcv')
alpha = gcv(U,s,dphi);%,BACKSOLVER)
end
savefig(fh,[fh.Name '.fig'])
end
disp(['alpha = ' num2str(alpha), 'tau = ',num2str(alpha/s(1))]);
disp('Solving...')
switch lower(BACKSOLVER)
case 'tikh'
disp('Tikhonov');
[dx,~] = tikhonov(U,s,V,dphi,alpha);
case 'tsvd'
disp('TSVD');
[dx,~] = tsvd(U,s,V,dphi,alpha);
case 'discrep'
disc_value = norm(sd(~mask))*10;
disp(['Discrepancy principle with value=' num2str(disc_value)]);
dx = discrep(U,s,V,dphi,disc_value);
case 'simon'
disp('Simon');
% tic;
% s1 = svds(J,1);
% toc;
% alpha = solver.tau * s1;
dx = [J;sqrt(alpha)*speye(nsol)]\[dphi;zeros(nsol,1)];
%dx = [dx;zeros(nsol,1)];
%rho
%cond(J)
%dx = [dx;zeros(nsol,1)];
%dx = [J;alpha*eye(2*nsol)]\[dphi;zeros(2*nsol,1)];
%dx = lsqr(J,dphi,1e-4,100);
%dx = pcg(@(x)JTJH(x,J,eye(2*nsol),alpha),J'*dphi,1e-4,100);
case 'gmres'
disp('gmres')
if strcmpi(REGU,'external')
lambda = sum(sum(J.^2));
alpha = lambda * alpha;
end
dx = gmres(@(x)JTJH(x,J,eye(nsol),alpha),J'*dphi,[],1e-6,100);
case 'pcg'
disp('pcg')
tic;
if strcmpi(REGU,'external')
lambda = sum(sum(J.^2));
alpha = alpha * lambda;
disp(['alpha=' num2str(alpha)]);
end
%dx = pcg(J'*J + alpha*speye(nsol),J'*dphi,1e-6,100);
dx = pcg(@(x)JTJH(x, J, speye(nsol),alpha),J'*dphi,1e-6,1000);
case 'lsqr'
disp('lsqr');
tic;
if strcmpi(REGU,'external')
%lambda = sum(sum(J.^2));
%alpha = alpha * lambda;
disp(['alpha=' num2str(alpha)]);
end
dx = lsqr([J;alpha*speye(nsol)],[dphi;zeros(nsol,1)],1e-6,1000);
toc;
%dx = J' * ((J*J' + alpha*eye(length(data)))\dphi);
end
%==========================================================================
%% Add update to solution
%==========================================================================
if ~isempty(solver.prior.refimage)
dx = D * dx;
end
x = x + dx;
x = BackTransfX(x,x0,xtransf);
[bmua,bmus,bconc,bAB] = XtoMuaMus_spectral(x,mua0,mus0,type_jac,spe,conc0,a0,b0);
bA = bAB(:,1);bB = bAB(:,2);
end
|
github
|
andreafarina/SOLUS-master
|
RecSolverL1_TD.m
|
.m
|
SOLUS-master/src/solvers/RecSolverL1_TD.m
| 7,236 |
utf_8
|
0b4532c2e96fb136be141dd62b376dc0
|
%==========================================================================
% This function contains solvers for DOT or fDOT.
% To have available all the functionalty install REGU toolbox
% Andrea Farina 12/16
%==========================================================================
function [bmua,bmus] = RecSolverL1_TD(solver,grid,mua0,mus0, n, A,...
Spos,Dpos,dmask, dt, nstep, twin, self_norm, data, irf, ref, sd, fwd_type)
%% Jacobain options
LOAD_JACOBIAN = solver.prejacobian.load; % Load a precomputed Jacobian
geom = 'semi-inf';
%% SOLVER PARAMETER CRITERION
SOLVER = 'ISTA';
%ISTA: "normal" (i.e. pixel) ISTA
%FISTA: "normal" (i.e. pixel) FISTA
%ADMM: "normal" (i.e. pixel) ADMM
NISTAit = 1000;
NFISTAit = 200;
NADMMit = 10;
LSQRit = 40; % solve LSQR with small number of iterations
LSQRtol = 1e-6; % tolerence of LSQR
% ISTA FLAGS
ISTA_FLAGS.FISTA= true;
ISTA_FLAGS.pos = true;
ISTA_FLAGS.Wavelets =true;
ISTA_FLAGS.Iterates = true;
%% path
%rdir = ['../results/test/precomputed_jacobians/'];
jacdir = ['../results/precomputed_jacobians/'];
jacfile = 'J';
% -------------------------------------------------------------------------
bdim = (grid.dim);
nQM = sum(dmask(:));
nwin = size(twin,1);
% -------------------------------------------------------------------------
[p,type_jac] = ExtractVariables(solver.variables);
Jacobian = @(mua, mus) JacobianTD (grid, Spos, Dpos, dmask, mua, mus, n, A, ...
dt, nstep, twin, irf, geom,type_jac,fwd_type);
%% self normalise (probably useless because input data are normalize)
% if self_norm == true
% data = data * spdiags(1./sum(data,'omitnan')',0,nQM,nQM);
% ref = ref * spdiags(1./sum(ref,'omitnan')',0,nQM,nQM);
% end%% Inverse solver
[proj, Aproj] = ForwardTD(grid,Spos, Dpos, dmask, mua0, mus0, n, ...
[],[], A, dt, nstep, self_norm,...
geom, fwd_type);
if numel(irf)>1
z = convn(proj,irf);
nmax = max(nstep,numel(irf));
proj = z(1:nmax,:);
clear nmax z
end
if self_norm == true
proj = proj * spdiags(1./sum(proj,'omitnan')',0,nQM,nQM);
end
proj = WindowTPSF(proj,twin);
proj = proj(:);
ref = ref(:);
data = data(:);
factor = proj./ref;
data = data .* factor;
ref = ref .* factor;
%% data scaling
sd = sd(:).*factor;
%sd = proj(:);
%sd = ones(size(proj(:)));
%% mask for excluding zeros
mask = ((ref(:).*data(:)) == 0) | ...
(isnan(ref(:))) | (isnan(data(:)));
%mask = false(size(mask));
if ref == 0
ref = proj(:);
end
ref(mask) = [];
data(mask) = [];
%sd(mask) = [];
% solution vector
x0 = PrepareX0([mua0,1./(3*mus0)],grid.N,type_jac);
x = ones(size(x0));
dphi = (data(:)-ref(:))./sd(~mask);%./ref(:);
%dphi = log(data(:)) - log(ref(:));
%save('dphi','dphi');
% ---------------------- Construct the Jacobian ---------------------------
if LOAD_JACOBIAN == true
fprintf (1,'Loading Jacobian\n');
tic;
%load([jacdir,jacfile])
load(solver.prejacobian.path);
toc;
else
%fprintf (1,'Calculating Jacobian\n');
tic;
J = Jacobian ( mua0, mus0);
[jpath,jname,jext] = fileparts(solver.prejacobian.path);
if ~exist(jpath,'dir')
mkdir(jpath)
end
save(solver.prejacobian.path,'J');
toc;
end
% if ~isempty(solver.prior.refimage)
% d1 = (solver.prior.refimage(:) > 0 )&(solver.prior.refimage(:)==min(solver.prior.refimage(:)));
% d2 = (solver.prior.refimage(:) > min(solver.prior.refimage(:)))&(solver.prior.refimage(:)==max(solver.prior.refimage(:)));
% D = [d1(:),d2(:)];
% J = J * D;
% end
if self_norm == true
for i=1:nQM
sJ = sum(J((1:nwin)+(i-1)*nwin,:),'omitnan');
sJ = repmat(sJ,nwin,1);
sJ = spdiags(proj((1:nwin)+(i-1)*nwin),0,nwin,nwin) * sJ;
J((1:nwin)+(i-1)*nwin,:) = (J((1:nwin)+(i-1)*nwin,:) - sJ)./Aproj(i);
end
end
J = spdiags(1./sd(:),0,numel(sd),numel(sd)) * J; % data normalisation
nsol = size(J,2);
% parameter normalisation (scale x0)
J = J * spdiags(x0,0,length(x0),length(x0));
%proj(mask) = [];
J(mask,:) = [];
%% now ISTA (slow!)
lambda = sum(sum(J.^2));
alpha = 1e-6 * lambda;
tau = 2/lambda;
T = alpha * tau;
%% set up operators for Shrinkage - pixel case
pops.W = @(x) x;
pops.Winv = @(c) c;
pops.WTr = @(c) c;
pops.B = @(x)x;
pops.Binv = @(x)x;
pops.A = @(x)J*x;
pops.ATr = @(y) J'*y;
pops.ntc = nsol;
pops.ndat = numel(data(:));
pops.nsol = nsol;
pops.Dims = grid.dim;
%% now ISTA (slow!)
if strcmpi(SOLVER,'ista')
xista = zeros(nsol,1);
Niter = NISTAit;
% T = alpha*tau;
ISTA_FLAGS.Rayleighstep = true;
ISTA_FLAGS.pos = false;
ISTA_FLAGS.FISTA = false;
ISTA_FLAGS.Wavelets = false;
ISTA_FLAGS.Iterates = true;
tic;
% [x,c,postista] = DotWavDeconvByISTA(hBasis,Ja,y,alpha,Niter,tau,ISTA_FLAGS);
[xx,c,postista] = LinearShrinkage(pops,dphi,alpha,NISTAit,tau,ISTA_FLAGS);
toc;
disp('-------------- solved using ISTA --------------');
xista = xx(:,end);
% for k = 1:NISTAit
% lerrista(k) = norm(y - Ja*x(:,k));
% xistim = reshape(hBasis.Map('S->B',x(:,k)),bx,by);
% xerrista(k) = norm(xistim-tgtmuaim );
% perrista(k) = norm(c(:,k),1);
% end
dx = xista;
% disp('-------------- solved using ISTA AF --------------');
% %lambda = solver.tau;
% %alpha = max(svd(J));
% [dx,J] = ista(dphi,J,lambda,alpha,NISTAit);
end
%% now FISTA (faster?)
if strcmpi(SOLVER,'fista')
Niter = NFISTAit;
ISTA_FLAGS.Rayleighstep = true;
ISTA_FLAGS.pos = false;
ISTA_FLAGS.FISTA = true;
ISTA_FLAGS.Wavelets = false;
ISTA_FLAGS.Iterates = true;
tic;
% [x,c,postfista] = DotWavDeconvByISTA(hBasis,Ja,y,alpha,Niter,tau,ISTA_FLAGS);
[xx,c,postfista] = LinearShrinkage(pops,dphi,alpha,NFISTAit,tau,ISTA_FLAGS);
toc;
disp('-------------- solved using FISTA --------------');
xfistay = xx(:,end);
% for k = 1:NFISTAit
% lerrfista(k) = norm(y - Ja*x(:,k));
% xfistim = reshape(hBasis.Map('S->B',x(:,k)),bx,by);
% xerrfista(k) = norm(xfistim-tgtmuaim );
% perrfista(k) = norm(c(:,k),1);
% end
dx = xfistay;
end
%% ADMM - pixels
if strcmpi(SOLVER,'admm')
ISTA_FLAGS.Rayleighstep = true;
ISTA_FLAGS.pos = false;
ISTA_FLAGS.FISTA = false;
ISTA_FLAGS.Wavelets = false;
ISTA_FLAGS.Iterates = true;
rho = 1e-2*lambda; % 1e-2*alpha/T; % what is best way to set rho ?
sqrho = sqrt(rho);
tic;
[xpadm,padm,postpadm] = LinearADMM(pops,dphi,alpha,NADMMit,tau,rho,LSQRtol,LSQRit,ISTA_FLAGS);
toc;
xpadmin = xpadm(:,end);
% for k = 1:NADMMit
% lerrpadm(k) = norm(y - Ja*xpadm(:,k));
% xpadmmim = reshape(hBasis.Map('S->B',xpadm(:,k)),bx,by);
% xerrpadm(k) = norm(xpadmmim-tgtmuaim );
% perrpadm(k) = norm(padm(:,k),1);
% end
disp('------------- solved using ADMM -------------- ');
dx = xpadmin;
end
%% update solution
x = x + dx;
%logx = logx + dx;
%x = exp(logx);
x = x.*x0;
[bmua,bmus] = XtoMuaMus(x,mua0,mus0,type_jac);
end
|
github
|
andreafarina/SOLUS-master
|
RecSolverGN_TD.m
|
.m
|
SOLUS-master/src/solvers/RecSolverGN_TD.m
| 12,667 |
utf_8
|
22bea224cd1aeec0f91147fef69edc03
|
%==========================================================================
% This function contains solvers for DOT or fDOT.
% To have available all the functionalty install REGU toolbox
% Andrea Farina 05/15
%==========================================================================
function [bmua,bmus,erri] = RecSolverGN_TD(solver,grid,hMesh,hBasis,mua0,mus0,refind,...
qvec,mvec,dmask,dt,nstep,twin,self_norm,data,irf,ref,sd,verbosity)
%global xd
step = 0.1;
LOAD_JACOBIAN = solver.prejacobian.load;
LOGX = false;
solver.Himplicit = true;
solver.itrmax = 3;
solver.tol = 1e-6;
solver.tolKrylov = 1e-6;
prm.method = 'TV';
% -------------------------------------------------------------------------
[~,type_jac] = ExtractVariables(solver.variables);
Jacobian = @(mua, mus) JacobianTD (grid, [], [], dmask, mua, mus, refind, [], ...
dt, nstep, twin, irf, [],type_jac,'fem');
%% self normalise (probably useless because input data are normalize)
nQM = sum(dmask(:));
% if self_norm == true
% data = data * spdiags(1./sum(data)',0,nQM,nQM);
% ref = ref * spdiags(1./sum(ref)',0,nQM,nQM);
% end
N = hMesh.NodeCount;
% Set up homogeneous initial parameter estimates
mua = ones(N,1) * mua0; % initial mua estimate
mus = ones(N,1) * mus0; % initial mus estimate
n = ones(N,1) * refind; % refractive index estimate
kap = 1./(3*mus); % diffusion coefficient
solmask = find(hBasis.GridElref>0);
slen = numel(solmask);
%% proj[x0] %%
[proj, Aproj] = ForwardTD([],[], [], dmask, mua0, mus0, n, ...
[],[], [], dt, nstep, self_norm,...
[], 'fem');
if numel(irf)>1
z = convn(proj,irf);
nmax = max(nstep,numel(irf));
proj = z(1:nmax,:);
clear nmax z
end
if self_norm == true
proj = proj * spdiags(1./sum(proj,'omitnan')',0,nQM,nQM);
end
proj = WindowTPSF(proj,twin);
%% prepareData
if self_norm == true
strfactor = 'factor_one';
strsd = 'poisson';
else
strfactor = 'factor_td';
strsd = 'Poisson';
end
[data,sd,ref,sdj,proj,mask] = PrepDataLH(data,sd,ref,proj,...
'nonlin',strfactor,strsd);
% map initial parameter estimates to solution basis
bdim = (hBasis.Dims())';
bmua = hBasis.Map('M->B', mua); % mua mapped to full grid
bmus = hBasis.Map('M->B', mus); % mus mapped to full grid
bkap = hBasis.Map('M->B', kap); % kap mapped to full grid
% mask non valid data
%ref(mask) = [];
%data(mask) = [];
% solution vector
x0 = PrepareX0([mua0,1./(3*mus0)],slen,type_jac);
x = x0./x0;%ones(size(x0));
if LOGX == true
logx =log(x);%x./x0;%log(x); % transform to log
else
logx = x;
end % transform to log
nsol = length(x);
% REGULARIZATION STRUCTURE
prm.basis = hBasis;
prm.x0 = logx;
prm.tau = solver.tau;
%prm.tv.beta = lprm.beta;
if isfield(solver.prior,'refimage')
if ~isempty(solver.prior.path)
ref_img = solver.prior.refimage;
prm.prior.refimg = [ref_img(:);ref_img(:)];
prm.prior.threshold = 0.25;
prm.prior.smooth = 0.1;
end
end
prm.tau = 1; %no tau is set
hreg = toastRegul(prm,logx);
% -------------------- Initial data error (=2 due to data scaling) --------
err0 = toastObjective (proj(~mask), data(~mask), sd(~mask), hreg, logx); %initial error
err = err0; % current error
errp = inf;%1e10; % previous error
erri(1) = err0;
itr = 1; % iteration counter
fprintf (1, '\n**** INITIAL ERROR %e\n\n', err);
tic;
% set figures for visualization
habs = figure;
hsca = figure;
% --------------------------- Exit condition ------------------------------
while (itr <= solver.itrmax) && (err > solver.tol*err0)...
&& (errp-err > solver.tol)
% -------------------------------------------------------------------------
errp = err;
% ---------------------- Construct the Jacobian ---------------------------
nwin = size(twin,1);
if LOAD_JACOBIAN == true
if (~exist('J','var'))
fprintf (1,'Loading Jacobian\n');
tic;
load(solver.prejacobian.path);
toc;
end
LOAD_JACOBIAN = false;
[jpath,~,~] = fileparts(solver.prejacobian.path);
if ~exist(jpath,'dir')
mkdir(jpath)
end
save(solver.prejacobian.path,'J');
toc;
else
fprintf (1,'Calculating Jacobian\n');
tj = tic;
J = Jacobian (mua, mus);
disp(['Jacobian computation time: ',num2str(toc(tj))]);
%save([jacdir,jacfile,'_it',num2str(itr)],'J');
%load Jpoint
if itr == 1
[jpath,~,~] = fileparts(solver.prejacobian.path);
if ~exist(jpath,'dir')
mkdir(jpath)
end
save(solver.prejacobian.path,'J');
end
%J(:,nsol+(1:nsol)) = 0;
end
%% Normalized measurements
if self_norm == true
for i=1:nQM
sJ = sum(J((1:nwin)+(i-1)*nwin,:));
sJ = repmat(sJ,nwin,1);
sJ = spdiags(proj((1:nwin)+(i-1)*nwin),0,nwin,nwin) * sJ;
J((1:nwin)+(i-1)*nwin,:) = (J((1:nwin)+(i-1)*nwin,:) - sJ)./Aproj(i);
end
end
% parameter normalisation (scale x0)
J = J * spdiags(x0,0,length(x0),length(x0));
% % Transform to df/ d logx
if LOGX == true
J = J * spdiags(x, 0,length(x0),length(x0)) ;
end
% ----------------------- Data normalization ------------------------------
%
for i = 1:numel(proj)
J(i,:) = J(i,:) / sdj(i);
end
J = spdiags(1./sd,0,numel(data),numel(data)) * J;
J(mask,:) = [];
% Normalisation of Hessian (map to diagonal 1)
%psiHdiag = hreg.HDiag(logx);
%M = zeros(nsol,1);
% for i = 1:p
% M(i) = sum(J(:,i) .* J(:,i));
% M(i) = M(i) + psiHdiag(i);
% M(i) = 1 ./ sqrt(M(i));
% end
M = ones(nsol,1);
for i = 1:nsol
J(:,i) = J(:,i) * M(i);
end
%M = ones(size(M));
% Gradient of cost function
tau = solver.tau * max(svd(J))
%tau = solver.tau * sum(sum(J.^2))
r = J' * (2*(data(~mask)-proj(~mask))./sd(~mask));
r = r - tau * hreg.Gradient (logx) .* M;
if solver.Himplicit == true
% Update with implicit Krylov solver
fprintf (1, 'Entering Krylov solver\n');
%dx = toastKrylov (x, J, r, M, 0, hreg, lprm.tolKrylov);
if exist('hreg','var')
HessReg = hreg.Hess (logx);
end
dx = krylov(r);
disp(['|dx| = ',num2str(norm(dx))])
else
% Update with explicit Hessian
H = J' * J;
lambda = 0.01;
H = H + eye(size(H)).* lambda;
dx = H \ r;
clear H;
end
%clear J;
% %% AF TBU is it needed??
% for i = 1:p
% dx(i) = dx(i) ./ M(i);
% end
% Line search
fprintf (1, 'Entering line search\n');
step0 = step;
%step0 = .1;
[step, err] = toastLineSearch (logx, dx, step0, err, @objective, 'verbose', 1);
if errp-err <= solver.tol
dx = r; % try steepest descent
fprintf (1, 'Try steepest descent\n');
step = toastLineSearch (logx, dx, step0, err, @objective, 'verbose', 1);
end
% Add update to solution
logx = logx + dx*step;
if LOGX == true
x = exp(logx);
else
x = logx;
end
x = x.*x0;
% Map parameters back to mesh
[smua,smus] = XtoMuaMus(x,mua0,mus0,type_jac);
mua = hBasis.Map('S->M',smua);
bmua = hBasis.Map('S->B',smua);
mus = hBasis.Map('S->M', smus);
bmus = hBasis.Map('S->B',smus);
% display the reconstructions
figure(habs);
ShowRecResults(grid,reshape(bmua,bdim),...
grid.z1,grid.z2,grid.dz,1,'auto',0.00,0.05);
%suptitle('Recon Mua');
%save_figure([rdir, 'mua_rec_it_',num2str(itr)]);
%saveas(gcf,[rdir,lprm.filename,'_mua_rec_it_',num2str(itr)],'tif');
figure(hsca);
ShowRecResults(grid,reshape(bmus,bdim),...
grid.z1,grid.z2,grid.dz,1,'auto');
%suptitle('Recon Mus');
%save_figure([rdir, 'mus_rec_it_',num2str(itr)]);
%saveas(gcf,[rdir,lprm.filename,'_mus_rec_it_',num2str(itr)],'tif');
drawnow;
tilefigs;
%==========================================================================
%% Update field projections
%==========================================================================
disp('----- Update field projections -------');tic;
[proj, Aproj] = ForwardTD([],[], [], dmask, mua, mus, n, ...
[],[], [], dt, nstep, self_norm,...
[], 'fem');
if numel(irf)>1
z = convn(proj,irf);
nmax = max(nstep,numel(irf));
proj = z(1:nmax,:);
clear nmax z
end
if self_norm == true
proj = proj * spdiags(1./sum(proj)',0,nQM,nQM);
end
proj = WindowTPSF(proj,twin);
proj = proj(:);%-proj0(:);% * factor;
%proj(mask) = [];
%proj = log(proj(:)) - log(proj0(:));
%sdj = proj(:);
%==========================================================================
%% Update objective function
%==========================================================================
err = toastObjective (proj(~mask), data(~mask), sd(~mask), hreg, logx);
fprintf (1, '**** GN ITERATION %d, ERROR %e\n\n', itr, err);
erri(itr) = err;
bmua_itr(itr,:) = bmua;
bmus_itr(itr,:) = bmus;
% REC.Data = REC.Data./REC.Data(1)*REC.proj(1);
% REC.Data = REC.Data./max(REC.Data)*max(REC.proj);
% it_dir = [rdir,filesep,solver.filename,filesep];
% mkdir(it_dir);
% save([it_dir,'res_',num2str(itr)],'bmua_itr','bmus_itr');
itr = itr+1;
end
%save([rdir,'sol'],'bmua_itr','bmus_itr');
% =====================================================================
% Callback function for objective evaluation (called by toastLineSearch)
function p = objective(x)
if LOGX == true
xx = exp(x);
else
xx = x;
end
xx = x.*x0;
if strcmpi(type_jac,'mua')
mua = hBasis.Map('S->M',xx);
else
mua = hBasis.Map('S->M',xx(1:slen));
mus = hBasis.Map('S->M',1./(3*xx(slen+1:end)));
end
%mua(mua<1e-4) = 1e-4;
%mus(mus<0.2) = 0.2;
%% if fixed scattering
% mus(:) = mus0;
% for j = 1:length(mua) % ensure positivity
% mua(j) = max(1e-4,mua(j));
% mus(j) = max(0.2,mus(j));
% end
%
[proj, Aproj] = ForwardTD([],[], [], dmask, mua, mus, n, ...
[],[], [], dt, nstep, self_norm,...
[], 'fem');
if numel(irf)>1
z = convn(proj,irf);
nmax = max(nstep,numel(irf));
proj = z(1:nmax,:);
clear nmax z
end
if self_norm == true
proj = proj * spdiags(1./sum(proj)',0,nQM,nQM);
end
proj = WindowTPSF(proj,twin);
proj = proj(:);%-proj0(:);% * factor;
%proj (mask) = [];
%proj = log(proj(:)) - log(proj0(:));
%sdj = proj(:);
%proj = privProject (hMesh, hBasis, x, ref, freq, qvec, mvec);
[p, p_data, p_prior] = toastObjective (proj(~mask), data(~mask), sd(~mask), hreg, x);
% if verbosity > 0
fprintf (1, ' [LH: %e, PR: %e]\n', p_data, p_prior);
% end
end
%save([rdir 'sol'], 'xiter');
%save([rdir 'err_pattern'],'erri');
% =====================================================================
% Krylov solver subroutine
function dx = krylov(r)
k_t = cputime;
%switch prm.solver.krylov.method
% case 'bicgstab'
% [dx, k_flag, k_res, k_iter] = bicgstab(@jtjx, r, lprm.tolKrylov,100);
% otherwise
% [dx, k_flag, k_res, k_iter] = gmres (@jtjx, r, 30,lprm.tolKrylov, 100);
[dx, k_flag, k_res, k_iter] = pcg (@jtjx, r, solver.tolKrylov, 100);
% end
k_dt = cputime-k_t;
% fprintf (1, '--> iter=%0.0f(%0.0f), time=%0.1fs, res=%g\n', ...
% k_iter(1), k_iter(2), k_dt, k_res);
fprintf (1, '--> iter=%0.0f, time=%0.1fs, res=%g\n', ...
k_iter(1), k_dt, k_res);
clear k_t k_dt k_flag k_res k_iter
end
% =====================================================================
% Callback function for matrix-vector product (called by toastKrylov)
function b = jtjx(x)
b = J' * (J*x);
if exist('hreg','var')
b = b + M .* (tau * HessReg * (M .* x));
end
end
end
|
github
|
andreafarina/SOLUS-master
|
RecSolverBORN_CW.m
|
.m
|
SOLUS-master/src/solvers/RecSolverBORN_CW.m
| 4,994 |
utf_8
|
f353cef1f4fa512abeb5e877a927313d
|
%==========================================================================
% This function contains solvers for DOT or fDOT.
% To have available all the functionalty install REGU toolbox
% Andrea Farina 12/16
%==========================================================================
function [bmua,bmus] = RecSolverBORN_CW(~,grid,mua0,mus0, A,...
Spos,Dpos,dmask,data,ref,~)
%% Jacobain options
SAVE_JACOBIAN = 1; % Save the Jacobian into a file
LOAD_JACOBIAN = 0; % Load a precomputed Jacobian
COMPUTE_JACOBIAN = 1; % Compute the Jacobian
geom = 'semi-inf';
%% REGULARIZATION PARAMETER CRITERION
REGU = 'lcurve'; % 'lcurve' or 'gcv'
BACKSOLVER = 'Tikh'; % 'Tikh' or 'tsvd' or 'simon'
rdir = ['../results/test/precomputed_jacobians/'];
mkdir(rdir);
disp(['Intermediate results will be stored in: ' rdir])
%save([rdir 'REC'], '-v7.3','REC'); %save REC structure which describes the experiment
% -------------------------------------------------------------------------
bdim = (grid.dim);
nQM = sum(dmask(:));
Jacobian = @(mua, mus) JacobianCW (grid, Spos, Dpos, dmask, mua, mus, A, geom);
%% Inverse solver
proj = ForwardCW(grid, Spos, Dpos, dmask, ...
mua0, mus0, [], [], A, geom, 'homo');
%% data scaling
%sd = proj(:);
sd = ones(size(proj));
if ref == 0
ref = proj(:);
end
% figure(400);
% subplot(2,2,1),
% plot([data(:) ref(:) proj(:)./sum(proj(:))]),legend('data','ref','proj'),grid;
% subplot(2,2,2),
% plot(ref(:)./proj(:)),legend('ratio ref/proj'),
% subplot(2,2,3),grid;
% plot([ref(:)./sum(ref(:)) proj(:)./sum(proj(:))]),
% legend('ref','proj'),grid;
% subplot(2,2,4),
% plot([ref(:)./sum(ref(:))-proj(:)./sum(proj(:))]),
% legend('ref - proj'),grid;
% drawnow;
% solution vector
x = ones(grid.N,1) * mua0;
x0 = x;
p = length(x);
dphi = (data(:)-ref(:));%./ref(:);
%dphi = log(data(:)) - log(ref(:));
%save('dphi','dphi');
% ---------------------- Construct the Jacobian ---------------------------
if COMPUTE_JACOBIAN == 1
fprintf (1,'Calculating Jacobian\n');
tic;
J = Jacobian ( mua0, mus0);
toc;
end
if LOAD_JACOBIAN == 1
fprintf (1,'Loading Jacobian\n');
tic;
load([rdir,'Jacobian'])
toc;
end
if SAVE_JACOBIAN == 1
fprintf (1,'Saving Jacobian\n');
tic;
save([rdir,'Jacobian'],'J');
toc;
end
J = spdiags(1./sd,0,nQM,nQM) * J; % data normalisation
nsol = size(J,2);
% parameter normalisation (map to log)
% for i = 1:p
% J(:,i) = J(:,i) * x(i);
% end
% ------- to solve only for mua uncomment the following sentence ----------
%J(:,nsol+(1:nsol)) = 0;
%% Solver
%alpha_vec = logspace(-6,-3,10); % Regularization parameter
%close all
alpha_vec = 0;%1e-10; % Regularization parameter
if ~strcmpi((BACKSOLVER),'simon')
[U,s,V]=csvd(J); % compact SVD (Regu toolbox)
figure(402);
picard(U,s,dphi); % Picard plot (Regu toolbox)
end
for i = 1:numel(alpha_vec)
alpha = alpha_vec(i)
if ~exist('alpha','var')
figure(403);
if strcmpi(REGU,'lcurve')
alpha = l_curve(U,s,dphi)%,BACKSOLVER); % L-curve (Regu toolbox)
elseif strcmpi(REGU,'gcv')
alpha = gcv(U,s,dphi,BACKSOLVER);
end
end
switch lower(BACKSOLVER)
case 'tikh'
disp('Tikhonov');
[dx,rho] = tikhonov(U,s,V,dphi,alpha);
case 'tsvd'
disp('TSVD');
[dx,rho] = tsvd(U,s,V,dphi,alpha);
case 'simon'
disp('Simon');
tic;
s1 = svds(J,1);
toc;
alpha = 1e0*s1
dx = [J;sqrt(alpha)*speye(nsol)]\[dphi;zeros(nsol,1)];
%dx = [dx;zeros(nsol,1)];
end
%rho
%cond(J)
%dx = [dx;zeros(nsol,1)];
%dx = [J;alpha*eye(2*nsol)]\[dphi;zeros(2*nsol,1)];
%dx = lsqr(J,dphi,1e-4,100);
%dx = pcg(@(x)JTJH(x,J,eye(2*nsol),alpha),J'*dphi,1e-4,100);
%dx = gmres(@(x)JTJH(x,J,eye(2*nsol),alpha),J'*dphi,[],1e-4,100);
%dx = J' * ((J*J' + alpha*eye(length(data)))\dphi);
%==========================================================================
%% Add update to solution
%==========================================================================
x = x + dx;
%logx = logx + dx;
%x = exp(logx);
bmua = x;
bmus = ones(size(bmua)) * mus0;
% display the reconstructions
figure(304);
%figure('Position',get(0,'ScreenSize'));
ShowRecResults(grid,reshape(bmua,bdim),grid.z1,grid.z2,grid.dz,1,...
min(bmua),max(bmua));
suptitle('Recon Mua');
%export_fig '../Results/20151111/rec_mua_1incl.pdf' -transparent
figure(305);
%figure('Position',get(0,'ScreenSize'));
ShowRecResults(grid,reshape(bmus,bdim),grid.z1,grid.z2,grid.dz,1,...
min(bmus),max(bmus));
suptitle('Recon Mus');
%export_fig '../Results/20151111/rec_mus_1incl.pdf' -transparent
drawnow;
tilefigs;
%pause
x = x0;
%save([rdir 'sol'], 'xiter');
%save([rdir 'err_pattern'],'erri');
end
end
|
github
|
andreafarina/SOLUS-master
|
RecSolverTK1_TD.m
|
.m
|
SOLUS-master/src/solvers/RecSolverTK1_TD.m
| 4,637 |
utf_8
|
e6ae7733c83a817546c4d99240d00bdf
|
%==========================================================================
% This function contains solvers for DOT or fDOT.
% Andrea Farina 04/17
% Andrea Farina 11/2020: simplified normalizations of X, Jac, Data, dphi
%==========================================================================
function [bmua,bmus] = RecSolverTK1_TD(solver,grid,mua0,mus0, n, A,...
Spos,Dpos,dmask, dt, nstep, twin, self_norm, data, irf, ref, sd, type_fwd)
%% Jacobain options
USEGPU = 0;%gpuDeviceCount;
LOAD_JACOBIAN = solver.prejacobian.load; % Load a precomputed Jacobian
geom = 'semi-inf';
xtransf = '(x/x0)'; %log(x),x,log(x/x0)
type_ratio = 'gauss'; % 'gauss', 'born', 'rytov';
type_ref = 'theor'; % 'theor', 'meas', 'area'
% -------------------------------------------------------------------------
[p,type] = ExtractVariables(solver.variables);
% if rytov and born jacobian is normalized to proj
if strcmpi(type_ratio,'rytov')||strcmpi(type_ratio,'born')
logdata = true;
else
logdata = false;
end
Jacobian = @(mua, mus) JacobianTD (grid, Spos, Dpos, dmask, mua, mus, n, A, ...
dt, nstep, twin, irf, geom,type,type_fwd,self_norm,logdata);
% homogeneous forward model
[proj, ~] = ForwardTD(grid,Spos, Dpos, dmask, mua0, mus0, n, ...
[],[], A, dt, nstep, 0, geom, 'linear', irf);
proj = WindowTPSF(proj,twin);
if self_norm
proj = NormalizeTPSF(proj);
end
[dphi,sd] = PrepareDataFitting(data,ref,sd,type_ratio,type_ref,proj);
%% creat mask for nan, ising
mask = (isnan(dphi(:))) | (isinf(dphi(:)));
dphi(mask) = [];
% solution vector
[x0,x] = PrepareX([mua0,1./(3*mus0)],grid.N,type,xtransf);
% ---------------------- Construct the Jacobian ---------------------------
if LOAD_JACOBIAN == true
fprintf (1,'Loading Jacobian\n');
tic;
load(solver.prejacobian.path);
toc;
else
tic;
J = Jacobian ( mua0, mus0);
[jpath,~,~] = fileparts(solver.prejacobian.path);
if ~exist(jpath,'dir')
mkdir(jpath)
end
save(solver.prejacobian.path,'J');
toc;
end
% sd jacobian normalization
J = spdiags(1./sd(:),0,numel(sd),numel(sd)) * J;
nsol = size(J,2);
% parameter normalisation (scale x0)
if ~strcmpi(xtransf,'x')
J = J * spdiags(x0,0,length(x0),length(x0));
end
J(mask,:) = [];
%% Structured laplacian prior
%siz_prior = size(solver.prior.refimage);
%solver.prior(solver.prior == max(solver.prior(:))) = 1.1*min(solver.prior(:));
%solver.prior = solver.prior .* (1 + 0.01*randn(size(solver.prior)));
%[L,~] = StructuredLaplacianPrior(solver.prior.refimage,siz_prior(1),siz_prior(2),siz_prior(3));
k3d = Kappa(solver.prior.refimage,5);
[Dx,Dy,Dz] = gradientOperator(grid.dim,[1,1,1],[],'none');
L = [sqrt(k3d)*Dx;sqrt(k3d)*Dy;sqrt(k3d)*Dz];
%% Solver
disp('Calculating the larger singular value');
s = svds(J,1);
% structured Laplacian
L1 = [];
for ip = 1:p
L1 = blkdiag(L1,L);
end
%% case Lcurve or direct solution
b = [dphi;zeros(p*3*nsol/p,1)];
if USEGPU
gpu = gpuDevice; %#ok<UNRCH>
disp('Using GPU');
%J = gpuArray(J);
b = gpuArray(b);
%dphiG = gpuArray(dphi);
%L1 = gpuArray(L1);
end
if numel(solver.tau)>1
for i = 1:numel(solver.tau)
alpha = solver.tau(i)*s(1);
disp(['Solving for tau = ',num2str(solver.tau(i))]);
tic;
if USEGPU
A = [J;alpha*L1]; %#ok<UNRCH>
A = gpuArray(sparse(A));
dx = lsqr(A*1e10,b*1e10,1e-6,1000);
else
dx = lsqr([J;alpha*L1],b,1e-6,1000);
end
toc;
res(i) = gather(norm(J*dx-dphi)); %#ok<AGROW>
prior(i) = gather(norm(L1*dx)); %#ok<AGROW>
figure(144),loglog(res,prior,'-o'),title('L-curve');
text(res,prior,num2cell(solver.tau(1:i)));xlabel('residual');ylabel('prior');
end
tau = solver.tau;
save('LcurveData','res','prior','tau');
% tau_suggested = l_corner(flip(res)',flip(prior)',flip(tau));
% disp(['Suggested tau = ',num2str(tau_suggested)]);
pause;
tau_sel = inputdlg('Choose tau');
solver.tau = str2double(tau_sel{1});
end
%% final solution
alpha = solver.tau * s(1);
disp(['Solving for tau = ',num2str(solver.tau)]);
if USEGPU > 0
A = [J;alpha*L1];
A = gpuArray(sparse(A));
dx = lsqr(A*1e10,b*1e10,1e-6,1000);
dx = gather(dx);
else
dx = lsqr([J;alpha*L1],b,1e-6,1000);
end
%==========================================================================
%% Add update to solution
%==========================================================================
x = x + dx;
x = BackTransfX(x,x0,xtransf);
[bmua,bmus] = XtoMuaMus(x,mua0,mus0,type);
end
|
github
|
andreafarina/SOLUS-master
|
Fit2Mua2Mus_TD.m
|
.m
|
SOLUS-master/src/solvers/Fit2Mua2Mus_TD.m
| 6,126 |
utf_8
|
35cf1e3b713af5f0162fad4ecd5c12f2
|
%==========================================================================
% This function contains a solver for fitting optical properties of
% 2 regions mesh using TOAST as forward and Matlab Optimization Toolbox
%
% Andrea Farina 02/18
%==========================================================================
function [bmua,bmus, OUTPUT] = Fit2Mua2Mus_TD(solver,grid,mua0,mus0, n, ~,...
Qpos,Mpos,dmask, dt, nstep, twin, self_norm, data, irf, ref, sd,verbosity)
verbosity = 1;
self_norm = true;
INCL_ONLY = false;
MUA_ONLY = true; musIN = 1.5;%real value of scattering to be used for MUA_ONLY
%% initial setting the FEM problem
% create the mesh
mdim = [grid.Nx,grid.Ny,grid.Nz] ;
[vtx,idx,eltp] = mkslab([grid.x1,grid.y1,grid.z1;...
grid.x2,grid.y2,grid.z2],mdim);
hmesh = toastMesh(vtx,idx,eltp);
refind = n * ones(hmesh.NodeCount,1);
% create basis
bdim = mdim;
% if priormask does not retunr back the same number of elemets as the DOT grid
%bdim = size(solver.prior.refimage);
hbasis = toastBasis(hmesh,bdim, 'LINEAR');
% map prior to mesh
priorM = hbasis.Map('B->M',double(solver.prior.refimage));
% set intermidiate values to 1;
% inter_UP = find(priorM >= 0.01);
% inter_DW = find( priorM < 0.5);
% priorM(inter_UP) = 1;
% priorM(inter_DW) = 0;
% create Q/M
Qds = 1; % width of Sources
Mds = 1.5; % width of Detectors
hmesh.SetQM(Qpos,Mpos);
qvec = hmesh.Qvec('Neumann','Gaussian',Qds);
mvec = hmesh.Mvec('Gaussian',Mds, n);
% mtot = mvec(:,1) + mvec(:,2) + mvec(:,3) + mvec(:,4) + mvec(:,5) + mvec(:,6) + mvec(:,7) + mvec(:,8); % FOR DISPLAY
% qtot = qvec(:,1) + qvec(:,2) + qvec(:,3) + qvec(:,4) + qvec(:,5) + qvec(:,6) + qvec(:,7) + qvec(:,8);
% tot = (max(qtot) / max(mtot)) * mtot + qtot;
% hmesh.Display(qtot);
nQM = sum(dmask(:));
%% normalize data
if self_norm == true
data = data * spdiags(1./sum(data,'omitnan')',0,nQM,nQM);
ref = ref * spdiags(1./sum(ref,'omitnan')',0,nQM,nQM);
sd = sqrt(data) * spdiags(1./sum(data,'omitnan')',0,nQM,nQM);
end
%% mask for excluding zeros
mask = (data(:) == 0) | (isnan(data(:)));
%sd = ones(size(data));%;%%ones(size(proj));%proj(:);
sd = ones(size(data));
data = data./sd;
data(mask) = [];
sd(mask) = [];
%data2 (mask) = [];
%% fitting procedure
if INCL_ONLY
x0 = [mua0,mus0]; lb = [0,0]; ub = [1, 10];
% fitfun = @forward2;
elseif MUA_ONLY
x0 = [mua0, mua0];lb = [0,0]; ub = [1, 10];
else
x0 =[mua0 + 0.001,mus0 + 0.1,mua0,mus0]; % [muaIN, musIN, muaOUT, musOUT]
%x0 = [0.001,1,0.001,1]; %start from homogeneous combination
lb = [0,0,0,0]; ub = [1, 10, 1, 10];
% fitfun = @forward;
end
% setting optimization
opts = optimoptions('lsqcurvefit',...
'Jacobian','off',...
...'Algorithm','trust-region-reflective',...
'DerivativeCheck','off',...
'MaxIter',100,'Display','iter-detailed',...%'FinDiffRelStep',[1e-4,1e-2],...%,
'TolFun',1e-10,'TolX',1e-10);
[x,~,~,~,OUTPUT] = lsqcurvefit(@forward,x0,[],data(:),lb,ub,opts);x_lsqr = x;
%[x] = fmincon(@forwardfmincon,x0); OUTPUT = 0;
%x_fmin = x
x_lsqr
%x = x0;
%x = bicg(@forward, data(:));
%x_pcg = x;
%% display fit result
if INCL_ONLY
display(['mua_IN = ',num2str(x(1))]);
display(['musp_IN = ',num2str(x(2))]);
elseif MUA_ONLY
display(['mua_IN = ',num2str(x(1))]);
display(['mua_BK = ',num2str(x(2))]);
else
display(['mua_BK = ',num2str(x(3))]);
display(['musp_BK = ',num2str(x(4))]);
display(['mua_IN = ',num2str(x(1))]);
display(['musp_IN = ',num2str(x(2))]);
end
%% Map parameters back to basis
if INCL_ONLY
optmua = x(1) * priorM;
optmus = x(2) * priorM;
optmua = optmua + (1-priorM)*x0(1);
optmus = optmus + (1-priorM)*x0(2);
elseif MUA_ONLY
optmua = x(1) * priorM;
optmua = optmua +(1-priorM)*x(2);
optmus = priorM*musIN + (1-priorM)*mus0;
else
optmua = x(1) * priorM;
optmus = x(2) * priorM;
optmua = optmua + (1-priorM)*x(3);
optmus = optmus + (1-priorM)*x(4);
end
% if priorMask does not return back the same number of elements
% hbasis_out = toastBasis(hmesh,mdim);
% bmua = hbasis_out.Map('M->B',optmua(:));
% bmus = hbasis_out.Map('M->B',optmus(:));
bmua = hbasis.Map('M->B',optmua(:));
bmus = hbasis.Map('M->B',optmus(:));
%bmua = optmua(:);
%bmus = optmus(:);
%% Delete Mesh and Basis
% hbasis_out.delete;
hbasis.delete;
hmesh.delete;
clearvars -except bmua bmus OUTPUT
return;
%% forward solvers
function [proj] = forward(x, ~)
if INCL_ONLY
mua = x(1) * priorM + mua0 * ( 1-priorM);
mus = x(2) * priorM + mus0 * ( 1-priorM);
elseif MUA_ONLY
mua = x(1) * priorM + x(2) * ( 1-priorM);
mus = musIN * priorM + mus0 * ( 1-priorM);
else
mua = x(1) * priorM + x(3) * ( 1-priorM);
mus = x(2) * priorM + x(4) * ( 1-priorM);
end
% Mus = basis.Map('B->M',mus);
% Mua = basis.Map('B->M',mua);
[proj,~] = ProjectFieldTD(hmesh,qvec,mvec,dmask, mua,mus,0,0,refind,dt,nstep,0,0,'diff',0);
proj = proj * spdiags(1./sum(proj)',0,nQM,nQM);
if numel(irf)>1
z = convn(proj,irf);
nmax = max(nstep,numel(irf));
proj = z(1:nmax,:);
clear nmax
if self_norm == true
proj = proj * spdiags(1./sum(proj,'omitnan')',0,nQM,nQM);
end
clear z
end
%proj = circshift(proj,round(t0/dt));
proj = WindowTPSF(proj,twin);
if self_norm == true
proj = proj * spdiags(1./sum(proj,'omitnan')',0,nQM,nQM);
end
proj(mask) = [];
proj = proj(:)./sd(:);
if verbosity
% plot forward
t = (1:numel(data)) * dt;
figure(1003);
semilogy(t,proj(:),'-',t,data(:),'.'),ylim([1e-3 1])
title(['||proj-data||=',num2str(norm(proj-data(:)))])
drawnow,
x
end
end
function [out ] = forwardfmincon(x)
out = norm(forward(x) - data(:));
end
end
|
github
|
andreafarina/SOLUS-master
|
RecSolverTK1_spectra_TD.m
|
.m
|
SOLUS-master/src/solvers/RecSolverTK1_spectra_TD.m
| 5,352 |
utf_8
|
ecf0e59511a88c73993c0a170b83dd4e
|
%==========================================================================
% This function contains solvers for DOT or fDOT.
% Andrea Farina 04/17
%==========================================================================
function [bmua,bmus,bconc,bA,bB] = RecSolverTK1_spectra_TD(solver,grid,mua0,mus0, n, A,...
Spos,Dpos,dmask, dt, nstep, twin, self_norm, data, irf, ref, sd, fwd_type,radiometry,spe,conc0,a0,b0)
%% Jacobain options
USEGPU = 0;%gpuDeviceCount;
LOAD_JACOBIAN = solver.prejacobian.load; % Load a precomputed Jacobian
geom = 'semi-inf';
xtransf = '(x/x0)'; %log(x),x,log(x/x0)
type_ratio = 'gauss'; % 'gauss', 'born', 'rytov';
type_ref = 'theor'; % 'theor', 'meas', 'area'
% -------------------------------------------------------------------------
nQM = sum(dmask(:));
% -------------------------------------------------------------------------
[p,type_jac] = ExtractVariables_spectral(solver.variables,spe);
% if rytov and born jacobian is normalized to proj
if strcmpi(type_ratio,'rytov')||strcmpi(type_ratio,'born')
logdata = true;
else
logdata = false;
end
Jacobian = @(mua, mus) JacobianTD_multiwave_spectral (grid, Spos, Dpos, dmask, mua, mus, n, A, ...
dt, nstep, twin, irf, geom,type_jac,fwd_type,radiometry,spe,self_norm,logdata);
% homogeneous forward model
[proj, ~] = ForwardTD_multi_wave(grid,Spos, Dpos, dmask, mua0, mus0, n, ...
[],[], A, dt, nstep, 0,...
geom, fwd_type,radiometry,irf);
%% Window TPSF for each wavelength
dummy_proj = zeros(size(twin,1),nQM*radiometry.nL);
for inl = 1:radiometry.nL
meas_set = (1:nQM)+(inl-1)*nQM; twin_set = (1:2)+(inl-1)*2;
proj_single = proj(:,meas_set);
proj_single = WindowTPSF(proj_single,twin(:,twin_set));
dummy_proj(:,meas_set) = proj_single;
end
proj = dummy_proj;
clear dummy_proj
if self_norm
proj = NormalizeTPSF(proj);
end
[dphi,sd] = PrepareDataFitting(data,ref,sd,type_ratio,type_ref,proj);
% creat mask for nan, isinf
mask = (isnan(dphi(:))) | (isinf(dphi(:)));
dphi(mask) = [];
% solution vector
[x0,x] = PrepareX_spectral(spe,grid.N,type_jac,xtransf);
% ---------------------- Construct the Jacobian ---------------------------
if LOAD_JACOBIAN == true
fprintf (1,'Loading Jacobian\n');
tic;
load(solver.prejacobian.path);
toc;
else
tic;
J = Jacobian ( mua0, mus0);
[jpath,~, ~] = fileparts(solver.prejacobian.path);
if ~exist(jpath,'dir')
mkdir(jpath)
end
save(solver.prejacobian.path,'J','-v7.3');
toc;
end
% sd normalisation
J = spdiags(1./sd(:),0,numel(sd),numel(sd)) * J;
nsol = size(J,2);
% parameter normalisation (scale x0)
if ~strcmpi(xtransf,'x')
J = J * spdiags(x0,0,length(x0),length(x0));
end
J(mask,:) = [];
%% Structured laplacian prior
%siz_prior = size(solver.prior.refimage);
%solver.prior(solver.prior == max(solver.prior(:))) = 1.1*min(solver.prior(:));
%solver.prior = solver.prior .* (1 + 0.01*randn(size(solver.prior)));
%[L,~] = StructuredLaplacianPrior(solver.prior.refimage,siz_prior(1),siz_prior(2),siz_prior(3));
%% new gradient
k3d = Kappa(solver.prior.refimage,5);
[Dy,Dx,Dz] = gradientOperator(grid.dim,[1,1,1],[],'none');
L = [sqrt(k3d)*Dx;sqrt(k3d)*Dy;sqrt(k3d)*Dz];
%% Solver
disp('Calculating singular values');
s = svds(J,1);
L1 = [];
for ip = 1:p
L1 = blkdiag(L1,L);
end
%% case Lcurve or direct solution
b = [dphi;zeros(p*3*nsol/p,1)];
if USEGPU
gpu = gpuDevice; %#ok<UNRCH>
disp('Using GPU');
b = gpuArray([full(dphi);zeros(p*3*nsol/p,1)]);
end
if numel(solver.tau)>1
for i = 1:numel(solver.tau)
alpha = solver.tau(i)*s(1);
disp(['Solving for tau = ',num2str(solver.tau(i))]);
tic;
if USEGPU
A = [J;alpha*L1]; %#ok<UNRCH>
A = gpuArray(sparse(A));
dx = lsqr(A*1e10,b*1e10,1e-6,1000);
else
dx = lsqr([J;alpha*L1],b,1e-6,1000);
end
toc;
%dx = [J;(alpha)*L]\[dphi;zeros(3*nsol,1)];
res(i) = gather(norm(J*dx-dphi)); %#ok<AGROW>
prior(i) = gather(norm(L1*dx)); %#ok<AGROW>
figure(144),loglog(res,prior,'-o'),title('L-curve');
text(res,prior,num2cell(solver.tau(1:i)));xlabel('residual');ylabel('prior');
end
tau = solver.tau;
save('LcurveData','res','prior','tau');
% tau_suggested = l_corner(flip(res)',flip(prior)',flip(tau));
% disp(['Suggested tau = ',num2str(tau_suggested)]);
pause;
tau_sel = inputdlg('Choose tau');
solver.tau = str2double(tau_sel{1});
end
%% final solution
alpha = solver.tau * s(1);
disp(['Solving for tau = ',num2str(solver.tau)]);
if USEGPU > 0
%J(abs(J)<1e-3) = 0;
A = [J;alpha*L1];
A = gpuArray(sparse(A));
dx = lsqr(A*1e10,b*1e10,1e-6,1000);
dx = gather(dx);
else
dx = lsqr([J;alpha*L1],b,1e-6,1000);
end
%==========================================================================
%% Add update to solution
%==========================================================================
x = x + dx;
x = BackTransfX(x,x0,xtransf);
[bmua,bmus,bconc,bAB] = XtoMuaMus_spectral(x,mua0,mus0,type_jac,spe,conc0,a0,b0);
bA = bAB(:,1);bB = bAB(:,2);
end
|
github
|
andreafarina/SOLUS-master
|
setHete.m
|
.m
|
SOLUS-master/src/subroutines/setHete.m
| 2,169 |
utf_8
|
475ae79d62d08c374b9af95a0844f3af
|
%==========================================================================
% This version of steHete requires the geometry of the honomogeneity
%
% N. Ducros - Departamento di Fisica - Politecnico di Milano - 15/01/09
% N. Ducros - Departamento di Fisica - Politecnico di Milano - 02/02/09
% N. Ducros - Departamento di Fisica - Politecnico di Milano - 06/07/09
%==========================================================================
function [DOT,hete] = setHete(DOT,hete,solver)
%==========================================================================
%% OPTIONS
%==========================================================================
%-- default --%
if not(isfield(hete,'profile')), hete.profile = 'gaussian'; end
if not(isfield(hete,'distrib')), hete.distrib = 'OFF'; end
if not(isfield(hete,'geometry')), hete.geometry = 'sphere'; end
%==========================================================================
%% MAIN
%==========================================================================
switch upper(hete.geometry)
case 'SPHERE'
disp('+++ Sphere')
[DOT, hete] = sphere3D(DOT, hete, solver);
case 'CYLINDER'
disp('+++ Cylinder')
[DOT, hete] = cylinder3D(DOT, hete, solver);
case 'USIMAGE'
disp('+++ Distance Transform');
[DOT,~] = prior3D(DOT, hete, solver);
otherwise
error(['+++ ',hete.geometry,' : type unknown']);
end
for itype = 1: size(hete.type,2)
if isfield(hete, 'randinhom')
fprintf('Setting pesudo-inhomogeneities for %s \n', hete.type{itype});
if hete.randinhom(1) ~= 0 && hete.randinhom(2) ~= 0
[DOT.opt.(hete.type{itype}), ~] = AddPseudoInhom(DOT.opt.(hete.type{itype}),...
[DOT.grid.Nx, DOT.grid.Ny, DOT.grid.Nz ] , ...
hete.randinhom(1)/DOT.grid.dx,...
hete.randinhom(2) );
end
end
end
end
|
github
|
andreafarina/SOLUS-master
|
sphere3D.m
|
.m
|
SOLUS-master/src/subroutines/sphere3D.m
| 6,285 |
utf_8
|
59757a2b622bcab5b18466c12af11847
|
%-------------------------------------------------------------------------%
% Add a spherical inhomogeneity
%
% c -- [1x3] -- position of the center of the sphere
% var -- string -- the field you wanna mofify
% back -- [1x1] -- background value of 'var'
% DISTRIB -- string -- indicates wheter you wanna distribute the
% intensity within the inhomogeneity ('ON' or
% 'OFF')
% INTENSITY -- [1x1] -- maximum value of the inhomogeneous 'var'
% SHAPE -- string -- 'gaussian' or 'step'
% SIGMA -- [1x1] -- Width of the inhomogeneity
%
% N. Ducros - Departamento di Fisica - Politecnico di Milano - 29/11/10
% N. Ducros - Departamento di Fisica - Politecnico di Milano - 16/12/09
% N. Ducros - Departamento di Fisica - Politecnico di Milano - 22/12/09
% N. Ducros - Departamento di Fisica - Politecnico di Milano - 14/01/09
% N. Ducros - Departamento di Fisica - Politecnico di Milano - 02/02/09
% N. Ducros - Departamento di Fisica - Politecnico di Milano - 17/05/09
%-------------------------------------------------------------------------%
function [DOT,hete] = sphere3D(DOT, hete, solver)
%%--
SPE = 0;
SPE_CONC = 0;
SPE_SCA = 0;
sp = 1;
if contains(solver,'spectral')
sp = 2;
end
c = hete.c;
for is = 1:sp
for itype = 1:size(hete.type,2)
var = hete.type{itype}; %change the inclusion type Mua in absorption and Musp in scattering
if is >= 2
SPE = 1;
if strcmpi(var,'Mua')
SPE_CONC = 1;
SPE_SCA = 0;
elseif strcmpi(var,'Musp')
SPE_SCA = 1;
SPE_CONC = 0;
end
end
back = eval(['DOT.opt.',lower(hete.type{itype}),'B']); %muaB (and muspB in the next cycle) for background calculated from concentrations in TraslateXVar
sigma= hete.sigma;
intensity = hete.val((1:DOT.radiometry.nL)+(itype-1)*DOT.radiometry.nL); %val has the 8 values of absorption and 8 of scattering for the inclusion calculated in TranslateXVar
shape = hete.profile;
distrib = hete.distrib;
if SPE
if SPE_CONC
back = eval(['DOT.opt.concB']);
if iscolumn(back),back=back';end
intensity = hete.conc;
if iscolumn(intensity),intensity=intensity';end
end
if SPE_SCA
back = [eval('DOT.opt.aB') eval('DOT.opt.bB')];
intensity = [hete.a hete.b];
end
end
%% ----------------------- distances au carree mesh centre ---------------%
%-- Unstructured mesh --%
if isfield(DOT,'grid')
[X,Y,Z] = ndgrid(DOT.grid.x, DOT.grid.y, DOT.grid.z);
X = reshape(X,DOT.grid.N,[]);
Y = reshape(Y,DOT.grid.N,[]);
Z = reshape(Z,DOT.grid.N,[]);
M = [X-c(1) Y-c(2) Z-c(3)];
add = zeros(DOT.grid.N,numel(intensity));
Nx = DOT.grid.Nx;
Ny = DOT.grid.Ny;
Nz = DOT.grid.Nz;
%-- Regular mesh --%
else
M = [DOT.mesh.pos(:,1)-c(1) DOT.mesh.pos(:,2)-c(2) DOT.mesh.pos(:,3)-c(3)];
add = zeros(DOT.mesh.N,numel(intensity));
Nx = DOT.mesh.Nx;
Ny = DOT.mesh.Ny;
Nz = DOT.mesh.Nz;
end
dist2 = sum(M.^2,2);
if SPE
if SPE_CONC
var = 'Conc';
end
if SPE_SCA
var = 'AB';
DOT.opt.AB = cat(4,DOT.opt.A,DOT.opt.B);
end
end
switch upper(shape)
%% ---------------------- profil de concentration gaussien ---------------%
case 'GAUSSIAN'
%-- selection des indices --%
indx = find(dist2 < 9*sigma*sigma); %in absolute value all the indexes of dist2 numbers different from zero less than 9*sigma*sigma
%-- update concentration --%
param = getfield(DOT.opt, var);
switch upper(distrib)
case 'ON'
add(indx,:) = add(indx,:) + exp(-dist2(indx,1)/sigma/sigma);
add = add.*intensity./sum(add,1);
case 'OFF'
add(indx,:) = add(indx,:) + (intensity-back).*exp(-dist2(indx,1)/sigma/sigma);
%here the inclusion is created: for every value of absorption and
%scattering i subtract the background values
end
%% --------------------- profil de concentration creneau -----------------%
case 'STEP'
%-- selection des indices --%
indx = find(dist2 <= sigma*sigma);
%-- update concentration --%
param = getfield(DOT.opt, var);
switch upper(distrib)
case 'ON', add = intensity./length(indx);
case 'OFF',
param = reshape(param,DOT.grid.N,numel(intensity));
param(indx,:) = param(indx,:) + (intensity-back);
param = reshape(param,Nx,Ny,Nz,numel(intensity));
end
end
%% ---------------------------- Update -----------------------------------%
add = squeeze(reshape(add,Nx,Ny,Nz,numel(intensity)));
indx_dummy = indx;
for inl = 1:numel(intensity)-1
indx = [indx;indx_dummy+inl*DOT.grid.N];
end
param(indx) = param(indx) + add(indx);
if strcmpi(var,'AB')
hete = setfield(hete, ['d','A'], add(:,:,:,1));
hete = setfield(hete, ['d','B'], add(:,:,:,2));
DOT.opt = rmfield(DOT.opt,'AB');
DOT.opt = setfield(DOT.opt, var(1), param(:,:,:,1));
DOT.opt = setfield(DOT.opt, var(2), param(:,:,:,2));
else
hete = setfield(hete, ['d',var], add);
DOT.opt = setfield(DOT.opt, var, param);
end
end
end
|
github
|
andreafarina/SOLUS-master
|
cylinder3D.m
|
.m
|
SOLUS-master/src/subroutines/cylinder3D.m
| 8,364 |
utf_8
|
33231d4c4a08d5b0dee675158407e8f3
|
%-------------------------------------------------------------------------%
% Add a cylindrical inhomogeneity
%
% c -- [1x3] -- a point on the axis of the cylinder
% d -- [1x3] -- the direction of the axis of the cylinder
% var -- string -- the field you wanna mofify
% back -- [1x1] -- background value of 'var'
% INTENSITY -- [1x1] -- maximum value of the inhomogeneous 'var'
% SHAPE -- string -- 'gaussian' or 'step'
% SIGMA -- [1x1] -- radius of the cylinder
%
% N. Ducros - Departamento di Fisica - Politecnico di Milano - 08/02/10
% N. Ducros - Departamento di Fisica - Politecnico di Milano - 06/07/10
% A. Farina - CNR-IFN - Dip. Fisica - Politecnico di Milano - 10/04/15
%-------------------------------------------------------------------------%
function [DOT,hete] = cylinder3D(DOT,hete,solver,varargin)
%--
SPE = 0;
SPE_CONC = 0;
SPE_SCA = 0;
sp = 1;
if contains(solver,'spectral')
sp = 2;
end
d = hete.d; % direction vector
d = d./norm(d); % unitary direction vector
c = hete.c; % first point on the axis
l = hete.l; % length of the cylinder
for is = 1:sp
for itype = 1:size(hete.type,2)
var = hete.type{itype}; %change the inclusion type Mua in absorption and Musp in scattering
if is >= 2
SPE = 1;
if strcmpi(var,'Mua')
SPE_CONC = 1;
SPE_SCA = 0;
elseif strcmpi(var,'Musp')
SPE_SCA = 1;
SPE_CONC = 0;
end
end
back = eval(['DOT.opt.',lower(hete.type{itype}),'B']);
sigma = hete.sigma;
intensity = hete.val((1:DOT.radiometry.nL)+(itype-1)*DOT.radiometry.nL);
shape = hete.profile;
distrib = hete.distrib;
if SPE
if SPE_CONC
back = eval(['DOT.opt.concB']);
if iscolumn(back),back=back';end
intensity = hete.conc;
if iscolumn(intensity),intensity=intensity';end
end
if SPE_SCA
back = [eval('DOT.opt.aB') eval('DOT.opt.bB')];
intensity = [hete.a hete.b];
end
end
%-- --%
if isfield(DOT,'grid'),
%-- distance to the axis of the cylinder --%
D = [d(1)*ones(DOT.grid.N,1),d(2)*ones(DOT.grid.N,1),d(3)*ones(DOT.grid.N,1)];
[X,Y,Z] = ndgrid(DOT.grid.x,DOT.grid.y,DOT.grid.z);
X = reshape(X,DOT.grid.N,[]);
Y = reshape(Y,DOT.grid.N,[]);
Z = reshape(Z,DOT.grid.N,[]);
M = [X-c(1) Y-c(2) Z-c(3)];
dist = sum(cross(D,M).^2,2).^0.5./norm(d);
add = zeros(DOT.grid.N,numel(intensity));
Nx = DOT.grid.Nx;
Ny = DOT.grid.Ny;
Nz = DOT.grid.Nz;
else
%-- distance to the axis of the cylinder --%
D = [d(1)*ones(DOT.mesh.N,1),d(2)*ones(DOT.mesh.N,1),d(3)*ones(DOT.mesh.N,1)];
M = [DOT.mesh.pos(:,1)-c(1) DOT.mesh.pos(:,2)-c(2) DOT.mesh.pos(:,3)-c(3)];
dist = sum(cross(D,M).^2,2).^0.5./norm(d);
add = zeros(DOT.mesh.N,numel(intensity));
Nx = DOT.grid.Nx;
Ny = DOT.grid.Ny;
Nz = DOT.grid.Nz;
end
%-- axial distance --%
L = M*d';
ind1 = find(L>=0);
ind2 = find(L<=l);
ind = intersect(ind1,ind2);
if SPE
if SPE_CONC
var = 'Conc';
end
if SPE_SCA
var = 'AB';
DOT.opt.AB = cat(4,DOT.opt.A,DOT.opt.B);
end
end
switch upper(shape)
%-- profil de concentration gaussien --%
case 'GAUSSIAN'
%-- selection des indices --%
indx = find(dist < 3*sigma);
indx = intersect(indx,ind);
%-- update concentration --%
if isfield(DOT,'grid'),
param = getfield(DOT.opt, var);
else
a=lower(hete.type{itype});
param=getfield(DOT.opt,a);
end
switch upper(distrib)
case 'ON'
add(indx,:) = add(indx,:) + exp(-dist(indx,1).^2/sigma/sigma);
add = add.*intensity./sum(add,1);
add = squeeze(reshape(add,Nx,Ny,Nz,numel(intensity)));
indx_dummy = indx;
for inl = 1:numel(intensity)-1
indx = [indx;indx_dummy+inl*DOT.grid.N];
end
param(indx) = param(indx) + add(indx);
case 'OFF'
add(indx,:) = add(indx,:) + (intensity-back).*exp(-dist(indx,1).^2/sigma/sigma);
add = squeeze(reshape(add,Nx,Ny,Nz,numel(intensity)));
indx_dummy = indx;
for inl = 1:numel(intensity)-1
indx = [indx;indx_dummy+inl*DOT.grid.N];
end
param(indx) = param(indx) + add(indx);
end
if strcmpi(var,'AB')
hete = setfield(hete, ['d','A'], add(:,:,:,1));
hete = setfield(hete, ['d','B'], add(:,:,:,2));
DOT.opt = rmfield(DOT.opt,'AB');
DOT.opt = setfield(DOT.opt, var(1), param(:,:,:,1));
DOT.opt = setfield(DOT.opt, var(2), param(:,:,:,2));
else
hete = setfield(hete, ['d',var], add);
if isfield(DOT,'grid'),
DOT.opt = setfield(DOT.opt, var, param);
else
DOT.opt = setfield(DOT.opt, lower(var), param);
end
end
%-- profil de concentration creneau --%
case 'STEP'
%add = zeros(MOL.mesh.N,1);
%-- selection des indices --%
indx = find(dist <= sigma);
indx = intersect(indx,ind);
%-- update concentration --%
if isfield(DOT,'grid'),
param = getfield(DOT.opt, var);
else
a=lower(hete.type{itype});
param=getfield(DOT.opt,a);
end
switch upper(distrib)
case 'ON'
add(indx,:) = repmat(intensity./length(indx),numel(indx),1);
add = squeeze(reshape(add,Nx,Ny,Nz,numel(intensity)));
indx_dummy = indx;
for inl = 1:numel(intensity)-1
indx = [indx;indx_dummy+inl*DOT.grid.N];
end
param(indx) = param(indx) + add(indx);
case 'OFF'
add(indx,:) = repmat((intensity-back),numel(indx),1);
add = squeeze(reshape(add,Nx,Ny,Nz,numel(intensity)));
indx_dummy = indx;
for inl = 1:numel(intensity)-1
indx = [indx;indx_dummy+inl*DOT.grid.N];
end
param(indx) = param(indx) + add(indx);
end
hete = setfield(hete, ['d',hete.type{itype}], add);
if strcmpi(var,'AB')
hete = setfield(hete, ['d','A'], add(:,:,:,1));
hete = setfield(hete, ['d','B'], add(:,:,:,2));
DOT.opt = rmfield(DOT.opt,'AB');
DOT.opt = setfield(DOT.opt, var(1), param(:,:,:,1));
DOT.opt = setfield(DOT.opt, var(2), param(:,:,:,2));
else
hete = setfield(hete, ['d',var], add);
if isfield(DOT,'grid'),
DOT.opt = setfield(DOT.opt, var, param);
else
DOT.opt = setfield(DOT.opt, lower(var), param);
end
end
end
end
end
|
github
|
andreafarina/SOLUS-master
|
prior3D.m
|
.m
|
SOLUS-master/src/subroutines/prior3D.m
| 3,176 |
utf_8
|
9bd7d15c3e7e055072acf30d162488f6
|
%-------------------------------------------------------------------------%
% Add a generic inhomogeneity
%
% var -- string -- the field you wanna mofify
% back -- [1x1] -- background value of 'var'
% INTENSITY -- [1x1] -- maximum value of the inhomogeneous 'var'
%
% No profiles are implemented. We get a binary tridimensional mask.
%-------------------------------------------------------------------------%
function [DOT, hete] = prior3D(DOT,hete,solver)
SPE = 0;
SPE_CONC = 0;
SPE_SCA = 0;
NumLoops = 1;
if contains(solver,'spectral')
NumLoops = 2;
end
for is = 1:NumLoops
for itype = 1:size(hete.type,2)
var = hete.type{itype};
if is >= 2
SPE = 1;
if strcmpi(var,'Mua')
SPE_CONC = 1;
SPE_SCA = 0;
elseif strcmpi(var,'Musp')
SPE_SCA = 1;
SPE_CONC = 0;
end
end
back = eval(['DOT.opt.',lower(hete.type{itype}),'B']);
intensity = hete.val((1:DOT.radiometry.nL)+(itype-1)*DOT.radiometry.nL);
%distrib = hete.distrib;
if SPE
if SPE_CONC
back = eval(['DOT.opt.concB']);
if iscolumn(back),back=back';end
intensity = hete.conc;
if iscolumn(intensity),intensity=intensity';end
end
if SPE_SCA
back = [eval('DOT.opt.aB') eval('DOT.opt.bB')];
intensity = [hete.a hete.b];
end
end
if isfield(DOT,'grid')
nx = DOT.grid.Nx;
ny = DOT.grid.Ny;
nz = DOT.grid.Nz;
add = zeros(DOT.grid.N,numel(intensity));
Nx = DOT.grid.Nx;
Ny = DOT.grid.Ny;
Nz = DOT.grid.Nz;
%-- Regular mesh --%
else
M = [DOT.mesh.pos(:,1)-c(1) DOT.mesh.pos(:,2)-c(2) DOT.mesh.pos(:,3)-c(3)];
add = zeros(DOT.mesh.N,numel(intensity));
Nx = DOT.mesh.Nx;
Ny = DOT.mesh.Ny;
Nz = DOT.mesh.Nz;
end
if SPE
if SPE_CONC
var = 'Conc';
end
if SPE_SCA
var = 'AB';
DOT.opt.AB = cat(4,DOT.opt.A,DOT.opt.B);
end
end
%% here!
smask = load(hete.path);
fn = fieldnames(smask);
delta = smask.(fn{1});
mask = smask.(fn{2});
%% swap fields... in case
if ~isvector(delta)
dd = mask;
mask = delta;
delta = dd;
end
prior = priormask3D(hete.path,DOT.grid);
param = getfield(DOT.opt, var);
for inl = 1:numel(intensity)
param(:,:,:,inl) = param(:,:,:,inl) + double(prior).*(intensity(inl)-back(inl));
end
if strcmpi(var,'AB')
DOT.opt = rmfield(DOT.opt,'AB');
DOT.opt = setfield(DOT.opt, var(1), param(:,:,:,1));
DOT.opt = setfield(DOT.opt, var(2), param(:,:,:,2));
else
DOT.opt = setfield(DOT.opt, var, param);
end
end
end
end
|
github
|
andreafarina/SOLUS-master
|
remove_voxels.m
|
.m
|
SOLUS-master/src/subroutines/remove_voxels.m
| 468 |
utf_8
|
bed213d459f444c0f6d71d1219b366df
|
% load('C:\Users\monia\Desktop\PROVE\15-2m\0.01spectral_tk1-ROItuttalacurva_fattorediconversione\Test_Standard_REC')
function [bmua, bmusp, bConc] = remove_voxels(bmua, bmusp, bConc, dim, mua0, musp0, conc0)
for j = 1 : (dim(1)*dim(2))
bConc(j,:) = conc0(:);
end
for j = 1 : (dim(1)*dim(2))
bmua(j,:) = mua0(:);
bmusp(j,:) = musp0(:);
end
end
% openfig('fig.fig')
% roi = drawcircle('Color','k','FaceAlpha',0.4);
% mask = createMask(roi);
% imshow(mask)
|
github
|
andreafarina/SOLUS-master
|
setGrid.m
|
.m
|
SOLUS-master/src/subroutines/setGrid.m
| 2,690 |
utf_8
|
732894c18aa28cb60b948248c2b5042e
|
% =========================================================================
% This function sets the reconstruction grid
%
% N. Ducros - Departimento di Fisica - Politecnico di Milano - 24/09/10
% A. Farina - CNR-IFN - Dip. di Fisica - Politecnico di Milano 14/04/15
% A. Farina - CNR-IFN - Dip di Fisica - Politecnico di Milano 20/12/16
% if hMesh doesn't exist it jump toastBasis
% =========================================================================
function grid = setGrid(DOT)
global mesh
grid = DOT.grid;
%
grid.dV = DOT.grid.dx*DOT.grid.dy*DOT.grid.dz;
%
if (sum(size(mesh)) == 0)
grid.x = (DOT.grid.x1:DOT.grid.dx:(DOT.grid.x2-DOT.grid.dx)) + DOT.grid.dx/2;
grid.y = (DOT.grid.y1:DOT.grid.dy:(DOT.grid.y2-DOT.grid.dy)) + DOT.grid.dy/2;
grid.z = (DOT.grid.z1:DOT.grid.dz:(DOT.grid.z2-DOT.grid.dz)) + DOT.grid.dz/2;
%
grid.Nx = length(grid.x);
grid.Ny = length(grid.y);
grid.Nz = length(grid.z);
grid.N = grid.Nx*grid.Ny*grid.Nz;
grid.dim = [grid.Nx, grid.Ny, grid.Nz];
%
else %isfield(DOT,'mesh')
bbox = mesh.hMesh.BoundingBox;
minX = min(bbox(:,1));
minY = min(bbox(:,2));
minZ = min(bbox(:,3));
maxX = max(bbox(:,1));
maxY = max(bbox(:,2));
maxZ = max(bbox(:,3));
grid.x = DOT.grid.x1:DOT.grid.dx:DOT.grid.x2;
grid.y = DOT.grid.y1:DOT.grid.dy:DOT.grid.y2;
grid.z = DOT.grid.z1:DOT.grid.dz:DOT.grid.z2;
%
grid.Nx = length(grid.x);
grid.Ny = length(grid.y);
grid.Nz = length(grid.z);
grid.N = grid.Nx*grid.Ny*grid.Nz;
grid.dim=[grid.Nx, grid.Ny, grid.Nz];
%------- no bounding box, i.e. the whole mesh volume is considered -------%
if (DOT.grid.x1 == minX) && (DOT.grid.y1 == minY) && (DOT.grid.z1 == minZ) && ...
(DOT.grid.x2 == maxX) && (DOT.grid.y2 == maxY) && (DOT.grid.z2 == maxZ)
% grid.hBasis = toastSetBasis('LINEAR', DOT.mesh.hMesh, ...
grid.hBasis = toastBasis(mesh.hMesh, ...
[grid.Nx, grid.Ny, grid.Nz],'LINEAR' );
%-------- with bounding box, i.e. the mesh is truncated ------------------%
else
% grid.hBasis = toastSetBasis('LINEAR', DOT.mesh.hMesh, ...
grid.hBasis = toastBasis(mesh.hMesh, ...
[grid.Nx, grid.Ny, grid.Nz], ...
[grid.Nx, grid.Ny, grid.Nz], ...
[DOT.grid.x1, DOT.grid.x2; ...
DOT.grid.y1,DOT.grid.y2; ...
DOT.grid.z1,DOT.grid.z2],'LINEAR' );
end
%
grid.mask = find(grid.hBasis.GridElref>0);
% following is a bit of a guess..
%grid.mask = grid.hBasis.Map('B->S',ones(grid.Nx, grid.Ny, grid.Nz));
%grid.NN =length(grid.mask);
end
|
github
|
andreafarina/SOLUS-master
|
SemiInfinite_TR.m
|
.m
|
SOLUS-master/src/fwd/SemiInfinite_TR.m
| 525 |
utf_8
|
395e442bc390be99bf780418ee65523f
|
% TIME-RESOLVED FLUENCE INSIDE A Semi-INFINITE MEDIUM using PCBC
% function phi = SemiInfinite_TR(time,rs,rd,mua,mus,v,A);
function phi = SemiInfinite_TR(time,rs,rd,mua,mus, v,A)
%%
% rs source position
% rd detector position
if rs(3) > 0
z0=rs(3);
elseif rs(3)==0
z0=1/mus;
rs(3)=z0;
end
D = 1/(3*mus);
ze=2*A*D;
rs_min=rs; rs_min(3)=-2*ze-z0;
%phi = zeros(size(time));
phi=(Infinite_TR(time,rs,rd,mua,mus,v)-Infinite_TR(time,rs_min,rd,mua,mus,v))./(2*A);
phi(isnan(phi))=0;
return
|
github
|
andreafarina/SOLUS-master
|
SemiInfinite_CW.m
|
.m
|
SOLUS-master/src/fwd/SemiInfinite_CW.m
| 393 |
utf_8
|
2f69b19854a125fc414d5463289a93e7
|
% CW FLUENCE INSIDE AN INFINITE MEDIUM
function phi = SemiInfinite_CW(rs,rd,mua,mus,A)
%%
% rs source position
% rd detector position
if rs(3) > 0,
z0=rs(3);
elseif rs(3)==0,
z0=1/mus;
rs(3)=z0;
end
D = 1/(3*mus);
ze=2*A*D;
rs_min=rs; rs_min(3)=-2*ze-z0;
phi=(Infinite_CW(rs,rd,mua,mus)-Infinite_CW(rs_min,rd,mua,mus))./(2*A);
phi(isnan(phi))=0;
return
|
github
|
andreafarina/SOLUS-master
|
Infinite_TR.m
|
.m
|
SOLUS-master/src/fwd/Infinite_TR.m
| 446 |
utf_8
|
4f1a24f68544581262548ceaea4bf7fb
|
% TIME-RESOLVED FLUENCE INSIDE AN INFINITE MEDIUM
% function phi = Infinite_TR(time,rs,rd,mua,mus, v,~);
function phi = Infinite_TR(time,rs,rd,mua,mus, v,~,~)
%%
% rs source position
% rd detector position
delta_r=rs-rd;
rhosq=delta_r*delta_r';
%cm/ps velocita' della luce
D = 1/(3*mus);
mu = 1./(4*D*v*time);
%phi = zeros(size(time));
phi=v./(4*pi*D*v*time).^(1.5).*exp(-mua*v*time-mu*rhosq);
phi(isnan(phi))=0;
return
|
github
|
andreafarina/SOLUS-master
|
Contini1997.m
|
.m
|
SOLUS-master/src/fwd/Contini1997.m
| 13,674 |
utf_8
|
63a3ea2a3b300d70e1033f4c76bece33
|
function [Rrhot,Trhot,Rrho,Trho,Rt,Tt,lrhoR,lrhoT,R,T,A,Z] = Contini1997(rho,t,s,mua,musp,n1,n2,phantom,DD,m)
%
% [Rrhot,Trhot,Rrho,Trho,Rt,Tt,lrhoR,lrhoT,R,T,A,Z] = Contini1997(rho,t,s,mua,musp,n1,n2,phantom,DD,m)
%
% From:
% Contini D, Martelli F, Zaccanti G.
% Photon migration through a turbid slab described by a model
% based diffusion approximation. I. Theory
% Applied Optics Vol 36, No 19, 1997, pp 4587-4599
%
% phantom: if phantom='semiinf' then semi-infinite medium (please set s=inf)
% if phantom='slab' then slab
% rho: radial position of the detector at distance s
% t: time (ns)
% s: slab thickness (mm)
% m: maximum number of positive or negative sources
% m automatically set to 200 if m=[] for a slab
% and automatically set to m=0 for a semi-infinite medium
% mua: absorption coefficient mm^(-1)
% musp: reduced scattering coefficient
% n1: external medium
% n2: diffusing medium
%
% The diffusion coefficient utilized for the calculation is
% DD: if DD = 'Dmuas' then mua dependent, D = 1/(3*(musp+mua)) (equation (19))
% if DD = 'Dmus' then D = 1/(3*musp) (page 4588)
% Rrhot: time resolved reflectance mm^(-2) ps^(-1) (equation (36))
% N x M matrix (N rho values and M t values)
% Trhot: time resolved transmittance mm^(-2) ps^(-1) (equation (39))
% N x M matrix (N rho values and M t values)
% Rrho: reflectance mm^(-2) (equation (45))
% N rho values
% Trho: transmittance mm^(-2) (equation (46))
% N rho values
% Rt: equation (40) ps^(-1)
% Tt: equation (41) ps^(-1)
% lrhoR: equation (47) mm
% lrhoT: equation (48) mm
% A : equations (27) and (29)
% Z : equations (37) for -m:m (first line -m, last line m)
%
% 22/3/2013
% Tiziano BINZONI (University of Geneva)
% Fabrizio MARTELLI (University of Firenze)
% Alessandro TORRICELLI (Politecnico di Milano)
%
% 18/4/2013
% 1) Now it is possible to use m as input of Contini1997
% 2) Contini1997 generates now a warning message if any of the generated
% variables values changes more than 1e-6 percent when going from m to m+1
if nargin < 10,
error('number of input arguments for Contini1997 must be 10');
end
if strcmp(phantom,'slab'),
if isempty(m),
m=200;
end
elseif strcmp(phantom,'semiinf'),
m=0;
s=1;
else
error('define phantom type as: ''slab'' or ''semiinf''');
end
t=t*1e-9;
rho=rho*1e-3;
s=s*1e-3;
mua=mua*1e3;
musp=musp*1e3;
% max accepted error on compuzed data
err=1e-6;
% Generates equations (36) and (39)
[Rrhot,Trhot] = RTrhotfunction(rho,t,s,m,mua,musp,n1,n2,DD);
if ~strcmp(phantom,'semiinf'),
[Rrhot1,Trhot1] = RTrhotfunction(rho,t,s,m+1,mua,musp,n1,n2,DD);
WarningPrcfunction(Rrhot,Rrhot1,'Rrhot',err);
WarningPrcfunction(Trhot,Trhot1,'Trhot',err);
end
% Generates equations (45) and (46)
[Rrho,Trho] = RTrhofunction(rho,s,m,mua,musp,n1,n2,DD);
if ~strcmp(phantom,'semiinf'),
[Rrho1,Trho1] = RTrhofunction(rho,s,m+1,mua,musp,n1,n2,DD);
WarningPrcfunction(Rrho,Rrho1,'Rrho',err);
WarningPrcfunction(Trho,Trho1,'Trho',err);
end
% Generates equations (40) and (41)
[Rt,Tt] = RTtfunction(t,s,m,mua,musp,n1,n2,DD);
if ~strcmp(phantom,'semiinf'),
[Rt1,Tt1] = RTtfunction(t,s,m+1,mua,musp,n1,n2,DD);
WarningPrcfunction(Rt,Rt1,'Rt',err);
WarningPrcfunction(Tt,Tt1,'Tt',err);
end
% Generates equations (47) and (48)
[lrhoR,lrhoT] = lrhoTRfunction(rho,s,m,mua,musp,n1,n2,DD);
if ~strcmp(phantom,'semiinf'),
[lrhoR1,lrhoT1] = lrhoTRfunction(rho,s,m+1,mua,musp,n1,n2,DD);
WarningPrcfunction(lrhoR,lrhoR1,'lrhoR',err);
WarningPrcfunction(lrhoT,lrhoT1,'lrhoT',err);
end
% Generates equations (49) and (50)
[R,T] = TRfunction(s,m,mua,musp,n1,n2,DD);
if ~strcmp(phantom,'semiinf'),
[R1,T1] = TRfunction(s,m+1,mua,musp,n1,n2,DD);
WarningPrcfunction(R,R1,'R',err);
WarningPrcfunction(T,T1,'T',err);
end
% Generates equations (27) and (29)
A = Afunction(n1,n2);
% Generates equations (37) for the utilized m values
Z=[];
for i=-m:m,
[z1,z2,z3,z4]=zfunction(s,i,mua,musp,n1,n2,DD);
Z=[Z;z1,z2,z3,z4];
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function A=Afunction(n1,n2)
% Computes parameter A; equation (27)
%
% n1: external medium
% n2: diffusing medium
% page 4590
n=n2/n1;
if n>1,
% equations (30)
t1 = 4*(-1-n^2+6*n^3-10*n^4-3*n^5+2*n^6+6*n^7-3*n^8-(6*n^2+9*n^6)*(n^2-1)^(1/2))/...
(3*n*(n^2-1)^2*(n^2+1)^3);
t2 = (-8+28*n^2+35*n^3-140*n^4+98*n^5-13*n^7+13*n*(n^2-1)^3*(1-(1/n^2))^(1/2))/...
(105*n^3*(n^2-1)^2);
t3 = 2*n^3*(3+2*n^4)*log(...
((n-(1+n^2)^(1/2))*(2+n^2+2*(1+n^2)^(1/2))*(n^2+(n^4-1)^(1/2)))/...
(n^2*(n+(1+n^2)^(1/2))*(-n^2+(n^4-1)^(1/2)))...
)/...
((n^2-1)^2*(n^2+1)^(7/2));
t4 = ( (1+6*n^4+n^8)*log((-1+n)/(1+n))+4*(n^2+n^6)*log((n^2*(1+n))/(n-1)) )/...
((n^2-1)^2*(n^2+1)^3);
% equation (29)
B = 1+(3/2)*( 2*(1-1/n^2)^(3/2)/3+t1+t2+( (1+6*n^4+n^8)*(1-(n^2-1)^(3/2)/n^3) )/( 3*(n^4-1)^2) +t3 );
C = 1-( (2+2*n-3*n^2+7*n^3-15*n^4-19*n^5-7*n^6+3*n^7+3*n^8+3*n^9)/(3*n^2*(n-1)*(n+1)^2*(n^2+1)^2) )-t4;
A = B/C;
elseif n==1,
%page 4591
A=1;
else
% equations (28)
r1 = (-4+n-4*n^2+25*n^3-40*n^4-6*n^5+8*n^6+30*n^7-12*n^8+n^9+n^11)/...
(3*n*(n^2-1)^2*(n^2+1)^3);
r2 = (2*n^3*(3+2*n^4))/((n^2-1)^2*(n^2+1)^(7/2))*...
log( (n^2*(n-(1+n^2)^(1/2)))*(2+n^2+2*(1+n^2)^(1/2))/...
(n+(1+n^2)^(1/2))/(-2+n^4-2*(1-n^4)^(1/2)) );
r3 = (4*(1-n^2)^(1/2)*(1+12*n^4+n^8))/...
(3*n*(n^2-1)^2*(n^2+1)^3);
r4 = ( (1+6*n^4+n^8)*log((1-n)/(1+n))+4*(n^2+n^6)*log((1+n)/(n^2*(1-n))) )/...
((n^2-1)^2*(n^2+1)^3);
% equation (27)
A = (1+(3/2)*(8*(1-n^2)^(3/2)/(105*n^3))-(((n-1)^2*(8+32*n+52*n^2+13*n^3))/(105*n^3*(1+n)^2)+r1+r2+r3) )/...
(1-(-3+7*n+13*n^2+9*n^3-7*n^4+3*n^5+n^6+n^7)/(3*(n-1)*(n+1)^2*(n^2+1)^2)-r4);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [Rrhot,Trhot] = RTrhotfunction(rho,t,s,m,mua,musp,n1,n2,DD)
% Computes equations (36) and (39)
%
% rho: radial position of the detector at distance s
% t: time
% s: slab thickness
% m: maximum number of positive or negative sources
% mua: absorption coefficient
% musp: reduced scattering coefficient
% n1: external medium
% n2: diffusing medium
% Generates equations (36) and (39)
Rrhot=[];
Trhot=[];
for i=1:length(rho);
[Rrhottmp,Trhottmp] = RTrhotfunctionPartial(rho(i),t,s,m,mua,musp,n1,n2,DD);
Rrhot=[Rrhot;Rrhottmp];
Trhot=[Trhot;Trhottmp];
end
if m==0, Trhot=[];end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [Rrhot,Trhot] = RTrhotfunctionPartial(rho,t,s,m,mua,musp,n1,n2,DD)
% speed of light
c=299792458; % m s^(-1)
v=c/n2;
% equation (19)
D=Dfunction(DD,mua,musp);
% equations (36) and (39)
Rrhottmp = 0;
Trhottmp = 0;
for i=-m:m,
[z1,z2,z3,z4]=zfunction(s,i,mua,musp,n1,n2,DD);
Rrhottmp = Rrhottmp + ...
z3*exp(-z3^2./(4*D*v*t)) - z4*exp(-z4^2./(4*D*v*t));
Trhottmp = Trhottmp + ...
z1*exp(-z1^2./(4*D*v*t)) - z2*exp(-z2^2./(4*D*v*t));
end
Rrhot = -exp(-mua*v*t-rho^2./(4*D*v*t))./(2*(4*pi*D*v)^(3/2)*t.^(5/2)) .* Rrhottmp;
Trhot = exp(-mua*v*t-rho^2./(4*D*v*t))./(2*(4*pi*D*v)^(3/2)*t.^(5/2)) .* Trhottmp;
Rrhot=Rrhot*1e-6*1e-12;
Trhot=Trhot*1e-6*1e-12;
Rrhot(t<=0)=0;
Trhot(t<=0)=0;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [Rrho,Trho] = RTrhofunction(rho,s,m,mua,musp,n1,n2,DD)
% Computes equations (45) and (46)
%
% rho: radial position of the detector at distance s
% s: slab thickness
% m: maximum number of positive or negative sources
% mua: absorption coefficient
% musp: reduced scattering coefficient
% n1: external medium
% n2: diffusing medium
% equation (19)
D=Dfunction(DD,mua,musp);
% equation (45) and (46)
Rrhotmp=0;
Trhotmp=0;
for i=-m:m,
[z1,z2,z3,z4]=zfunction(s,i,mua,musp,n1,n2,DD);
Rrhotmp=Rrhotmp+...
z3*( D^(-1/2)*mua^(1/2)*(rho.^2+z3^2).^(-1) + (rho.^2+z3^2).^(-3/2) ).*exp( -(mua*(rho.^2+z3^2)/D).^(1/2) )-...
z4*( D^(-1/2)*mua^(1/2)*(rho.^2+z4^2).^(-1) + (rho.^2+z4^2).^(-3/2) ).*exp( -(mua*(rho.^2+z4^2)/D).^(1/2) );
Trhotmp=Trhotmp+...
z1*( D^(-1/2)*mua^(1/2)*(rho.^2+z1^2).^(-1) + (rho.^2+z1^2).^(-3/2) ).*exp( -(mua*(rho.^2+z1^2)/D).^(1/2) )-...
z2*( D^(-1/2)*mua^(1/2)*(rho.^2+z2^2).^(-1) + (rho.^2+z2^2).^(-3/2) ).*exp( -(mua*(rho.^2+z2^2)/D).^(1/2) );
end
Rrho=-1/(4*pi)*Rrhotmp;
Trho= 1/(4*pi)*Trhotmp;
Rrho=Rrho*1e-6;
Trho=Trho*1e-6;
if m==0, Trho=[];end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [Rt,Tt] = RTtfunction(t,s,m,mua,musp,n1,n2,DD)
% Computes equations (40) and (41)
%
% t: time
% s: slab thickness
% m: maximum number of positive or negative sources
% mua: absorption coefficient
% musp: reduced scattering coefficient
% n1: external medium
% n2: diffusing medium
% speed of light
c=299792458; % m s^(-1)
v=c/n2;
% equation (19)
D=Dfunction(DD,mua,musp);
% equations (40) and (41)
Rttmp=0;
Tttmp=0;
for i=-m:m,
[z1,z2,z3,z4]=zfunction(s,i,mua,musp,n1,n2,DD);
Rttmp=Rttmp+z3*exp(-z3^2./(4*D*v*t))-z4*exp(-z4^2./(4*D*v*t));
Tttmp=Tttmp+z1*exp(-z1^2./(4*D*v*t))-z2*exp(-z2^2./(4*D*v*t));
end
Rt=-exp(-mua*v*t)./(2*(4*pi*D*v)^(1/2)*t.^(3/2)).*Rttmp;
Tt= exp(-mua*v*t)./(2*(4*pi*D*v)^(1/2)*t.^(3/2)).*Tttmp;
Rt=Rt*1e-12;
Tt=Tt*1e-12;
if m==0, Tt=[];end
Tt(t<=0)=0;
Rt(t<0)=0;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [lrhoR,lrhoT] = lrhoTRfunction(rho,s,m,mua,musp,n1,n2,DD)
% Computes equations (47) and (48)
% These equations are valid only for mua>0
%
% rho: radial position of the detector at distance s
% s: slab thickness
% m: maximum number of positive or negative sources
% mua: absorption coefficient
% musp: reduced scattering coefficient
% n1: external medium
% n2: diffusing medium
% equation (19)
D=Dfunction(DD,mua,musp);
% equations (45) and (46)
[Rrho,Trho] = RTrhofunction(rho,s,m,mua,musp,n1,n2,DD);
Rrho=Rrho*1e6;
Trho=Trho*1e6;
% equations (47) and (48)
if mua<=0,
lrhoR=[];
lrhoT=[];
else
lrhoRtmp=0;
lrhoTtmp=0;
for i=-m:m,
[z1,z2,z3,z4]=zfunction(s,i,mua,musp,n1,n2,DD);
lrhoRtmp=lrhoRtmp+...
z3*(rho.^2+z3^2).^(-1/2).*exp(-(mua*(rho.^2+z3^2)/D).^(1/2))-...
z4*(rho.^2+z4^2).^(-1/2).*exp(-(mua*(rho.^2+z4^2)/D).^(1/2));
lrhoTtmp=lrhoTtmp+...
z1*(rho.^2+z1^2).^(-1/2).*exp(-(mua*(rho.^2+z1^2)/D).^(1/2))-...
z2*(rho.^2+z2^2).^(-1/2).*exp(-(mua*(rho.^2+z2^2)/D).^(1/2));
end
lrhoR=(-1./(8*pi*D*Rrho)).*lrhoRtmp;
if ~isempty(Trho),
lrhoT= (1./(8*pi*D*Trho)).*lrhoTtmp;
else
lrhoT=[];
end
lrhoR=lrhoR*1e3;
lrhoT=lrhoT*1e3;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [R,T] = TRfunction(s,m,mua,musp,n1,n2,DD)
% Computes equations (49) and (50)
% These equations are valid only for mua>0
%
% s: slab thickness
% m: maximum number of positive or negative sources
% mua: absorption coefficient
% musp: reduced scattering coefficient
% n1: external medium
% n2: diffusing medium
% equation (19)
D=Dfunction(DD,mua,musp);
% equations (49) and (50)
if mua>0,
Rtmp=0;
Ttmp=0;
for i=-m:m,
[z1,z2,z3,z4]=zfunction(s,i,mua,musp,n1,n2,DD);
Rtmp=Rtmp+...
(sign(z3)*exp(-(mua/D)^(1/2)*abs(z3))-sign(z4)*exp(-(mua/D)^(1/2)*abs(z4)));
Ttmp=Ttmp+...
(sign(z1)*exp(-(mua/D)^(1/2)*abs(z1))-sign(z2)*exp(-(mua/D)^(1/2)*abs(z2)));
end
R=-(1/2)*Rtmp;
T= (1/2)*Ttmp;
else
R=[];
T=[];
end
if m==0, T=[];end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [z1,z2,z3,z4]=zfunction(s,m,mua,musp,n1,n2,DD)
% Computes equation (37)
%
% s: slab thickness
% m: maximum number of positive or negative sources
% mua: absorption coefficient
% musp: reduced scattering coefficient
% n1: external medium
% n2: diffusing medium
% page 4592
z0 = 1/musp;
%z0 = 1/(musp+mua);
% equation (27)
A = Afunction(n1,n2);
% A=504.332889-2641.0021*(n2/n1)+5923.699064*(n2/n1)^2-...
% 7376.355814*(n2/n1)^3+5507.53041*(n2/n1)^4-...
% 2463.357945*(n2/n1)^5+610.956547*(n2/n1)^6-...
% 64.8047*(n2/n1)^7;
% equation (19)
D=Dfunction(DD,mua,musp);
%page 4592
ze = 2*A*D;
z1 = s*(1-2*m) - 4*m*ze - z0;
z2 = s*(1-2*m) - (4*m-2)*ze + z0;
z3 = -2*m*s -4*m*ze - z0;
z4 = -2*m*s -(4*m-2)*ze + z0;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function D=Dfunction(DD,mua,musp)
% equation (19)
if strcmp(DD,'Dmuas'),
D = 1/(3*(musp+mua));
elseif strcmp(DD,'Dmus'),
D = 1/(3*(musp));
else
error('DD must be equal to ''Dmuas'' or ''Dmus''');
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function WarningPrcfunction(x,y,label,err)
%size(x)
%size(y)
if ~isempty(x) && ~isempty(y),
prcMax=max(max(abs( (x-y)./x*100)));
if prcMax>err,
warning(['increase m (error larger than ',num2str(err),'% for ',label,')']);
end
end
end
|
github
|
andreafarina/SOLUS-master
|
Infinite_CW.m
|
.m
|
SOLUS-master/src/fwd/Infinite_CW.m
| 301 |
utf_8
|
28ac6a483f8c19ea5e80ec219038914b
|
% CW FLUENCE INSIDE AN INFINITE MEDIUM
function phi = Infinite_CW(rs,rd,mua,mus)
%%
% rs source position
% rd detector position
delta_r=rs-rd;
rho=sqrt(delta_r*delta_r');
mueff=sqrt(mua*mus*3);
D = 1/(3*mus);
phi=1./(4*pi*D*rho).*exp(-mueff*rho);
%phi(isnan(phi))=0;
return
|
github
|
andreafarina/SOLUS-master
|
priormask3D.m
|
.m
|
SOLUS-master/src/UCLutils/priormask3D.m
| 1,111 |
utf_8
|
184186495cd0560c9d45d51990567d4a
|
function mask = priormask3D(path,grid, type)
Nx = grid.Nx;
Ny = grid.Ny;
Nz = grid.Nz;
DOT_GRID = 1;FACT = [1,1,1];
%% here!
smask = load(path);
fn = fieldnames(smask);
mask = smask.(fn{1});
delta = smask.(fn{2});
%% swap fields... in case
if ~isvector(delta)
dd = mask;
mask = delta;
delta = dd;
end
final_dims = [grid.x1,grid.y1,grid.z1;...
grid.x2,grid.y2,grid.z2];
mask_oversampled = segment2grid(mask, delta, final_dims);
if DOT_GRID == 1 %if manual mapping of prior of DOT grid
mask = logical(imresizen(single(mask_oversampled),...
[Nx,Ny,Nz]./size(mask_oversampled),'nearest'));
return;
else
if exist('type', 'var') == 1
if strcmpi(type,'fit4param') == 1 % when considering TOAST is better not to resize it, proportions are already handled
mask = logical(imresizen(single(mask_oversampled),...
FACT,'nearest'));
return;
end
else
mask = logical(imresizen(single(mask_oversampled),...
[Nx,Ny,Nz]./size(mask_oversampled),'nearest'));
return;
end
% end
end
|
github
|
andreafarina/SOLUS-master
|
snake_fitting.m
|
.m
|
SOLUS-master/src/UCLutils/snake_fitting.m
| 8,043 |
utf_8
|
f7a210f7a4dd17eb784c7d0857801cdd
|
function [sgm, param] = snake_fitting(im, cor)
%
% [SGM, PARAM] = snake_fitting(IM, COR)
% This function takes as input a 2d rgb US-image IM and a set of user generated
% points COR and tries to fit a better contour to the inclusion.
% It returns the resulted segmented image SGM and an updated set of points
% PARAM to generate the spline if needed.
%load to_load3 % load for safety test
% convert image to double and normailise
im = double(rgb2gray(im));
im = im/max(im(:));
% keep user selected points
cor0 = cor;
% number of points after spline
npoints = 400;
% number of parameters though which the updated spline will be run
nparam = 2*(numel(cor)-1);
points0 = Lee_spline(cor, npoints);
param = Lee_spline(cor, nparam+1);
param = param(:,1:end-1);
param0 = param;
order = 1;
dStep = 0.1;
%drawfitting(param, npoints, im);
nsigma = 15;
minsigma = 0.15;
maxsigma = 0.7;
sigma_p = linspace(maxsigma,minsigma,nsigma);
i_s = 1;
% calculate image features
dstruct = setDomain(im, param0, sigma_p, points0);
dstruct0 = dstruct;
dstruct0dist = dstruct0.dist;
dstruct.dist = dstruct0.dist(:,:,i_s);
dstruct.points0 = points0;
% initialise cycle
k = 1;
max_k = 16;
max_ik = 100;
alpha0 = 30*dStep;
% compute initial loss
Ln = Loss(forward(param,npoints), dstruct,param, param0);
while k <= max_k
% update loss
L = Ln;
% compute gradient
[~, ~, dUp] = computeGradient2(param, dStep, npoints, dstruct, param0, L, order);
dUp = dUp/max(abs(dUp(:)));
% update parameters
alpha = alpha0;
ik = 1;
% compute loss
Ln = Loss(forward((param - alpha*(dUp)),npoints), dstruct,param, param0);
while Ln > L && ik <= max_ik
alpha = alpha * 0.9;
%dUp = dUp;% .* (abs(dUp/L) > 0 );
Ln = Loss(forward((param - alpha*(dUp)),npoints), dstruct,param, param0);
ik = ik + 1;
end
if Ln < L % check if line search went well
param = param - alpha*(dUp);
else % end minimisation for current smoothing
k = max_k +1;
end
if k>=max_k && i_s < numel(sigma_p)
% move to narrower smoothing
i_s = i_s + 1;
dstruct.dist = dstruct0dist(:,:,i_s);
dstruct.points0 = points0;
Ln = Loss(forward(param,npoints), dstruct,param, param0);
k = 0;
end
k = k+1;
% drawfitting(param, npoints, im);
end
drawfitting(param, npoints, im);
points=forward(param, npoints)';
sgm=roipoly(im,points(:,1),points(:,2));
end
function drawfitting(param, npoints, im)
% draws
points = forward(param, npoints);
figure(1), imagesc(im);colormap('gray'),hold on
plot(points(1,:),points(2,:),'r','LineWidth',2);
plot(cat(2,param(1,:), param(1,1)),cat(2,param(2,:), param(2,1)),'y.');
drawnow;
end
function out = forward(spline_points, num)
corf = cat(2, spline_points, spline_points(:,1));
%cor = spline_points;
out = Lee_spline(corf, num);
end
function d = setDomain(im,cor, sigma_p, pp)
[gx,gy] = imgradientxy(im);
[gx2,~] = imgradientxy(gx);
[~, gy2] = imgradientxy(gy);
lap = gx2 + gy2;
minx = min(cor(1,:));
maxx = max(cor(1,:));
miny = min(cor(2,:));
maxy = max(cor(2,:));
semix = (maxx-minx)/2;
semiy = (maxy-miny)/2;
minx = floor(minx - 0.2 * min(semix,semiy));
maxx = ceil(maxx + 0.2 * min(semix,semiy));
miny = floor(miny - 0.2 * min(semix,semiy));
maxy = ceil(maxy + 0.2 * min(semix,semiy));
[xx, yy] = meshgrid(1:size(lap',1), 1:size(lap',2));
roi_idx = zeros(size(lap));
roi_idx(xx>=minx & xx<=maxx & yy>= miny & yy <= maxy) = 1;
roi_idx = logical(roi_idx(:));
[sigma, add_dist] = findRadius(pp,im);
add_dist = conv2fft(add_dist,mygaussian(2, size(add_dist)));
G = mygaussian(sigma_p.*sigma, size(im));
d.dist = zeros(size(im,1), size(im,2), numel(sigma_p));
prc1 = 0;
prc2 = 10;
% calculate smoothed images via fft2
smlap3 = conv2fft(lap, G);
for i_sigma = 1:numel(sigma_p)
%smlapc = abs(conv2(lap, G(:,:,i_sigma), 'same'));
smlap = smlap3(:,:,i_sigma);
i = prctile(smlap(roi_idx), prc1);
j = prctile(smlap(roi_idx), prc2);
dist = double( bwdist(smlap >= i & smlap <= j ));%+ bwdist(smlap <= i).^2 );
dist = dist - min(dist(:));
dist = dist/ max(dist(:));
d.dist(:,:,i_sigma) = dist.^2+ (add_dist*(max(dist(roi_idx))/max(add_dist(:)))).^2;
end
d.lap = lap;
% imagesc(sum(d.dist(:,:,3)));
end
function smlap3 = conv2fft(lap, G)
padsize = ceil([size(lap,1), size(lap,2)]);
lap_pad = padarray(repmat(lap, [1,1,size(G,3)]),padsize);
smlappad = abs(ifftshift(ifft2(fftshift(fft2(lap_pad)).*fftshift(fft2(padarray(G(:,:,:), padsize))))));
smlap3 = smlappad(padsize(1):end - padsize(1)-1,padsize(2):end - padsize(2)-1,:);
end
function g = mygaussian(sigma, siz)
g = zeros(siz(1),siz(2), numel(sigma));
x = linspace(-0.5*siz(2),0.5*siz(2) ,siz(2));
y = linspace(-0.5*siz(1),0.5*siz(1) ,siz(1));
[xx, yy] = meshgrid(x,y);
eucl = repmat(xx.^2 +yy.^2, [1,1, numel(sigma)]);
sigma_ = zeros(1,1,numel(sigma));
sigma_(1,1,:) = sigma;
sigma = repmat(sigma_, [siz(1), siz(2), 1]);
g = exp( - 0.5 * (eucl./sigma.^2));
g = g ./ sum(sum(g, 1),2);
end
function [rmax,out_dist] = findRadius(pp,ima)
points=pp';
sgm=roipoly(ima,points(:,1),points(:,2))';
sgm=sgm';
dist_transform = double(bwdist(logical(1 - sgm)));
rmax = max(dist_transform(dist_transform >0));
out_dist = double(dist_transform)/max(double(dist_transform(:)));
end
function [dL,d2L, dUp] = computeGradient2(param, dStep, npoints, domain, cor0, L, order)
L = L(:);
dL = 0 * param(:);
if order ==2
d2L = zeros(numel(dL),numel(dL));
end
sizparam = size(param);
for i = 1:numel(dL)
dparam = 0*param(:);
dparam(i) = dStep;
dparam = param(:) + dparam;
dpoints = forward(reshape(dparam,sizparam), npoints);
dL(i) = Loss(dpoints, domain,reshape(dparam,sizparam), cor0) - L;
%dL(i) = dL(i)/dStep;
if order ==2
for j = 1:numel(dL)
ddparam = 0*param(:);
ddparam(j) = dStep;
ddparam = dparam + ddparam;
ddpoints = forward(reshape(ddparam, size(param)), npoints);
d2L(i,j) = 0.5 * (Loss(ddpoints, domain,reshape(ddparam, sizparam), cor0) - dL(i));
d2L(i,j) = d2L(i,j)/dStep;
end
end
end
if order ==2
dUp = reshape(d2L'\dL, size(param));
return;
else
dUp = reshape(dL/dStep, sizparam);
d2L = 0;
return;
end
end
function L = Loss(points, d,~,~)%param, cor0)
Eim = 0;
idx = sub2ind(size(d.dist),round(points(2,:)),round(points(1,:)));
%idx0 = sub2ind(size(d.dist),round(d.points0(2,:)),round(d.points0(1,:)));
distim = d.dist;
dsize3 = size(distim,3);
for i_s = 1:dsize3
dist_ = distim(:,:,i_s);
eim = dist_(idx);
Eim = Eim + sum(eim(:));
end
Eim = Eim / dsize3;
% regu = param - cor0;
% Regu = sum(regu(1,:).^2 + regu(2,:).^2 );
a = 0;
b = 2;
ab = a + b;
a = a / ab;
b = b / ab;
% eint0 = circshift(d.points0,1,2) - d.points0;
% eint0 = sum( a *( eint0(1,:).^2 + eint0(2,:).^2)/numel(idx0) );
eint1 = (circshift(points,1,2) - points) /numel(idx);
eint1 = a*(eint1(1,:).^2 + eint1(2,:).^2);
eint2 = 0.5 * (circshift(points,1,2) - 2 * points + circshift(points,-1,2));
eint2 =b * ( eint1(1,:).^2 + eint2(2,:).^2);
Eint = (sum(-eint1 + eint2)); % - 0*eint0;
% centre = mean(cor0(:,:),2);
% dist2 = sqrt((cor0(1,:) - centre(1)).^2 + (cor0(2,:) - centre(2)).^2);
% Eext = 1/sum(dist2);
L = 0.05*Eint + Eim ;% 0 * Eext +0 * Regu;
end
|
github
|
andreafarina/SOLUS-master
|
Lee_spline.m
|
.m
|
SOLUS-master/src/UCLutils/Lee_spline.m
| 708 |
utf_8
|
d0dfb4b20892c4b75f850645482cb8e2
|
function out_curve = Lee_spline(points, npoints)
% takes points as input and returns the spline interpolant using Eugene
% Lee's centripetal method
x = points(1,:);
y = points(2,:);
if points(:,1)==points(:,end)
endconds = 'periodic';
else
endconds = 'variational';
end
if length(x)==1
dt = 0;
else
dt = sum((diff(points.').^2).');
end
t = cumsum([0,dt.^(1/4)]);
sample_points = linspace(t(1), t(end), npoints);
splinex = computeSpline(t,x, sample_points, endconds);
spliney = computeSpline(t,y, sample_points, endconds);
out_curve = [splinex';spliney'];
end
|
github
|
andreafarina/SOLUS-master
|
roispline_OLD.m
|
.m
|
SOLUS-master/src/UCLutils/roispline_OLD.m
| 13,939 |
utf_8
|
fab1bf8f64640fa91ea9ba554df2526f
|
function mask=roispline_OLD(I,kind,tension)
% function [mask,perimeter,area]=roispline(I,str,tension)
%
% INPUT :
% - I : Grayscale or color image
% - kind : String specifying the kind of spline ('natural' for natural
% cubic spline, 'cardinal' for cardinal cubic spline).
% DEFAULT = 'natural'
% - tension : Tension parameter between 0 and 1 for cardinal spline.
% DEFAULT = 0
%
% OUTPUT :
% - mask : Binary mask of segmented ROI
warning off
if nargin<2
kind='natural';
elseif nargin<3
tension = 0;
end
siz=size(I);
imshow(I, [0, 255]);
title('Click right button or close curve clicking near first point');
hold on;
% initializes number of points for each step
npoints=sqrt(siz(1)*siz(2))*.1;
dim=10/835*sqrt(siz(1)*siz(2));
if dim<8
dim=8;
end
bottone=1;
i=0;
flag=1;
points=[];
switch kind
case 'natural'
while flag
i=i+1;
[cor(1,i),cor(2,i),bottone]=ginput(1);
if bottone ~= 1
if i>1
cor(:,i)=cor(:,1);
flag=0;
else
break;
end
end
plot(cor(1,i),cor(2,i),'y.');
if i>1
if (norm(cor(:,1)-cor(:,i))<dim & i>2) & flag
cor(:,i)=cor(:,1);
flag=0;
end
imshow(I,[0, 255])
hold on;
spcv = cscvn(cor);
points=myfnplt(spcv,npoints*i);
plot(points(1,:),points(2,:),'b','LineWidth',2);
plot(cor(1,:),cor(2,:),'y.');
drawnow;
end
end
case 'cardinal'
while flag
i=i+1;
[x(i),y(i),bottone]=ginput(1);
if bottone ~= 1
if i>1
x(i)=[];
y(i)=[];
Px=[x(end) x x(1) x(2)];
Py=[y(end) y y(1) y(2)];
i=i-1;
flag=0;
else
break;
end
end
plot(x(i),y(i),'y.');
if i>1
if flag
if (norm([x(1) y(1)]-[x(i) y(i)])<dim & i>2)
x(i)=[];
y(i)=[];
Px=[x(end) x x(1) x(2)];
Py=[y(end) y y(1) y(2)];
flag=0;
else
Px=[x(1) x x(end)];
Py=[y(1) y y(end)];
end
end
pointsx=[];
pointsy=[];
for k=1:length(Px)-3
[xvec,yvec]=EvaluateCardinal2DAtNplusOneValues([Px(k),Py(k)],[Px(k+1),Py(k+1)],[Px(k+2),Py(k+2)],[Px(k+3),Py(k+3)],tension,npoints);
pointsx=[pointsx, xvec];
pointsy=[pointsy, yvec];
end
imshow(I,[0, 255]);
hold on;
plot(pointsx,pointsy,'LineWidth',2);
plot(x,y,'y.');
drawnow;
end
end
points=[pointsx; pointsy];
end
% mask calculation
points=points';
if i>2
mask=roipoly(I,points(:,1),points(:,2));
else
mask=logical(zeros(siz(1),siz(2)));
end
% internal functions
function [points,t] = myfnplt(f,npoints,varargin)
% interpret the input:
symbol=''; interv=[]; linewidth=[]; jumps=0;
for j=3:nargin
arg = varargin{j-1};
if ~isempty(arg)
if ischar(arg)
if arg(1)=='j', jumps = 1;
else, symbol = arg;
end
else
[ignore,d] = size(arg);
if ignore~=1
error('SPLINES:FNPLT:wrongarg',['arg',num2str(j),' is incorrect.']), end
if d==1
linewidth = arg;
else
interv = arg;
end
end
end
end
% generate the plotting info:
if ~isstruct(f), f = fn2fm(f); end
% convert ND-valued to equivalent vector-valued:
d = fnbrk(f,'dz'); if length(d)>1, f = fnchg(f,'dim',prod(d)); end
switch f.form(1:2)
case 'st'
if ~isempty(interv), f = stbrk(f,interv);
else
interv = stbrk(f,'interv');
end
% npoints = 150;
d = stbrk(f,'dim');
switch fnbrk(f,'var')
case 1
x = linspace(interv{1}(1),interv{1}(2),npoints);
v = stval(f,x);
case 2
x = {linspace(interv{1}(1),interv{1}(2),npoints), ...
linspace(interv{2}(1),interv{2}(2),npoints)};
[xx,yy] = ndgrid(x{1},x{2});
v = reshape(stval(f,[xx(:),yy(:)].'),[d,size(xx)]);
otherwise
error('SPLINES:FNPLT:atmostbivar', ...
'Cannot handle st functions with more than 2 variables.')
end
otherwise
if ~strcmp(f.form([1 2]),'pp')
givenform = f.form; f = fn2fm(f,'pp'); basicint = ppbrk(f,'interval');
end
if ~isempty(interv), f = ppbrk(f,interv); end
[breaks,coefs,l,k,d] = ppbrk(f);
if iscell(breaks)
m = length(breaks);
for i=m:-1:3
x{i} = (breaks{i}(1)+breaks{i}(end))/2;
end
% npoints = 150;
ii = [1]; if m>1, ii = [2 1]; end
for i=ii
x{i}= linspace(breaks{i}(1),breaks{i}(end),npoints);
end
v = ppual(f,x);
if exist('basicint','var')
% we converted from B-form to ppform, hence must now
% enforce the basic interval for the underlying spline.
for i=ii
temp = find(x{i}<basicint{i}(1)|x{i}>basicint{i}(2));
if d==1
if ~isempty(temp), v(:,temp,:) = 0; end
v = permute(v,[2,1]);
else
if ~isempty(temp), v(:,:,temp,:) = 0; end
v = permute(v,[1,3,2]);
end
end
end
else % we are dealing with a univariate spline
% npoints = 500;
x = [breaks(2:l) linspace(breaks(1),breaks(l+1),npoints)];
v = ppual(f,x);
if l>1 % make sure of proper treatment at jumps if so required
if jumps
tx = breaks(2:l); temp = repmat(NaN, d,l-1);
else
tx = []; temp = zeros(d,0);
end
x = [breaks(2:l) tx x];
v = [ppual(f,breaks(2:l),'left') temp v];
end
[x,inx] = sort(x); v = v(:,inx);
if exist('basicint','var')
% we converted from B-form to ppform, hence must now
% enforce the basic interval for the underlying spline.
% Note that only the first d components are set to zero
% outside the basic interval, i.e., the (d+1)st
% component of a rational spline is left unaltered :-)
if jumps, extrap = repmat(NaN,d,1); else, extrap = zeros(d,1); end
temp = find(x<basicint(1)); ltp = length(temp);
if ltp
x = [x(temp),basicint([1 1]), x(ltp+1:end)];
v = [zeros(d,ltp+1),extrap,v(:,ltp+1:end)];
end
temp = find(x>basicint(2)); ltp = length(temp);
if ltp
x = [x(1:temp(1)-1),basicint([2 2]),x(temp)];
v = [v(:,1:temp(1)-1),extrap,zeros(d,ltp+1)];
end
% temp = find(x<basicint(1)|x>basicint(2));
% if ~isempty(temp), v(temp) = zeros(d,length(temp)); end
end
end
if exist('givenform','var')&&givenform(1)=='r'
% we are dealing with a rational fn:
% need to divide by last component
d = d-1;
sizev = size(v); sizev(1) = d;
% since fnval will replace any zero value of the denominator by 1,
% so must we here, for consistency:
v(d+1,find(v(d+1,:)==0)) = 1;
v = reshape(v(1:d,:)./repmat(v(d+1,:),d,1),sizev);
end
end
% use the plotting info, to plot or else to output:
if nargout==0
if iscell(x)
switch d
case 1
[yy,xx] = meshgrid(x{2},x{1});
surf(xx,yy,reshape(v,length(x{1}),length(x{2})))
case 2
v = squeeze(v); roughp = 1+(npoints-1)/5;
vv = reshape(cat(1,...
permute(v(:,1:5:npoints,:),[3,2,1]),...
repmat(NaN,[1,roughp,2]),...
permute(v(:,:,1:5:npoints),[2,3,1]),...
repmat(NaN,[1,roughp,2])), ...
[2*roughp*(npoints+1),2]);
plot(vv(:,1),vv(:,2))
case 3
v = permute(reshape(v,[3,length(x{1}),length(x{2})]),[2 3 1]);
surf(v(:,:,1),v(:,:,2),v(:,:,3))
otherwise
end
else
if isempty(symbol), symbol = '-'; end
if isempty(linewidth), linewidth = 2; end
switch d
case 1, plot(x,v,symbol,'linew',linewidth)
case 2, plot(v(1,:),v(2,:),symbol,'linew',linewidth)
otherwise
plot3(v(1,:),v(2,:),v(3,:),symbol,'linew',linewidth)
end
end
else
if iscell(x)
switch d
case 1
[yy,xx] = meshgrid(x{2},x{1});
points = {xx,yy,reshape(v,length(x{1}),length(x{2}))};
case 2
[yy,xx] = meshgrid(x{2},x{1});
points = {xx,yy,reshape(v,[2,length(x{1}),length(x{2})])};
case 3
points = {squeeze(v(1,:)),squeeze(v(2,:)),squeeze(v(3,:))};
t = {x{1:2}}
otherwise
end
else
if d==1, points = [x;v];
else, t = x; points = v([1:min([d,3])],:); end
end
end
function [xvec,yvec]=EvaluateCardinal2DAtNplusOneValues(P0,P1,P2,P3,T,N)
% Evaluate cardinal spline at N+1 values for given four points and tesion.
% Uniform parameterization is used.
% P0,P1,P2 and P3 are given four points.
% T is tension.
% N is number of intervals (spline is evaluted at N+1 values).
xvec=[]; yvec=[];
% u vareis b/w 0 and 1.
% at u=0 cardinal spline reduces to P1.
% at u=1 cardinal spline reduces to P2.
u=0;
[xvec(1),yvec(1)] =EvaluateCardinal2D(P0,P1,P2,P3,T,u);
du=1/N;
for k=1:N
u=k*du;
[xvec(k+1),yvec(k+1)] =EvaluateCardinal2D(P0,P1,P2,P3,T,u);
end
function [xt,yt] =EvaluateCardinal2D(P0,P1,P2,P3,T,u)
% Evaluates 2D Cardinal Spline at parameter value u
% INPUT
% P0,P1,P2,P3 are given four points. Each have x and y values.
% P1 and P2 are endpoints of curve.
% P0 and P3 are used to calculate the slope of the endpoints (i.e slope of P1 and
% P2).
% T is tension (T=0 for Catmull-Rom type)
% u is parameter at which spline is evaluated
% OUTPUT
% cardinal spline evaluated values xt,yt,zt at parameter value u
s= (1-T)./2;
% MC is cardinal matrix
MC=[-s 2-s s-2 s;
2.*s s-3 3-(2.*s) -s;
-s 0 s 0;
0 1 0 0];
GHx=[P0(1); P1(1); P2(1); P3(1)];
GHy=[P0(2); P1(2); P2(2); P3(2)];
U=[u.^3 u.^2 u 1];
xt=U*MC*GHx;
yt=U*MC*GHy;
function cs = cscvn(points)
%CSCVN `Natural' or periodic interpolating cubic spline curve.
%
% CS = CSCVN(POINTS)
%
% returns a parametric `natural' cubic spline that interpolates to
% the given points POINTS(:,i) at parameter values t(i) ,
% i=1,2,..., with t(i) chosen by Eugene Lee's centripetal scheme,
% i.e., as accumulated square root of chord-length.
%
% When first and last point coincide and there are no double points,
% then a parametric *periodic* cubic spline is constructed instead.
% However, double points result in corners.
%
% For example,
%
% fnplt(cscvn( [1 0 -1 0 1;0 1 0 -1 0] ))
%
% shows a (circular) curve through the four vertices of the standard diamond
% (because of the periodic boundary conditions enforced), while
%
% fnplt(cscvn( [1 0 -1 -1 0 1;0 1 0 0 -1 0] ))
%
% shows a corner at the double point as well as at the curve endpoint.
%
% See also CSAPI, CSAPE, GETCURVE, SPCRVDEM, SPLINE.
% Carl de Boor 28 jan 90
% cb : May 12, 1991 change from csapn to csape
% cb : 9 may '95 csape can now handle vector-valued data
% cb : 9 may '95 (use .' instead of ')
% cb : 7 mar '96 (reduce to one statement)
% cb :23 may '96 (use periodic spline for a closed curve)
% cb :23 mar '97 (make double points corners; permit input of just one point)
% Copyright 1987-2008 The MathWorks, Inc.
if points(:,1)==points(:,end)
endconds = 'periodic';
else
endconds = 'variational';
end
if length(points(1,:))==1
dt = 0;
else
dt = sum((diff(points.').^2).');
end
t = cumsum([0,dt.^(1/4)]);
if all(dt>0)
cs = csape(t,points,endconds);
else
dtp = find(dt>0);
if isempty(dtp) % there is only one distinct point
cs = csape([0 1],points(:,[1 1]),endconds);
elseif length(dtp)==1 % there are only two distinct points
cs = csape([0 t(dtp+1)],points(:,dtp+[0 1]),endconds);
else
dtpbig = find(diff(dtp)>1);
if isempty(dtpbig) % there is only one piece
temp = dtp(1):(dtp(end)+1); cs = csape(t(temp),points(:,temp),endconds);
else % there are several pieces
dtpbig = [dtpbig,length(dtp)];
temp = dtp(1):(dtp(dtpbig(1))+1);
coefs = ppbrk(csape(t(temp),points(:,temp),'variatonal'),'c');
for j=2:length(dtpbig)
temp = dtp(dtpbig(j-1)+1):(dtp(dtpbig(j))+1);
coefs=[coefs;ppbrk(csape(t(temp),points(:,temp),'variational'),'c')];
end
cs = ppmak(t([dtp(1) dtp+1]),coefs,length(points(:,1)));
end
end
end
|
github
|
HanyangLiu/SOGE-master
|
SOGE.m
|
.m
|
SOGE-master/SOGE.m
| 1,689 |
utf_8
|
277980301ed17c6f0202f387e43a3562
|
function [ W_final, obj, prop ] = SOGE( X, T, L, U, para )
%SOGE Recursively projecting the data
% X: each colomn is a data point
% L: Laplacian matrix
% T: n*c matrix, class indicator matrix. Tij=1 if xi is labeled as j, Tij=0 otherwise
% para: parameters
% para.alpha trade-off parameter alpha
% para.uu weight of the diagonal matrix U
% para.nn block size of affinity matrix
% para.p the number of data points with labels per class
% para.K the number of recursive loops
% W_final: the final projection matrix
[~,n] = size(X);
H = eye(n) - 1/n*ones(n); X = X*H; % centering the data
W_final = [];
for Recu = 1: para.K
[ W, ~, ~, obj, prop ] = Optim( X, T, L, U, para );
X = X-W*W'*X;
W_final = [W_final W];
end
end
function [ W, F, b, obj, prop ] = Optim( X, Y, L, U, para )
%Optim Optimization of the objective function
% b: bias vector
% F: soft label matrix
[d,n] = size(X);
r = para.alpha;
Hc = eye(n)-(1/n)*ones(n,n);
P = eye(n)/(L+U+r*Hc);
M = r^2*X*Hc*(1/r*eye(n)-P)*Hc*X';
N = -r*X*Hc*P*U*Y;
lam = max(eig(M));
A = lam*eye(d)-M;
B = -N;
[W, obj] = GPI(A, B, 1);
F = P*(U*Y+r*X'*W);
b = 1/n*(F'*ones(n,1)-W'*X*ones(n,1));
prop = struct;
prop.GraEmb = trace(F'*L*F);
prop.SupVis = trace((F-Y)'*U*(F-Y));
prop.LinReg = norm(X'*W+ones(n,1)*b'-F,'fro');
end
function [X, obj] = GPI(A, B, r)
% max_{X'*X=I} trace(X'*A*X) + 2*r*trace(X'*B)
% A must be positive semi-definite
NITER = 500;
[n,m] = size(B);
X = orth(rand(n,m));
for iter = 1:NITER
M = A*X + r*B;
[U,~,V] = svd(M,'econ');
X = U*V';
obj(iter,1) = trace(X'*A*X) + 2*r*trace(X'*B);
display(iter);
end
end
|
github
|
HanyangLiu/SOGE-master
|
constructW_PKN.m
|
.m
|
SOGE-master/func/CLR_code/constructW_PKN.m
| 1,137 |
utf_8
|
f211e688d3d381a5961c15b41baa3d67
|
% construct similarity matrix with probabilistic k-nearest neighbors. It is a parameter free, distance consistent similarity.
function W = constructW_PKN(X, k, issymmetric)
% X: each column is a data point
% k: number of neighbors
% issymmetric: set W = (W+W')/2 if issymmetric=1
% W: similarity matrix
if nargin < 3
issymmetric = 1;
end;
if nargin < 2
k = 5;
end;
[dim, n] = size(X);
D = L2_distance_1(X, X);
[dumb, idx] = sort(D, 2); % sort each row
W = zeros(n);
for i = 1:n
id = idx(i,2:k+2);
di = D(i, id);
W(i,id) = (di(k+1)-di)/(k*di(k+1)-sum(di(1:k))+eps);
end;
if issymmetric == 1
W = (W+W')/2;
end;
% compute squared Euclidean distance
% ||A-B||^2 = ||A||^2 + ||B||^2 - 2*A'*B
function d = L2_distance_1(a,b)
% a,b: two matrices. each column is a data
% d: distance matrix of a and b
if (size(a,1) == 1)
a = [a; zeros(1,size(a,2))];
b = [b; zeros(1,size(b,2))];
end
aa=sum(a.*a); bb=sum(b.*b); ab=a'*b;
d = repmat(aa',[1 size(bb,2)]) + repmat(bb,[size(aa,2) 1]) - 2*ab;
d = real(d);
d = max(d,0);
% % force 0 on the diagonal?
% if (df==1)
% d = d.*(1-eye(size(d)));
% end
|
github
|
HanyangLiu/SOGE-master
|
CLR.m
|
.m
|
SOGE-master/func/CLR_code/CLR.m
| 3,020 |
utf_8
|
17b2b5bb1a290856916058c30a4e4fad
|
% min_{S>=0, S*1=1, F'*F=I} ||S - A||^2 + r*||S||^2 + 2*lambda*trace(F'*L*F)
% or
% min_{S>=0, S*1=1, F'*F=I} ||S - A||_1 + r*||S||^2 + 2*lambda*trace(F'*L*F)
function [y, S, evs, cs] = CLR(A0, c, isrobust, islocal)
% A0: the given affinity matrix
% c: cluster number
% isrobust: solving the second (L1 based) problem if isrobust=1
% islocal: only update the similarities of neighbors if islocal=1
% y: the final clustering result, cluster indicator vector
% S: learned symmetric similarity matrix
% evs: eigenvalues of learned graph Laplacian in the iterations
% cs: suggested cluster numbers, effective only when the cluster structure is clear
% Ref:
% Feiping Nie, Xiaoqian Wang, Michael I. Jordan, Heng Huang.
% The Constrained Laplacian Rank Algorithm for Graph-Based Clustering.
% The 30th Conference on Artificial Intelligence (\textbf{AAAI}), Phoenix, USA, 2016.
NITER = 30;
zr = 10e-11;
lambda = 0.1;
r = 0;
if nargin < 4
islocal = 1;
end;
if nargin < 3
isrobust = 0;
end;
A0 = A0-diag(diag(A0));
num = size(A0,1);
A10 = (A0+A0')/2;
D10 = diag(sum(A10));
L0 = D10 - A10;
% automatically determine the cluster number
[F0, ~, evs]=eig1(L0, num, 0);
a = abs(evs); a(a<zr)=eps; ad=diff(a);
ad1 = ad./a(2:end);
ad1(ad1>0.85)=1; ad1 = ad1+eps*(1:num-1)'; ad1(1)=0; ad1 = ad1(1:floor(0.9*end));
[te, cs] = sort(ad1,'descend');
% sprintf('Suggested cluster number is: %d, %d, %d, %d, %d', cs(1),cs(2),cs(3),cs(4),cs(5))
if nargin == 1
c = cs(1);
end;
F = F0(:,1:c);
if sum(evs(1:c+1)) < zr
error('The original graph has more than %d connected component', c);
end;
if sum(evs(1:c)) < zr
[clusternum, y]=graphconncomp(sparse(A10)); y = y';
S = A0;
return;
end;
for i=1:num
a0 = A0(i,:);
if islocal == 1
idxa0 = find(a0>0);
else
idxa0 = 1:num;
end;
u{i} = ones(1,length(idxa0));
end;
for iter = 1:NITER
dist = L2_distance_1(F',F');
S = zeros(num);
for i=1:num
a0 = A0(i,:);
if islocal == 1
idxa0 = find(a0>0);
else
idxa0 = 1:num;
end;
ai = a0(idxa0);
di = dist(i,idxa0);
if isrobust == 1
for ii = 1:1
ad = u{i}.*ai-lambda*di/2;
si = EProjSimplexdiag(ad, u{i}+r*ones(1,length(idxa0)));
u{i} = 1./(2*sqrt((si-ai).^2+eps));
end;
S(i,idxa0) = si;
else
ad = ai-0.5*lambda*di; S(i,idxa0) = EProjSimplex_new(ad);
end;
end;
A = S;
A = (A+A')/2;
D = diag(sum(A));
L = D-A;
F_old = F;
[F, ~, ev]=eig1(L, c, 0);
evs(:,iter+1) = ev;
fn1 = sum(ev(1:c));
fn2 = sum(ev(1:c+1));
if fn1 > zr
lambda = 2*lambda;
elseif fn2 < zr
lambda = lambda/2; F = F_old;
else
break;
end;
end;
%[labv, tem, y] = unique(round(0.1*round(1000*F)),'rows');
[clusternum, y]=graphconncomp(sparse(A)); y = y';
if clusternum ~= c
sprintf('Can not find the correct cluster number: %d', c)
end;
|
github
|
HanyangLiu/SOGE-master
|
L2_distance_1.m
|
.m
|
SOGE-master/func/CLR_code/funs/L2_distance_1.m
| 491 |
utf_8
|
2f9db3fa2b71ea0e0afa9786182f85ed
|
% compute squared Euclidean distance
% ||A-B||^2 = ||A||^2 + ||B||^2 - 2*A'*B
function d = L2_distance_1(a,b)
% a,b: two matrices. each column is a data
% d: distance matrix of a and b
if (size(a,1) == 1)
a = [a; zeros(1,size(a,2))];
b = [b; zeros(1,size(b,2))];
end
aa=sum(a.*a); bb=sum(b.*b); ab=a'*b;
d = repmat(aa',[1 size(bb,2)]) + repmat(bb,[size(aa,2) 1]) - 2*ab;
d = real(d);
d = max(d,0);
% % force 0 on the diagonal?
% if (df==1)
% d = d.*(1-eye(size(d)));
% end
|
github
|
pkaroly/Data-Driven-Estimation-master
|
generateData.m
|
.m
|
Data-Driven-Estimation-master/examples/generateData.m
| 1,443 |
utf_8
|
be7cb3a61869036096febbe4eecac1d6
|
%% generateData
% plots simulated data from the neural mass model at different input values
%%
% Dean Freestone, Philippa Karoly 2016
% This code is licensed under the MIT License 2018
%%
clear
clc
close all
addpath(genpath('../src/'));
time = 60;
Fs = 1e3;
x = 1/Fs:1/Fs:time;
sigma_R = 0;
for input = 0:10:320
[A,B,C,N_states,N_syn,N_inputs,N_samples,xi, ...
v0,varsigma,Q,R,H,y] = set_params(input,[],time,Fs, sigma_R);
plot(x,y,'k');
set(gca,'box','off','xtick',[0 time]);
xlabel('Time (s)');
ylabel('ECoG (mV)');
title(sprintf('input / drive: %d',input));
drawnow;
pause(0.5);
end
%%
function plotPotentials(xi)
figure
figure('name','parameter estimates' ,'units','normalized','position',[0 0 1 1] )
subplot(411),plot(xi(1,:))
title('Inhibitory -> Pyramidal');
subplot(412),plot(xi(3,:))
title('Pyramidal -> Inhibitory');
subplot(413),plot(xi(5,:))
title('Pyramidal -> Excitatory');
subplot(414),plot(xi(7,:))
title('Excitatory -> Pyramidal');
end
function plotAlpha(xi)
figure('name','parameter estimates' ,'units','normalized','position',[0 0 1 1] )
subplot(511),plot(xi(9,:))
title('Input');
subplot(512),plot(xi(10,:))
title('Inhibitory -> Pyramidal');
subplot(513),plot(xi(11,:))
title('Pyramidal -> Inhibitory');
subplot(514),plot(xi(12,:))
title('Pyramidal -> Excitatory');
subplot(515),plot(xi(13,:))
title('Excitatory -> Pyramidal');
end
|
github
|
pkaroly/Data-Driven-Estimation-master
|
g.m
|
.m
|
Data-Driven-Estimation-master/src/g.m
| 175 |
utf_8
|
3c2d4fd0784019408a5147bb4676cfc0
|
% error function sigmoid
function out = g(v,v0,varsigma)
out = 0.5*erf((v - v0) / (sqrt(2)*varsigma)) + 0.5;
% out = 1 ./ (1 + exp(varsigma*(-v+v0)));
end
|
github
|
saradindusengupta/Regularization_parametre_in_reconstruction_of_cparallel-MR-image-master
|
grid_setup.m
|
.m
|
Regularization_parametre_in_reconstruction_of_cparallel-MR-image-master/@GRID/private/grid_setup.m
| 1,092 |
utf_8
|
2a9d539e9ee619df6e32025f9304f7ae
|
function mtx = grid_setup(k,kernel,ks,imSize, os)
k = k(:);
sk = length(k);
sx= imSize(1); sy = imSize(2);
ks = ks;
% cconvert k-space samples to matrix indices
nx = (sx/2+1) + sx*real(k) ;
ny = (sy/2+1) + sy*imag(k) ;
% make sparse matrix
mtx = sparse(sk,sx*sy);
% loop over kernel
for lx=-(ks-1)/2:(ks-1)/2
for ly = -(ks-1)/2:(ks-1)/2
% find nearest samples
nxt = floor(nx+lx);
nyt = floor(ny+ly);
% find index of samples inside matrix
idk = find(nxt<=sx & nxt >=1 & nyt <=sy & nyt>=1);
% find index of neares samples
idx = (nyt(idk)-1)*sx + nxt(idk);
% compute distance
distx = nx(idk)-nxt(idk);
disty = ny(idk)-nyt(idk);
% compute weights
wx = KERNEL(distx, kernel,ks,os);
wy = KERNEL(disty, kernel,ks,os);
%d = d + wy.*wx.*img(idx);
mtx = mtx + sparse(idk,idx, wx.*wy, sk, sx*sy);
end
end
%function w = KERNEL(dist,kernel,ks,os)
%w = sinc(real(dist)/os);
function w = KERNEL(dist, kernel,ks,os)
x = linspace(-(ks-1)/2,(ks-1)/2,length(kernel));
w = interp1(x,[kernel(:)]',dist,'linear');
w(find(isnan(w))) = 0;
|
github
|
saradindusengupta/Regularization_parametre_in_reconstruction_of_cparallel-MR-image-master
|
AdSPIRiT_recon.m
|
.m
|
Regularization_parametre_in_reconstruction_of_cparallel-MR-image-master/Template/AdSPIRiT_recon.m
| 2,156 |
utf_8
|
44b588ac39447c31f99ba7e2bf577464
|
function [K, E] = AdSPIRiT_recon(Kz, GOP, nIter, x0, im,bet)
%
%
% res = pocsSPIRIT(y, GOP, nIter, x0, T, show)
%
% Implementation of the Cartesian, POCS l1-SPIRiT reconstruction
%
% INPUTS:
% data - Undersampled k-space data. Make sure that empty entries are zero
% or else they will not be filled.
% GOP - the SPIRiT kernel operator obtained by calibration
% nIter - Maximum number of iterations
% x0 - initial guess
% T - wavlet threshodling parameter
%
% OUTPUTS:
% res - Full k-space matrix
%
% (c) Michael Lustig 2007
%
acq_ind= find(abs(Kz)>0);
% find the closest diadic size for the images
[sx,sy,nc] = size(Kz);
W = Wavelet('Daubechies',6,4);
mask = (Kz==0);
K = x0;
bet=1;
for n=1:nIter
Err = zeros(size(Kz));
%------------ Apply (G-I)*x + x for reconstructing initially----
Gk = GOP*K;
Kcon = (K + GOP*K ).*(mask);
K = (bet* Kcon) + Kz;
Err (acq_ind) = Kz(acq_ind)-Gk(acq_ind);
cerr(n) = norm(Err(:));
K = K.*mask + Kz; % fix the data (POCS)
Istk = ifft2c(K);
I_recon=sos(Istk);
E(n) = NRMSE(sos(im),I_recon);
end
function x = softThresh(y,t)
% apply joint sparsity soft-thresholding
absy = sqrt(sum(abs(y).^2,3));
unity = y./(repmat(absy,[1,1,size(y,3)])+eps);
res = absy-t;
res = (res + abs(res))/2;
x = unity.*repmat(res,[1,1,size(y,3)]);
function[X]=getDiadic(K)
% zpad to the closest diadic
[sx,sy,nc] = size(K);
ssx = 2^ceil(log2(sx));
ssy = 2^ceil(log2(sy));
ss = max(ssx, ssy);
X= zpad(ifft2c(K),ss,ss,nc);
function[T1,l1res,l1pert,delt] = Update_Thresh(wres,wpert,T)
l1res = norm(sum(wres,3),1);
l1pert = norm(sum(wpert,3),1);
delt = abs(l1res-l1pert);
Cres = get_cov(wres);
Cpert = get_cov(wpert);
res = sum(sqrt(Cres(:)));
pert = 1/(T^2)*sum(sqrt(Cpert(:)));
T1 = sqrt(res/(delt+pert));
%------------------- calling function ----------
function [res]=NRMSE(I1,I2)
L2_error=I1-I2;
res=norm(L2_error(:),2)./norm(I1(:),2);
function[eX]=expectatn(X)
[h,bin]=hist(X(:),1001);
h=h/sum(h);
eX=sum(bin.*h);
|
github
|
saradindusengupta/Regularization_parametre_in_reconstruction_of_cparallel-MR-image-master
|
main_Ad_spirit.m
|
.m
|
Regularization_parametre_in_reconstruction_of_cparallel-MR-image-master/Template/main_Ad_spirit.m
| 1,265 |
utf_8
|
a5c5c19a58a2380a5ad7b4b5f82059d4
|
function[I_recon,Istk,Kstk,E]=main_Ad_spirit(DATA, kSize, nIter, mask)
% INPUTS
% kSize : SPIRiT kernel size
% nIter : number of iteration; phantom requires twice as much as the brain.
% mask : mask can be uniform or random
% lambda : Tykhonov regularization in the calibration
% T : Wavelet soft-thresholding regularization in the reconstruction
% OUTPUTS
% I_recon : Reconstructed Image (SoS combined)
% Istk : Reconstructed image (Coil-wise)
% Kstk : Reconstructed k-space (Coil-wise)
% Recon_err : Reconstruction Error
bet = 1;
im = ifft2c(DATA);
%-----------------------UnderSampling--------------------------
[DATA, CalibSize, scale_fctr]=get_SampledData(DATA,mask);
% im_dc = ifft2c(DATAcomp);
im = im/scale_fctr;
%-----------------------Perform Calibration--------------------------
[GOP]=tsvdgcvCalib(DATA,CalibSize,kSize);
%--------------------------Reconstruction------------------------
[Kstk,E] = AdSPIRiT_recon(DATA, GOP, nIter, DATA, im,bet);
% [Kstk, E] = AdWSPIRiT_recon2(DATA, GOP, nIter, DATA, T, im, bet);
Istk = ifft2c(Kstk);
I_recon=sos(Istk);
%------------------- calling function ----------
function [res]=NRMSE(I1,I2)
L2_error=I1-I2;
res=norm(L2_error(:),2)./norm(I1(:),2);
|
github
|
saradindusengupta/Regularization_parametre_in_reconstruction_of_cparallel-MR-image-master
|
AdSPIRiT_recon.m
|
.m
|
Regularization_parametre_in_reconstruction_of_cparallel-MR-image-master/GCV/AdSPIRiT_recon.m
| 2,221 |
utf_8
|
8875cd86c27db78e6f6d1b39d8310845
|
function [K, E] = AdSPIRiT_recon(Kz, GOP, nIter, x0, im,bet)
%
%
% res = pocsSPIRIT(y, GOP, nIter, x0, T, show)
%
% Implementation of the Cartesian, POCS l1-SPIRiT reconstruction
%
% INPUTS:
% data - Undersampled k-space data. Make sure that empty entries are zero
% or else they will not be filled.
% GOP - the SPIRiT kernel operator obtained by calibration
% nIter - Maximum number of iterations
% x0 - initial guess
% T - wavlet threshodling parameter
%
% OUTPUTS:
% res - Full k-space matrix
%
% (c) Michael Lustig 2007
%
acq_ind= find(abs(Kz)>0);
% find the closest diadic size for the images
[sx,sy,nc] = size(Kz);
W = Wavelet('Daubechies',6,4);
mask = (Kz==0);
K = x0;
bet=1;
for n=1:nIter
Err = zeros(size(Kz));
%------------ Apply (G-I)*x + x for reconstructing initially----
Gk = GOP*K;
Kcon = (K + GOP*K ).*(mask);
K = (bet* Kcon) + Kz;
Err (acq_ind) = Kz(acq_ind)-Gk(acq_ind);
cerr(n) = norm(Err(:));
K = K.*mask + Kz; % fix the data (POCS)
Istk = ifft2c(K);
I_recon=sos(Istk);
E(n) = NRMSE(sos(im),I_recon);
end
% figure; plot(er); hold on; plot(ep,'r');
% figure; plot(cerr);
function x = softThresh(y,t)
% apply joint sparsity soft-thresholding
absy = sqrt(sum(abs(y).^2,3));
unity = y./(repmat(absy,[1,1,size(y,3)])+eps);
res = absy-t;
res = (res + abs(res))/2;
x = unity.*repmat(res,[1,1,size(y,3)]);
function[X]=getDiadic(K)
% zpad to the closest diadic
[sx,sy,nc] = size(K);
ssx = 2^ceil(log2(sx));
ssy = 2^ceil(log2(sy));
ss = max(ssx, ssy);
X= zpad(ifft2c(K),ss,ss,nc);
function[T1,l1res,l1pert,delt] = Update_Thresh(wres,wpert,T)
l1res = norm(sum(wres,3),1);
l1pert = norm(sum(wpert,3),1);
delt = abs(l1res-l1pert);
Cres = get_cov(wres);
Cpert = get_cov(wpert);
res = sum(sqrt(Cres(:)));
pert = 1/(T^2)*sum(sqrt(Cpert(:)));
T1 = sqrt(res/(delt+pert));
%------------------- calling function ----------
function [res]=NRMSE(I1,I2)
L2_error=I1-I2;
res=norm(L2_error(:),2)./norm(I1(:),2);
function[eX]=expectatn(X)
[h,bin]=hist(X(:),1001);
h=h/sum(h);
eX=sum(bin.*h);
|
github
|
saradindusengupta/Regularization_parametre_in_reconstruction_of_cparallel-MR-image-master
|
main_Ad_spirit.m
|
.m
|
Regularization_parametre_in_reconstruction_of_cparallel-MR-image-master/GCV/main_Ad_spirit.m
| 1,339 |
utf_8
|
39fef43bcf3728de325214772a17a60a
|
function[I_recon,Istk,Kstk,E]=main_Ad_spirit(DATA, kSize, nIter, nACS,s)
% INPUTS
% kSize : SPIRiT kernel size
% nIter : number of iteration; phantom requires twice as much as the brain.
% mask : mask can be uniform or random
% lambda : Tykhonov regularization in the calibration
% T : Wavelet soft-thresholding regularization in the reconstruction
% OUTPUTS
% I_recon : Reconstructed Image (SoS combined)
% Istk : Reconstructed image (Coil-wise)
% Kstk : Reconstructed k-space (Coil-wise)
% Recon_err : Reconstruction Error
bet = 1;
im = ifft2c(DATA);
[~,~,~,~,mask] = micsplkspacesubsample(DATA,nACS,s);
mask=mask(:,:,1);
%-----------------------UnderSampling--------------------------
[DATA, CalibSize, scale_fctr]=get_SampledData(DATA,mask);
% im_dc = ifft2c(DATAcomp);
im = im/scale_fctr;
%-----------------------Perform Calibration--------------------------
[GOP]=tsvdgcvCalib(DATA,CalibSize,kSize);
%--------------------------Reconstruction------------------------
[Kstk,E] = AdSPIRiT_recon(DATA, GOP, nIter, DATA, im,bet);
% [Kstk, E] = AdWSPIRiT_recon2(DATA, GOP, nIter, DATA, T, im, bet);
Istk = ifft2c(Kstk);
I_recon=sos(Istk);
%------------------- calling function ----------
function [res]=NRMSE(I1,I2)
L2_error=I1-I2;
res=norm(L2_error(:),2)./norm(I1(:),2);
|
github
|
saradindusengupta/Regularization_parametre_in_reconstruction_of_cparallel-MR-image-master
|
cgESPIRiT.m
|
.m
|
Regularization_parametre_in_reconstruction_of_cparallel-MR-image-master/ESPIRiT_code/cgESPIRiT.m
| 1,647 |
utf_8
|
01cddc231e49ccce3c4b83fdefb870ea
|
function [res,imgs, RESVEC] = cgESPIRiT(y,ESP, nIter, lambda, x0)
%
%
% res = cgESPIRiT(y,ESP, nIter, lambda,x0)
%
% Implementation of the Cartesian, conjugate gradient ESPIRiT
% reconstruction. This implementation is similar to Cartesian SPIRiT. It
% only solves for missing data in k-space.
%
%
% Input:
% y - Undersampled k-space data. Make sure that empty entries are zero
% or else they will not be filled.
% ESP - the ESPIRiT operator obtained by calibration
% nIter - Maximum number of iterations
% lambda- Tykhonov regularization parameter
% x0 - Initil value
%
% Outputs:
% res - Full k-space matrix
% imgs - Combined ESPIRiT images.
%
%
%
% (c) Michael Lustig 2013
%
if nargin < 4
lambda = 0;
end
if nargin < 5
x0 = y;
end
[sx,sy,nCoils] = size(y);
idx_acq = find(abs(y)>0);
idx_nacq = find(abs(y)==0);
N = length(idx_nacq(:));
yy = fft2c(ESP*(ESP'*(ifft2c(y))))-y; yy = [-yy(:); idx_nacq(:)*0];
[tmpres,FLAG,RELRES,ITER,RESVEC] = lsqr(@aprod,yy,1e-6,nIter, speye(N,N),speye(N,N),x0(idx_nacq),ESP,sx,sy,nCoils,idx_nacq, lambda);
res = y;
res(idx_nacq) = tmpres;
imgs = ESP'*(ifft2c(res));
function [res,tflag] = aprod(x,ESP,sx,sy,nCoils,idx_nacq, lambda,tflag)
if strcmp(tflag,'transp');
tmpy = reshape(x(1:sx*sy*nCoils),sx,sy,nCoils);
tmpy = ifft2c(tmpy);
res = ESP*(ESP'*tmpy)-tmpy;
res = fft2c(res);
res = res(idx_nacq)+ x(sx*sy*nCoils+1:end)*lambda;
else
tmpx = zeros(sx,sy,nCoils);
tmpx(idx_nacq) = x;
tmpx = ifft2c(tmpx);
res = ESP*(ESP'*tmpx)-tmpx;
res = fft2c(res);
res = [res(:) ; lambda*x(:)];
end
|
github
|
saradindusengupta/Regularization_parametre_in_reconstruction_of_cparallel-MR-image-master
|
cgL1ESPIRiT.m
|
.m
|
Regularization_parametre_in_reconstruction_of_cparallel-MR-image-master/ESPIRiT_code/cgL1ESPIRiT.m
| 3,034 |
utf_8
|
ffc184de7b5326ee960cc9fd6f28520b
|
function [res] = cgL1ESPIRiT(kData, x0, FT, MapOp, nIterCG, XOP, lambda, alpha,nIterSplit)
%
%[res] = cgESPIRiT(kData, x0, FT, MapOp, nIterCG, [ XOP, lambda, alpha,nIterSplit)
%
% Implementation of image-domain L1-Wavelet regularized ESPIRiT reconstruction from arbitrary
% k-space. The splitting is based on F. Huang MRM 2010;64:1078?1088
% Solves the problem: || Em - y ||^2 + \lambda ||\Psi x||_1 + \alpha||x-m||^2
% by splitting into two subproblems:
% I) ||Em - y || ^2 + \alpha ||x-m||^2
% II) \alpha||x-m||^2 + \lambda ||\Psi x||_1
%
% large \alpha has slower splitting iterations and faster cg ones.
%
%
%
% Inputs:
% kData - k-space data matrix it is 3D corresponding to [readout,interleaves,coils]
% x0 - Initial estimate of the coil images
% FT - fft/nufft operator (see @NUFFT @p2DFT classes)
% nIterCG - number of LSQR iterations
% MapOp - ESPIRiT Operator (See @ESPIRiT)
% XOP - transform thresholding operator for l1 based soft
% thresholding
% lambda - L1-Wavelet penalty
% alpha - splitting parameter (0.5 default)
% nIterSplit - number of splitting iterations
%
% Outputs:
% res - reconstructed ESPIRiT images
%
%
%
%
% (c) Michael Lustig 2006, modified 2010, 2013
if nargin < 6
XOP = 1;
lambda = 0;
alpha = 0;
nIterSplit = 1;
end
N = prod(size(x0));
M = prod(size(kData));
imSize = size(x0);
% make dyadic size if Wavelets are used.
if strcmp(class(XOP),'Wavelet') == 1
if length(imSize)>2
imSize_dyd = [max(2.^ceil(log2(imSize(1:2)))), max(2.^ceil(log2(imSize(1:2)))),imSize(3)];
else
imSize_dyd = [max(2.^ceil(log2(imSize(1:2)))), max(2.^ceil(log2(imSize(1:2))))];
end
else
imSize_dyd = imSize;
end
dataSize = [size(kData)];
res = x0(:);
for n=1:nIterSplit;
b = [kData(:); sqrt(alpha)*res(:)];
[res,FLAG,RELRES,ITER,RESVEC,LSVEC] = lsqr(@(x,tflag)afun(x,FT,MapOp,dataSize, imSize, alpha, tflag), b, [], nIterCG,speye(N,N),speye(N,N), res(:));
res = reshape(res,imSize);
if lambda > 0
tmp = zpad(res,imSize_dyd);
tmp = XOP*tmp;
tmp = SoftThresh(tmp,lambda/sqrt(alpha));
res = XOP'*tmp;
res = reshape(res,imSize_dyd);
res = crop(res,imSize);
end
obj1 = (FT* (MapOp * res) - kData);
figure(100), imshow3(abs(res),[]), drawnow;
disp(sprintf('Iteration: %d, consistency: %f',n,norm(obj1(:))));
end
res = weight(MapOp,res);
function [y, tflag] = afun(x,FT, MapOp, dataSize, imSize, alpha, tflag)
if strcmp(tflag,'transp')
y = reshape(x(1:prod(dataSize)),dataSize);
xtmp = x(prod(dataSize)+1:end);
x = FT'.*y;
x = MapOp'*x;
y = x(:)+ sqrt(alpha)*xtmp(:);
else
x = reshape(x,imSize);
x_ = MapOp * x;
y = FT.*x_;
y = [y(:); sqrt(alpha) * x(:)];
end
|
github
|
saradindusengupta/Regularization_parametre_in_reconstruction_of_cparallel-MR-image-master
|
pocsSPIRiT.m
|
.m
|
Regularization_parametre_in_reconstruction_of_cparallel-MR-image-master/SPIRiT_code/pocsSPIRiT.m
| 2,051 |
utf_8
|
274d8938904dd230725d40a0c62d69c7
|
function x = pocsSPIRiT(data, GOP, nIter, x0, wavWeight, show)
%
%
% res = pocsSPIRIT(y, GOP, nIter, x0, wavWeight, show)
%
% Implementation of the Cartesian, POCS l1-SPIRiT reconstruction
%
% Input:
% y - Undersampled k-space data. Make sure that empty entries are zero
% or else they will not be filled.
% GOP - the SPIRiT kernel operator obtained by calibration
% nIter - Maximum number of iterations
% x0 - initial guess
% wavWeight - wavlet threshodling parameter
% show - >1 to display progress (slower)
%
% Outputs:
% res - Full k-space matrix
%
% (c) Michael Lustig 2007
%
% if no l1 penalt then skip wavelet thresholding.
if wavWeight==0
mask = (data==0);
x = x0;
for n=1:nIter
tmpx =(x + GOP*x).*(mask); % Apply (G-I)x + x
x = tmpx + data; % fix the data
if show
X = ifft2c(x);
Xsqr = sqrt(sum(abs(X).^2,3));
figure(show), imshow(Xsqr,[],'InitialMagnification',400);, drawnow
end
end
else
% find the closest diadic size for the images
[sx,sy,nc] = size(data);
ssx = 2^ceil(log2(sx));
ssy = 2^ceil(log2(sy));
ss = max(ssx, ssy);
W = Wavelet('Daubechies',4,4);
%W = Wavelet('Haar',2,3);
mask = (data==0);
x = x0;
x_old = x0;
for n=1:nIter
x = (x + GOP*x ).*(mask) + data; % Apply (G-I)*x + x
% apply wavelet thresholding
X = ifft2c(x); % goto image domain
X= zpad(X,ss,ss,nc); % zpad to the closest diadic
X = W*(X); % apply wavelet
X = softThresh(X,wavWeight); % threshold ( joint sparsity)
X = W'*(X); % get back the image
X = crop(X,sx,sy,nc); % return to the original size
xx = fft2c(X); % go back to k-space
x = xx.*mask + data; % fix the data
if show
X = ifft2c(x);
Xsqr = sqrt(sum(abs(X).^2,3));
figure(show), imshow(Xsqr,[],'InitialMagnification',400);, drawnow
end
end
end
function x = softThresh(y,t)
% apply joint sparsity soft-thresholding
absy = sqrt(sum(abs(y).^2,3));
unity = y./(repmat(absy,[1,1,size(y,3)])+eps);
res = absy-t;
res = (res + abs(res))/2;
x = unity.*repmat(res,[1,1,size(y,3)]);
|
github
|
saradindusengupta/Regularization_parametre_in_reconstruction_of_cparallel-MR-image-master
|
cgSPIRiT.m
|
.m
|
Regularization_parametre_in_reconstruction_of_cparallel-MR-image-master/SPIRiT_code/cgSPIRiT.m
| 2,348 |
utf_8
|
49959baab3f3a7c18e3c25fbe672e09d
|
function [res, RESVEC] = cgSPIRiT(y,GOP, nIter, lambda, x0)
%
%
% res = cgSPIRiT(y,GOP, nIter, lambda,x0)
%
% Implementation of the Cartesian, conjugate gradiend SPIRiT reconstruction
%
% Input:
% y - Undersampled k-space data. Make sure that empty entries are zero
% or else they will not be filled.
% GOP - the SPIRiT kernel operator obtained by calibration
% nIter - Maximum number of iterations
% lambda- Tykhonov regularization parameter
% x0 - Initil value
%
% Outputs:
% res - Full k-space matrix
%
%
% Example:
%
% [x,y] = meshgrid(linspace(0,1,128));
% % Generate fake Sensitivity maps
% sMaps = cat(3,x.^2,1-x.^2,y.^2,1-y.^2);
% % generate 4 coil phantom
% imgs = repmat(phantom(128),[1,1,4]).*sMaps;
% DATA = fft2c(imgs);
% % crop 20x20 window from the center of k-space for calibration
% kCalib = crop(DATA,[20,20,4]);
%
% %calibrate a kernel
% kSize = [5,5];
% coils = 4;
% kernel = zeros([kSize,coils,coils]);
% [AtA,] = corrMatrix(kCalib,kSize);
% for n=1:coils
% kernel(:,:,:,n) = calibrate(AtA,kSize,coils,n,0.01);
% end
% GOP = SPIRiT(kernel, 'fft',[128,128]);
%
% % undersample by a factor of 2
% DATA(1:2:end,2:2:end,:) = 0;
% DATA(2:2:end,1:2:end,:) = 0;
%
% %reconstruct:
% [res] = cgSPIRiT(DATA,GOP, 20, 1e-5, DATA);
% figure, imshow(cat(2,sos(imgs), 2*sos(ifft2c(DATA)), sos(ifft2c(res))),[]);
% title('full, zero-fill, result')
%
% (c) Michael Lustig 2007
%
if nargin < 4
lambda = 0;
end
if nargin < 5
x0 = y;
end
kernel = getKernel(GOP);
kSize = [size(kernel,1),size(kernel,2)];
[sx,sy,nCoils] = size(y);
idx_acq = find(abs(y)>0);
idx_nacq = find(abs(y)==0);
N = length(idx_nacq(:));
yy = GOP*y; yy = [-yy(:); idx_nacq(:)*0];
[tmpres,FLAG,RELRES,ITER,RESVEC] = lsqr(@aprod,yy,1e-6,nIter, speye(N,N),speye(N,N),x0(idx_nacq),GOP,sx,sy,nCoils,idx_nacq, lambda);
res = y;
res(idx_nacq) = tmpres;
function [res,tflag] = aprod(x,GOP,sx,sy,nCoils,idx_nacq, lambda,tflag)
kernel = getKernel(GOP);
kSize = [size(kernel,1),size(kernel,2)];
if strcmp(tflag,'transp');
tmpy = reshape(x(1:sx*sy*nCoils),sx,sy,nCoils);
res = GOP'*tmpy;
res = res(idx_nacq)+ x(sx*sy*nCoils+1:end)*lambda;
else
tmpx = zeros(sx,sy,nCoils);
tmpx(idx_nacq) = x;
res = GOP*tmpx;
res = [res(:) ; lambda*x(:)];
end
|
github
|
saradindusengupta/Regularization_parametre_in_reconstruction_of_cparallel-MR-image-master
|
cgNUSPIRiT.m
|
.m
|
Regularization_parametre_in_reconstruction_of_cparallel-MR-image-master/SPIRiT_code/cgNUSPIRiT.m
| 1,504 |
utf_8
|
672fd0e5a854d1c34d0ff92f72ef2f28
|
function [res,FLAG,RELRES,ITER,RESVEC,LSVEC] = cgNUSPIRiT(kData, x0, NUFFTOP, GOP, nIter, lambda)
% Implementation of image-domain SPIRiT reconstruction from arbitrary
% k-space. The function is based on Jeff Fessler's nufft code and LSQR
%
% Inputs:
% kData - k-space data matrix it is 3D corresponding to [readout,interleaves,coils]
% x0 - Initial estimate of the coil images
% NUFFTOP - nufft operator (see @NUFFT class)
% GOP - SPIRiT Operator (See @SPIRiT)
% nIter - number of LSQR iterations
% lambda - ratio between data consistency and SPIRiT consistency (1 is recommended)
%
% Outputs:
% res - reconstructed coil images
% FLAG,RELRES,ITER,RESVEC,LSVEC - See LSQR documentation
%
% See demo_nuSPIRiT for a demo on how to use this function.
%
% (c) Michael Lustig 2006, modified 2010
N = prod(size(x0));
imSize = size(x0);
dataSize = [size(kData)];
b = [kData(:) ; zeros(prod(imSize),1)];
[res,FLAG,RELRES,ITER,RESVEC,LSVEC] = lsqr(@(x,tflag)afun(x,NUFFTOP,GOP,dataSize, imSize,lambda,tflag), b, [], nIter,speye(N,N),speye(N,N), x0(:));
res = reshape(res,imSize);
function [y, tflag] = afun(x,NUFFTOP,GOP,dataSize,imSize,lambda,tflag)
if strcmp(tflag,'transp')
x1 = reshape(x(1:prod(dataSize)),dataSize);
x2 = reshape(x(prod(dataSize)+1:end),imSize);
y = NUFFTOP'.*x1 + lambda*(GOP'*x2);
y = y(:);
else
x = reshape(x,imSize);
y1 = NUFFTOP.*x;
y2 = GOP*x;
y = [y1(:); lambda*y2(:)];
end
|
github
|
saradindusengupta/Regularization_parametre_in_reconstruction_of_cparallel-MR-image-master
|
GRAPPA.m
|
.m
|
Regularization_parametre_in_reconstruction_of_cparallel-MR-image-master/utils/GRAPPA.m
| 3,551 |
utf_8
|
a089a5cd2acaf2d6a4e638b4cee1ea54
|
function res = GRAPPA(kData,kCalib,kSize,lambda, dispp)
% res = GRAPPA(kData,kCalib,kSize,lambda [, disp)
%
% This is a GRAPPA reconstruction algorithm that supports
% arbitrary Cartesian sampling. However, the implementation
% is highly inefficient in Matlab because it uses for loops.
% This implementation is very similar to the GE ARC implementation.
%
% The reconstruction looks at a neighborhood of a point and
% does a calibration according to the neighborhood to synthesize
% the missing point. This is a k-space varying interpolation.
% A sampling configuration is stored in a list, and retrieved
% when needed to accelerate the reconstruction (a bit)
%
% Inputs:
% kData - [Size x, Size y, num coils] 2D multi-coil k-space data to reconstruct from.
% Make sure that the missing entries have exact zeros in them.
% kCalib - calibration data (fully sampled k-space)
% kSize - size of the 2D GRAPPA kernel [kx, ky]
% lambda - Tykhonov regularization for the kernel calibration.
% dispp - Figure number to display images as they are
% reconstructed
% Outputs:
% res - k-space data where missing entries have been filled in.
%
% Example:
% [x,y] = meshgrid(linspace(0,1,128));
% % Generate fake Sensitivity maps
% sMaps = cat(3,x.^2,1-x.^2,y.^2,1-y.^2);
% % generate 4 coil phantom
% imgs = repmat(phantom(128),[1,1,4]).*sMaps;
% DATA = fft2c(imgs);
% % crop 20x20 window from the center of k-space for calibration
% kCalib = crop(DATA,[20,20,4]);
%
% %calibrate a kernel
% kSize = [5,5];
% coils = 4;
%
% % undersample by a factor of 2
% DATA(1:2:end,2:2:end,:) = 0;
% DATA(2:2:end,1:2:end,:) = 0;
%
% %reconstruct:
% [res] = GRAPPA(DATA,kCalib, kSize, 0.01);
% figure, imshow(cat(2,sos(imgs), 2*sos(ifft2c(DATA)), sos(ifft2c(res))),[]);
% title('full, zero-fill, result')
%
%
%
% (c) Michael Lustig 2008
if nargin < 5
dispp = 0;
end
pe = size(kData,2); fe = size(kData,1); coils = size(kData,3); % get sizes
res = kData*0;
%[AtA] = corrMatrix(kCalib,kSize); % build coil correlation matrix
AtA = dat2AtA(kCalib, kSize); % build coil calibrating matrix
for n=1:coils
disp(sprintf('reconstructing coil %d',n));
res(:,:,n) = ARC(kData, AtA,kSize, n,lambda); % reconstruct single coil image
if dispp ~=0
figure(dispp), imshow3(abs(ifft2c(res)),[]); drawnow
end
end
function [res] = ARC(kData, AtA, kSize, c,lambda);
[sx,sy,nCoil] = size(kData);
kData = zpad(kData,[sx+kSize(1)-1, sy+kSize(2)-1,nCoil]);
dummyK = zeros(kSize(1),kSize(2),nCoil); dummyK((end+1)/2,(end+1)/2,c) = 1;
idxy = find(dummyK);
res = zeros(sx,sy);
MaxListLen = 100;
LIST = zeros(kSize(1)*kSize(2)*nCoil,MaxListLen);
KEY = zeros(kSize(1)*kSize(2)*nCoil,MaxListLen);
count = 0;
%H = waitbar(0);
for y = 1:sy
for x=1:sx
% waitbar((x + (y-1)*sx)/sx/sy,H);
tmp = kData(x:x+kSize(1)-1,y:y+kSize(2)-1,:);
pat = abs(tmp)>0;
if pat(idxy) | sum(pat)==0
res(x,y) = tmp(idxy);
else
key = pat(:);
idx = 0;
for nn=1:size(KEY,2);
if sum(key==KEY(:,nn))==length(key)
idx = nn;
break;
end
end
if idx == 0
count = count + 1;
kernel = calibrate(AtA,kSize,nCoil,c,lambda,pat);
KEY(:,mod(count,MaxListLen)+1) = key(:);
LIST(:,mod(count,MaxListLen)+1) = kernel(:);
%disp('add another key');size(KEY,2)
else
kernel = LIST(:,idx);
end
res(x,y) = sum(kernel(:).*tmp(:));
end
end
end
%close(H);
|
github
|
saradindusengupta/Regularization_parametre_in_reconstruction_of_cparallel-MR-image-master
|
main_Ad_spiritL.m
|
.m
|
Regularization_parametre_in_reconstruction_of_cparallel-MR-image-master/l-curve/main_Ad_spiritL.m
| 1,263 |
utf_8
|
863a20754a0c874ae20d3ca1ff5cc697
|
function[I_recon,Istk,Kstk,E]=main_Ad_spiritL(DATA, kSize, nIter, mask)
% INPUTS
% kSize : SPIRiT kernel size
% nIter : number of iteration; phantom requires twice as much as the brain.
% mask : mask can be uniform or random
% lambda : Tykhonov regularization in the calibration
% T : Wavelet soft-thresholding regularization in the reconstruction
% OUTPUTS
% I_recon : Reconstructed Image (SoS combined)
% Istk : Reconstructed image (Coil-wise)
% Kstk : Reconstructed k-space (Coil-wise)
% Recon_err : Reconstruction Error
bet = 1;
im = ifft2c(DATA);
%-----------------------UnderSampling--------------------------
[DATA, CalibSize, scale_fctr]=get_SampledData(DATA,mask);
% im_dc = ifft2c(DATAcomp);
im = im/scale_fctr;
%-----------------------Perform Calibration--------------------------
[GOP]=tsvdLCalib(DATA,CalibSize,kSize);
%--------------------------Reconstruction------------------------
[Kstk,E] = AdSPIRiT_recon(DATA, GOP, nIter, DATA, im,bet);
% [Kstk, E] = AdWSPIRiT_recon2(DATA, GOP, nIter, DATA, T, im, bet);
Istk = ifft2c(Kstk);
I_recon=sos(Istk);
%------------------- calling function ----------
function [res]=NRMSE(I1,I2)
L2_error=I1-I2;
res=norm(L2_error(:),2)./norm(I1(:),2);
|
github
|
saradindusengupta/Regularization_parametre_in_reconstruction_of_cparallel-MR-image-master
|
splsqr.m
|
.m
|
Regularization_parametre_in_reconstruction_of_cparallel-MR-image-master/REGU/splsqr.m
| 4,613 |
utf_8
|
0181a37f320874537246273fe4ae9b3a
|
function x = splsqr(A,b,lambda,Vsp,maxit,tol,reorth)
%SPLSQR Subspace preconditioned LSQR for discrete ill-posed problems.
%
% x = splsqr(A,b,lambda,Vsp,maxit,tol,reorth)
%
% Subspace preconditioned LSQR (SP-LSQR) for solving the Tikhonov problem
% min { || A x - b ||^2 + lambda^2 || x ||^2 }
% with a preconditioner based on the subspace defined by the columns of
% the matrix Vsp. While not necessary, we recommend to use a matrix Vsp
% with orthonormal columns.
%
% The output x holds all the solution iterates as columns, and the last
% iterate x(:,end) is the best approximation to x_lambda.
%
% The parameter maxit is the maximum allowed number of iterations (default
% value is maxit = 300). The parameter tol is used a stopping criterion
% for the norm of the least squares residual relative to the norm of the
% right-hand side (default value is tol = 1e-12).
%
% A seventh input parameter reorth ~= 0 enforces MGS reorthogonalization
% of the Lanczos vectors.
% This is a model implementation of SP-LSQR. In a real implementation the
% Householder transformations should use LAPACK routines, only the final
% iterate should be returned, and reorthogonalization is not used. Also,
% if Vsp represents a fast transformation (such as the DCT) then explicit
% storage of Vsp should be avoided. See the reference for details.
% Reference: M. Jacobsen, P. C. Hansen and M. A. Saunders, "Subspace pre-
% conditioned LSQR for discrete ill-posed problems", BIT 43 (2003), 975-989.
% Per Christian Hansen and Michael Jacobsen, IMM, July 29, 2007.
% Input check.
if nargin < 5, maxit = 300; end
if nargin < 6, tol = 1e-12; end
if nargin < 7, reorth = 0; end
if maxit < 1, error('Number of iterations must be positive'); end;
% Prepare for SP-LSQR algorithm.
[m,n] = size(A);
k = size(Vsp,2);
z = zeros(n,1);
if reorth
UU = zeros(m+n,maxit);
VV = zeros(n,maxit);
end
% Initial QR factorization of [A;lamnda*eye(n)]*Vsp;
QQ = qr([A*Vsp;lambda*Vsp]);
% Prepare for LSQR iterations.
u = app_house_t(QQ,[b;z]);
u(1:k) = 0;
beta = norm(u);
u = u/beta;
v = app_house(QQ,u);
v = A'*v(1:m) + lambda*v(m+1:end);
alpha = norm(v);
v = v/alpha;
w = v;
Wxw = zeros(n,1);
phi_bar = beta;
rho_bar = alpha;
if reorth, UU(:,1) = u; VV(:,1) = v; end;
for i=1:maxit
% beta*u = A*v - alpha*u;
uu = [A*v;lambda*v];
uu = app_house_t(QQ,uu);
uu(1:k) = 0;
u = uu - alpha*u;
if reorth
for j=1:i-1, u = u - (UU(:,j)'*u)*UU(:,j); end
end
beta = norm(u);
u = u/beta;
% alpha * v = A'*u - beta*v;
vv = app_house(QQ,u);
v = A'*vv(1:m) + lambda*vv(m+1:end) - beta*v;
if reorth
for j=1:i-1, v = v - (VV(:,j)'*v)*VV(:,j); end
end
alpha = norm(v);
v = v/alpha;
if reorth, UU(:,i) = u; VV(:,i) = v; end;
% Update LSQR parameters.
rho = norm([rho_bar beta]);
c = rho_bar/rho;
s = beta/rho;
theta = s*alpha;
rho_bar = -c*alpha;
phi = c*phi_bar;
phi_bar = s*phi_bar;
% Update the LSQR solution.
Wxw = Wxw + (phi/rho)*w;
w = v - (theta/rho)*w;
% Compute residual and update the SP-LSQR iterate.
r = [b - A*Wxw ; -lambda*Wxw];
r = app_house_t(QQ,r);
r = r(1:k);
xv = triu(QQ(1:k,:))\r;
x(:,i) = Vsp*xv + Wxw;
% Stopping criterion.
if phi_bar*alpha*abs(c) < tol*norm(b), break, end
end
%-----------------------------------------------------------------
function Y = app_house(H,X)
% Y = app_house(H,X)
% Input: H = matrix containing the necessary information of the
% Householder vectors v in the lower triangle and R in
% the upper triangle; e.g., computed as H = qr(A).
% X = matrix to be multiplied with orthogonal matrix.
% Output: Y = Q*X
[n,p] = size(H);
Y = X;
for k = p:-1:1
v = ones(n+1-k,1);
v(2:n+1-k) = H(k+1:n,k);
beta = 2/(v'*v);
Y(k:n,:) = Y(k:n,:) - beta*v*(v'*Y(k:n,:));
end
%-----------------------------------------------------------------
function Y = app_house_t(H,X)
% Y = app_house_t(H,X)
% Input: H = matrix containing the necessary information of the
% Householder vectors v in the lower triangle and R in
% the upper triangle; e.g., computed as H = qr(A).
% X = matrix to be multiplied with transposed orthogonal matrix.
% Output: Y = Q'*X
[n,p] = size(H);
Y = X;
for k = 1:p
v = ones(n+1-k,1);
v(2:n+1-k) = H(k+1:n,k);
beta = 2/(v'*v);
Y(k:n,:) = Y(k:n,:) - beta*v*(v'*Y(k:n,:));
end
|
github
|
saradindusengupta/Regularization_parametre_in_reconstruction_of_cparallel-MR-image-master
|
discrep.m
|
.m
|
Regularization_parametre_in_reconstruction_of_cparallel-MR-image-master/REGU/discrep.m
| 5,655 |
utf_8
|
43a45ee002360136ca2339f5e1e85164
|
function [x_delta,lambda] = discrep(U,s,V,b,delta,x_0)
%DISCREP Discrepancy principle criterion for choosing the reg. parameter.
%
% [x_delta,lambda] = discrep(U,s,V,b,delta,x_0)
% [x_delta,lambda] = discrep(U,sm,X,b,delta,x_0) , sm = [sigma,mu]
%
% Least squares minimization with a quadratic inequality constraint:
% min || x - x_0 || subject to || A x - b || <= delta
% min || L (x - x_0) || subject to || A x - b || <= delta
% where x_0 is an initial guess of the solution, and delta is a
% positive constant. Requires either the compact SVD of A saved as
% U, s, and V, or part of the GSVD of (A,L) saved as U, sm, and X.
% The regularization parameter lambda is also returned.
%
% If delta is a vector, then x_delta is a matrix such that
% x_delta = [ x_delta(1), x_delta(2), ... ] .
%
% If x_0 is not specified, x_0 = 0 is used.
% Reference: V. A. Morozov, "Methods for Solving Incorrectly Posed
% Problems", Springer, 1984; Chapter 26.
% Per Christian Hansen, IMM, August 6, 2007.
% Initialization.
m = size(U,1); n = size(V,1);
[p,ps] = size(s); ld = length(delta);
x_delta = zeros(n,ld); lambda = zeros(ld,1); rho = zeros(p,1);
if (min(delta)<0)
error('Illegal inequality constraint delta')
end
if (nargin==5), x_0 = zeros(n,1); end
if (ps == 1), omega = V'*x_0; else omega = V\x_0; end
% Compute residual norms corresponding to TSVD/TGSVD.
beta = U'*b;
if (ps == 1)
delta_0 = norm(b - U*beta);
rho(p) = delta_0^2;
for i=p:-1:2
rho(i-1) = rho(i) + (beta(i) - s(i)*omega(i))^2;
end
else
delta_0 = norm(b - U*beta);
rho(1) = delta_0^2;
for i=1:p-1
rho(i+1) = rho(i) + (beta(i) - s(i,1)*omega(i))^2;
end
end
% Check input.
if (min(delta) < delta_0)
error('Irrelevant delta < || (I - U*U'')*b ||')
end
% Determine the initial guess via rho-vector, then solve the nonlinear
% equation || b - A x ||^2 - delta_0^2 = 0 via Newton's method.
if (ps == 1)
% The standard-form case.
s2 = s.^2;
for k=1:ld
if (delta(k)^2 >= norm(beta - s.*omega)^2 + delta_0^2)
x_delta(:,k) = x_0;
else
[dummy,kmin] = min(abs(rho - delta(k)^2));
lambda_0 = s(kmin);
lambda(k) = newton(lambda_0,delta(k),s,beta,omega,delta_0);
e = s./(s2 + lambda(k)^2); f = s.*e;
x_delta(:,k) = V(:,1:p)*(e.*beta + (1-f).*omega);
end
end
elseif (m>=n)
% The overdetermined or square genera-form case.
omega = omega(1:p); gamma = s(:,1)./s(:,2);
x_u = V(:,p+1:n)*beta(p+1:n);
for k=1:ld
if (delta(k)^2 >= norm(beta(1:p) - s(:,1).*omega)^2 + delta_0^2)
x_delta(:,k) = V*[omega;U(:,p+1:n)'*b];
else
[dummy,kmin] = min(abs(rho - delta(k)^2));
lambda_0 = gamma(kmin);
lambda(k) = newton(lambda_0,delta(k),s,beta(1:p),omega,delta_0);
e = gamma./(gamma.^2 + lambda(k)^2); f = gamma.*e;
x_delta(:,k) = V(:,1:p)*(e.*beta(1:p)./s(:,2) + ...
(1-f).*s(:,2).*omega) + x_u;
end
end
else
% The underdetermined general-form case.
omega = omega(1:p); gamma = s(:,1)./s(:,2);
x_u = V(:,p+1:m)*beta(p+1:m);
for k=1:ld
if (delta(k)^2 >= norm(beta(1:p) - s(:,1).*omega)^2 + delta_0^2)
x_delta(:,k) = V*[omega;U(:,p+1:m)'*b];
else
[dummy,kmin] = min(abs(rho - delta(k)^2));
lambda_0 = gamma(kmin);
lambda(k) = newton(lambda_0,delta(k),s,beta(1:p),omega,delta_0);
e = gamma./(gamma.^2 + lambda(k)^2); f = gamma.*e;
x_delta(:,k) = V(:,1:p)*(e.*beta(1:p)./s(:,2) + ...
(1-f).*s(:,2).*omega) + x_u;
end
end
end
%-------------------------------------------------------------------
function lambda = newton(lambda_0,delta,s,beta,omega,delta_0)
%NEWTON Newton iteration (utility routine for DISCREP).
%
% lambda = newton(lambda_0,delta,s,beta,omega,delta_0)
%
% Uses Newton iteration to find the solution lambda to the equation
% || A x_lambda - b || = delta ,
% where x_lambda is the solution defined by Tikhonov regularization.
%
% The initial guess is lambda_0.
%
% The norm || A x_lambda - b || is computed via s, beta, omega and
% delta_0. Here, s holds either the singular values of A, if L = I,
% or the c,s-pairs of the GSVD of (A,L), if L ~= I. Moreover,
% beta = U'*b and omega is either V'*x_0 or the first p elements of
% inv(X)*x_0. Finally, delta_0 is the incompatibility measure.
% Reference: V. A. Morozov, "Methods for Solving Incorrectly Posed
% Problems", Springer, 1984; Chapter 26.
% Per Christian Hansen, IMM, 12/29/97.
% Set defaults.
thr = sqrt(eps); % Relative stopping criterion.
it_max = 50; % Max number of iterations.
% Initialization.
if (lambda_0 < 0)
error('Initial guess lambda_0 must be nonnegative')
end
[p,ps] = size(s);
if (ps==2), sigma = s(:,1); s = s(:,1)./s(:,2); end
s2 = s.^2;
% Use Newton's method to solve || b - A x ||^2 - delta^2 = 0.
% It was found experimentally, that this formulation is superior
% to the formulation || b - A x ||^(-2) - delta^(-2) = 0.
lambda = lambda_0; step = 1; it = 0;
while (abs(step) > thr*lambda & abs(step) > thr & it < it_max), it = it+1;
f = s2./(s2 + lambda^2);
if (ps==1)
r = (1-f).*(beta - s.*omega);
z = f.*r;
else
r = (1-f).*(beta - sigma.*omega);
z = f.*r;
end
step = (lambda/4)*(r'*r + (delta_0+delta)*(delta_0-delta))/(z'*r);
lambda = lambda - step;
% If lambda < 0 then restart with smaller initial guess.
if (lambda < 0), lambda = 0.5*lambda_0; lambda_0 = 0.5*lambda_0; end
end
% Terminate with an error if too many iterations.
if (abs(step) > thr*lambda & abs(step) > thr)
error(['Max. number of iterations (',num2str(it_max),') reached'])
end
|
github
|
saradindusengupta/Regularization_parametre_in_reconstruction_of_cparallel-MR-image-master
|
corner.m
|
.m
|
Regularization_parametre_in_reconstruction_of_cparallel-MR-image-master/REGU/corner.m
| 8,640 |
utf_8
|
1fc59ce57e9ede542069ef7b1fce444d
|
function [k_corner,info] = corner(rho,eta,fig)
%CORNER Find corner of discrete L-curve via adaptive pruning algorithm.
%
% [k_corner,info] = corner(rho,eta,fig)
%
% Returns the integer k_corner such that the corner of the log-log
% L-curve is located at ( log(rho(k_corner)) , log(eta(k_corner)) ).
%
% The vectors rho and eta must contain corresponding values of the
% residual norm || A x - b || and the solution's (semi)norm || x ||
% or || L x || for a sequence of regularized solutions, ordered such
% that rho and eta are monotonic and such that the amount of
% regularization decreases as k increases.
%
% The second output argument describes possible warnings.
% Any combination of zeros and ones is possible.
% info = 000 : No warnings - rho and eta describe a discrete
% L-curve with a corner.
% info = 001 : Bad data - some elements of rho and/or eta are
% Inf, NaN, or zero.
% info = 010 : Lack of monotonicity - rho and/or eta are not
% strictly monotonic.
% info = 100 : Lack of convexity - the L-curve described by rho
% and eta is concave and has no corner.
%
% The warnings described above will also result in text warnings on the
% command line. Type 'warning off Corner:warnings' to disable all
% command line warnings from this function.
%
% If a third input argument is present, then a figure will show the discrete
% L-curve in log-log scale and also indicate the found corner.
% Reference: P. C. Hansen, T. K. Jensen and G. Rodriguez, "An adaptive
% pruning algorithm for the discrete L-curve criterion," J. Comp. Appl.
% Math., 198 (2007), 483-492.
% Per Christian Hansen and Toke Koldborg Jensen, IMM, DTU;
% Giuseppe Rodriguez, University of Cagliari, Italy; March 22, 2006.
% Initialization of data
rho = rho(:); % Make rho and eta column vectors.
eta = eta(:);
if (nargin < 3) | isempty(fig)
fig = 0; % Default is no figure.
elseif fig < 0,
fig = 0;
end
info = 0;
fin = isfinite(rho+eta); % NaN or Inf will cause trouble.
nzr = rho.*eta~=0; % A zero will cause trouble.
kept = find(fin & nzr);
if isempty(kept)
error('Too many Inf/NaN/zeros found in data')
end
if length(kept) < length(rho)
info = info + 1;
warning('Corner:warnings', ...
['Bad data - Inf, NaN or zeros found in data\n' ...
' Continuing with the remaining data'])
end
rho = rho(kept); % rho and eta with bad data removed.
eta = eta(kept);
if any(rho(1:end-1)<rho(2:end)) | any(eta(1:end-1)>eta(2:end))
info = info + 10;
warning('Corner:warnings', 'Lack of monotonicity')
end
% Prepare for adaptive algorithm.
nP = length(rho); % Number of points.
P = log10([rho eta]); % Coordinates of the loglog L-curve.
V = P(2:nP,:)-P(1:nP-1,:); % The vectors defined by these coordinates.
v = sqrt(sum(V.^2,2)); % The length of the vectors.
W = V./repmat(v,1,2); % Normalized vectors.
clist = []; % List of candidates.
p = min(5, nP-1); % Number of vectors in pruned L-curve.
convex = 0; % Are the pruned L-curves convex?
% Sort the vectors according to the length, the longest first.
[Y,I] = sort(v);
I = flipud(I);
% Main loop -- use a series of pruned L-curves. The two functions
% 'Angles' and 'Global_Behavior' are used to locate corners of the
% pruned L-curves. Put all the corner candidates in the clist vector.
while p < (nP-1)*2
elmts = sort(I(1:min(p, nP-1)));
% First corner location algorithm
candidate = Angles( W(elmts,:), elmts);
if candidate>0,
convex = 1;
end
if candidate & ~any(clist==candidate)
clist = [clist;candidate];
end
% Second corner location algorithm
candidate = Global_Behavior(P, W(elmts,:), elmts);
if ~any(clist==candidate)
clist = [clist; candidate];
end
p = p*2;
end
% Issue a warning and return if none of the pruned L-curves are convex.
if convex==0
k_corner = [];
info = info + 100;
warning('Corner:warnings', 'Lack of convexity')
return
end
% Put rightmost L-curve point in clist if not already there; this is
% used below to select the corner among the corner candidates.
if sum(clist==1) == 0
clist = [1;clist];
end
% Sort the corner candidates in increasing order.
clist = sort(clist);
% Select the best corner among the corner candidates in clist.
% The philosophy is: select the corner as the rightmost corner candidate
% in the sorted list for which going to the next corner candidate yields
% a larger increase in solution (semi)norm than decrease in residual norm,
% provided that the L-curve is convex in the given point. If this is never
% the case, then select the leftmost corner candidate in clist.
vz = find(diff(P(clist,2)) ... % Points where the increase in solution
>= abs(diff(P(clist,1)))); % (semi)norm is larger than or equal
% to the decrease in residual norm.
if length(vz)>1
if(vz(1) == 1), vz = vz(2:end); end
elseif length(vz)==1
if(vz(1) == 1), vz = []; end
end
if isempty(vz)
% No large increase in solution (semi)norm is found and the
% leftmost corner candidate in clist is selected.
index = clist(end);
else
% The corner is selected as described above.
vects = [P(clist(2:end),1)-P(clist(1:end-1),1) ...
P(clist(2:end),2)-P(clist(1:end-1),2)];
vects = sparse(diag(1./sqrt(sum(vects.^2,2)))) * vects;
delta = vects(1:end-1,1).*vects(2:end,2) ...
- vects(2:end,1).*vects(1:end-1,2);
vv = find(delta(vz-1)<=0);
if isempty(vv)
index = clist(vz(end));
else
index = clist(vz(vv(1)));
end
end
% Corner according to original vectors without Inf, NaN, and zeros removed.
k_corner = kept(index);
if fig % Show log-log L-curve and indicate the found corner.
figure(fig); clf
diffrho2 = (max(P(:,1))-min(P(:,1)))/2;
diffeta2 = (max(P(:,2))-min(P(:,2)))/2;
loglog(rho, eta, 'k--o'); hold on; axis square;
% Mark the corner.
loglog([min(rho)/100,rho(index)],[eta(index),eta(index)],':r',...
[rho(index),rho(index)],[min(eta)/100,eta(index)],':r')
% Scale axes to same number of decades.
if abs(diffrho2)>abs(diffeta2),
ax(1) = min(P(:,1)); ax(2) = max(P(:,1));
mid = min(P(:,2)) + (max(P(:,2))-min(P(:,2)))/2;
ax(3) = mid-diffrho2; ax(4) = mid+diffrho2;
else
ax(3) = min(P(:,2)); ax(4) = max(P(:,2));
mid = min(P(:,1)) + (max(P(:,1))-min(P(:,1)))/2;
ax(1) = mid-diffeta2; ax(2) = mid+diffeta2;
end
ax = 10.^ax; ax(1) = ax(1)/2; axis(ax);
xlabel('residual norm || A x - b ||_2')
ylabel('solution (semi)norm || L x ||_2');
title(sprintf('Discrete L-curve, corner at %d', k_corner));
end
% =========================================================================
% First corner finding routine -- based on angles
function index = Angles( W, kv)
% Wedge products
delta = W(1:end-1,1).*W(2:end,2) - W(2:end,1).*W(1:end-1,2);
[mm kk] = min(delta);
if mm < 0 % Is it really a corner?
index = kv(kk) + 1;
else % If there is no corner, return 0.
index = 0;
end
% =========================================================================
% Second corner finding routine -- based on global behavior of the L-curve
function index = Global_Behavior(P, vects, elmts)
hwedge = abs(vects(:,2)); % Abs of wedge products between
% normalized vectors and horizontal,
% i.e., angle of vectors with horizontal.
[An, In] = sort(hwedge); % Sort angles in increasing order.
% Locate vectors for describing horizontal and vertical part of L-curve.
count = 1;
ln = length(In);
mn = In(1);
mx = In(ln);
while(mn>=mx)
mx = max([mx In(ln-count)]);
count = count + 1;
mn = min([mn In(count)]);
end
if count > 1
I = 0; J = 0;
for i=1:count
for j=ln:-1:ln-count+1
if(In(i) < In(j))
I = In(i); J = In(j); break
end
end
if I>0, break; end
end
else
I = In(1); J = In(ln);
end
% Find intersection that describes the "origin".
x3 = P(elmts(J)+1,1)+(P(elmts(I),2)-P(elmts(J)+1,2))/(P(elmts(J)+1,2) ...
-P(elmts(J),2))*(P(elmts(J)+1,1)-P(elmts(J),1));
origin = [x3 P(elmts(I),2)];
% Find distances from the original L-curve to the "origin". The corner
% is the point with the smallest Euclidian distance to the "origin".
dists = (origin(1)-P(:,1)).^2+(origin(2)-P(:,2)).^2;
[Y,index] = min(dists);
|
github
|
saradindusengupta/Regularization_parametre_in_reconstruction_of_cparallel-MR-image-master
|
splsqrL.m
|
.m
|
Regularization_parametre_in_reconstruction_of_cparallel-MR-image-master/REGU/splsqrL.m
| 5,128 |
utf_8
|
1e24aa441349e75e253fbc2c5296364f
|
function x = splsqr(A,L,b,lambda,Vsp,maxit,tol,reorth)
%SPLSQR Subspace preconditioned LSQR for discrete ill-posed problems.
%
% x = splsqr(A,L,b,lambda,Vsp,maxit,tol,reorth)
%
% Subspace preconditioned LSQR (SP-LSQR) for solving the Tikhonov problem
% min { || A x - b ||^2 + lambda^2 || L x ||^2 }
% with a preconditioner based on the subspace defined by the columns of
% the matrix Vsp. While not necessary, we recommend to use a matrix Vsp
% with orthonormal columns.
%
% If L is the identity matrix, use L = [] for efficiency reasons.
%
% The output x holds all the solution iterates as columns, and the last
% iterate x(:,end) is the best approximation to x_lambda.
%
% The parameter maxit is the maximum allowed number of iterations (default
% value is maxit = 300). The parameter tol is used a stopping criterion
% for the norm of the least squares residual relative to the norm of the
% right-hand side (default value is tol = 1e-12).
%
% A eighth input parameter reorth ~= 0 enforces MGS reorthogonalization
% of the Lanczos vectors.
% This is a model implementation of SP-LSQR. In a real implementation the
% Householder transformations should use LAPACK routines, only the final
% iterate should be returned, and reorthogonalization is not used. Also,
% if Vsp represents a fast transformation (such as the DCT) then explicit
% storage of Vsp should be avoided. See the reference for details.
% Reference: M. Jacobsen, P. C. Hansen and M. A. Saunders, "Subspace pre-
% conditioned LSQR for discrete ill-posed problems", BIT 43 (2003), 975-989.
% Per Christian Hansen and Michael Jacobsen, IMM, July 30, 2007.
% Input check.
if nargin < 6, maxit = 300; end
if nargin < 7, tol = 1e-12; end
if nargin < 8, reorth = 0; end
if maxit < 1, error('Number of iterations must be positive'); end;
% Prepare for SP-LSQR algorithm.
[m,n] = size(A);
k = size(Vsp,2);
isI = isempty(L);
if isI, p = n; else p = size(L,1); end
z = zeros(p,1);
if reorth
UU = zeros(m+p,maxit);
VV = zeros(n,maxit);
end
% Initial QR factorization of [A;lambda*L]*Vsp;
if isI
QQ = qr([A*Vsp;lambda*Vsp]);
else
QQ = qr([A*Vsp;lambda*L*Vsp]);
end
% Prepare for LSQR iterations.
u = app_house_t(QQ,[b;z]);
u(1:k) = 0;
beta = norm(u);
u = u/beta;
v = app_house(QQ,u);
if isI
v = A'*v(1:m) + lambda*v(m+1:end);
else
v =A'*v(1:m) + lambda*L'*v(m+1:end);
end
alpha = norm(v);
v = v/alpha;
w = v;
Wxw = zeros(n,1);
phi_bar = beta;
rho_bar = alpha;
if reorth, UU(:,1) = u; VV(:,1) = v; end;
for i=1:maxit
% beta*u = [A;lambda*L]*v - alpha*u;
if isI
uu = [A*v;lambda*v];
else
uu = [A*v;lambda*L*v];
end
uu = app_house_t(QQ,uu);
uu(1:k) = 0;
u = uu - alpha*u;
if reorth
for j=1:i-1, u = u - (UU(:,j)'*u)*UU(:,j); end
end
beta = norm(u);
u = u/beta;
% alpha * v = [A;lambda*L]'*u - beta*v;
vv = app_house(QQ,u);
if isI
v = A'*vv(1:m) + lambda*vv(m+1:end) - beta*v;
else
v = A'*vv(1:m) + lambda*L'*vv(m+1:end) - beta*v;
end
if reorth
for j=1:i-1, v = v - (VV(:,j)'*v)*VV(:,j); end
end
alpha = norm(v);
v = v/alpha;
if reorth, UU(:,i) = u; VV(:,i) = v; end;
% Update LSQR parameters.
rho = norm([rho_bar beta]);
c = rho_bar/rho;
s = beta/rho;
theta = s*alpha;
rho_bar = -c*alpha;
phi = c*phi_bar;
phi_bar = s*phi_bar;
% Update the LSQR solution.
Wxw = Wxw + (phi/rho)*w;
w = v - (theta/rho)*w;
% Compute residual and update the SP-LSQR iterate.
if isI
r = [b - A*Wxw ; -lambda*Wxw];
else
r = [b - A*Wxw ; -lambda*L*Wxw];
end
r = app_house_t(QQ,r);
r = r(1:k);
xv = triu(QQ(1:k,:))\r;
x(:,i) = Vsp*xv + Wxw;
% Stopping criterion.
if phi_bar*alpha*abs(c) < tol*norm(b), break, end
end
%-----------------------------------------------------------------
function Y = app_house(H,X)
% Y = app_house(H,X)
% Input: H = matrix containing the necessary information of the
% Householder vectors v in the lower triangle and R in
% the upper triangle; e.g., computed as H = qr(A).
% X = matrix to be multiplied with orthogonal matrix.
% Output: Y = Q*X
[n,p] = size(H);
Y = X;
for k = p:-1:1
v = ones(n+1-k,1);
v(2:n+1-k) = H(k+1:n,k);
beta = 2/(v'*v);
Y(k:n,:) = Y(k:n,:) - beta*v*(v'*Y(k:n,:));
end
%-----------------------------------------------------------------
function Y = app_house_t(H,X)
% Y = app_house_t(H,X)
% Input: H = matrix containing the necessary information of the
% Householder vectors v in the lower triangle and R in
% the upper triangle; e.g., computed as H = qr(A).
% X = matrix to be multiplied with transposed orthogonal matrix.
% Output: Y = Q'*X
[n,p] = size(H);
Y = X;
for k = 1:p
v = ones(n+1-k,1);
v(2:n+1-k) = H(k+1:n,k);
beta = 2/(v'*v);
Y(k:n,:) = Y(k:n,:) - beta*v*(v'*Y(k:n,:));
end
|
github
|
Rafnuss-PhD/A2PK-master
|
A2PK.m
|
.m
|
A2PK-master/A2PK.m
| 2,973 |
utf_8
|
db3017b89b940420b2dfebbc8d3abe49
|
%% Area-to-Point kriging A2PK
% *Area-to-Point kriging A2PK* generates stocastic Gaussian realization
% |*z*| constrained to a variable |*Z*| which is lineraly related
% to |*z*| by |*G*|:
%
% $$\mathbf{Z = Gz}$$
%
%
% The argument of the function are
% * |x|: vector of coordinates along the first axes
% * |y|: vector of coordinates along the second axes
% * |hd|: Hard data, see |functions/sampling_pt.m|
% * |Z|: Coarse scale
% * |G|: Linear link
% * |covar|: covariance structure defined as in
% |FastGaussianSimulation/covarIni.m|
% * |n_real|: number of realization desired
%
% The output of the function are
% * |zcs|: Conditional realizations cells of size n_real
% * |zh|: Krigging estimation
% * |S|: Variance of kriging estimation
%
% *Script*
%
% *Exemples*: Available in the folder |examples| with unconditional and
% conditional Gaussian simulation and a case study of electrical tomography
function [zcs,zh,S] = A2PK(x,y,hd,Z,G,covar,n_real)
%% Checkin input argument
validateattributes(x,{'numeric'},{'vector'})
validateattributes(y,{'numeric'},{'vector'})
if isempty(hd)
hd.id=[];
hd.n=0;
hd.d=[];
end
validateattributes(hd,{'struct'},{})
% validateattributes(hd.id,{'numeric'},{'vector','integer'})
% validateattributes(hd.d,{'numeric'},{'vector'})
validateattributes(hd.n,{'numeric'},{'integer','nonnegative','scalar'})
validateattributes(Z,{'numeric'},{'2d'})
validateattributes(G,{'numeric'},{'2d'})
validateattributes(n_real,{'numeric'},{'integer','positive','scalar'})
assert(all(size(G)==[numel(Z) numel(x)*numel(y)]),'The size of the upscaling matrix G need to be equal to [numel(Z) numel(x)*numel(y)]')
%% Inlude the dependancy
addpath('./FastGaussianSimulation');
addpath('./functions');
%% Convert the covariance
covar = covarIni(covar);
[X, Y] = meshgrid(x, y); X=X(:); Y=Y(:);
nx=numel(x); ny=numel(y); nZ=numel(Z);
%% Calcul of the covariance and cross covariance.
% Because the covariance matrix can be quite large, an iterative loop might
% be faster
if nx*ny>100000
Czz=zeros(nx*ny,nx*ny);
wradius = parm.k.wradius;
for ixy=1:nx*ny
u=zeros(1,nx*ny);
id = X-X(ixy)<covar.range(1)*wradius & Y-Y(ixy)<covar.range(2)*wradius;
u(id) = covar.g(pdist2([X(id) Y(id)]*covar.cx,[X(ixy) Y(ixy)]*covar.cx));
Czz(ixy,:) = u;
end
Czz=sparse(Czz);
else
Czz = covar.g(squareform(pdist([X Y]*covar.cx)));
end
CzZ = Czz * G';
CZZ = G * CzZ;
Chd = Czz(hd.id,hd.id);
Czhd = Czz(:,hd.id);
CZhd = CzZ(hd.id,:);
CCa = [ CZZ CZhd' ; CZhd Chd ];
CCb = [ CzZ' ; Czhd' ];
%% Compute the kriging weights W, variance S and kriging map zh
W = (CCa \ CCb)';
zh = reshape( W * [Z(:) ; hd.d], ny, nx);
S = reshape(covar.g(0) - diag(W * CCb), ny, nx);
%% Create Simulation
zcs=nan(ny, nx,n_real);
for i_real=1:n_real
zs = FGS(struct('s',[numel(x) numel(y)]), covar);
zhs = reshape( W * [G * zs{1}(:) ; zs{1}(hd.id)'], ny, nx);
zcs(:,:,i_real) = zh + (zs{1} - zhs);
end
|
github
|
Rafnuss-PhD/A2PK-master
|
Matlat2R2min.m
|
.m
|
A2PK-master/ERT/R2/Matlat2R2min.m
| 1,323 |
utf_8
|
35f6061fcd250c1e80c714cf42ee08eb
|
%% Create R2.in and protocol.dat
%
% Comment are from the Readme Manual (2.7a)
%
% INPUT (generated with this script):
% * R2.in : geometry informaton
% * protocol.dat : index, 4 electrodes index
% ( * mesh.dat : for triangulare meshing)
%
% OUPUT:
% * R2.out : main log exectution
% * electrodes.dat : x,y-coordinate of electrodes
% * electrodes.vtk : idem in vtk format
% FORWARD OUTPUT
% * R2_forward.dat : similare to protocol.dat + calculated resistances +
% calculated apparent resistivities
% * forward_model.dat : x, y, resis, log10(resis)
% INVERSE
function [resistance, pseudo] = Matlat2R2min(d)
% d is either the inverser (i) or forward (f) structure
% RESISITIVITY
d.value = d.rho(:)' ;
% PROTOCOL
% createProtocoldat(d)
% CREATE THE FILES
% createR2in(d)
content_start=strfind(d.content,'<< elem_1, elem_2, value')+24;
content_end=strfind(d.content,'<< num_xy_poly')-8;
content = [d.content(1:content_start ) sprintf('%5d %5d %5d\n',[d.elem_1;d.elem_2;d.value]) d.content(content_end:end)];
fId = fopen( [d.filepath 'R2.in'], 'w' ) ;
fwrite( fId, content);
fclose( fId );
% RUN .EXE
pwd_temp = pwd;
cd(d.filepath);
[~,~]=system('R2.exe');
cd(pwd_temp);
% OUPUT
data=dlmread([d.filepath 'R2_forward.dat'],'',1,5);
resistance=data(:,1);
pseudo=data(:,2);
end
|
github
|
Rafnuss-PhD/A2PK-master
|
Matlat2R2.m
|
.m
|
A2PK-master/ERT/R2/Matlat2R2.m
| 9,124 |
UNKNOWN
|
19b55369dab4c602fb74b47c8b60cc04
|
%% Create R2.in and protocol.dat
%
% Comment are from the Readme Manual (2.7a)
%
% INPUT (generated with this script):
% * R2.in : geometry informaton
% * protocol.dat : index, 4 electrodes index
% ( * mesh.dat : for triangulare meshing)
%
% OUPUT:
% * R2.out : main log exectution
% * electrodes.dat : x,y-coordinate of electrodes
% * electrodes.vtk : idem in vtk format
% FORWARD OUTPUT
% * R2_forward.dat : similare to protocol.dat + calculated resistances +
% calculated apparent resistivities
% * forward_model.dat : x, y, resis, log10(resis)
% INVERSE
function d = Matlat2R2(d,elec)
% d is either the inverser (i) or forward (f) structure
%% BASIC GENERAL SETTING
% d.header = d.header; % title of up to 80 characters
% d.job_type = d.job_type; % 0 for forward solution only or 1 for inverse solution
d.mesh_type = 4; % mesh: 3-triangular, 4-regular quadrilateral, 5-generalised quadrilateral
d.flux_type = 3.0; % current flow: 2.0-2D (i.e. line electrodes) or 3.0-fully 3D (usual mode)
d.singular_type = 0; % Singularity: 1-removal applied , 0-no removal
% d.res_matrix = d.res_matrix; % resolution matrix: 1-'sensitivity' matrix, 2-true resolution matrix or 0-none
% d.filepath = d.filepath; % where to write the file
%% MESH CONSTRUCTION
switch d.mesh_type
case 3 % Trigular Mesh
d.scale = NaN; % scaling factor for the mesh co-ordinates.
case 4
d.xx = d.grid.x_n; % array containing x coordinates of each of numnp_x node columns
d.yy = d.grid.y_n; % array containing y coordinates of each of numnp_y node rows relative to the topog array.
% Set yy(1) to zero and the other values to a positive number
d.numnp_x = numel(d.xx); % number of nodes in the x direction
d.numnp_y = numel(d.yy); % number of nodes in the y direction
d.topog = zeros(1,d.numnp_x); % garray containing elevations of each of numnp_x node columns. If the topography is flat then set
% topog to zero for all values.
case 5
d.numnp_x = NaN; % number of nodes in the x direction
d.numnp_y = NaN; % number of nodes in the y direction
d.xx = NaN; % array containing x coordinates of each of numnp_x node columns
d.yy = NaN; % array containing y coordinates of each of numnp_y node columns.
% Set yy(1) to zero and the other values to a positive number
end
%% RESISITIVITY
if d.job_type == 0 % one value per grid cells in the inside grid plus a cst value for the buffer zone
% d.rho_numnp = nan(d.numnp_y-1,d.numnp_x-1);
% d.rho_numnp(1:(d.numnp_y-1-n_plus),(n_plus+1):(d.numnp_x-1-n_plus)) = d.rho;
% idx = 1:((d.numnp_y-1)*(d.numnp_x-1));
% d.elem_1 = [1 idx(~isnan(d.rho_numnp(:)))];
% d.elem_2 = [(d.numnp_y-1)*(d.numnp_x-1) idx(~isnan(d.rho_numnp(:)))];
% d.value = [d.rho_avg d.rho_numnp(~isnan(d.rho_numnp(:)))'] ;
d.elem_1 = 1:((d.numnp_y-1)*(d.numnp_x-1));
d.elem_2 = 1:((d.numnp_y-1)*(d.numnp_x-1));
d.value = d.rho(:)' ;
elseif d.job_type == 1 % for inversion, only one average value is given...
% d.elem_1 = [1 ];% 3461 3509 3557 3605 3653 3701 3749 3797];
% d.elem_2 = [(d.numnp_y-1)*(d.numnp_x-1)];% 3472 3520 3568 3616 3664 3712 3760 3808];
% d.value = [d.rho_avg ];% 10 10 10 10 10 10 10 10] ;
warning('check this')
d.elem_1 = 1:((d.numnp_y-1)*(d.numnp_x-1));
d.elem_2 = 1:((d.numnp_y-1)*(d.numnp_x-1));
d.value = d.rho(:)' ;
end
d.num_regions = numel(d.value); % number of resistivity regions
if d.num_regions == 0 % file, not working... instead set-up one value per grid cells, so num_regions is huge...
error('Using a input file is not yet implemented working')
end
%% INVERSE SOLUTION
if d.job_type==1 % inverse solution
d.inverse_type = 1; % Inverse type: 0-pseudo-Marquardt, 1-regularised solution with linear filter (usual mode),
d.target_decrease = 0;
% 2-regularised type with quadratic filter, 3-qualitative solution or 4-blocked linear regularised type
if d.mesh_type==4 || d.mesh_type==5 % quadrilateral mesh
d.patch_size_x = 1; % parameter block sizes in the x and y direction, respectively.
d.patch_size_y = 1;
if d.patch_size_x==0 && d.patch_size_y==0
d.num_param_x = NaN; % number of parameter blocks in the x directions
d.num_param_y = NaN; % number of parameter blocks in the y directions
d.npxstart = NaN; % column number in the mesh where the parameters start
d.npystart = NaN;
d.npx = NaN; % specifies the number of elements in each parameter block
d.npy = NaN;
end
d.data_type = 1; % 0-true data based inversion or 1-log data based.
d.reg_mode = 0; % Regularisation: 0-normal, 1-relative to starting resistivity or 2-relative to a previous dataset
% using the �Differenceinversion� of LaBrecque and Yang (2000)
d.tolerance = d.tolerance; % desired misfit (usually 1.0)
d.max_iterations = d.max_iterations; % maximum number of iteration
d.error_mod = 0; % 0 -preserve the data weights, 1 or 2-update the weights as the inversion progresses (error_mod=2 is recommended)
d.alpha_aniso = d.alpha_aniso; % anisotropy of the smoothing factor: > 1 for smoother horizontal, alpha_aniso < 1 for smoother
% vertical models, or alpha_aniso=1 for normal (isotropic) regularisation
if d.reg_mode==1
d.alpha_s = NaN; % regularisation to the starting model
end
d.a_wgt = d.a_wgt; % error variance with var(R) = (a_wgt*a_wgt) + (b_wgt*b_wgt) * (R*R)
d.b_wgt = d.b_wgt; % where R is the resistance measured
if d.patch_size_x==0 && d.patch_size_y==0
d.param_symbol
end
elseif d.mesh_type==3 % Trigular Mesh
d.qual_ratio = NaN; % 0 for qualitative comparison with forward solution, i.e. only when one observed data set is available,
% or qual_ratio is 1 if the observed data in protocol.dat contains a ratio of two datasets
end
d.rho_min = 0; % minimum observed apparent resistivity to be used
d.rho_max = 5000; % maximum observed apparent resistivity to be used
end
%% REGION OUTPUT (new in 2.7)
d.num_xy_poly = 5; % number of x,y co-ordinates that define a polyline bounding (4 corners + repeat the first corner)
d.x_poly = [d.xx(1) d.xx(end) d.xx(end) d.xx(1) d.xx(1)];% [x(1) x(end) x(end) x(1) x(1)]; % co-ordinates of points on the polyline
d.y_poly = -[d.yy(1) d.yy(1) d.yy(end) d.yy(end) d.yy(1)];%-[y(1) y(1) y(end) y(end) y(1)];
%% ELECTRODE
d.num_electrodes = elec.n; % Number of electrodes
d.j_e = 1:d.num_electrodes; % electrode number
if d.job_type==1 && d.inverse_type==3
d.node = NaN; % node number in the finite element mesh
else
d.column = d.elec_id; % column index for the node the finite element mesh
d.row = ones(1,d.num_electrodes); % row index for the node in the finite element mesh
end
%% PROTOCOL
d.num_ind_meas = size(elec.data,1); % number of measurements to follow in file
d.j_p = 1:d.num_ind_meas; %
d.elec = elec.data;
if d.job_type == 1 % inverse solution
d.v_i_ratio = NaN; %
d.v_i_ratio_0 = NaN; %
d.data_sd = NaN; %
copyfile([d.filepath 'R2_forward.dat'],[d.filepath 'protocol.dat']) % used the output of the forward model
else
createProtocoldat(d)
end
%% CREATE THE FILES
createR2in(d)
%% RUN .EXE
if ~d.readonly
copyfile('R2/R2.exe',d.filepath,'f');
pwd_temp = pwd;
cd(d.filepath); tic;
if ismac
warning('You will need wine for mac in order to work !')
status = unix('wine R2.exe');
elseif isunix
status = unix('wine R2.exe');
elseif ispc
[status] = system('R2.exe');
else
error('Cannot recognize platform')
end
cd(pwd_temp);
%disp(['Model run in ' num2str(toc) ' secondes.'])
if status~=0
error('Model did not worked')
end
end
%% OUPUT
d.pseudo_x=elec.pseudo_x;
d.pseudo_y=elec.pseudo_y;
d.output=readOutput(d);
end
|
github
|
Rafnuss-PhD/A2PK-master
|
Matlat2R2.m
|
.m
|
A2PK-master/HT/R2/Matlat2R2.m
| 9,204 |
UNKNOWN
|
d6cba5cbe13d7f795688bb216cfba617
|
%% Create R2.in and protocol.dat
%
% Comment are from the Readme Manual (2.7a)
%
% INPUT (generated with this script):
% * R2.in : geometry informaton
% * protocol.dat : index, 4 electrodes index
% ( * mesh.dat : for triangulare meshing)
%
% OUPUT:
% * R2.out : main log exectution
% * electrodes.dat : x,y-coordinate of electrodes
% * electrodes.vtk : idem in vtk format
% FORWARD OUTPUT
% * R2_forward.dat : similare to protocol.dat + calculated resistances +
% calculated apparent resistivities
% * forward_model.dat : x, y, resis, log10(resis)
% INVERSE
function d = Matlat2R2(d,elec)
% d is either the inverser (i) or forward (f) structure
% x and y need to be node (intersection of cells) and not cell centered
x = d.grid.x_n;
y = d.grid.y_n;
%% BASIC GENERAL SETTING
% d.header = d.header; % title of up to 80 characters
% d.job_type = d.job_type; % 0 for forward solution only or 1 for inverse solution
d.mesh_type = 4; % mesh: 3-triangular, 4-regular quadrilateral, 5-generalised quadrilateral
d.flux_type = 3.0; % current flow: 2.0-2D (i.e. line electrodes) or 3.0-fully 3D (usual mode)
d.singular_type = 0; % Singularity: 1-removal applied , 0-no removal
% d.res_matrix = d.res_matrix; % resolution matrix: 1-'sensitivity' matrix, 2-true resolution matrix or 0-none
% d.filepath = d.filepath; % where to write the file
%% MESH CONSTRUCTION
switch d.mesh_type
case 3 % Trigular Mesh
d.scale = NaN; % scaling factor for the mesh co-ordinates.
case 4
n_plus = 10; % number of buffer cells
x_plus = logspace(log10(x(end)-x(end-1)), log10(10*(x(end)-x(1))), n_plus); % generate n_plus value logspaced between the dx and 3 times the range of x value
% y_plus = logspace(log10(y(end)-y(end-1)), log10(10*(y(end)-y(1))), n_plus);
% x_plus = (x(2)-x(1)).* 1.3.^(1:n_plus);
d.xx = sort([x(1)-x_plus x x(end)+x_plus]); % array containing x coordinates of each of numnp_x node columns
d.yy = y;%sort([y y(end)+y_plus]); % array containing y coordinates of each of numnp_y node rows relative to the topog array.
% Set yy(1) to zero and the other values to a positive number
d.numnp_x = numel(d.xx); % number of nodes in the x direction
d.numnp_y = numel(d.yy); % number of nodes in the y direction
d.topog = zeros(1,d.numnp_x); % garray containing elevations of each of numnp_x node columns. If the topography is flat then set
% topog to zero for all values.
case 5
d.numnp_x = NaN; % number of nodes in the x direction
d.numnp_y = NaN; % number of nodes in the y direction
d.xx = NaN; % array containing x coordinates of each of numnp_x node columns
d.yy = NaN; % array containing y coordinates of each of numnp_y node columns.
% Set yy(1) to zero and the other values to a positive number
end
%% RESISITIVITY
if 0 % file, not working... instead set-up one value per grid cells, so num_regions is huge... f.num_regions = 0;
error('Using a input file is not yet implemented working')
d.rho_true = d.rho_avg*ones(d.numnp_y-1,d.numnp_x-1);
d.rho_true(1:(d.numnp_y-1-n_plus),(n_plus+1):(d.numnp_x-1-n_plus)) = d.rho_true;
writeMatrix2Resdat(d) % write the rho_true
elseif d.job_type == 0 % one value per grid cells in the inside grid plus a cst value for the buffer zone
d.rho_numnp = nan(d.numnp_y-1,d.numnp_x-1);
d.rho_numnp(:,(n_plus+1):(d.numnp_x-1-n_plus)) = 1;
idx = 1:((d.numnp_y-1)*(d.numnp_x-1));
d.elem_1 = [1 idx(d.rho_numnp==1)];
d.elem_2 = [(d.numnp_y-1)*(d.numnp_x-1) idx(d.rho_numnp==1)];
d.value = [d.rho_avg d.rho(:)'] ;
elseif d.job_type == 1 % for inversion, only one average value is given...
d.rho_numnp = nan(d.numnp_y-1,d.numnp_x-1);
d.elem_1 = [1 ];
d.elem_2 = [(d.numnp_y-1)*(d.numnp_x-1) ];
d.value = [d.rho_avg ];
end
d.num_regions = numel(d.value); % number of resistivity regions
%% INVERSE SOLUTION
if d.job_type==1 % inverse solution
d.inverse_type = 1; % Inverse type: 0-pseudo-Marquardt, 1-regularised solution with linear filter (usual mode),
d.target_decrease = 0;
% 2-regularised type with quadratic filter, 3-qualitative solution or 4-blocked linear regularised type
if d.mesh_type==4 || d.mesh_type==5 % quadrilateral mesh
d.patch_size_x = 1; % parameter block sizes in the x and y direction, respectively.
d.patch_size_y = 1;
if d.patch_size_x==0 && d.patch_size_y==0
d.num_param_x = NaN; % number of parameter blocks in the x directions
d.num_param_y = NaN; % number of parameter blocks in the y directions
d.npxstart = NaN; % column number in the mesh where the parameters start
d.npystart = NaN;
d.npx = NaN; % specifies the number of elements in each parameter block
d.npy = NaN;
end
d.data_type = 1; % 0-true data based inversion or 1-log data based.
d.reg_mode = 0; % Regularisation: 0-normal, 1-relative to starting resistivity or 2-relative to a previous dataset
% using the �Differenceinversion� of LaBrecque and Yang (2000)
d.tolerance = d.tolerance; % desired misfit (usually 1.0)
d.max_iterations = 10; % maximum number of iteration
d.error_mod = 0; % 0 -preserve the data weights, 1 or 2-update the weights as the inversion progresses (error_mod=2 is recommended)
d.alpha_aniso = d.alpha_aniso; % anisotropy of the smoothing factor: > 1 for smoother horizontal, alpha_aniso < 1 for smoother
% vertical models, or alpha_aniso=1 for normal (isotropic) regularisation
if d.reg_mode==1
d.alpha_s = NaN; % regularisation to the starting model
end
d.a_wgt = d.a_wgt; % error variance with var(R) = (a_wgt*a_wgt) + (b_wgt*b_wgt) * (R*R)
d.b_wgt = d.b_wgt; % where R is the resistance measured
if d.patch_size_x==0 && d.patch_size_y==0
d.param_symbol
end
elseif d.mesh_type==3 % Trigular Mesh
d.qual_ratio = NaN; % 0 for qualitative comparison with forward solution, i.e. only when one observed data set is available,
% or qual_ratio is 1 if the observed data in protocol.dat contains a ratio of two datasets
end
end
%% REGION OUTPUT (new in 2.7)
d.num_xy_poly = 5; % number of x,y co-ordinates that define a polyline bounding (4 corners + repeat the first corner)
d.x_poly = [x(1) x(end) x(end) x(1) x(1)]; % co-ordinates of points on the polyline
d.y_poly = -[y(1) y(1) y(end) y(end) y(1)];
%% ELECTRODE
d.num_electrodes = elec.n+2; % Number of electrodes
d.j_e = 1:d.num_electrodes; % electrode number
if d.job_type==1 && d.inverse_type==3
d.node = NaN; % node number in the finite element mesh
else
d.column = [n_plus+d.elec_X_id(:)' 1 d.numnp_x]; % column index for the node the finite element mesh
d.row = [d.elec_Y_id(:)' 1 1]; % row index for the node in the finite element mesh
end
%% PROTOCOL
d.num_ind_meas = size(elec.data,1); % number of measurements to follow in file
d.j_p = 1:d.num_ind_meas; %
d.elec = elec.data;
if d.job_type == 1 % inverse solution
d.v_i_ratio = NaN; %
d.v_i_ratio_0 = NaN; %
d.data_sd = NaN; %
copyfile([d.filepath 'R2_forward.dat'],[d.filepath 'protocol.dat']) % used the output of the forward model
else
createProtocoldat(d)
end
%% CREATE THE FILES
createR2in(d)
%% RUN .EXE
if ~d.readonly
copyfile('R2/R2.exe',d.filepath);
pwd_temp = pwd;
cd(d.filepath); tic;
if ismac
warning('You will need wine for mac in order to work !')
status = unix('wine R2.exe');
elseif isunix
status = unix('wine R2.exe');
elseif ispc
status = system('R2.exe');
else
error('Cannot recognize platform')
end
cd(pwd_temp);
disp(['Model run in ' num2str(toc) ' secondes.'])
if status~=0
error('Model did not worked')
end
end
%% OUPUT
% d.pseudo_x=elec.pseudo_x;
% d.pseudo_y=elec.pseudo_y;
d.output=readOutput(d);
end
|
github
|
Rafnuss-PhD/A2PK-master
|
fftma_perso.m
|
.m
|
A2PK-master/functions/fftma_perso.m
| 3,643 |
UNKNOWN
|
b7a05f9031a738f87199ecb466f92df6
|
function field_f=fftma_perso(covar, grid)
%% Create super grid
grid_s.x_min = grid.x(1);
grid_s.x_max = grid.x(end)*3;
grid_s.y_min = grid.y(1);
grid_s.y_max = grid.y(end)*3;
if ~isfield(grid, 'dx')
grid_s.dx = grid.x(2)-grid.x(1);
grid_s.dy = grid.y(2)-grid.y(1);
else
grid_s.dx = grid.dx;
grid_s.dy = grid.dy;
end
if ~isfield(grid, 'nx')
grid.nx = numel(grid.x);
grid.ny = numel(grid.y);
end
%% Generate field
% addpath('C:\Users\rafnu\Documents\MATLAB\mGstat')
% addpath('C:\Users\rafnu\Documents\MATLAB\mGstat\misc')
% Va=[num2str(gen.covar.c(2)),' Nug(0) + ', num2str(gen.covar.c(1)),' Sph(', num2str(gen.covar.modele(1,2)), ',90,', num2str(gen.covar.modele(1,3)/gen.covar.modele(1,2)) ,')']; % V = �sill Sph(range,rotation,anisotropy_factor)�
% field_g=fft_ma_2d(grid_s.x,grid_s.y,Va);
field_g = fftma(grid_s.x_min,grid_s.dx,grid_s.x_max,grid_s.y_min,grid_s.dy,grid_s.y_max,covar);
%% Resample the field to initial size
field_p=field_g(grid.ny+1:2*grid.ny,grid.nx+1:2*grid.nx);
%% Adjust the field
field_f = (field_p-mean(field_p(:)))./std(field_p(:))*covar.c0;
%% Plot
% figure;imagesc(field_f);axis equal;colorbar;
% figure; hist(field_f(:));
%
% myfun = @(x,h) semivariogram1D(h,1,x,'sph',0);
%
% [gamma_x, gamma_y] = variogram_gridded_perso(field_f);
% figure; subplot(1,2,1); hold on;
% id= grid.x<covar.modele(1,2);
% plot(grid.x(id),gamma_x(id),'linewidth',2)
% plot(grid.x(id),myfun(covar.modele(1,2),grid.x(id)),'linewidth',2)
% subplot(1,2,2);hold on
% id= grid.y<covar.modele(1,3);
% plot(grid.y(id),gamma_y(id),'linewidth',2)
% plot(grid.y(id),myfun(covar.modele(1,3),grid.y(id)),'linewidth',2)
end
function [zs]=fftma(xmin,dx,xmax,ymin,dy,ymax,covar)
% [zs]=fftma(xmin,dx,xmax,ymin,dy,ymax,covar)
% Copyright (C) 2005 Erwan Gloaguen, Bernard Giroux
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
%
small=1e-6;
Nx=2*(1+length(xmin:dx:xmax+small));
Ny=2*(1+length(ymin:dy:ymax+small));
Nx2 = Nx/2;
Ny2 = Ny/2;
x = dx*(0:Nx2-1);
x = [x fliplr(-x)]';
y = dy*(0:Ny2-1);
y = [y fliplr(-y)]';
x = kron(ones(Ny,1), x);
y = kron(y, ones(Nx,1));
d = covardm_perso([x y],[0 0],covar);
K = reshape(d,Nx,Ny)';
%%%%%%%%%%%%%%%%%%%%%%%%%%
%On s'assure que la covariance tombe bien à zéro
mk=0;
if min(K(:,1))>1e-6
Ny=2*Ny;
mk=1;
end
if min(K(1,:))>1e-6
Nx=2*Nx;
mk=1;
end
if mk==1
Nx2 = Nx/2;
Ny2 = Ny/2;
x = dx*(0:Nx2-1);
x = [x fliplr(-x)]';
y = dy*(0:Ny2-1);
y = [y fliplr(-y)]';
x = kron(ones(Ny,1), x);
y = kron(y, ones(Nx,1));
d = covardm_perso([x y],[0 0],covar);
K = reshape(d,Nx,Ny)';
end
% Calcul de G
G=fft2(K).^0.5;
U=fft2(randn(size(K)));
GU=G.*U;
% Transformation de Fourier inverse donnant g*u et z
Z=real(ifft2(GU));
%reconstruction de la simulation sur la taille du champ
if mk==0
zs=Z((Ny+2)/2+1:end,(Nx+2)/2+1:end);
elseif mk==1
zs=Z((Ny+2)/2+1:(Ny+2)/2+length(ymin:dy:ymax+small),(Nx+2)/2+1:(Nx+2)/2+length(xmin:dx:xmax+small));
end
end
|
github
|
UMich-BipedLab/Cassie_Model-master
|
ExportJacobians_IMU.m
|
.m
|
Cassie_Model-master/@Cassie/ExportJacobians_IMU.m
| 4,985 |
utf_8
|
090bed5ffa0a31f9a377539e9242bffd
|
function ExportJacobians_IMU(obj, export_function, export_path)
% Computes the Manipulator Jacobians to be used for state estimation (IMU to contact)
%
% Author: Ross Hartley
% Date: 7/17/2018
%
% Encoder Vector
encoders = SymVariable(obj.States.x(7:end));
% --- Frames ---
H_WI = obj.OtherPoints.VectorNav.computeForwardKinematics;
H_WL = obj.ContactPoints.LeftToeBottom.computeForwardKinematics;
H_WR = obj.ContactPoints.RightToeBottom.computeForwardKinematics;
H_IL = H_WI\H_WL; H_IL = subs(H_IL, obj.States.x(1:6), zeros(6,1));
H_IR = H_WI\H_WR; H_IR = subs(H_IR, obj.States.x(1:6), zeros(6,1));
H_LR = H_WL\H_WR; H_LR = subs(H_LR, obj.States.x(1:6), zeros(6,1));
H_RL = H_WR\H_WL; H_RL = subs(H_RL, obj.States.x(1:6), zeros(6,1));
% ---- Compute Jacobians ----
% World to VectorNav (body and spatial Jacobians)
Jb_WI = obj.OtherPoints.VectorNav.computeBodyJacobian(20);
Jb_WI = Jb_WI([4:6,1:3],:);
Js_WI = obj.OtherPoints.VectorNav.computeSpatialJacobian(20);
Js_WI = Js_WI([4:6,1:3],:);
% World to Left Contact and Base to Right Contact (body and spatial Jacobians)
Jb_WL = obj.ContactPoints.LeftToeBottom.computeBodyJacobian(20);
Jb_WL = Jb_WL([4:6,1:3],:);
Js_WL = obj.ContactPoints.LeftToeBottom.computeSpatialJacobian(20);
Js_WL = Js_WL([4:6,1:3],:);
Jb_WR = obj.ContactPoints.RightToeBottom.computeBodyJacobian(20);
Jb_WR = Jb_WR([4:6,1:3],:);
Js_WR = obj.ContactPoints.RightToeBottom.computeSpatialJacobian(20);
Js_WR = Js_WR([4:6,1:3],:);
% Compute VectorNav to Contact Jacobians
Jb_IL = -Adjoint(inv(H_IL))*Jb_WI + Jb_WL;
Jb_IL = subs(Jb_IL, obj.States.x(1:6), zeros(6,1));
Jb_IL = Jb_IL(:,7:end);
Js_IL = Adjoint(inv(H_WI))*(-Js_WI + Js_WL);
Js_IL = subs(Js_IL, obj.States.x(1:6), zeros(6,1));
Js_IL = Js_IL(:,7:end);
Jb_IR = -Adjoint(inv(H_IR))*Jb_WI + Jb_WR;
Jb_IR = subs(Jb_IR, obj.States.x(1:6), zeros(6,1));
Jb_IR = Jb_IR(:,7:end);
Js_IR = Adjoint(inv(H_WI))*(-Js_WI + Js_WR);
Js_IR = subs(Js_IR, obj.States.x(1:6), zeros(6,1));
Js_IR = Js_IR(:,7:end);
% Compute Contact to Contact Jacobians
Jb_LR = -Adjoint(inv(H_LR))*Jb_WL + Jb_WR;
Jb_LR = subs(Jb_LR, obj.States.x(1:6), zeros(6,1));
Jb_LR = Jb_LR(:,7:end);
Js_LR = Adjoint(inv(H_WL))*(-Js_WL + Js_WR);
Js_LR = subs(Js_LR, obj.States.x(1:6), zeros(6,1));
Js_LR = Js_LR(:,7:end);
Jb_RL = -Adjoint(inv(H_RL))*Jb_WR + Jb_WL;
Jb_RL = subs(Jb_RL, obj.States.x(1:6), zeros(6,1));
Jb_RL = Jb_RL(:,7:end);
Js_RL = Adjoint(inv(H_WR))*(-Js_WR + Js_WL);
Js_RL = subs(Js_RL, obj.States.x(1:6), zeros(6,1));
Js_RL = Js_RL(:,7:end);
% ---- Export Functions ----
export_function(Jb_IL, 'Jb_VectorNav_to_LeftToeBottom', export_path, encoders);
export_function(Jb_IL(1:3,:), 'Jwb_VectorNav_to_LeftToeBottom', export_path, encoders);
export_function(Jb_IL(4:6,:), 'Jvb_VectorNav_to_LeftToeBottom', export_path, encoders);
export_function(Js_IL, 'Js_VectorNav_to_LeftToeBottom', export_path, encoders);
export_function(Js_IL(1:3,:), 'Jws_VectorNav_to_LeftToeBottom', export_path, encoders);
export_function(Js_IL(4:6,:), 'Jvs_VectorNav_to_LeftToeBottom', export_path, encoders);
export_function(Jb_IR, 'Jb_VectorNav_to_RightToeBottom', export_path, encoders);
export_function(Jb_IR(1:3,:), 'Jwb_VectorNav_to_RightToeBottom', export_path, encoders);
export_function(Jb_IR(4:6,:), 'Jvb_VectorNav_to_RightToeBottom', export_path, encoders);
export_function(Js_IR, 'Js_VectorNav_to_RightToeBottom', export_path, encoders);
export_function(Js_IR(1:3,:), 'Jws_VectorNav_to_RightToeBottom', export_path, encoders);
export_function(Js_IR(4:6,:), 'Jvs_VectorNav_to_RightToeBottom', export_path, encoders);
export_function(Jb_LR, 'Jb_LeftToeBottom_to_RightToeBottom', export_path, encoders);
export_function(Jb_LR(1:3,:), 'Jwb_LeftToeBottom_to_RightToeBottom', export_path, encoders);
export_function(Jb_LR(4:6,:), 'Jvb_LeftToeBottom_to_RightToeBottom', export_path, encoders);
export_function(Jb_RL, 'Jb_RightToeBottom_to_LeftToeBottom', export_path, encoders);
export_function(Jb_RL(1:3,:), 'Jwb_RightToeBottom_to_LeftToeBottom', export_path, encoders);
export_function(Jb_RL(4:6,:), 'Jvb_RightToeBottom_to_LeftToeBottom', export_path, encoders);
export_function(Js_LR, 'Js_LeftToeBottom_to_RightToeBottom', export_path, encoders);
export_function(Js_LR(1:3,:), 'Jws_LeftToeBottom_to_RightToeBottom', export_path, encoders);
export_function(Js_LR(4:6,:), 'Jvs_LeftToeBottom_to_RightToeBottom', export_path, encoders);
export_function(Js_RL, 'Js_RightToeBottom_to_LeftToeBottom', export_path, encoders);
export_function(Js_RL(1:3,:), 'Jws_RightToeBottom_to_LeftToeBottom', export_path, encoders);
export_function(Js_RL(4:6,:), 'Jvs_RightToeBottom_to_LeftToeBottom', export_path, encoders);
end
function [ Ad ] = Adjoint( X )
%ADJOINT_SE3 Computes the adjoint of SE(3)
Ad = [X(1:3,1:3), zeros(3);
skew(X(1:3,4))*X(1:3,1:3), X(1:3,1:3)];
end
function [Ax] = skew(v)
% Convert from vector to skew symmetric matrix
Ax = [ 0, -v(3), v(2);
v(3), 0, -v(1);
-v(2), v(1), 0];
end
|
github
|
snigdhabhagat/Thin-plate-spline-interpolation-master
|
thinplatespline.m
|
.m
|
Thin-plate-spline-interpolation-master/thinplatespline.m
| 832 |
utf_8
|
f126bb402acf44d12293eb07645998c0
|
%% Thin plate spline
function [new_location]=thinplatespline(ctrl_pts,mask_location,new_location,image)
[m,n] = size(ctrl_pts);
P = [ones(m,1) ctrl_pts];
[K,P,control_points,ctrl_val] = computeK(ctrl_pts,m,mask_location,P,image);
clear i j;
[t,u] = size(control_points);
L = [K P;P.' zeros(3,3)];
det(L);
zero_pad = size(L);
p=zero_pad(1)-t;
Y = [ctrl_val;zeros(p,1)] ;
X = linsolve(L,Y);
length = size(new_location,1);
for f_off = 1:length
temp = single(new_location(f_off,:));
a=temp(1);
b=temp(2);
generated_patch=[a b];
out = 0;
for(i=1:t)
temp = pdist2(control_points(i,:),generated_patch);
X_2 = X(i)*computelog(temp);
out = out+X_2;
end
X_1 = X(t+1) + X(t+2)*a +X(t+3)*b;
new_location(f_off,3)=X_1 +out;
end
end %%%% Computes Z
|
github
|
chaovite/crack_pipe-master
|
sbp_staggered_strong_4th.m
|
.m
|
crack_pipe-master/source/SBP/staggered/strong/sbp_staggered_strong_4th.m
| 2,654 |
utf_8
|
5eec22304ac1706dda70c9c08352b1e5
|
function [xp,xm,Pp,Pm,Qp,Qm] = sbp_staggered_strong_4nd(n,h,test)
if nargin < 3
test = false;
end
assert(n >= 8,'Not enough grid points');
% Free parameters determined by optimizing spectral radius/truncation error
x = [0.002435378086542 0.999421296296229];
qm03 = x(1);
pm3 = x(2);
% Coefficients determined such that the SBP property is satisfied
qp22 = -3*pm3 - 9*qm03 + 2;
qm31 = -2*pm3 - 3*qm03 + 49/24;
pp3 = -pm3 + 143/72;
qp02 = -3*qm03 - 1/24;
qm30 = pm3 + qm03 - 73/72;
qp03 = 2*pm3 + 3*qm03 - 37/18;
qp31 = -qm03;
qm21 = 6*pm3 + 9*qm03 - 49/8;
qp14 = 2*pm3 + 3*qm03 - 49/24;
pm2 = -3*pm3 + 97/24;
qm10 = 3*qm03 + 1/24;
qp30 = 0;
qm20 = -2*pm3 - 3*qm03 + 37/18;
qm11 = -3*pm3 - 9*qm03 + 2;
pp0 = pm3 - 11/18;
qp01 = -pm3 + qm03 + 25/12;
pp1 = -3*pm3 + 33/8;
qp12 = 3*pm3 + 9*qm03 - 2;
qm02 = -3*qm03;
qm22 = -3*pm3 - 9*qm03 + 2;
qp11 = pm3 - 3*qm03 - 25/12;
qm23 = -pm3 + 3*qm03 + 19/9;
qm13 = -3*qm03 - 1/24;
qp20 = 0;
qm12 = 3*pm3 + 9*qm03 - 2;
qp10 = 0;
qp04 = -pm3 - qm03 + 73/72;
qm32 = 3*qm03;
qp21 = 3*qm03;
qm33 = pm3 - qm03 - 19/9;
qp33 = pm3 - 3*qm03 - 19/9;
qm01 = -pm3 + 3*qm03 + 25/12;
qp24 = -3*qm03;
qp32 = 3*qm03 + 1/24;
pm1 = 3*pm3 - 17/8;
qm00 = pm3 - qm03 - 25/12;
qp34 = -pm3 + qm03 + 19/9;
qp00 = -1;
qp13 = -6*pm3 - 9*qm03 + 49/8;
pm0 = -pm3 + 25/12;
pp2 = 3*pm3 - 2;
qp23 = 3*pm3 + 9*qm03 - 2;
% Number of coefficients
b = 4;
% Q+ and Q-, top-left corner
QpL = [...
qp00, qp01, qp02, qp03, qp04;
qp10, qp11, qp12, qp13, qp14;
qp20, qp21, qp22, qp23, qp24;
qp30, qp31, qp32, qp33, qp34
];
QmL = [...
0, 0, 0, 0;
qm00, qm01, qm02, qm03;
qm10, qm11, qm12, qm13;
qm20, qm21, qm22, qm23;
qm30, qm31, qm32, qm33
];
% Q+ and Q-
w = b;
s = rot90(vander(1:w))\((0:(w-1)).*(w/2-1/2+1).^([0 0:w-2]))';
Qp = spdiags(repmat(-s(end:-1:1)',[n+2 1]), -(w/2-1):w/2, n+2, n+2);
Qm = spdiags(repmat(s(:)',[n+2 1]), -(w/2-1)-1:w/2-1, n+2, n+2);
Qp(end,:) = [];
Qm(:,end) = [];
% Add SBP boundary closures
Qp(1:b,1:b+1) = QpL;
Qp(end-b+1:end,end-b:end) = -fliplr(flipud(QpL));
Qm(1:b+1,1:b) = QmL;
Qm(end-b:end,end-b+1:end) = -fliplr(flipud(QmL));
% P+ and P-
Pp = ones(n+1,1);
Pm = ones(n+2,1);
Pp(1:b) = [pp0, pp1, pp2, pp3];
Pp(end-b+1:end) = Pp(b:-1:1);
Pm(1:b+1) = [0, pm0, pm1, pm2, pm3];
Pm(end-b:end) = Pm(b+1:-1:1);
Pp = spdiags(Pp,0,n+1,n+1);
Pm = spdiags(Pm,0,n+2,n+2);
Pp = h*Pp;
Pm = h*Pm;
xp = h*[0:n]';
xm = h*[0 1/2+0:n n]';
% Test operators
if test
for j=0:b/2
disp([ 'Dp, j = ' num2str(j) ' Error max = ' ...
num2str(max(abs(Qp*xm.^j-j*Pp*xp.^max([j-1,0]))))]);
disp([ 'Dm, j = ' num2str(j) ' Error max = '...
num2str(max(abs(Qm*xp.^j-j*Pm*xm.^max([j-1,0]))))]);
end
end
|
github
|
chaovite/crack_pipe-master
|
pipe_crack_inf.m
|
.m
|
crack_pipe-master/source/analytical_solutions/pipe_crack_inf.m
| 3,800 |
utf_8
|
219166998275fca0b070a9ebfab08aa4
|
function [p, v, t, R, omega] = pipe_crack_inf(L, a, d, rho, cp0, cc0, ...
g, dt, z, r, mu)
% [p, v, t, R, omega] = pipe_crack_inf(L, a, d, rho, c, ...
% g, dt, z, r, mu)
% calculate the pressure and velocity response of a pipe-crack system.
% Infinite pipe starts from [-L, +inf) and penetrates a crack at z = 0.
% The crack is radially symmetric and intersects the pipe at r = 0. The
% fluid is inviscid and crack wall is rigid (non-dispersive)
%
% Solutions based on formula in:
%
% Hornby et al., 1989, fracture evaluation using reflected Stoneley-wave
% arrivals.
%
% boundary condition, p(x = -L, t) = g(t).
%
% Notation of Fourier transform:
% ghat = int_{-inf}^{+inf} g(t)*exp(i*omega*t) dt, consistent with Hornby et al. 1989.
%
% argins:
% L: distance from pipe top to crack interface.
% a: pipe radius
% d: crack total opening.
% rho: fluid density
% c: fluid wave speed.
% g: pressure source time function at the top
% dt: time step of the source.
% z: z coordinate of the query point, range: [-L, +inf)
% r: r coordinate from the crack center. range [a, +inf)
% mu: viscosity
%
% argouts:
% p: pressure
% v: velocity in +z or +r direction depending on the location of the query
% point.
% t : time vector
% R: reflection coefficient.
% omega: angular frequency.
%
if nargin<11
mu = 0;
end
if z>0
error('z must be [-L, 0]');
end
% location of query point.
if z ==0 && r >= a
loc_q = 'crack';
else
loc_q = 'pipe';
end
[ghat, f] = fft_dim(g, dt);
omega = f*2*pi;
alpha = 8*mu/a^2; % drag coefficient in the pipe.
beta = 12*mu/d^2; % drag coefficient in the crack.
if d==0
beta = 0;
end
cp = cp0*sqrt(1./(1+1i*alpha./(rho*omega))); % phase velocity in pipe.
cc = cc0*sqrt(1./(1+1i*beta./(rho*omega))); % phase velocity in crack.
% k = omega./c;
kp = omega./cp;
kc = omega./cc;
%% reflection and transmission coefficient:
% solution in the pipe:
% p = [exp(i*k*z) + R*exp(-i*k*z)]*A, when z<0
% v = c/(rho*c0^2)*[exp(i*k*z) - R*exp(-i*k*z)]*A, when z<0
% where A is to be determined by b.c.
%
% solution in the crack:
% p(r) = GH01(k*r), r>a
% v(r) = i*G*H11(k*a)c/(rho*c0^2), r>a
%
% hankel's function.
h01 = besselh(0,1,kc*a);
h11 = besselh(1,1,kc*a);
% reflection and transmission:
F = (2*1i*d*cc.*h11) ./(a*h01.*cp)*cp0^2/cc0^2;
R = (1 - F)./(1 + F);
A = ghat./(exp(1i*kp*(-L)) + R.*exp(-1i*kp*(-L)));
G = A.*(1+R)./h01;
switch loc_q
case 'pipe'
phat = (exp(1i*kp*z) + R.*exp(-1i*kp*z)).*A;
vhat = (exp(1i*kp*z) - R.*exp(-1i*kp*z)).*A.*cp/(rho*cp0^2);
case 'crack'
phat = G.*besselh(0,1,r*kc);
vhat = 1i*G.*besselh(1,1,kc*r).*cc./(rho*cc0^2);
end
df = f(2) - f(1);
phat(1) = 0; % remove dc component.
vhat(1) = 0; % remove dc component.
[p, t] = ifft_dim(phat, df);
[v, ~] = ifft_dim(vhat, df);
end
function [G,f] = fft_dim(g,dt)
% Notation of Fourier transform:
% ghat = int_{-inf}^{+inf} g(t)*exp(i*omega*t) dt
% Fourier transform real g(t) to G(f), where f=frequency
% (f is NOT natural frequency, omega)
N = length(g);
% drop the last element if the signal is odd.
if mod(N,2)~=0, g=g(1:N-1); N=N-1; end
fN = 1/(2*dt); % Nyquist
f = fN*linspace(0,1,N/2+1);
G = dt*conj(fft(g));
G = G(1:N/2+1);
end
function [g,t] = ifft_dim(G,df)
% Inverse Fourier transform:
% g= int_{-inf}^{+inf} ghat(omega)*exp(-i*omega*t) domega
%
% check if the G is a column vector or a row vector
if size(G,1) == 1
g = [G conj(G(end-1:-1:2))];%row vector
else
g = [G; conj(G(end-1:-1:2))];%column vector
end
N = length(g);
t = [0:N-1]/(N*df);
g = ifft(conj(g))/t(2);
end
|
github
|
chaovite/crack_pipe-master
|
acoustics2D_pointsource.m
|
.m
|
crack_pipe-master/source/analytical_solutions/acoustics2D_pointsource.m
| 1,235 |
utf_8
|
60d76a44e90b7ff161ef5b3958104165
|
function [p, t] = acoustics2D_pointsource(r, c, g, dt)
% 2d linear acoustics with subject to a point source at xs, ys.
% Greens' function G = -i/4*H_0^{2}.
%
% dp+ux+uy = g(t)*delta(r).
%
% 1/c^2*d^2p/dt^2 + Lap(p) = g'(t)*delta(r)
%
% Notation of fourier transform ghat(omega) = int exp(-i*omega*t)*g(t)dt.
% this notation is different from Eric's notation.
%
[ghat, f] = fft_dim(g,dt);
omega = 2*pi*f;
k = omega/c;
ghat = (1i*omega).*ghat;
H = besselh(0, 2, k*r);
phat = -1i/4*H.*ghat;
phat(1) = 0;
[p,t] = ifft_dim(phat,f(2));
end
function [G,f] = fft_dim(g,dt)
% Fourier transform real g(t) to G(f), where f=frequency
% (f is NOT natural frequency, omega)
N = length(g);
% drop the last element if the signal is odd.
if mod(N,2)~=0, g=g(1:N-1); N=N-1; end
% zeropad the signal if the signal is odd;
fN = 1/(2*dt); % Nyquist
f = fN*linspace(0,1,N/2+1);
G = dt*(fft(g));
G = (G(1:N/2+1));
end
function [g,t] = ifft_dim(G,df)
% check if the G is a column vector or a row vector
% handle the nyquist.
if size(G,1) == 1
g = [G conj(G(end-1:-1:2))];%row vector
else
g = [G; conj(G(end-1:-1:2))];%column vector
end
N = length(g);
t = [0:N-1]/(N*df);
g = ifft((g))/t(2);
end
|
github
|
chaovite/crack_pipe-master
|
acoustics2D_axial_sym.m
|
.m
|
crack_pipe-master/source/analytical_solutions/acoustics2D_axial_sym.m
| 1,520 |
utf_8
|
62e7e95fd2ecd2e3818fa4b3c175f24f
|
function [p, v, t] = acoustics2D_axial_sym(a, rho, c0, g, dt, r, d, mu, btype)
% outgoing wave for axial-symmetrical 2d acoustics. velocity boundary
% condition is prescribed at r=a.
%
if nargin<9
btype='p';
end
beta = 12*mu/d^2;
[ghat, f] = fft_dim(g,dt);
omega = 2*pi*f;
c = c0./sqrt(1+1i*beta./(rho*omega));
k = omega./c;
H01a = besselh(0,1,k*a);
H01r = besselh(0,1,k*r);
H11a = besselh(1,1,k*a);
H11r = besselh(1,1,k*r);
switch btype
case 'p'
G = ghat./H01a;
case 'v'
G = ghat.*rho*c0^2./(1i*c.*H11a);
end
phat = G.*H01r;
vhat = 1i*c/rho/c0^2.*G.*H11r;
phat(1) = 0;
vhat(1) = 0;
df = f(2) - f(1);
[p, t] = ifft_dim(phat, df);
[v, ~] = ifft_dim(vhat, df);
end
function [G,f] = fft_dim(g,dt)
% Notation of Fourier transform:
% ghat = int_{-inf}^{+inf} g(t)*exp(i*omega*t) dt
% Fourier transform real g(t) to G(f), where f=frequency
% (f is NOT natural frequency, omega)
N = length(g);
% drop the last element if the signal is odd.
if mod(N,2)~=0, g=g(1:N-1); N=N-1; end
fN = 1/(2*dt); % Nyquist
f = fN*linspace(0,1,N/2+1);
G = dt*conj(fft(g));
G = G(1:N/2+1);
end
function [g,t] = ifft_dim(G,df)
% Inverse Fourier transform:
% g= int_{-inf}^{+inf} ghat(omega)*exp(i*omega*t) domega
% check if the G is a column vector or a row vector
if size(G,1) == 1
g = [G conj(G(end-1:-1:2))];%row vector
else
g = [G; conj(G(end-1:-1:2))];%column vector
end
N = length(g);
t = [0:N-1]/(N*df);
g = ifft(conj(g))/t(2);
end
|
github
|
chaovite/crack_pipe-master
|
pipe_inf_crack_inf.m
|
.m
|
crack_pipe-master/source/analytical_solutions/pipe_inf_crack_inf.m
| 4,001 |
utf_8
|
f88a9bb0f94cb78bfc72f14fdee0c642
|
function [p, v, t, R, T, omega] = pipe_inf_crack_inf(L, a, d, rho, cp0, cc0, ...
g, dt, z, r, mu)
% [p, v] = pipe_inf_crack_inf(l, a, d, rho, c, g, z, r)
% calculate the pressure and velocity response of a pipe-crack system.
% Infinite pipe starts from [-L, +inf) and penetrates a crack at z = 0.
% The crack is radially symmetric and intersects the pipe at r = 0. The
% fluid is inviscid and crack wall is rigid (non-dispersive)
%
% Solutions based on formula in:
%
% Hornby et al., 1989, fracture evaluation using reflected Stoneley-wave
% arrivals.
%
% boundary condition, p(x = -L, t) = g(t).
%
% Notation of Fourier transform:
% ghat = int_{-inf}^{+inf} g(t)*exp(i*omega*t) dt, consistent with Hornby et al. 1989.
%
% argins:
% L: distance from pipe top to crack interface.
% a: pipe radius
% d: crack total opening.
% rho: fluid density
% cp0: fluid acoustic wave speed, in the pipe
% cc0: fluid acoustic wave speed, in the crack.
% g: pressure source time function at the top
% dt: time step of the source.
% z: z coordinate of the query point, range: [-L, +inf)
% r: r coordinate from the crack center. range [a, +inf)
% mu: viscosity
%
% argouts:
% p: pressure
% v: velocity in +z or +r direction depending on the location of the query
% point.
% t : time vector
% R: reflection coefficient.
% T: transmission coefficient.
% omega: angular frequency.
%
if nargin<11
mu = 0;
end
% location of query point.
if z ==0 && r >= a
loc_q = 'crack';
else
loc_q = 'pipe';
end
[ghat, f] = fft_dim(g, dt);
omega = f*2*pi;
alpha = 8*mu/a^2; % drag coefficient in the pipe.
beta = 12*mu/d^2; % drag coefficient in the crack.
if d==0
beta = 0;
end
cp = cp0*sqrt(1./(1+1i*alpha./(rho*omega))); % phase velocity in pipe.
cc = cc0*sqrt(1./(1+1i*beta./(rho*omega))); % phase velocity in crack.
% k = omega./c;
kp = omega./cp;
kc = omega./cc;
%% reflection and transmission coefficient:
% solution in the pipe:
% p = [exp(i*k*z) + R*exp(-i*k*z)]*A, when z<0
% p = A*T*exp(i*k*z), when z>0
% v = 1/(rho*c)*[exp(i*k*z) - R*exp(-i*k*z)]*A, when z<0
% v = 1/(rho*c)*T*exp(i*k*z) *A, when z>0
% where A is to be determined by b.c.
%
% solution in the crack:
% p(r) = GH01(k*r), r>a
% v(r) = i*G*H11(k*a)/(rho*c), r>a
%
% hankel's function.
h01 = besselh(0,1,kc*a);
h11 = besselh(1,1,kc*a);
% reflection and transmission:
F = 1i*d*h11.*cc./cp./(a*h01);
R = - F./(1 + F);
T = 1./(1 + F);
A = ghat./(exp(1i*kp*(-L)) + R.*exp(-1i*kp*(-L)));
G = A.*T./h01;
switch loc_q
case 'pipe'
if z<=0
phat = (exp(1i*kp*z) + R.*exp(-1i*kp*z)).*A;
vhat = (exp(1i*kp*z) - R.*exp(-1i*kp*z)).*A.*cp/(rho*c^2);
else
phat = A.*T.*exp(1i*kp*z);
vhat = A.*T.*exp(1i*kp*z).*cp/(rho*cp0^2);
end
case 'crack'
phat = G.*besselh(0,1,r*kc);
vhat = 1i*G.*besselh(1,1,kc*r).*cc./(rho*cc0^2);
end
df = f(2) - f(1);
phat(1) = 0; % remove dc component.
vhat(1) = 0; % remove dc component.
[p, t] = ifft_dim(phat, df);
[v, ~] = ifft_dim(vhat, df);
end
function [G,f] = fft_dim(g,dt)
% Notation of Fourier transform:
% ghat = int_{-inf}^{+inf} g(t)*exp(i*omega*t) dt
% Fourier transform real g(t) to G(f), where f=frequency
% (f is NOT natural frequency, omega)
N = length(g);
% drop the last element if the signal is odd.
if mod(N,2)~=0, g=g(1:N-1); N=N-1; end
fN = 1/(2*dt); % Nyquist
f = fN*linspace(0,1,N/2+1);
G = dt*conj(fft(g));
G = G(1:N/2+1);
end
function [g,t] = ifft_dim(G,df)
% Inverse Fourier transform:
% g= int_{-inf}^{+inf} ghat(omega)*exp(-i*omega*t) domega
%
% check if the G is a column vector or a row vector
if size(G,1) == 1
g = [G conj(G(end-1:-1:2))];%row vector
else
g = [G; conj(G(end-1:-1:2))];%column vector
end
N = length(g);
t = [0:N-1]/(N*df);
g = ifft(conj(g))/t(2);
end
|
github
|
chaovite/crack_pipe-master
|
stretched_grid.m
|
.m
|
crack_pipe-master/source/helper/stretched_grid.m
| 2,742 |
utf_8
|
fe8b5830c559f4d057f908134be4d64c
|
function g = stretched_grid(grid_type,order,operator_type,nx,ny,Lx,Ly,r_g,r_bl,truncate)
% Construct grids with np = n + 1, and nm = n + 2 grid points
order = min(order,6);
[xp,xm, Pxp, Pxm, Qxp, Qxm] = sbp_staggered_weak(order,nx,Lx/nx);
[yp, ym, Pyp, Pym, Qyp, Qym] = sbp_staggered_weak(order,ny,Ly/ny);
Dxp = inv(Pxp)*Qxp;
Dyp = inv(Pyp)*Qyp;
Dxm = inv(Pxm)*Qxm;
Dym = inv(Pym)*Qym;
g.hx = xp(2) - xp(1);
g.hy = yp(2) - yp(1);
g.nx = nx;
g.ny = ny;
yp = boundary_layer_thickness(yp/Ly, r_g, r_bl);
ym = boundary_layer_thickness(ym/Ly, r_g, r_bl);
xp = xp'; xm = xm';
yp = Ly*yp'; ym = Ly*ym';
nxp = length(xp);
nyp = length(yp);
nxm = length(xm);
nym = length(ym);
Jxp = spdiags(Dxp*xm,0, nxp, nxp);
Jxm = spdiags(Dxm*xp,0, nxm, nxm);
Jyp = spdiags(Dyp*ym,0, nyp, nyp);
Jym = spdiags(Dym*yp,0, nym, nym);
Jxpi = inv(Jxp);
Jxmi = inv(Jxm);
Jypi = inv(Jyp);
Jymi = inv(Jym);
Jxm = trunc_mat( Jxm,truncate);
Jxmi = trunc_mat(Jxmi,truncate);
Jym = trunc_mat( Jym,truncate);
Jymi = trunc_mat(Jymi,truncate);
xm = trunc_vec(xm,truncate);
ym = trunc_vec(ym,truncate);
grid_types = select_grid(grid_type);
if grid_types.is_p
g.n1 = length(xp);
g.n2 = length(yp);
g.x = xp;
g.y = yp;
g.Jx = Jxp;
g.Jy = Jyp;
g.Jxi = Jxpi;
g.Jyi = Jypi;
end
if grid_types.is_m
g.n1 = length(xm);
g.x = xm;
g.n2 = length(ym);
g.y = ym;
g.Jx = Jxm;
g.Jy = Jym;
g.Jxi = Jxmi;
g.Jyi = Jymi;
end
if grid_types.is_pp
g.n1 = length(xp);
g.n2 = length(yp);
g.x = xp;
g.y = yp;
[g.X g.Y] = meshgrid(xp,yp);
g.Jx = Jxp;
g.Jy = Jyp;
g.Jxi = Jxpi;
g.Jyi = Jypi;
end
if grid_types.is_mm
g.n1 = length(xm);
g.n2 = length(ym);
g.x = xm;
g.y = ym;
[g.X g.Y] = meshgrid(xm,ym);
g.Jx = Jxm;
g.Jy = Jym;
g.Jxi = Jxmi;
g.Jyi = Jymi;
end
if grid_types.is_pm
g.n1 = length(xp);
g.n2 = length(ym);
g.x = xp;
g.y = ym;
[g.X g.Y] = meshgrid(xp,ym);
g.Jx = Jxp;
g.Jy = Jym;
g.Jxi = Jxpi;
g.Jyi = Jymi;
end
if grid_types.is_mp
g.n1 = length(xm);
g.n2 = length(yp);
g.x = xm;
g.y = yp;
[g.X, g.Y] = meshgrid(xm,yp);
g.Jx = Jxm;
g.Jy = Jyp;
g.Jxi = Jxmi;
g.Jyi = Jypi;
end
g.vec = @(u) reshape(u,g.n1*g.n2,1);
g.grd = @(u) reshape(u,g.n2,g.n1);
end
function A = trunc_mat(A,truncate)
if ~truncate
return;
end
A = A(2:end-1,2:end-1);
end
function a = trunc_vec(a,truncate)
if ~truncate
return;
end
a = a(2:end-1);
end
|
github
|
chaovite/crack_pipe-master
|
grids_frac1d.m
|
.m
|
crack_pipe-master/source/helper/grids_frac1d.m
| 1,533 |
utf_8
|
af9f4425bee148a7dccdbc6d4f977839
|
function [g, op] = grids_frac1d(nx, Lx, order, operator_type)
% construct grid and operators for 1d fracture, grouped by unknowns, p, u
% weak b.c. treatment is used in this code.
%
% p: on staggered grid (m)
% u: on standard grid (p)
if nargin < 4
operator_type = 'weak';
end
switch operator_type
case 'weak'
truncate = 0;
case 'strong'
truncate = 1;
otherwise
error('Incorrect operator type.');
end
%% ***************************************grid and operators********************************************
% Now, generate grid and operators for each of the unknow field, p, u
switch operator_type
case 'weak'
[xp, xm, Pxp, Pxm, Qxp, Qxm] = sbp_staggered_weak(order, nx, Lx/nx);
case 'strong'
[xp, xm, Pxp, Pxm, Qxp, Qxm] = sbp_staggered_strong(order,nx,Lx/nx,true);
end
xp = xp'; xm = xm';
% Difference operators
Dxp = inv(Pxp)*Qxp;
Dxm = inv(Pxm)*Qxm;
nxp = length(xp);
nxm = length(xm);
hx = Lx/nx;
%% p grid and op. staggered grid.
g.p.x = xp;
g.p.hx = hx;
g.p.nx = nxp;
% p op:
op.p.Dx = Dxp;% 1D.
op.p.Px = Pxp; % 1D
op.p.restrictions = restrictions(nxp); % restriction operator.
%% v grid and op. standard grid.
g.v.x = xm;
g.v.hx = hx;
g.v.nx = nxm;
% v op:
op.v.Dx = Dxm;% 1D.
op.v.Px = Pxm;% 1D.
op.v.restrictions = restrictions(nxm);
end
function A = trunc_mat(A,truncate)
if ~truncate
return;
end
A = A(2:end-1,2:end-1);
end
function a = trunc_vec(a,truncate)
if ~truncate
return;
end
a = a(2:end-1);
end
|
github
|
chaovite/crack_pipe-master
|
grids_frac3d.m
|
.m
|
crack_pipe-master/source/helper/grids_frac3d.m
| 6,463 |
utf_8
|
ed40b791e1a831e8a023bc7bd0df6f3c
|
function [g, op] = grids_frac3d(nx,ny,nz, Lx, Ly, Lz, order, operator_type, r_g, r_bl, order_z)
% construct grid and operators for 3d fracture, grouped by unknowns, p, vx, vy, ux, uy.
% r_g, r_bl are grid stretching parameters in z direction.
%
% p: x,y standard grid, z, staggered grid. (ppm)
% vx: x staggered, y,z standard. (mpp)
% vy: y staggered, x,z standard. (pmp)
% ux: x staggered, y standard.(mp)
% uy: y staggered, x standard.(pm)
if nargin < 10
% no grid stretching.
r_g = 0.3;
r_bl = 0.3;
end
if nargin < 8
operator_type = 'weak';
end
switch operator_type
case 'weak'
truncate = 0;
case 'strong'
truncate = 1;
otherwise
error('Incorrect operator type.');
end
%% ******************************construct Jacobian in z direction*************************************
% weak operators are used to construct the Jacobian.
[zp, zm, Pzp, Pzm, Qzp, Qzm] = sbp_staggered_weak(order_z,nz,Lz/nz);
% Dzp = inv(Pzp)*Qzp;
% Dzm = inv(Pzm)*Qzm;
% stretch the grid only in z direction.
[zp, Jzp] = boundary_layer_thickness(zp/Lz, r_g, r_bl);% stretched grid
[zm, Jzm] = boundary_layer_thickness(zm/Lz, r_g, r_bl);% stretched grid.
zp = Lz*zp'; zm = Lz*zm';
% construct Jacobian analytically.
%
% nzp = length(zp);
% nzm = length(zm);
% %
% % % Jacobian. d_eta/dz. (eta is the stretched grid and z is the uniform grid)
% Jzp = spdiags(Dzp*zm,0, nzp, nzp);
% Jzm = spdiags(Dzm*zp,0, nzm, nzm);
% Jacobian. dz/d_eta.
Jzpi = inv(Jzp);
Jzmi = inv(Jzm);
% if the operator type is 'strong', then truncate the end points.
Jzm = trunc_mat(Jzm,truncate);
Jzmi = trunc_mat(Jzmi,truncate);
zm = trunc_vec(zm,truncate);
nzp = length(zp);
nzm = length(zm);
%% ***************************************grid and operators********************************************
% Now, generate grid and operators for each of the unknow field, p, vx, vy, ux, uy
switch operator_type
case 'weak'
[xp, xm, Pxp, Pxm, Qxp, Qxm] = sbp_staggered_weak(order,nx,Lx/nx);
[yp, ym, Pyp, Pym, Qyp, Qym] = sbp_staggered_weak(order,ny,Ly/ny);
[~, ~, Pzp, Pzm, Qzp, Qzm] = sbp_staggered_weak(order_z,nz,Lz/nz);
case 'strong'
[xp, xm, Pxp, Pxm, Qxp, Qxm] = sbp_staggered_strong(order,nx,Lx/nx,true);
[yp, ym, Pyp, Pym, Qyp, Qym] = sbp_staggered_strong(order,ny,Ly/ny,true);
[~, ~, Pzp, Pzm, Qzp, Qzm] = sbp_staggered_strong(order_z,nz,Lz/nz, true);
end
xp = xp'; xm = xm';
yp = yp'; ym = ym';
% Difference operators
Dxp = inv(Pxp)*Qxp;
Dxm = inv(Pxm)*Qxm;
Dyp = inv(Pyp)*Qyp;
Dym = inv(Pym)*Qym;
Dzp = inv(Pzp)*Qzp;
Dzm = inv(Pzm)*Qzm;
nxp = length(xp);
nxm = length(xm);
nyp = length(yp);
nym = length(ym);
% Identity matrices
Ixp = speye(nxp);
Iyp = speye(nyp);
Izp = speye(nzp);
Ixm = speye(nxm);
Iym = speye(nym);
Izm = speye(nzm);
hx = Lx/nx;
hy = Ly/ny;
hz = Lz/nz;
%% p grid:
g.p.x = xp;
g.p.y = yp;
g.p.hx = hx;
g.p.hy = hy;
g.p.nx = nxp;
g.p.ny = nyp;
[g.p.X, g.p.Y] = meshgrid(xp,yp);
g.p.vec = @(u) reshape(u, g.p.ny*g.p.nx, 1);
g.p.grd = @(u) reshape(u, g.p.ny, g.p.nx);
% p op:
op.p.Dx1 = Dxm;% 1D.
op.p.Dy1 = Dym;
op.p.Dx3 = kron(kron(Dxm, Iyp), Izm);% dp/dx for vx (mpm)
op.p.Dy3 = kron(kron(Ixp,Dym), Izm); % dp/dy for vy (pmm)
op.p.ez = ones(nzm, 1);
op.p.Ez = kron(kron(Ixp, Iyp), op.p.ez); % extend p in z direction into 3D.
op.p.Px1 = Pxp; % 1D
op.p.Py1 = Pyp;
op.p.Pxy2 = kron(Pxp, Pyp); % for energy norm dp/dt.
op.p.restrictions = restrictions(nxp, nyp); % restriction operator.
%% vx, grid and op.
g.vx.x = xm;
g.vx.y = yp;
g.vx.z = zm;
g.vx.Jzp = Jzp;
g.vx.Jzm = Jzm;
g.vx.Jzpi = Jzpi;
g.vx.Jzmi = Jzmi;
g.vx.hx = hx;
g.vx.hy = hy;
g.vx.hz = hz;
g.vx.nx = nxm;
g.vx.ny = nyp;
g.vx.nz = nzm;
% store 1D grid and construct 3D when using it.
g.vx.mesh = @() meshgrid(xm, yp, zm);
% [g.vx.X, g.vx.Y, g.vx.Z] = meshgrid(xm, yp, zm); this cost too much memory.
g.vx.vec = @(u) reshape(permute(u,[3,1,2]), g.vx.nz*g.vx.ny*g.vx.nx,1);
g.vx.grd = @(u) reshape(u, g.vx.nz, g.vx.ny, g.vx.nx);
% vx, op. Attention! Grid stretch in z direction!
op.vx.D2z1 = Jzmi*Dzm*Jzpi* Dzp;% D2z in 1D
op.vx.D2z3 = kron(kron(Ixm,Iyp), op.vx.D2z1); % D2z in 3D
% first derivative of vx.
op.vx.D1z1 = Jzpi* Dzp; % D1z in 1D
op.vx.D1z3 = kron(kron(Ixm,Iyp), op.vx.D1z1); % D1z in 3D.
op.vx.Wz1 = 1/Lz*ones(1, g.vx.nz)*Jzm*Pzm;% width-average operator in 1D
op.vx.Wz3 = kron(kron(Ixm, Iyp), op.vx.Wz1);% width-average operator in 3D
op.vx.Pxyz3 = kron(kron(Pxm,Pyp), Jzm*Pzm);% for the energy norm.
% quadrature of dvx/dz
op.vx.Pxyz3_dz = kron(kron(Pxm,Pyp), Jzp*Pzp);% for the energy norm.
op.vx.restrictions = restrictions(nxm,nyp,nzm);
%% vy grid and op.
g.vy.x = xp;
g.vy.y = ym;
g.vy.z = zm;
g.vy.Jzp = Jzp;
g.vy.Jzm = Jzm;
g.vy.Jzpi = Jzpi;
g.vy.Jzmi = Jzmi;
g.vy.hx = hx;
g.vy.hy = hy;
g.vy.hz = hz;
g.vy.nx = nxp;
g.vy.ny = nym;
g.vy.nz = nzm;
g.vy.mesh = @() meshgrid(xp, ym, zm);
g.vy.vec = @(u) reshape(permute(u,[3,1,2]), g.vy.nz*g.vy.ny*g.vy.nx,1);
g.vy.grd = @(u) reshape(u, g.vy.nz, g.vy.ny, g.vy.nx);
op.vy.D2z1 = Jzmi*Dzm*Jzpi* Dzp;
op.vy.D2z3 = kron(kron(Ixp,Iym), op.vy.D2z1);
op.vy.D1z1 = Jzpi* Dzp;
op.vy.D1z3 = kron(kron(Ixp,Iym), op.vy.D1z1);
op.vy.Wz1 = 1/Lz*ones(1, g.vx.nz)*Jzm*Pzm;
op.vy.Wz3 = kron(kron(Ixp, Iym), op.vy.Wz1);
op.vy.Pxyz3 = kron(kron(Pxp,Pym), Jzm*Pzm);% for the energy norm.
% quadrature of dvx/dz
op.vy.Pxyz3_dz = kron(kron(Pxp,Pym), Jzp*Pzp);% for the energy norm.
op.vy.restrictions = restrictions(nxp,nym,nzm);
%% ux grid (x, y) and op.
g.ux.x = xm;
g.ux.y = yp;
g.ux.hx = hx;
g.ux.hy = hy;
g.ux.nx = nxm;
g.ux.ny = nyp;
[g.ux.X, g.ux.Y] = meshgrid(xm,yp);
g.ux.vec = @(u) reshape(u, g.ux.ny*g.ux.nx, 1);
g.ux.grd = @(u) reshape(u, g.ux.ny, g.ux.nx);
% p op:
op.ux.Dx1 = Dxp;% 1D.
op.ux.Dx2 = kron(Dxp, Iyp);%dux/dx for dp/dt
op.ux.restrictions = restrictions(nxm, nyp);
%% uy grid (x, y) and op.
g.uy.x = xp;
g.uy.y = ym;
g.uy.hx = hx;
g.uy.hy = hy;
g.uy.nx = nxp;
g.uy.ny = nym;
[g.uy.X, g.uy.Y] = meshgrid(xp,ym);
g.uy.vec = @(u) reshape(u, g.uy.ny*g.uy.nx, 1);
g.uy.grd = @(u) reshape(u, g.uy.ny, g.uy.nx);
% p op:
op.uy.Dy1 = Dyp;% 1D.
op.uy.Dy2 = kron(Ixp, Dyp);% duy/dy for dp/dt. 2D.
op.uy.restrictions = restrictions(nxp, nym);
end
function A = trunc_mat(A,truncate)
if ~truncate
return;
end
A = A(2:end-1,2:end-1);
end
function a = trunc_vec(a,truncate)
if ~truncate
return;
end
a = a(2:end-1);
end
|
github
|
chaovite/crack_pipe-master
|
intgrV.m
|
.m
|
crack_pipe-master/source/surface_disp/frac_disp/Fialk2001/intgrV.m
| 621 |
utf_8
|
a1d9e3cfc6c1878f0300aa46e09313cb
|
%function [V,Vs]=intgrV(fi,psi,h,Wt,t)
function [V]=intgrV(fi,h,Wt,t)
% V,Vs - volume of crack, volume of surface uplift
% fi,psi: basis functions
% t: interval of integration
%large=1e10;
V = sum(Wt.*fi.*t);
%Vs = sum(Wt.*fi.*(t-h*(h-t)./(h^2+t.^2)));
%V1 = sum(Wt.*(fi.*Q(0,t,0,41)));
%V2 = sum(Wt.*(fi.*Q(0,t,large,41)));
%V=V2-V1;
%I1=sqrt(2)*h*t.*Qr(h,t,1)
%I2=(h*Qr(h,t,3)-t.*Qr(h,t,2))/sqrt(2)
%I3=(h*Qr(h,t,2)+t.*Qr(h,t,3))/sqrt(2)
%Vs = sum(Wt.*(fi.*(I1+h*I2)+psi.*(I1./t-I3)))
%Vs2 = sum(Wt.*(fi.*(Q(h,t,large,41)+h*Q(h,t,large,51))+...,
% psi.*(Q(h,t,large,41)./t-Q(h,t,large,61))));
%Vs=Vs2-Vs1;
|
github
|
chaovite/crack_pipe-master
|
fpkernel.m
|
.m
|
crack_pipe-master/source/surface_disp/frac_disp/Fialk2001/fpkernel.m
| 1,020 |
utf_8
|
34db1a95baafa67be73b2e36d10f0cc8
|
function [K]=fpkernel(h,t,r,n)
% Kernels calculation
p=4*h^2;
K=[];
%[dumb,nr]=size(r);
%[dumb,nt]=size(t);
switch n
case 1 %KN
K=p*h*(KG(t-r,p)-KG(t+r,p));
case 2 %KN1
Dlt=1e-6;
a=t+r;
b=t-r;
y=a.^2;
z=b.^2;
g=2*p*h*(p^2+6*p*(t.^2+r.^2)+5*(a.*b).^2);
s=((p+z).*(p+y)).^2;
s=g./s;
trbl=-4*h/(p+t.^2)*ones(size(t));
rs=find(r>Dlt);
if t<Dlt
trbl=-4*h./(p+r.^2);
else
trbl(rs)=h/t./r(rs).*log((p+z(rs))./(p+y(rs)));
end
K=trbl+s+h*(KERN(b,p)+KERN(a,p));
case 3 %KM
y=(t+r).^2; z=(t-r).^2;
a=((p+y).*(p+z)).^2;
c=t+r; d=t-r;
b=p*t*((3*p^2-(c.*d).^2+2*p*(t^2+r.^2))./a);
a=p/2*(c.*KG(c,p)+d.*KG(d,p));
K=b-a;
case 4 %%KM1(t,r)=KM(r,t);
y=(t+r).^2; z=(t-r).^2;
a=((p+y).*(p+z)).^2;
c=t+r; d=-t+r;
b=p*r.*((3*p^2-(c.*d).^2+2*p*(t^2+r.^2))./a);
a=p/2*(c.*KG(c,p)+d.*KG(d,p));
K=b-a;
end %switch n
function [fKG]=KG(s,p)
z=s.^2;
y=p+z;
fKG=(3*p-z)./y.^3;
function [fKERN]=KERN(w,p);
u=(p+w.^2).^3;
fKERN=2*(p^2/2+w.^4-p*w.^2/2)./u;
|
github
|
chaovite/crack_pipe-master
|
fred.m
|
.m
|
crack_pipe-master/source/surface_disp/frac_disp/Fialk2001/fred.m
| 1,218 |
utf_8
|
3f8d821d21a1dc0a806aed26bd8921b8
|
function [fi,psi,t,Wt]=fred(h,m,er)
% fi,psi: basis functions
% t: interval of integration
% m: size(t)
%er=1e-7;
lamda=2/pi;
RtWt;
NumLegendreTerms=length(Rt);
for k=1:m
for i=1:NumLegendreTerms
d1=1/m;
t1=d1*(k-1);
r1:=d1*k;
j=NumLegendreTerms*(k-1)+i;
t(j)=Rt(j)*(r1-t1)*0.5+(r1+t1)*0.5;
end
end
%[t,Wt]=SimpRtWt(m);
fi1=-lamda*t;
psi1=zeros(size(t));
fi=zeros(size(t));
psi=zeros(size(t));
res=1e9;
% start iterating
%e=0:1/7:1;
%for i=1:7
%y=fpkernel(h,e(i),t,4);
% line(t,y), hold on
%end
%print out.ps
%end
%return
while res > er
for i=1:m+1
fi(i)=-t(i)+sum(Wt.*(fi1.*fpkernel(h,t(i),t,1)+...,
psi1.*fpkernel(h,t(i),t,3)));
psi(i)=sum(Wt.*(psi1.*fpkernel(h,t(i),t,2)+...,
fi1.*fpkernel(h,t(i),t,4)));
end
fi=fi*lamda; psi=psi*lamda;
% find maximum relative change
[fim,im]=max(abs(fi1-fi));
fim=fim/abs(fi(im));
[psim,im]=max(abs(psi1-psi));
psim=psim/abs(psi(im));
res=max([fim psim]);
fi1=fi;
psi1=psi;
end %while
function [t,Wt] =SimpRtWt(m); % nodes and weights for Simpson integration
t=0:1/m:1;
Wt=2/3/m*ones(size(t));
I=1:m+1;
ev=find(mod(I,2)==0);
Wt(ev)=4/3/m;
Wt(1)=1/3/m;
Wt(m+1)=1/3/m;
|
github
|
chaovite/crack_pipe-master
|
ex.m
|
.m
|
crack_pipe-master/source/disloc3d/ex.m
| 2,524 |
utf_8
|
f4fafe38d971840a9496c5c90f7ed9cd
|
function ex()
% Example showing how to use disloc3d.
mu = 1;
nu = 0.25;
n = 200;
d = -100;
x = linspace(-3,1,n);
z = linspace(d-2,d+2,n);
[xm zm] = meshgrid(x,z);
obs = [xm(:)'
zeros(1,n^2)
zm(:)'];
% I sent length to a very large number to simulate a 2D (in-plane) problem.
length = 1e5; % N-S
width = 2; % E-W
depth = -d;
dip = 12;
strike = 0;
east = 0;
north = 0;
ss = 0;
ds = 1;
op = 0;
mdl = [length width depth dip strike east north ss ds op]';
% You can use any of these three versions. The 'pm' version is very slow.
tic
[U D S flag] = disloc3d(mdl,obs,mu,nu);
% [U D S flag] = disloc3dpm(mdl,obs,mu,nu);
% [U D S flag] = disloc3domp(mdl,obs,mu,nu,4);
toc
% Displacements
figure; clf;
c = 'xyz';
for(i=1:3)
subplot(2,2,i); im(x,z,reshape(U(i,:),n,n));
title(sprintf('U_{%s}',c(i)));
end
figure; clf;
Ux = reshape(U(1,:),n,n);
Uz = reshape(U(3,:),n,n);
k = ceil(n/20);
xs = x(1:k:end); zs = z(1:k:end);
Ux = Ux(1:k:end,1:k:end); Uz = Uz(1:k:end,1:k:end);
quiver(xs,zs,Ux,Uz); axis tight;
title('Displacements');
% Stresses in global coordinates
figure; clf;
subplot(221); im(x,z,reshape(S(1,:),n,n));
title('S_{xx}');
subplot(222); im(x,z,reshape(S(3,:),n,n));
title('S_{xz}');
subplot(223); im(x,z,reshape(S(6,:),n,n));
title('S_{zz}');
% Stress resolved along and normal to the fault
cd = cosd(dip);
sd = sind(dip);
normal = [sd 0 cd]';
along = [cd 0 -sd]';
[shr_stress nml_stress] = Stresses(S,along,normal);
figure;
subplot(211); im(x,z,reshape(shr_stress,n,n)); title('Shear stress');
subplot(212); im(x,z,reshape(nml_stress,n,n)); title('Normal stress');
function im(x,y,I)
n = length(x);
imagesc(x,y,reshape(I,n,n));
colorbar;
caxis(1e1*median(abs(I(:)))*[-1 1]);
axis xy;
function [ss ns] = Stresses(S,along,normal)
% From S, the output of disloc3d, compute the shear and normal stresses. along
% and normal are vectors pointing along and normal to the fault.
n = size(S,2);
ss = zeros(n,1);
ns = zeros(n,1);
% Vectorized code that is equivalent to
% sigma = [Sxx(i) Sxy(i) Sxz(i)
% Sxy(i) Syy(i) Syz(i)
% Sxz(i) Syz(i) Szz(i)];
% ss(i) = along' *sigma*normal;
% ns(i) = normal'*sigma*normal;
normal = normal(:);
S = S([1 2 3 2 4 5 3 5 6],:);
nml = repmat(normal(repmat(1:3,1,3)),1,n);
a = S.*nml;
a = [sum(a(1:3,:))
sum(a(4:6,:))
sum(a(7:9,:))];
ss = along(:)'*a;
ns = normal(:)'*a;
|
github
|
chaovite/crack_pipe-master
|
disloc3dpm.m
|
.m
|
crack_pipe-master/source/disloc3d/disloc3dpm.m
| 45,369 |
utf_8
|
c0e73ca06a4b54e4daa2aecee257bfa9
|
function [U D S flag] = disloc3dpm(mdl,stat,mu,nu)
%[U D S flag] = disloc3dpm(m,x,mu,nu) [pure Matlab version of disloc3d]
%
% Returns the deformation at point 'x', given dislocation model 'm'. 'mu'
% specifies the shear modulus and 'nu' specifies Poisson's ratio.
%
% Both 'm' and 'x' can be matrices, holding different models and observation
% coordinates in the columns. In this case, the function returns the
% deformation at the points specified in the columns of 'x' from the sum of
% all the models in the columns of 'm'. 'x' must be 3xi (i = number of
% observation coordinates) and 'm' must be 10xj (j = number of models).
%
% The coordinate system is as follows:
% east = positive X, north = positive Y, up = positive Z.
% Observation coordinates with positive Z values return a warning.
%
% The outputs are 'U', the three displacement components: east, north, and up
% (on the cols); 'D', the nine spatial derivatives of the displacement: Uxx,
% Uxy, Uxz, Uyx, Uyy, Uyz, Uzx, Uzy, and Uzz (on the cols); and 'S', the 6
% independent stress components: Sxx, Sxy, Sxz, Syy, Syz, and Szz (on the
% cols). All these outputs have the same number of columns as 'x'.
%
% Output 'flag' is set for a singularity.
%
% The dislocation model is specified as:
% length width depth dip strike east north strike-slip dip-slip opening.
% The coordinates (depth, east, north) specify a point at the middle of the
% bottom edge of the fault for positive dips and the middle of the top edge
% for negative dips. The coordinates (east, north) are specified just as for
% obs; however, note carefully that depth is a positive number in 'm', while
% in 'x' the equivalent coordinate is z and so is negative.
%
% Mind your units: for example, if lengths are given in km, then so should be
% slips.
%
% ---------------
% This is a pure-Matlab version of disloc3d based on the Matlab translation
% of Y. Okada's dc3d.f found in Coulomb 3.1. The citations are as follows:
% Toda, S., R. S. Stein, K. Richards-Dinger and S. Bozkurt (2005),
% Forecasting the evolution of seismicity in southern California:
% Animations built on earthquake stress transfer, J. Geophys. Res.,
% B05S16, doi:10.1029/2004JB003415.
% Lin, J., and R.S. Stein, Stress triggering in thrust and subduction
% earthquakes, and stress interaction between the southern San Andreas
% and nearby thrust and strike-slip faults, J. Geophys. Res., 109,
% B02303, doi:10.1029/2003JB002607, 2004.
% Okada, Y., Internal deformation due to shear and tensile faults in a
% half-space, Bull. Seismol. Soc. Amer., 82 (2), 1018-1040, 1992.
% 20 Oct 2010. AMB. Initial version.
global N_CELL
N_CELL = 1;
lambda = 2*mu*nu/(1-2*nu);
n = size(stat,2);
nm = size(mdl,2);
U = zeros(3,n);
D = zeros(9,n);
S = zeros(6,n);
flag = zeros(1,n);
for(j = 1:nm) % dislocation elements
m = mdl(:,j);
alpha = (lambda + mu)/(lambda + 2*mu);
strike = m(5) - 90;
cs = cosd(strike);
ss = sind(strike);
R = [ cs ss 0
-ss cs 0
0 0 1];
dip = m(4);
cd = cosd(dip);
sd = sind(dip);
disl1 = m(8);
disl2 = m(9);
disl3 = m(10);
al1 = m(1)/2;
al2 = al1;
aw1 = m(2)/2;
aw2 = aw1;
for(i = 1:n) % observation points
s = stat(:,i);
% disloc3d coords -> dc3d coords
x = cs*(-m(6) + s(1)) - ss*(-m(7) + s(2));
y = -cd*m(2)/2 + ss*(-m(6) + s(1)) + cs*(-m(7) + s(2));
z = s(3);
depth = m(3) - 0.5*m(2)*sd;
[Ux Uy Uz Uxx Uyx Uzx Uxy Uyy Uzy Uxz Uyz Uzz iret] = Okada_DC3D(...
alpha,x,y,z,depth,dip,...
al1,al2,aw1,aw2,disl1,disl2,disl3);
% dc3d coords -> disloc3d coords and accumulate
flag(i) = flag(i) | iret;
U(:,i) = U(:,i) + R*[Ux Uy Uz]';
ud = R*[Uxx Uxy Uxz; Uyx Uyy Uyz; Uzx Uzy Uzz]'*R';
D(:,i) = D(:,i) + ud(:);
end
end
% stress
for(i = 1:n) % observation points
Ud = reshape(D(:,i),3,3);
Ud = (Ud + Ud')/2; % symmetrize
s = 2*mu*Ud + lambda*sum(diag(Ud))*eye(3); % isotropic form of Hooke's law
S(:,i) = s([1:3 5:6 9]); % six unique elements due to symmetry
end
clear global N_CELL ...
ALE ALP4 CD ET2 FZ HZ R3 SDCD X32 Y32 ...
ALP1 ALP5 CDCD EY GY Q2 R5 SDSD XI2 ...
ALP2 ALX D EZ GZ R S2D TT Y ...
ALP3 C2D DUMMY FY HY R2 SD X11 Y11;
% ------------------------------------------------------------------------------
% The rest of the code is from Coulomb 3.1.
% ------------------------------------------------------------------------------
function[UX,UY,UZ,UXX,UYX,UZX,UXY,UYY,UZY,UXZ,UYZ,UZZ,IRET] = Okada_DC3D(ALPHA,...
X,Y,Z,DEPTH,DIP,...
AL1,AL2,AW1,AW2,DISL1,DISL2,DISL3)
% IMPLICIT REAL*8 (A-H,O-Z) 04640000
% REAL*4 ALPHA,X,Y,Z,DEPTH,DIP,AL1,AL2,AW1,AW2,DISL1,DISL2,DISL3, 04650000
% * UX,UY,UZ,UXX,UYX,UZX,UXY,UYY,UZY,UXZ,UYZ,UZZ 04660000
% C 04670000
% C******************************************************************** 04680000
% C***** ***** 04690000
% C***** DISPLACEMENT AND STRAIN AT DEPTH ***** 04700000
% C***** DUE TO BURIED FINITE FAULT IN A SEMIINFINITE MEDIUM ***** 04710000
% C***** CODED BY Y.OKADA ... SEP 1991 ***** 04720002
% C***** REVISED Y.OKADA ... NOV 1991 ***** 04730002
% C***** ***** 04740000
% C******************************************************************** 04750000
% C 04760000
% C***** INPUT 04770000
% C***** ALPHA : MEDIUM CONSTANT (LAMBDA+MYU)/(LAMBDA+2*MYU) 04780000
% C***** X,Y,Z : COORDINATE OF OBSERVING POINT 04790000
% C***** DEPTH : SOURCE DEPTH 04800000
% C***** DIP : DIP-ANGLE (DEGREE) 04810000
% C***** AL1,AL2 : FAULT LENGTH (-STRIKE,+STRIKE) 04820000
% C***** AW1,AW2 : FAULT WIDTH ( DOWNDIP, UPDIP) 04830000
% C***** DISL1-DISL3 : STRIKE-, DIP-, TENSILE-DISLOCATIONS 04840000
% C 04850000
% C***** OUTPUT 04860000
% C***** UX, UY, UZ : DISPLACEMENT ( UNIT=(UNIT OF DISL) 04870000
% C***** UXX,UYX,UZX : X-DERIVATIVE ( UNIT=(UNIT OF DISL) / 04880000
% C***** UXY,UYY,UZY : Y-DERIVATIVE (UNIT OF X,Y,Z,DEPTH,AL,AW) )04890000
% C***** UXZ,UYZ,UZZ : Z-DERIVATIVE 04900000
% C***** IRET : RETURN CODE ( =0....NORMAL, =1....SINGULAR ) 04910002
% C 04920000
global DUMMY SD CD
global XI2 ET2 Q2 R
global N_CELL
% COMMON /C0/DUMMY(5),SD,CD 04930000
% COMMON /C2/XI2,ET2,Q2,R 04940000
% DIMENSION U(12),DU(12),DUA(12),DUB(12),DUC(12) 04950000
% DATA F0/0.D0/ 04960000
% F0 = double(0.0);
F0 = zeros(N_CELL,1,'double');
%C-----
if Z>0.0
disp(' ** POSITIVE Z WAS GIVEN IN SUB-DC3D');
end
%for I=1:1:12
U = zeros(N_CELL,12,'double');
DUA = zeros(N_CELL,12,'double');
DUB = zeros(N_CELL,12,'double');
DUC = zeros(N_CELL,12,'double');
IRET = zeros(N_CELL,1,'double');
% U (1:N_CELL,1:12)=0.0;
% DUA(1:N_CELL,1:12)=0.0;
% DUB(1:N_CELL,1:12)=0.0;
% DUC(1:N_CELL,1:12)=0.0;
% IRET(1:N_CELL,1:12)=0.0;
%end
AALPHA=ALPHA;
DDIP=DIP;
% % NEED TO CHECK THE CODE CAREFULLY but here is a temporal solution!
% % high dip gives really unstable solutions
% if DDIP>=89.999
% DDIP = double(89.999);
% end
DCCON0(AALPHA,DDIP);
% C====================================== 05080000
% C===== REAL-SOURCE CONTRIBUTION ===== 05090000
% C====================================== 05100000
D=DEPTH+Z;
P=Y.*CD+D.*SD;
Q=Y.*SD-D.*CD;
% JXI=0;
% JET=0;
JXI = int8(zeros(N_CELL,1));
JET = int8(zeros(N_CELL,1));
aa = (X+AL1).*(X-AL2);
cneg = aa <= 0.0;
JXI = JXI + int8(cneg);
jxi_sum = sum(rot90(sum(JXI)));
bb = (P+AW1).*(P-AW2);
cneg = bb <= 0.0;
JET = JET + int8(cneg);
jet_sum = sum(rot90(sum(JET)));
% if aa<=0.0
% JXI=1;
% end
% if bb<=0.0
% JET=1;
% end
DD1=DISL1;
DD2=DISL2;
DD3=DISL3;
%C----- 05210000
for K=1:2
if(K==1)
ET=P+AW1;
end
if(K==2)
ET=P-AW2;
end
for J=1:2
if(J==1)
XI=X+AL1;
end
if(J==2)
XI=X-AL2;
end
DCCON2(XI,ET,Q,SD,CD);
% To detect singular point
cjxi1 = JXI == 1;
cjxi2 = JXI ~= 1;
cjet1 = JET == 1;
cjet2 = JET ~= 1;
cq1 = abs(Q) <= 1.0e-12;
cq2 = abs(Q) > 1.0e-12;
cet1 = abs(ET) <= 1.0e-12;
cet2 = abs(ET) > 1.0e-12;
cxi1 = abs(XI) <= 1.0e-12;
cxi2 = abs(XI) > 1.0e-12;
% cq1 = Q == 0.0;
% cq2 = Q ~= 0.0;
% cet1 = ET == 0.0;
% cet2 = ET ~= 0.0;
% cxi1 = XI == 0.0;
% cxi2 = XI ~= 0.0;
cc1 = cjxi1.*cq1.*cet1; cc2 = (cc1 - 1.0).*(-1.0);
cc3 = cjet1.*cq1.*cxi1; cc4 = (cc3 - 1.0).*(-1.0);
cc0 = (cc1 + cc3) >= 1;
cc5 = (cc1 + cc3) < 1;
IRET = IRET + cc0;
% sum(rot90(sum(cc3)))
% q_sum = sum(rot90(sum(Q)));
% et_sum = sum(rot90(sum(ET)));
% xi_sum = sum(rot90(sum(ET)));
% % if ((jxi_sum>=1 & Q==F0 & ET==F0) | (jet_sum>=1 & Q==F0 & XI==F0))
% if ((jxi_sum>=1 & q_sum==0.0 & et_sum==0.0) | (jet_sum>=1 & q_sum==0.0 & xi_sum==0.0))
% % if ((jxi_sum>=1) | (jet_sum>=1))
% % C======================================= 06030000
% % C===== IN CASE OF SINGULAR (R=0) ===== 06040000
% % C======================================= 06050000
% UX=zeros(N_CELL,1,'double');
% UY=zeros(N_CELL,1,'double');
% UZ=zeros(N_CELL,1,'double');
% UXX=zeros(N_CELL,1,'double');
% UYX=zeros(N_CELL,1,'double');
% UZX=zeros(N_CELL,1,'double');
% UXY=zeros(N_CELL,1,'double');
% UYY=zeros(N_CELL,1,'double');
% UZY=zeros(N_CELL,1,'double');
% UXZ=zeros(N_CELL,1,'double');
% UYZ=zeros(N_CELL,1,'double');
% UZZ=zeros(N_CELL,1,'double');
% IRET=ones(N_CELL,1,'double');
% disp('error');
% % return
% break;
% end
DUA = UA(XI,ET,Q,DD1,DD2,DD3);
%C----- 05320000
for I=1:3:10
DU(:,I) =-DUA(:,I);
DU(:,I+1)=-DUA(:,I+1).*CD+DUA(:,I+2).*SD;
DU(:,I+2)=-DUA(:,I+1).*SD-DUA(:,I+2).*CD;
if I<10.0
continue;
end
DU(:,I) =-DU(:,I);
DU(:,I+1)=-DU(:,I+1);
DU(:,I+2)=-DU(:,I+2);
end
% for I=1:1:12
if(J+K)~=3
U(:,1:12)=U(:,1:12)+DU(:,1:12);
end
if(J+K)==3
U(:,1:12)=U(:,1:12)-DU(:,1:12);
end
% end
end
end
% C======================================= 05490000
% C===== IMAGE-SOURCE CONTRIBUTION ===== 05500000
% C======================================= 05510000
ZZ=Z;
D=DEPTH-Z;
P=Y.*CD+D.*SD;
Q=Y.*SD-D.*CD;
% JET=0;
JET = int8(ones(N_CELL,1));
cc=(P+AW1).*(P-AW2);
c1 = cc <= 0.0;
c2 = cc > 0.0;
JET = int8(c1).*JET;
% if cc<=0.0
% JET=1;
% end
%C----- 05580000
for K=1:2
if K==1
ET=P+AW1;
end
if K==2
ET=P-AW2;
end
for J=1:2
if J==1
XI=X+AL1;
end
if J==2
XI=X-AL2;
end
DCCON2(XI,ET,Q,SD,CD);
DUA = UA(XI,ET,Q,DD1,DD2,DD3);
DUB = UB(XI,ET,Q,DD1,DD2,DD3);
DUC = UC(XI,ET,Q,ZZ,DD1,DD2,DD3);
%C----- 05690000
for I=1:3:10
DU(:,I)=DUA(:,I)+DUB(:,I)+Z.*DUC(:,I);
DU(:,I+1)=(DUA(:,I+1)+DUB(:,I+1)+Z.*DUC(:,I+1)).*CD...
-(DUA(:,I+2)+DUB(:,I+2)+Z.*DUC(:,I+2)).*SD;
DU(:,I+2)=(DUA(:,I+1)+DUB(:,I+1)-Z.*DUC(:,I+1)).*SD...
+(DUA(:,I+2)+DUB(:,I+2)-Z.*DUC(:,I+2)).*CD;
if I<10.0
continue;
end
DU(:,10)=DU(:,10)+DUC(:,1);
DU(:,11)=DU(:,11)+DUC(:,2).*CD-DUC(:,3).*SD;
DU(:,12)=DU(:,12)-DUC(:,2).*SD-DUC(:,3).*CD;
end
% for I=1:1:12
if(J+K~=3)
U(:,1:12)=U(:,1:12)+DU(:,1:12);
end
if(J+K==3)
U(:,1:12)=U(:,1:12)-DU(:,1:12);
% end
end
%C----- 05850000
end
end
%C===== 05880000
UX=U(:,1);
UY=U(:,2);
UZ=U(:,3);
UXX=U(:,4);
UYX=U(:,5);
UZX=U(:,6);
UXY=U(:,7);
UYY=U(:,8);
UZY=U(:,9);
UXZ=U(:,10);
UYZ=U(:,11);
UZZ=U(:,12);
cc5 = IRET >= 1;
IRET = cc5;
% IRET=0;
% IRET = zeros(N_CELL,1,'double');
% IRET = IRET + cc0;
sum(rot90(sum(IRET)));
% isa(UX,'double')
% isa(UXX,'double')
% isa(UYZ,'double')
% isa(IRET,'double')
% RETURN 06020000
% C======================================= 06030000
% C===== IN CASE OF SINGULAR (R=0) ===== 06040000
% C======================================= 06050000
% 99 UX=F0 06060000
% UY=F0 06070000
% UZ=F0 06080000
% UXX=F0 06090000
% UYX=F0 06100000
% UZX=F0 06110000
% UXY=F0 06120000
% UYY=F0 06130000
% UZY=F0 06140000
% UXZ=F0 06150000
% UYZ=F0 06160000
% UZZ=F0 06170000
% IRET=1 06180002
% RETURN 06190000
% END
% ------------------------------------------------------------------------------
function DCCON0(ALPHA,DIP)
% Okada 92 code subroutine DCCON0
%
global ALP1 ALP2 ALP3 ALP4 ALP5 SD CD SDSD CDCD SDCD S2D C2D
global N_CELL
% DATA F0,F1,F2,PI2/0.D0,1.D0,2.D0,6.283185307179586D0/ %09430000
% DATA EPS/1.D-6/
F0 = zeros(N_CELL,1,'double');
F1 = ones(N_CELL,1,'double');
F2 = ones(N_CELL,1,'double').*2.0;
PI2 = ones(N_CELL,1,'double').*6.283185307179586;
EPS = ones(N_CELL,1,'double').*1.0e-6;
ALP1=(F1-ALPHA)./F2;
ALP2= ALPHA./F2;
ALP3=(F1-ALPHA)./ALPHA;
ALP4= F1-ALPHA;
ALP5= ALPHA;
P18=PI2./double(360.0); %09520000
SD=double(sin(DIP.*P18)); %09530000
CD=double(cos(DIP.*P18));
c1 = abs(CD) < EPS;
c2 = abs(CD) >= EPS;
s1 = SD > F0;
s2 = SD == F0;
s3 = SD < F0;
CD = F0.*c1 + CD.*c2;
% CAUTION ************ modified by Shinji Toda (CD = 0.0 produces 'nan')
% in MATLAB
% c3 = abs(CD) < EPS;
% c4 = abs(CD) <= EPS;
% CD = c3.*EPS + c4.*CD;
% CAUTION ***************************************************************
%09560000
% if SD>F0
% SD= F1;
% end
% if SD<F0
% SD=-F1; %09580000
% end
SD = c1.*(F1.*s1 + SD.*s2 + (-1.0).*F1.*s3) + c2.*SD;
%end
%09590000
SDSD=SD.*SD; %09600000
CDCD=CD.*CD; %09610000
SDCD=SD.*CD; %09620000
S2D=F2.*SDCD; %09630000
C2D=CDCD-SDSD; %09640000
% RETURN %09650000
% END %09660000
% ------------------------------------------------------------------------------
function DCCON11(X,Y,D)
% SUBROUTINE DCCON1(X,Y,D) 09670000
% IMPLICIT REAL*8 (A-H,O-Z) 09680000
% C 09690000
% C********************************************************************** 09700000
% C***** CALCULATE STATION GEOMETRY CONSTANTS FOR POINT SOURCE ***** 09710000
% C********************************************************************** 09720000
% C 09730000
% C***** INPUT 09740000
% C***** X,Y,D : STATION COORDINATES IN FAULT SYSTEM 09750000
% C### CAUTION ### IF X,Y,D ARE SUFFICIENTLY SMALL, THEY ARE SET TO ZERO 09760000
% C 09770000
% COMMON /C0/DUMMY(5),SD,CD 09780000
% COMMON /C1/P,Q,S,T,XY,X2,Y2,D2,R,R2,R3,R5,QR,QRX,A3,A5,B3,C3, 09790000
% * UY,VY,WY,UZ,VZ,WZ 09800000
global DUMMY SD CD
global P Q S T XY X2 Y2 D2 R R2 R3 R5 QR QRX A3 A5 B3 C3 UY VY WY UZ VZ WZ
global N_CELL
F0 = zeros(N_CELL,1,'double');
F1 = ones(N_CELL,1,'double');
F3 = ones(N_CELL,1,'double').*3.0;
F5 = ones(N_CELL,1,'double').*5.0;
EPS = ones(N_CELL,1,'double').*0.000001;
% DATA F0,F1,F3,F5,EPS/0.D0,1.D0,3.D0,5.D0,1.D-6/ 09810000
% C----- 09820000
c1 = abs(X) < EPS;
c2 = abs(X) >= EPS;
X = F0.*c1 + X.*c2;
c1 = abs(Y) < EPS;
c2 = abs(Y) >= EPS;
Y = F0.*c1 + Y.*c2;
c1 = abs(D) < EPS;
c2 = abs(D) >= EPS;
D = F0.*c1 + D.*c2;
% IF(DABS(X).LT.EPS) X=F0 09830000
% IF(DABS(Y).LT.EPS) Y=F0 09840000
% IF(DABS(D).LT.EPS) D=F0 09850000
P=Y.*CD+D.*SD;
Q=Y.*SD-D.*CD;
S=P.*SD+Q.*CD;
T=P.*CD-Q.*SD;
XY=X.*Y;
X2=X.*X;
Y2=Y.*Y;
D2=D.*D;
R2=X2+Y2+D2;
R =sqrt(R2);
% IF(R.EQ.F0) RETURN 09960000
c1 = R == F0;
if sum(rot90(sum(c1))) > 0
return
end
R3=R .*R2;
R5=R3.*R2;
R7=R5.*R2;
% C----- 10000000
A3=F1-F3.*X2./R2;
A5=F1-F5.*X2./R2;
B3=F1-F3.*Y2./R2;
C3=F1-F3.*D2./R2;
% C----- 10050000
QR=F3.*Q./R5;
QRX=F5.*QR.*X./R2;
% C----- 10080000
UY=SD-F5.*Y.*Q./R2;
UZ=CD+F5.*D.*Q./R2;
VY=S -F5.*Y.*P.*Q./R2;
VZ=T +F5.*D.*P.*Q./R2;
WY=UY+SD;
WZ=UZ+CD;
% RETURN 10150000
% END 10160000
% ------------------------------------------------------------------------------
function DCCON2(XI,ET,Q,SD,CD)
% Okada 92 code subroutine DCCON2
%
global XI2 ET2 Q2 R R2 R3 R5 Y D TT ALX ALE X11 Y11 X32 Y32
global EY EZ FY FZ GY GZ HY HZ
global N_CELL
%disp('DCCON2');
% DATA F0,F1,F2,EPS/0.D0,1.D0,2.D0,1.D-6/
F0 = zeros(N_CELL,1,'double');
F1 = ones(N_CELL,1,'double');
F2 = ones(N_CELL,1,'double').*2.0;
EPS = ones(N_CELL,1,'double').*0.000001;
c1 = abs(XI) < EPS;
c2 = abs(XI) >= EPS;
% if abs(XI)<EPS
% XI=F0;
% end
XI = F0.*c1 + XI.*c2;
% if abs(ET)<EPS
% ET=F0;
% end
c1 = abs(ET) < EPS;
c2 = abs(ET) >= EPS;
ET = F0.*c1 + ET.*c2;
% if abs( Q)<EPS
% Q=F0;
% end
c1 = abs(Q) < EPS;
c2 = abs(Q) >= EPS;
Q = F0.*c1 + Q.*c2;
XI2=XI.*XI;
ET2=ET.*ET;
Q2=Q.*Q;
R2=XI2+ET2+Q2;
R =double(sqrt(R2));
c1 = R==F0;
c1_sum = sum(rot90(sum(c1)));
if c1_sum > 0
return;
end
R3=R .*R2;
R5=R3.*R2;
Y =ET.*CD+Q.*SD;
D =ET.*SD-Q.*CD;
%C-----
c1 = Q == F0;
c2 = Q ~= F0;
s1 = Q.*R == F0;
s2 = Q.*R ~= F0;
% if Q==F0 %10480000
% TT=F0; %10490000
% else
% % if (Q.*R)==0.0 % modified by Shinji Toda
% % TT=double(atan(XI.*ET./EPS)); % modified by Shinji Toda
% % else % modified by Shinji Toda
% TT=double(atan(XI.*ET./(Q.*R)));
% % end % modified by Shinji Toda
% end
% TT = c1.*F0 + c2.*(double(atan(XI.*ET./EPS)).*s1+double(atan(XI.*ET./(Q.*R))).*s2);
TT = c1.*F0 + c2.*double(atan(XI.*ET./(Q.*R)));
%C-----
c1 = XI < F0; c2 = Q == F0; c3 = ET == F0;
c4 = c1.*c2.*c3;
c5 = zeros(N_CELL,1,'double'); c5 = (c5 - c4)+1.0;
RXI=R+XI;
ALX = (-double(log(R-XI))).*c4 + double(log(RXI)).*c5;
X11 = F0.*c4 + (F1./(R.*RXI)).*c5;
X32 = F0.*c4 + ((R+RXI).*X11.*X11./R) .*c5;
% if(XI<F0 & Q==F0 & ET==F0) %10540002
% ALX=-double(log(R-XI)); %10550000
% X11=F0; %10560000
% X32=F0; %10570000
% else %10580000
% RXI=R+XI; %10590002
% ALX=double(log(RXI)); %10600000
% X11=F1./(R.*RXI); %106%10000
% X32=(R+RXI).*X11.*X11./R; %10620002
% end %10630000
%C-----
c1 = ET < F0; c2 = Q == F0; c3 = XI == F0;
c4 = c1.*c2.*c3;
c5 = zeros(N_CELL,1,'double'); c5 = (c5 - c4)+1.0;
RET=R+ET;
ALE = (-double(log(R-ET))).*c4 + double(log(RET)).*c5;
Y11 = F0.*c4 + (F1./(R.*RET)).*c5;
Y32 = F0.*c4 + ((R+RET).*Y11.*Y11./R).*c5;
%
% if(ET<F0 & Q==F0 & XI==F0) %10650002
% ALE=-double(log(R-ET)); %10660000
% Y11=F0; %10670000
% Y32=F0; %10680000
% else %10690000
% RET=R+ET; %10700002
% ALE=double(log(RET)); %107%10000
% Y11=F1./(R.*RET); %10720000
% Y32=(R+RET).*Y11.*Y11./R; %10730002
% end %10740000
%C----- %10750000
EY=SD./R-Y.*Q./R3; %10760000
EZ=CD./R+D.*Q./R3; %10770000
FY=D./R3+XI2.*Y32.*SD; %10780000
FZ=Y./R3+XI2.*Y32.*CD; %10790000
GY=F2.*X11.*SD-Y.*Q.*X32; %10800000
GZ=F2.*X11.*CD+D.*Q.*X32; %108%10000
HY=D.*Q.*X32+XI.*Q.*Y32.*SD; %10820000
HZ=Y.*Q.*X32+XI.*Q.*Y32.*CD; %10830000
% RETURN %10840000
% END %10850000
% ------------------------------------------------------------------------------
function [U] = UA(XI,ET,Q,DISL1,DISL2,DISL3)
% DIMENSION U(12),DU(12) 06230000
% C 06240000
% C******************************************************************** 06250000
% C***** DISPLACEMENT AND STRAIN AT DEPTH (PART-A) ***** 06260000
% C***** DUE TO BURIED FINITE FAULT IN A SEMIINFINITE MEDIUM ***** 06270000
% C******************************************************************** 06280000
% C 06290000
% C***** INPUT 06300000
% C***** XI,ET,Q : STATION COORDINATES IN FAULT SYSTEM 06310000
% C***** DISL1-DISL3 : STRIKE-, DIP-, TENSILE-DISLOCATIONS 06320000
% C***** OUTPUT 06330000
% C***** U(12) : DISPLACEMENT AND THEIR DERIVATIVES 06340000
% C 06350000
% COMMON /C0/ALP1,ALP2,ALP3,ALP4,ALP5,SD,CD,SDSD,CDCD,SDCD,S2D,C2D 06360000
% COMMON /C2/XI2,ET2,Q2,R,R2,R3,R5,Y,D,TT,ALX,ALE,X11,Y11,X32,Y32, 06370000
% * EY,EZ,FY,FZ,GY,GZ,HY,HZ 06380000
global ALP1 ALP2 ALP3 ALP4 ALP5 SD CD SDSD CDCD SDCD S2D C2D
global XI2 ET2 Q2 R R2 R3 R5 Y D TT ALX ALE X11 Y11 X32 Y32
global EY EZ FY FZ GY GZ HY HZ
global N_CELL
% DATA F0,F2,PI2/0.D0,2.D0,6.283185307179586D0/ 06390000
F0 = zeros(N_CELL,1,'double');
F2 = ones(N_CELL,1,'double').*2.0;
PI2 = ones(N_CELL,1,'double').*6.283185307179586;
DU = zeros(N_CELL,12,'double');
du1 = zeros(N_CELL,12,'double');
du2 = zeros(N_CELL,12,'double');
du3 = zeros(N_CELL,12,'double');
%C-----
%for I=1:1:12
U(1:N_CELL,1:12)=0.0;
%end
XY=XI.*Y11;
QX=Q .*X11;
QY=Q .*Y11;
% C====================================== 06460000
% C===== STRIKE-SLIP CONTRIBUTION ===== 06470000
% C====================================== 06480000
% if DISL1~=F0
c1 = DISL1 ~= F0;
du1(:,1)= TT./F2 +ALP2.*XI.*QY;
du1(:,2)= ALP2.*Q./R;
du1(:,3)= ALP1.*ALE -ALP2.*Q.*QY;
du1(:,4)=-ALP1.*QY -ALP2.*XI2.*Q.*Y32;
du1(:,5)= -ALP2.*XI.*Q./R3;
du1(:,6)= ALP1.*XY +ALP2.*XI.*Q2.*Y32;
du1(:,7)= ALP1.*XY.*SD +ALP2.*XI.*FY+D./F2.*X11;
du1(:,8)= ALP2.*EY;
du1(:,9)= ALP1.*(CD./R+QY.*SD) -ALP2.*Q.*FY;
du1(:,10)= ALP1.*XY.*CD +ALP2.*XI.*FZ+Y./F2.*X11;
du1(:,11)= ALP2.*EZ;
du1(:,12)=-ALP1.*(SD./R-QY.*CD) -ALP2.*Q.*FZ;
% for I=1:1:12
U(1:N_CELL,1:12)=U(1:N_CELL,1:12)...
+repmat(DISL1./PI2,1,12).*du1(1:N_CELL,1:12)...
.*repmat(c1,1,12);
% end
% end
% C====================================== 06650000
% C===== DIP-SLIP CONTRIBUTION ===== 06660000
% C====================================== 06670000
% if DISL2~=F0
c2 = DISL2 ~= F0;
du2(:,1)= ALP2.*Q./R;
du2(:,2)= TT./F2 +ALP2.*ET.*QX;
du2(:,3)= ALP1.*ALX -ALP2.*Q.*QX;
du2(:,4)= -ALP2.*XI.*Q./R3;
du2(:,5)= -QY./F2 -ALP2.*ET.*Q./R3;
du2(:,6)= ALP1./R +ALP2.*Q2./R3;
du2(:,7)= ALP2.*EY;
du2(:,8)= ALP1.*D.*X11+XY./F2.*SD +ALP2.*ET.*GY;
du2(:,9)= ALP1.*Y.*X11 -ALP2.*Q.*GY;
du2(:,10)= ALP2.*EZ;
du2(:,11)= ALP1.*Y.*X11+XY./F2.*CD +ALP2.*ET.*GZ;
du2(:,12)=-ALP1.*D.*X11 -ALP2.*Q.*GZ;
% for I=1:1:12
U(1:N_CELL,1:12)=U(1:N_CELL,1:12)...
+repmat(DISL2./PI2,1,12).*du2(1:N_CELL,1:12)...
.*repmat(c2,1,12);
% end
% C======================================== 06840000
% C===== TENSILE-FAULT CONTRIBUTION ===== 06850000
% C======================================== 06860000
% if DISL3~=F0
c3 = DISL3 ~= F0;
du3(:,1)=-ALP1.*ALE -ALP2.*Q.*QY;
du3(:,2)=-ALP1.*ALX -ALP2.*Q.*QX;
du3(:,3)= TT./F2 -ALP2.*(ET.*QX+XI.*QY);
du3(:,4)=-ALP1.*XY +ALP2.*XI.*Q2.*Y32;
du3(:,5)=-ALP1./R +ALP2.*Q2./R3;
du3(:,6)=-ALP1.*QY -ALP2.*Q.*Q2.*Y32;
du3(:,7)=-ALP1.*(CD./R+QY.*SD) -ALP2.*Q.*FY;
du3(:,8)=-ALP1.*Y.*X11 -ALP2.*Q.*GY;
du3(:,9)= ALP1.*(D.*X11+XY.*SD) +ALP2.*Q.*HY;
du3(:,10)= ALP1.*(SD./R-QY.*CD) -ALP2.*Q.*FZ;
du3(:,11)= ALP1.*D.*X11 -ALP2.*Q.*GZ;
du3(:,12)= ALP1.*(Y.*X11+XY.*CD) +ALP2.*Q.*HZ;
% for I=1:1:12
U(1:N_CELL,1:12)=U(1:N_CELL,1:12)...
+repmat(DISL3./PI2,1,12).*du3(1:N_CELL,1:12)...
.*repmat(c3,1,12);
% end
% end
%
% RETURN 07030000
% END
% ------------------------------------------------------------------------------
function [U] = UB(XI,ET,Q,DISL1,DISL2,DISL3)
% DIMENSION U(12),DU(12)
% C 07080000
% C******************************************************************** 07090000
% C***** DISPLACEMENT AND STRAIN AT DEPTH (PART-B) ***** 07100000
% C***** DUE TO BURIED FINITE FAULT IN A SEMIINFINITE MEDIUM ***** 07110000
% C******************************************************************** 07120000
% C 07130000
% C***** INPUT 07140000
% C***** XI,ET,Q : STATION COORDINATES IN FAULT SYSTEM 07150000
% C***** DISL1-DISL3 : STRIKE-, DIP-, TENSILE-DISLOCATIONS 07160000
% C***** OUTPUT 07170000
% C***** U(12) : DISPLACEMENT AND THEIR DERIVATIVES 07180000
% C 07190000
% COMMON /C0/ALP1,ALP2,ALP3,ALP4,ALP5,SD,CD,SDSD,CDCD,SDCD,S2D,C2D 07200000
% COMMON /C2/XI2,ET2,Q2,R,R2,R3,R5,Y,D,TT,ALX,ALE,X11,Y11,X32,Y32, 07210000
% * EY,EZ,FY,FZ,GY,GZ,HY,HZ 07220000
global ALP2 ALP3 ALP4 ALP5 SD CD SDSD CDCD SDCD S2D C2D
global XI2 ET2 Q2 R R2 R3 R5 Y D TT ALX ALE X11 Y11 X32 Y32
global EY EZ FY FZ GY GZ HY HZ
global N_CELL
% DATA F0,F1,F2,PI2/0.D0,1.D0,2.D0,6.283185307179586D0/ 07230000
F0 = zeros(N_CELL,1,'double');
F1 = ones(N_CELL,1,'double');
F2 = ones(N_CELL,1,'double').*2.0;
PI2 = ones(N_CELL,1,'double').*6.283185307179586;
DU = zeros(N_CELL,12,'double');
%C----- 07240000
RD=R+D;
D11=F1./(R.*RD);
AJ2=XI.*Y./RD.*D11;
AJ5=-(D+Y.*Y./RD).*D11;
% if CD~=F0
c1 = CD ~= F0;
c2 = CD == F0;
s1 = XI == F0;
s2 = XI ~= F0;
% ----- To avoid 'Inf' and 'nan' troubles (divided by zero) ------
tempCD = CD;
tempCDCD = CDCD;
CD = c1.*CD + c2.*1.0e-12;
CDCD = c1.*CDCD + c2.*1.0e-12;
X=double(sqrt(XI2+Q2));
RD2=RD.*RD;
AI4 = c1.*(s1.*F0 + s2.*(F1./CDCD.*( XI./RD.*SDCD...
+F2.*atan((ET.*(X+Q.*CD)+X.*(R+X).*SD)./(XI.*(R+X).*CD)))))...
+c2.*(XI.*Y./RD2./F2);
AI3 = c1.*((Y.*CD./RD-ALE+SD.*double(log(RD)))./CDCD)...
+c2.*((ET./RD+Y.*Q./RD2-ALE)./F2);
AK1 = c1.*(XI.*(D11-Y11.*SD)./CD)+c2.*(XI.*Q./RD.*D11);
AK3 = c1.*((Q.*Y11-Y.*D11)./CD)+c2.*(SD./RD.*(XI2.*D11-F1));
AJ3 = c1.*((AK1-AJ2.*SD)./CD)+c2.*(-XI./RD2.*(Q2.*D11-F1./F2));
AJ6 = c1.*((AK3-AJ5.*SD)./CD)+c2.*(-Y./RD2.*(XI2.*D11-F1./F2));
CD = tempCD;
CDCD = tempCDCD;
% -----
XY=XI.*Y11;
AI1=-XI./RD.*CD-AI4.*SD;
AI2= double(log(RD))+AI3.*SD;
AK2= F1./R+AK3.*SD;
AK4= XY.*CD-AK1.*SD;
AJ1= AJ5.*CD-AJ6.*SD;
AJ4=-XY-AJ2.*CD+AJ3.*SD;
%C===== 07590000
% for I=1:1:12
U(1:N_CELL,1:12) = 0.0;
% end
QX=Q.*X11;
QY=Q.*Y11;
% C====================================== 07640000
% C===== STRIKE-SLIP CONTRIBUTION ===== 07650000
% C====================================== 07660000
% if DISL1~=F0
c1 = DISL1 ~= F0;
DU(:,1)=-XI.*QY-TT -ALP3.*AI1.*SD;
DU(:,2)=-Q./R +ALP3.*Y./RD.*SD;
DU(:,3)= Q.*QY -ALP3.*AI2.*SD;
DU(:,4)= XI2.*Q.*Y32 -ALP3.*AJ1.*SD;
DU(:,5)= XI.*Q./R3 -ALP3.*AJ2.*SD;
DU(:,6)=-XI.*Q2.*Y32 -ALP3.*AJ3.*SD;
DU(:,7)=-XI.*FY-D.*X11 +ALP3.*(XY+AJ4).*SD;
DU(:,8)=-EY +ALP3.*(F1./R+AJ5).*SD;
DU(:,9)= Q.*FY -ALP3.*(QY-AJ6).*SD;
DU(:,10)=-XI.*FZ-Y.*X11 +ALP3.*AK1.*SD;
DU(:,11)=-EZ +ALP3.*Y.*D11.*SD;
DU(:,12)= Q.*FZ +ALP3.*AK2.*SD;
% for I=1:1:12
U(1:N_CELL,1:12)=U(1:N_CELL,1:12)...
+repmat(DISL1./PI2,1,12).*DU(1:N_CELL,1:12)...
.*repmat(c1,1,12);
% end
% end
% C====================================== 07830000
% C===== DIP-SLIP CONTRIBUTION ===== 07840000
% C====================================== 07850000
% if DISL2~=F0
c2 = DISL2 ~= F0;
DU(:,1)=-Q./R +ALP3.*AI3.*SDCD;
DU(:,2)=-ET.*QX-TT -ALP3.*XI./RD.*SDCD;
DU(:,3)= Q.*QX +ALP3.*AI4.*SDCD;
DU(:,4)= XI.*Q./R3 +ALP3.*AJ4.*SDCD;
DU(:,5)= ET.*Q./R3+QY +ALP3.*AJ5.*SDCD;
DU(:,6)=-Q2./R3 +ALP3.*AJ6.*SDCD;
DU(:,7)=-EY +ALP3.*AJ1.*SDCD;
DU(:,8)=-ET.*GY-XY.*SD +ALP3.*AJ2.*SDCD;
DU(:,9)= Q.*GY +ALP3.*AJ3.*SDCD;
DU(:,10)=-EZ -ALP3.*AK3.*SDCD;
DU(:,11)=-ET.*GZ-XY.*CD -ALP3.*XI.*D11.*SDCD;
DU(:,12)= Q.*GZ -ALP3.*AK4.*SDCD;
% for I=1:1:12
U(1:N_CELL,1:12)=U(1:N_CELL,1:12)...
+repmat(DISL2./PI2,1,12).*DU(1:N_CELL,1:12)...
.*repmat(c2,1,12);
% end
% end
% C======================================== 08020000
% C===== TENSILE-FAULT CONTRIBUTION ===== 08030000
% C======================================== 08040000
% if DISL3~=F0
c3 = DISL3 ~= F0;
DU(:,1)= Q.*QY -ALP3.*AI3.*SDSD;
DU(:,2)= Q.*QX +ALP3.*XI./RD.*SDSD;
DU(:,3)= ET.*QX+XI.*QY-TT -ALP3.*AI4.*SDSD;
DU(:,4)=-XI.*Q2.*Y32 -ALP3.*AJ4.*SDSD;
DU(:,5)=-Q2./R3 -ALP3.*AJ5.*SDSD;
DU(:,6)= Q.*Q2.*Y32 -ALP3.*AJ6.*SDSD;
DU(:,7)= Q.*FY -ALP3.*AJ1.*SDSD;
DU(:,8)= Q.*GY -ALP3.*AJ2.*SDSD;
DU(:,9)=-Q.*HY -ALP3.*AJ3.*SDSD;
DU(:,10)= Q.*FZ +ALP3.*AK3.*SDSD;
DU(:,11)= Q.*GZ +ALP3.*XI.*D11.*SDSD;
DU(:,12)=-Q.*HZ +ALP3.*AK4.*SDSD;
% for I=1:1:12
U(1:N_CELL,1:12)=U(1:N_CELL,1:12)...
+repmat(DISL3./PI2,1,12).*DU(1:N_CELL,1:12)...
.*repmat(c3,1,12);
% end
% end
% RETURN 08210000
% END 08220000
% ------------------------------------------------------------------------------
function [U] = UC(XI,ET,Q,Z,DISL1,DISL2,DISL3)
%
% DIMENSION U(12),DU(12) 08250000
% C 08260000
% C******************************************************************** 08270000
% C***** DISPLACEMENT AND STRAIN AT DEPTH (PART-C) ***** 08280000
% C***** DUE TO BURIED FINITE FAULT IN A SEMIINFINITE MEDIUM ***** 08290000
% C******************************************************************** 08300000
% C 08310000
% C***** INPUT 08320000
% C***** XI,ET,Q,Z : STATION COORDINATES IN FAULT SYSTEM 08330000
% C***** DISL1-DISL3 : STRIKE-, DIP-, TENSILE-DISLOCATIONS 08340000
% C***** OUTPUT 08350000
% C***** U(12) : DISPLACEMENT AND THEIR DERIVATIVES 08360000
% C 08370000
% COMMON /C0/ALP1,ALP2,ALP3,ALP4,ALP5,SD,CD,SDSD,CDCD,SDCD,S2D,C2D 08380000
% COMMON /C2/XI2,ET2,Q2,R,R2,R3,R5,Y,D,TT,ALX,ALE,X11,Y11,X32,Y32, 08390000
% * EY,EZ,FY,FZ,GY,GZ,HY,HZ 08400000
global ALP1 ALP2 ALP3 ALP4 ALP5 SD CD SDSD CDCD SDCD S2D C2D
global XI2 ET2 Q2 R R2 R3 R5 Y D TT ALX ALE X11 Y11 X32 Y32
global EY EZ FY FZ GY GZ HY HZ
global N_CELL
% DATA F0,F1,F2,F3,PI2/0.D0,1.D0,2.D0,3.D0,6.283185307179586D0/ 08410000
%F0 = double(0.0);
F0 = zeros(N_CELL,1,'double');
F1 = ones(N_CELL,1,'double');
F2 = ones(N_CELL,1,'double').*2.0;
F3 = ones(N_CELL,1,'double').*3.0;
PI2 = ones(N_CELL,1,'double').*6.283185307179586;
DU = zeros(N_CELL,12,'double');
%C----- 08420000
C=D+Z; %08430000
X53=(double(8.0).*R2+double(9.0).*R.*XI+F3.*XI2).*X11.*X11.*X11./R2;
Y53=(double(8.0).*R2+double(9.0).*R.*ET+F3.*ET2).*Y11.*Y11.*Y11./R2;
H=Q.*CD-Z;
Z32=SD./R3-H.*Y32;
Z53=F3.*SD./R5-H.*Y53;
Y0=Y11-XI2.*Y32;
Z0=Z32-XI2.*Z53;
PPY=CD./R3+Q.*Y32.*SD;
PPZ=SD./R3-Q.*Y32.*CD;
QQ=Z.*Y32+Z32+Z0;
QQY=F3.*C.*D./R5-QQ.*SD;
QQZ=F3.*C.*Y./R5-QQ.*CD+Q.*Y32;
XY=XI.*Y11;
QX=Q.*X11;
QY=Q.*Y11;
QR=F3.*Q./R5;
CQX=C.*Q.*X53;
CDR=(C+D)./R3;
YY0=Y./R3-Y0.*CD;
%C=====
% for I=1:1:12
U(1:N_CELL,1:12)=0.0;
% end
% C====================================== 08660000
% C===== STRIKE-SLIP CONTRIBUTION ===== 08670000
% C====================================== 08680000
% if DISL1~=F0
c1 = DISL1 ~= F0;
DU(:,1)= ALP4.*XY.*CD -ALP5.*XI.*Q.*Z32;
DU(:,2)= ALP4.*(CD./R+F2.*QY.*SD) -ALP5.*C.*Q./R3;
DU(:,3)= ALP4.*QY.*CD -ALP5.*(C.*ET./R3-Z.*Y11+XI2.*Z32);
DU(:,4)= ALP4.*Y0.*CD -ALP5.*Q.*Z0;
DU(:,5)=-ALP4.*XI.*(CD./R3+F2.*Q.*Y32.*SD) +ALP5.*C.*XI.*QR;
DU(:,6)=-ALP4.*XI.*Q.*Y32.*CD +ALP5.*XI.*(F3.*C.*ET./R5-QQ);
DU(:,7)=-ALP4.*XI.*PPY.*CD -ALP5.*XI.*QQY;
DU(:,8)= ALP4.*F2.*(D./R3-Y0.*SD).*SD-Y./R3.*CD...
-ALP5.*(CDR.*SD-ET./R3-C.*Y.*QR);
DU(:,9)=-ALP4.*Q./R3+YY0.*SD +ALP5.*(CDR.*CD+C.*D.*QR-(Y0.*CD+Q.*Z0).*SD);
DU(:,10)= ALP4.*XI.*PPZ.*CD -ALP5.*XI.*QQZ;
DU(:,11)= ALP4.*F2.*(Y./R3-Y0.*CD).*SD+D./R3.*CD -ALP5.*(CDR.*CD+C.*D.*QR);
DU(:,12)= YY0.*CD -ALP5.*(CDR.*SD-C.*Y.*QR-Y0.*SDSD+Q.*Z0.*CD);
% for I=1:1:12
U(1:N_CELL,1:12)=U(1:N_CELL,1:12)...
+repmat(DISL1./PI2,1,12).*DU(1:N_CELL,1:12)...
.*repmat(c1,1,12);
% end
% end
% C====================================== 08860000
% C===== DIP-SLIP CONTRIBUTION ===== 08870000
% C====================================== 08880000
% if DISL2~=F0
c2 = DISL2 ~= F0;
DU(:,1)= ALP4.*CD./R -QY.*SD -ALP5.*C.*Q./R3;
DU(:,2)= ALP4.*Y.*X11 -ALP5.*C.*ET.*Q.*X32;
DU(:,3)= -D.*X11-XY.*SD -ALP5.*C.*(X11-Q2.*X32);
DU(:,4)=-ALP4.*XI./R3.*CD +ALP5.*C.*XI.*QR +XI.*Q.*Y32.*SD;
DU(:,5)=-ALP4.*Y./R3 +ALP5.*C.*ET.*QR;
DU(:,6)= D./R3-Y0.*SD +ALP5.*C./R3.*(F1-F3.*Q2./R2);
DU(:,7)=-ALP4.*ET./R3+Y0.*SDSD -ALP5.*(CDR.*SD-C.*Y.*QR);
DU(:,8)= ALP4.*(X11-Y.*Y.*X32) -ALP5.*C.*((D+F2.*Q.*CD).*X32-Y.*ET.*Q.*X53);
DU(:,9)= XI.*PPY.*SD+Y.*D.*X32 +ALP5.*C.*((Y+F2.*Q.*SD).*X32-Y.*Q2.*X53);
DU(:,10)= -Q./R3+Y0.*SDCD -ALP5.*(CDR.*CD+C.*D.*QR);
DU(:,11)= ALP4.*Y.*D.*X32 -ALP5.*C.*((Y-F2.*Q.*SD).*X32+D.*ET.*Q.*X53);
DU(:,12)=-XI.*PPZ.*SD+X11-D.*D.*X32-ALP5.*C.*((D-F2.*Q.*CD).*X32-D.*Q2.*X53);
% for I=1:1:12
U(1:N_CELL,1:12)=U(1:N_CELL,1:12)...
+repmat(DISL2./PI2,1,12).*DU(1:N_CELL,1:12)...
.*repmat(c2,1,12);
% end
% end
% C======================================== 09050000
% C===== TENSILE-FAULT CONTRIBUTION ===== 09060000
% C======================================== 09070000
% if DISL3~=F0
c3 = DISL3 ~= F0;
DU(:,1)=-ALP4.*(SD./R+QY.*CD) -ALP5.*(Z.*Y11-Q2.*Z32);
DU(:,2)= ALP4.*F2.*XY.*SD+D.*X11 -ALP5.*C.*(X11-Q2.*X32);
DU(:,3)= ALP4.*(Y.*X11+XY.*CD) +ALP5.*Q.*(C.*ET.*X32+XI.*Z32);
DU(:,4)= ALP4.*XI./R3.*SD+XI.*Q.*Y32.*CD+ALP5.*XI.*(F3.*C.*ET./R5-F2.*Z32-Z0);
DU(:,5)= ALP4.*F2.*Y0.*SD-D./R3 +ALP5.*C./R3.*(F1-F3.*Q2./R2);
DU(:,6)=-ALP4.*YY0 -ALP5.*(C.*ET.*QR-Q.*Z0);
DU(:,7)= ALP4.*(Q./R3+Y0.*SDCD) +ALP5.*(Z./R3.*CD+C.*D.*QR-Q.*Z0.*SD);
DU(:,8)=-ALP4.*F2.*XI.*PPY.*SD-Y.*D.*X32...
+ALP5.*C.*((Y+F2.*Q.*SD).*X32-Y.*Q2.*X53);
DU(:,9)=-ALP4.*(XI.*PPY.*CD-X11+Y.*Y.*X32)...
+ALP5.*(C.*((D+F2.*Q.*CD).*X32-Y.*ET.*Q.*X53)+XI.*QQY);
DU(:,10)= -ET./R3+Y0.*CDCD -ALP5.*(Z./R3.*SD-C.*Y.*QR-Y0.*SDSD+Q.*Z0.*CD);
DU(:,11)= ALP4.*F2.*XI.*PPZ.*SD-X11+D.*D.*X32...
-ALP5.*C.*((D-F2.*Q.*CD).*X32-D.*Q2.*X53);
DU(:,12)= ALP4.*(XI.*PPZ.*CD+Y.*D.*X32)...
+ALP5.*(C.*((Y-F2.*Q.*SD).*X32+D.*ET.*Q.*X53)+XI.*QQZ);
% for I=1:1:12
U(1:N_CELL,1:12)=U(1:N_CELL,1:12)...
+repmat(DISL3./PI2,1,12).*DU(1:N_CELL,1:12)...
.*repmat(c3,1,12);
% end
% end
% RETURN 09280000
% END 09290000
|
github
|
chaovite/crack_pipe-master
|
TDstressFS.m
|
.m
|
crack_pipe-master/source/TriDisloc3d/TDstressFS.m
| 13,751 |
utf_8
|
95ddebabb6cd9e49e3d39122c78e8974
|
function [Stress,Strain]=TDstressFS(X,Y,Z,P1,P2,P3,Ss,Ds,Ts,mu,lambda)
% TDstressFS
% Calculates stresses and strains associated with a triangular dislocation
% in an elastic full-space.
%
% TD: Triangular Dislocation
% EFCS: Earth-Fixed Coordinate System
% TDCS: Triangular Dislocation Coordinate System
% ADCS: Angular Dislocation Coordinate System
%
% INPUTS
% X, Y and Z:
% Coordinates of calculation points in EFCS (East, North, Up). X, Y and Z
% must have the same size.
%
% P1,P2 and P3:
% Coordinates of TD vertices in EFCS.
%
% Ss, Ds and Ts:
% TD slip vector components (Strike-slip, Dip-slip, Tensile-slip).
%
% mu and lambda:
% Lame constants.
%
% OUTPUTS
% Stress:
% Calculated stress tensor components in EFCS. The six columns of Stress
% are Sxx, Syy, Szz, Sxy, Sxz and Syz, respectively. The stress components
% have the same unit as Lame constants.
%
% Strain:
% Calculated strain tensor components in EFCS. The six columns of Strain
% are Exx, Eyy, Ezz, Exy, Exz and Eyz, respectively. The strain components
% are dimensionless.
%
%
% Example: Calculate and plot the first component of stress tensor on a
% regular grid.
%
% [X,Y,Z] = meshgrid(-3:.02:3,-3:.02:3,2);
% [Stress,Strain] = TDstressFS(X,Y,Z,[-1 0 0],[1 -1 -1],[0 1.5 .5],...
% -1,2,3,.33e11,.33e11);
% h = surf(X,Y,reshape(Stress(:,1),size(X)),'edgecolor','none');
% view(2)
% axis equal
% axis tight
% set(gcf,'renderer','painters')
% Reference journal article:
% Nikkhoo M. and Walter T.R., 2015. Triangular dislocation: An analytical,
% artefact-free solution.
% Submitted to Geophysical Journal International
% Copyright (c) 2014 Mehdi Nikkhoo
%
% Permission is hereby granted, free of charge, to any person obtaining a
% copy of this software and associated documentation files
% (the "Software"), to deal in the Software without restriction, including
% without limitation the rights to use, copy, modify, merge, publish,
% distribute, sublicense, and/or sell copies of the Software, and to permit
% persons to whom the Software is furnished to do so, subject to the
% following conditions:
%
% The above copyright notice and this permission notice shall be included
% in all copies or substantial portions of the Software.
%
% THE SOFTWARE 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. IN
% NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
% DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
% OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
% USE OR OTHER DEALINGS IN THE SOFTWARE.
% I appreciate any comments or bug reports.
% Mehdi Nikkhoo
% created: 2012.5.14
% Last modified: 2014.7.30
%
% VolcanoTectonics Research Group
% Section 2.1, Physics of Earthquakes and Volcanoes
% Department 2, Physics of the Earth
% Helmholtz Centre Potsdam
% German Research Centre for Geosciences (GFZ)
%
% Email:
% [email protected]
% [email protected]
nu = 1/(1+lambda/mu)/2; % Poisson's ratio
bx = Ts; % Tensile-slip
by = Ss; % Strike-slip
bz = Ds; % Dip-slip
X = X(:);
Y = Y(:);
Z = Z(:);
P1 = P1(:);
P2 = P2(:);
P3 = P3(:);
% Calculate unit strike, dip and normal to TD vectors: For a horizontal TD
% as an exception, if the normal vector points upward, the strike and dip
% vectors point Northward and Westward, whereas if the normal vector points
% downward, the strike and dip vectors point Southward and Westward,
% respectively.
Vnorm = cross(P2-P1,P3-P1);
Vnorm = Vnorm/norm(Vnorm);
eY = [0 1 0]';
eZ = [0 0 1]';
Vstrike = cross(eZ,Vnorm);
if norm(Vstrike)==0
Vstrike = eY*Vnorm(3);
end
Vstrike = Vstrike/norm(Vstrike);
Vdip = cross(Vnorm,Vstrike);
% Transform coordinates from EFCS into TDCS
p1 = zeros(3,1);
p2 = zeros(3,1);
p3 = zeros(3,1);
A = [Vnorm Vstrike Vdip]';
[x,y,z] = CoordTrans(X'-P2(1),Y'-P2(2),Z'-P2(3),A);
[p1(1),p1(2),p1(3)] = CoordTrans(P1(1)-P2(1),P1(2)-P2(2),P1(3)-P2(3),A);
[p3(1),p3(2),p3(3)] = CoordTrans(P3(1)-P2(1),P3(2)-P2(2),P3(3)-P2(3),A);
% Calculate the unit vectors along TD sides in TDCS
e12 = (p2-p1)/norm(p2-p1);
e13 = (p3-p1)/norm(p3-p1);
e23 = (p3-p2)/norm(p3-p2);
% Calculate the TD angles
A = acos(e12'*e13);
B = acos(-e12'*e23);
C = acos(e23'*e13);
% Determine the best arteact-free configuration for each calculation point
Trimode = trimodefinder(y,z,x,p1(2:3),p2(2:3),p3(2:3));
casepLog = Trimode==1;
casenLog = Trimode==-1;
casezLog = Trimode==0;
xp = x(casepLog);
yp = y(casepLog);
zp = z(casepLog);
xn = x(casenLog);
yn = y(casenLog);
zn = z(casenLog);
% Configuration I
if nnz(casepLog)~=0
% Calculate first angular dislocation contribution
[Exx1Tp,Eyy1Tp,Ezz1Tp,Exy1Tp,Exz1Tp,Eyz1Tp] = TDSetupS(xp,yp,zp,A,...
bx,by,bz,nu,p1,-e13);
% Calculate second angular dislocation contribution
[Exx2Tp,Eyy2Tp,Ezz2Tp,Exy2Tp,Exz2Tp,Eyz2Tp] = TDSetupS(xp,yp,zp,B,...
bx,by,bz,nu,p2,e12);
% Calculate third angular dislocation contribution
[Exx3Tp,Eyy3Tp,Ezz3Tp,Exy3Tp,Exz3Tp,Eyz3Tp] = TDSetupS(xp,yp,zp,C,...
bx,by,bz,nu,p3,e23);
end
% Configuration II
if nnz(casenLog)~=0
% Calculate first angular dislocation contribution
[Exx1Tn,Eyy1Tn,Ezz1Tn,Exy1Tn,Exz1Tn,Eyz1Tn] = TDSetupS(xn,yn,zn,A,...
bx,by,bz,nu,p1,e13);
% Calculate second angular dislocation contribution
[Exx2Tn,Eyy2Tn,Ezz2Tn,Exy2Tn,Exz2Tn,Eyz2Tn] = TDSetupS(xn,yn,zn,B,...
bx,by,bz,nu,p2,-e12);
% Calculate third angular dislocation contribution
[Exx3Tn,Eyy3Tn,Ezz3Tn,Exy3Tn,Exz3Tn,Eyz3Tn] = TDSetupS(xn,yn,zn,C,...
bx,by,bz,nu,p3,-e23);
end
% Calculate the strain tensor components in TDCS
if nnz(casepLog)~=0
exx(casepLog,1) = Exx1Tp+Exx2Tp+Exx3Tp;
eyy(casepLog,1) = Eyy1Tp+Eyy2Tp+Eyy3Tp;
ezz(casepLog,1) = Ezz1Tp+Ezz2Tp+Ezz3Tp;
exy(casepLog,1) = Exy1Tp+Exy2Tp+Exy3Tp;
exz(casepLog,1) = Exz1Tp+Exz2Tp+Exz3Tp;
eyz(casepLog,1) = Eyz1Tp+Eyz2Tp+Eyz3Tp;
end
if nnz(casenLog)~=0
exx(casenLog,1) = Exx1Tn+Exx2Tn+Exx3Tn;
eyy(casenLog,1) = Eyy1Tn+Eyy2Tn+Eyy3Tn;
ezz(casenLog,1) = Ezz1Tn+Ezz2Tn+Ezz3Tn;
exy(casenLog,1) = Exy1Tn+Exy2Tn+Exy3Tn;
exz(casenLog,1) = Exz1Tn+Exz2Tn+Exz3Tn;
eyz(casenLog,1) = Eyz1Tn+Eyz2Tn+Eyz3Tn;
end
if nnz(casezLog)~=0
exx(casezLog,1) = nan;
eyy(casezLog,1) = nan;
ezz(casezLog,1) = nan;
exy(casezLog,1) = nan;
exz(casezLog,1) = nan;
eyz(casezLog,1) = nan;
end
% Transform the strain tensor components from TDCS into EFCS
[Exx,Eyy,Ezz,Exy,Exz,Eyz] = TensTrans(exx,eyy,ezz,exy,exz,eyz,...
[Vnorm,Vstrike,Vdip]);
% Calculate the stress tensor components in EFCS
Sxx = 2*mu*Exx+lambda*(Exx+Eyy+Ezz);
Syy = 2*mu*Eyy+lambda*(Exx+Eyy+Ezz);
Szz = 2*mu*Ezz+lambda*(Exx+Eyy+Ezz);
Sxy = 2*mu*Exy;
Sxz = 2*mu*Exz;
Syz = 2*mu*Eyz;
Strain = [Exx,Eyy,Ezz,Exy,Exz,Eyz];
Stress = [Sxx,Syy,Szz,Sxy,Sxz,Syz];
function [Txx2,Tyy2,Tzz2,Txy2,Txz2,Tyz2]=TensTrans(Txx1,Tyy1,Tzz1,Txy1,...
Txz1,Tyz1,A)
% TensTrans Transforms the coordinates of tensors,from x1y1z1 coordinate
% system to x2y2z2 coordinate system. "A" is the transformation matrix,
% whose columns e1,e2 and e3 are the unit base vectors of the x1y1z1. The
% coordinates of e1,e2 and e3 in A must be given in x2y2z2. The transpose
% of A (i.e., A') does the transformation from x2y2z2 into x1y1z1.
Txx2 = A(1)^2*Txx1+2*A(1)*A(4)*Txy1+2*A(1)*A(7)*Txz1+2*A(4)*A(7)*Tyz1+...
A(4)^2*Tyy1+A(7)^2*Tzz1;
Tyy2 = A(2)^2*Txx1+2*A(2)*A(5)*Txy1+2*A(2)*A(8)*Txz1+2*A(5)*A(8)*Tyz1+...
A(5)^2*Tyy1+A(8)^2*Tzz1;
Tzz2 = A(3)^2*Txx1+2*A(3)*A(6)*Txy1+2*A(3)*A(9)*Txz1+2*A(6)*A(9)*Tyz1+...
A(6)^2*Tyy1+A(9)^2*Tzz1;
Txy2 = A(1)*A(2)*Txx1+(A(1)*A(5)+A(2)*A(4))*Txy1+(A(1)*A(8)+...
A(2)*A(7))*Txz1+(A(8)*A(4)+A(7)*A(5))*Tyz1+A(5)*A(4)*Tyy1+...
A(7)*A(8)*Tzz1;
Txz2 = A(1)*A(3)*Txx1+(A(1)*A(6)+A(3)*A(4))*Txy1+(A(1)*A(9)+...
A(3)*A(7))*Txz1+(A(9)*A(4)+A(7)*A(6))*Tyz1+A(6)*A(4)*Tyy1+...
A(7)*A(9)*Tzz1;
Tyz2 = A(2)*A(3)*Txx1+(A(3)*A(5)+A(2)*A(6))*Txy1+(A(3)*A(8)+...
A(2)*A(9))*Txz1+(A(8)*A(6)+A(9)*A(5))*Tyz1+A(5)*A(6)*Tyy1+...
A(8)*A(9)*Tzz1;
function [X1,X2,X3]=CoordTrans(x1,x2,x3,A)
% CoordTrans transforms the coordinates of the vectors, from
% x1x2x3 coordinate system to X1X2X3 coordinate system. "A" is the
% transformation matrix, whose columns e1,e2 and e3 are the unit base
% vectors of the x1x2x3. The coordinates of e1,e2 and e3 in A must be given
% in X1X2X3. The transpose of A (i.e., A') will transform the coordinates
% from X1X2X3 into x1x2x3.
x1 = x1(:);
x2 = x2(:);
x3 = x3(:);
r = A*[x1';x2';x3'];
X1 = r(1,:)';
X2 = r(2,:)';
X3 = r(3,:)';
function [trimode]=trimodefinder(x,y,z,p1,p2,p3)
% trimodefinder calculates the normalized barycentric coordinates of
% the points with respect to the TD vertices and specifies the appropriate
% artefact-free configuration of the angular dislocations for the
% calculations. The input matrices x, y and z share the same size and
% correspond to the y, z and x coordinates in the TDCS, respectively. p1,
% p2 and p3 are two-component matrices representing the y and z coordinates
% of the TD vertices in the TDCS, respectively.
% The components of the output (trimode) corresponding to each calculation
% points, are 1 for the first configuration, -1 for the second
% configuration and 0 for the calculation point that lie on the TD sides.
x = x(:);
y = y(:);
z = z(:);
a = ((p2(2)-p3(2)).*(x-p3(1))+(p3(1)-p2(1)).*(y-p3(2)))./...
((p2(2)-p3(2)).*(p1(1)-p3(1))+(p3(1)-p2(1)).*(p1(2)-p3(2)));
b = ((p3(2)-p1(2)).*(x-p3(1))+(p1(1)-p3(1)).*(y-p3(2)))./...
((p2(2)-p3(2)).*(p1(1)-p3(1))+(p3(1)-p2(1)).*(p1(2)-p3(2)));
c = 1-a-b;
trimode = ones(length(x),1);
trimode(a<=0 & b>c & c>a) = -1;
trimode(b<=0 & c>a & a>b) = -1;
trimode(c<=0 & a>b & b>c) = -1;
trimode(a==0 & b>=0 & c>=0) = 0;
trimode(a>=0 & b==0 & c>=0) = 0;
trimode(a>=0 & b>=0 & c==0) = 0;
trimode(trimode==0 & z~=0) = 1;
function [exx,eyy,ezz,exy,exz,eyz]=TDSetupS(x,y,z,alpha,bx,by,bz,nu,...
TriVertex,SideVec)
% TDSetupS transforms coordinates of the calculation points as well as
% slip vector components from ADCS into TDCS. It then calculates the
% strains in ADCS and transforms them into TDCS.
% Transformation matrix
A = [[SideVec(3);-SideVec(2)] SideVec(2:3)]';
% Transform coordinates of the calculation points from TDCS into ADCS
r1 = A*[y'-TriVertex(2);z'-TriVertex(3)];
y1 = r1(1,:)';
z1 = r1(2,:)';
% Transform the in-plane slip vector components from TDCS into ADCS
r2 = A*[by;bz];
by1 = r2(1,:)';
bz1 = r2(2,:)';
% Calculate strains associated with an angular dislocation in ADCS
[exx,eyy,ezz,exy,exz,eyz] = AngDisStrain(x,y1,z1,-pi+alpha,bx,by1,bz1,nu);
% Transform strains from ADCS into TDCS
B = [[1 0 0];[zeros(2,1),A']]; % 3x3 Transformation matrix
[exx,eyy,ezz,exy,exz,eyz] = TensTrans(exx,eyy,ezz,exy,exz,eyz,B);
function [Exx,Eyy,Ezz,Exy,Exz,Eyz]=AngDisStrain(x,y,z,alpha,bx,by,bz,nu)
% AngDisStrain calculates the strains associated with an angular
% dislocation in an elastic full-space.
sinA = sin(alpha);
cosA = cos(alpha);
eta = y.*cosA-z.*sinA;
zeta = y.*sinA+z.*cosA;
x2 = x.^2;
y2 = y.^2;
z2 = z.^2;
r2 = x2+y2+z2;
r = sqrt(r2);
r3 = r.*r2;
rz = r.*(r-z);
r2z2 = r2.*(r-z).^2;
r3z = r3.*(r-z);
W = zeta-r;
W2 = W.^2;
Wr = W.*r;
W2r = W2.*r;
Wr3 = W.*r3;
W2r2 = W2.*r2;
C = (r*cosA-z)./Wr;
S = (r*sinA-y)./Wr;
% Partial derivatives of the Burgers' function
rFi_rx = (eta./r./(r-zeta)-y./r./(r-z))/4/pi;
rFi_ry = (x./r./(r-z)-cosA*x./r./(r-zeta))/4/pi;
rFi_rz = (sinA*x./r./(r-zeta))/4/pi;
Exx = bx.*(rFi_rx)+...
bx/8/pi/(1-nu)*(eta./Wr+eta.*x2./W2r2-eta.*x2./Wr3+y./rz-...
x2.*y./r2z2-x2.*y./r3z)-...
by*x/8/pi/(1-nu).*(((2*nu+1)./Wr+x2./W2r2-x2./Wr3)*cosA+...
(2*nu+1)./rz-x2./r2z2-x2./r3z)+...
bz*x*sinA/8/pi/(1-nu).*((2*nu+1)./Wr+x2./W2r2-x2./Wr3);
Eyy = by.*(rFi_ry)+...
bx/8/pi/(1-nu)*((1./Wr+S.^2-y2./Wr3).*eta+(2*nu+1)*y./rz-y.^3./r2z2-...
y.^3./r3z-2*nu*cosA*S)-...
by*x/8/pi/(1-nu).*(1./rz-y2./r2z2-y2./r3z+...
(1./Wr+S.^2-y2./Wr3)*cosA)+...
bz*x*sinA/8/pi/(1-nu).*(1./Wr+S.^2-y2./Wr3);
Ezz = bz.*(rFi_rz)+...
bx/8/pi/(1-nu)*(eta./W./r+eta.*C.^2-eta.*z2./Wr3+y.*z./r3+...
2*nu*sinA*C)-...
by*x/8/pi/(1-nu).*((1./Wr+C.^2-z2./Wr3)*cosA+z./r3)+...
bz*x*sinA/8/pi/(1-nu).*(1./Wr+C.^2-z2./Wr3);
Exy = bx.*(rFi_ry)./2+by.*(rFi_rx)./2-...
bx/8/pi/(1-nu).*(x.*y2./r2z2-nu*x./rz+x.*y2./r3z-nu*x*cosA./Wr+...
eta.*x.*S./Wr+eta.*x.*y./Wr3)+...
by/8/pi/(1-nu)*(x2.*y./r2z2-nu*y./rz+x2.*y./r3z+nu*cosA*S+...
x2.*y*cosA./Wr3+x2*cosA.*S./Wr)-...
bz*sinA/8/pi/(1-nu).*(nu*S+x2.*S./Wr+x2.*y./Wr3);
Exz = bx.*(rFi_rz)./2+bz.*(rFi_rx)./2-...
bx/8/pi/(1-nu)*(-x.*y./r3+nu*x*sinA./Wr+eta.*x.*C./Wr+...
eta.*x.*z./Wr3)+...
by/8/pi/(1-nu)*(-x2./r3+nu./r+nu*cosA*C+x2.*z*cosA./Wr3+...
x2*cosA.*C./Wr)-...
bz*sinA/8/pi/(1-nu).*(nu*C+x2.*C./Wr+x2.*z./Wr3);
Eyz = by.*(rFi_rz)./2+bz.*(rFi_ry)./2+...
bx/8/pi/(1-nu).*(y2./r3-nu./r-nu*cosA*C+nu*sinA*S+eta*sinA*cosA./W2-...
eta.*(y*cosA+z*sinA)./W2r+eta.*y.*z./W2r2-eta.*y.*z./Wr3)-...
by*x/8/pi/(1-nu).*(y./r3+sinA*cosA^2./W2-cosA*(y*cosA+z*sinA)./...
W2r+y.*z*cosA./W2r2-y.*z*cosA./Wr3)-...
bz*x*sinA/8/pi/(1-nu).*(y.*z./Wr3-sinA*cosA./W2+(y*cosA+z*sinA)./...
W2r-y.*z./W2r2);
|
github
|
chaovite/crack_pipe-master
|
TDdispHS.m
|
.m
|
crack_pipe-master/source/TriDisloc3d/TDdispHS.m
| 19,206 |
utf_8
|
733bdbfdf3c4c66242e92cfcb69b7d73
|
function [ue,un,uv]=TDdispHS(X,Y,Z,P1,P2,P3,Ss,Ds,Ts,nu)
% TDdispHS
% Calculates displacements associated with a triangular dislocation in an
% elastic half-space.
%
% TD: Triangular Dislocation
% EFCS: Earth-Fixed Coordinate System
% TDCS: Triangular Dislocation Coordinate System
% ADCS: Angular Dislocation Coordinate System
%
% INPUTS
% X, Y and Z:
% Coordinates of calculation points in EFCS (East, North, Up). X, Y and Z
% must have the same size.
%
% P1,P2 and P3:
% Coordinates of TD vertices in EFCS.
%
% Ss, Ds and Ts:
% TD slip vector components (Strike-slip, Dip-slip, Tensile-slip).
%
% nu:
% Poisson's ratio.
%
% OUTPUTS
% ue, un and uv:
% Calculated displacement vector components in EFCS. ue, un and uv have
% the same unit as Ss, Ds and Ts in the inputs.
%
%
% Example: Calculate and plot the first component of displacement vector
% on a regular grid.
%
% [X,Y,Z] = meshgrid(-3:.02:3,-3:.02:3,-5);
% [ue,un,uv] = TDdispHS(X,Y,Z,[-1 0 0],[1 -1 -1],[0 1.5 -2],-1,2,3,.25);
% h = surf(X,Y,reshape(ue,size(X)),'edgecolor','none');
% view(2)
% axis equal
% axis tight
% set(gcf,'renderer','painters')
% Reference journal article:
% Nikkhoo M. and Walter T.R., 2015. Triangular dislocation: An analytical,
% artefact-free solution.
% Submitted to Geophysical Journal International
% Copyright (c) 2014 Mehdi Nikkhoo
%
% Permission is hereby granted, free of charge, to any person obtaining a
% copy of this software and associated documentation files
% (the "Software"), to deal in the Software without restriction, including
% without limitation the rights to use, copy, modify, merge, publish,
% distribute, sublicense, and/or sell copies of the Software, and to permit
% persons to whom the Software is furnished to do so, subject to the
% following conditions:
%
% The above copyright notice and this permission notice shall be included
% in all copies or substantial portions of the Software.
%
% THE SOFTWARE 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. IN
% NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
% DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
% OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
% USE OR OTHER DEALINGS IN THE SOFTWARE.
% I appreciate any comments or bug reports.
% Mehdi Nikkhoo
% created: 2013.1.24
% Last modified: 2014.7.30
%
% VolcanoTectonics Research Group
% Section 2.1, Physics of Earthquakes and Volcanoes
% Department 2, Physics of the Earth
% Helmholtz Centre Potsdam
% German Research Centre for Geosciences (GFZ)
%
% email:
% [email protected]
% [email protected]
if any(Z>0 | P1(3)>0 | P2(3)>0 | P3(3)>0)
error('Half-space solution: Z coordinates must be negative!')
end
X = X(:);
Y = Y(:);
Z = Z(:);
P1 = P1(:);
P2 = P2(:);
P3 = P3(:);
% Calculate main dislocation contribution to displacements
[ueMS,unMS,uvMS] = TDdispFS(X,Y,Z,P1,P2,P3,Ss,Ds,Ts,nu);
% Calculate harmonic function contribution to displacements
[ueFSC,unFSC,uvFSC] = TDdisp_HarFunc(X,Y,Z,P1,P2,P3,Ss,Ds,Ts,nu);
% Calculate image dislocation contribution to displacements
P1(3) = -P1(3);
P2(3) = -P2(3);
P3(3) = -P3(3);
[ueIS,unIS,uvIS] = TDdispFS(X,Y,Z,P1,P2,P3,Ss,Ds,Ts,nu);
if P1(3)==0 && P2(3)==0 && P3(3)==0
uvIS = -uvIS;
end
% Calculate the complete displacement vector components in EFCS
ue = ueMS+ueIS+ueFSC;
un = unMS+unIS+unFSC;
uv = uvMS+uvIS+uvFSC;
if P1(3)==0 && P2(3)==0 && P3(3)==0
ue = -ue;
un = -un;
uv = -uv;
end
function [ue,un,uv]=TDdispFS(X,Y,Z,P1,P2,P3,Ss,Ds,Ts,nu)
% TDdispFS
% Calculates displacements associated with a triangular dislocation in an
% elastic full-space.
bx = Ts; % Tensile-slip
by = Ss; % Strike-slip
bz = Ds; % Dip-slip
% Calculate unit strike, dip and normal to TD vectors: For a horizontal TD
% as an exception, if the normal vector points upward, the strike and dip
% vectors point Northward and Westward, whereas if the normal vector points
% downward, the strike and dip vectors point Southward and Westward,
% respectively.
Vnorm = cross(P2-P1,P3-P1);
Vnorm = Vnorm/norm(Vnorm);
eY = [0 1 0]';
eZ = [0 0 1]';
Vstrike = cross(eZ,Vnorm);
if norm(Vstrike)==0
Vstrike = eY*Vnorm(3);
% For horizontal elements in case of half-space calculation!!!
% Correct the strike vector of image dislocation only
if P1(3)>0
Vstrike = -Vstrike;
end
end
Vstrike = Vstrike/norm(Vstrike);
Vdip = cross(Vnorm,Vstrike);
% Transform coordinates and slip vector components from EFCS into TDCS
p1 = zeros(3,1);
p2 = zeros(3,1);
p3 = zeros(3,1);
At = [Vnorm Vstrike Vdip]';
[x,y,z] = CoordTrans(X'-P2(1),Y'-P2(2),Z'-P2(3),At);
[p1(1),p1(2),p1(3)] = CoordTrans(P1(1)-P2(1),P1(2)-P2(2),P1(3)-P2(3),At);
[p3(1),p3(2),p3(3)] = CoordTrans(P3(1)-P2(1),P3(2)-P2(2),P3(3)-P2(3),At);
% Calculate the unit vectors along TD sides in TDCS
e12 = (p2-p1)/norm(p2-p1);
e13 = (p3-p1)/norm(p3-p1);
e23 = (p3-p2)/norm(p3-p2);
% Calculate the TD angles
A = acos(e12'*e13);
B = acos(-e12'*e23);
C = acos(e23'*e13);
% Determine the best arteact-free configuration for each calculation point
Trimode = trimodefinder(y,z,x,p1(2:3),p2(2:3),p3(2:3));
casepLog = Trimode==1;
casenLog = Trimode==-1;
casezLog = Trimode==0;
xp = x(casepLog);
yp = y(casepLog);
zp = z(casepLog);
xn = x(casenLog);
yn = y(casenLog);
zn = z(casenLog);
% Configuration I
if nnz(casepLog)~=0
% Calculate first angular dislocation contribution
[u1Tp,v1Tp,w1Tp] = TDSetupD(xp,yp,zp,A,bx,by,bz,nu,p1,-e13);
% Calculate second angular dislocation contribution
[u2Tp,v2Tp,w2Tp] = TDSetupD(xp,yp,zp,B,bx,by,bz,nu,p2,e12);
% Calculate third angular dislocation contribution
[u3Tp,v3Tp,w3Tp] = TDSetupD(xp,yp,zp,C,bx,by,bz,nu,p3,e23);
end
% Configuration II
if nnz(casenLog)~=0
% Calculate first angular dislocation contribution
[u1Tn,v1Tn,w1Tn] = TDSetupD(xn,yn,zn,A,bx,by,bz,nu,p1,e13);
% Calculate second angular dislocation contribution
[u2Tn,v2Tn,w2Tn] = TDSetupD(xn,yn,zn,B,bx,by,bz,nu,p2,-e12);
% Calculate third angular dislocation contribution
[u3Tn,v3Tn,w3Tn] = TDSetupD(xn,yn,zn,C,bx,by,bz,nu,p3,-e23);
end
% Calculate the "incomplete" displacement vector components in TDCS
if nnz(casepLog)~=0
u(casepLog,1) = u1Tp+u2Tp+u3Tp;
v(casepLog,1) = v1Tp+v2Tp+v3Tp;
w(casepLog,1) = w1Tp+w2Tp+w3Tp;
end
if nnz(casenLog)~=0
u(casenLog,1) = u1Tn+u2Tn+u3Tn;
v(casenLog,1) = v1Tn+v2Tn+v3Tn;
w(casenLog,1) = w1Tn+w2Tn+w3Tn;
end
if nnz(casezLog)~=0
u(casezLog,1) = nan;
v(casezLog,1) = nan;
w(casezLog,1) = nan;
end
% Calculate the Burgers' function contribution corresponding to the TD
a = [-x p1(2)-y p1(3)-z];
b = [-x -y -z];
c = [-x p3(2)-y p3(3)-z];
na = sqrt(sum(a.^2,2));
nb = sqrt(sum(b.^2,2));
nc = sqrt(sum(c.^2,2));
Fi = -2*atan2((a(:,1).*(b(:,2).*c(:,3)-b(:,3).*c(:,2))-...
a(:,2).*(b(:,1).*c(:,3)-b(:,3).*c(:,1))+...
a(:,3).*(b(:,1).*c(:,2)-b(:,2).*c(:,1))),...
(na.*nb.*nc+sum(a.*b,2).*nc+sum(a.*c,2).*nb+sum(b.*c,2).*na))/4/pi;
% Calculate the complete displacement vector components in TDCS
u = bx.*Fi+u;
v = by.*Fi+v;
w = bz.*Fi+w;
% Transform the complete displacement vector components from TDCS into EFCS
[ue,un,uv] = CoordTrans(u,v,w,[Vnorm Vstrike Vdip]);
function [ue,un,uv]=TDdisp_HarFunc(X,Y,Z,P1,P2,P3,Ss,Ds,Ts,nu)
% TDdisp_HarFunc calculates the harmonic function contribution to the
% displacements associated with a triangular dislocation in a half-space.
% The function cancels the surface normal tractions induced by the main and
% image dislocations.
bx = Ts; % Tensile-slip
by = Ss; % Strike-slip
bz = Ds; % Dip-slip
% Calculate unit strike, dip and normal to TD vectors: For a horizontal TD
% as an exception, if the normal vector points upward, the strike and dip
% vectors point Northward and Westward, whereas if the normal vector points
% downward, the strike and dip vectors point Southward and Westward,
% respectively.
Vnorm = cross(P2-P1,P3-P1);
Vnorm = Vnorm/norm(Vnorm);
eY = [0 1 0]';
eZ = [0 0 1]';
Vstrike = cross(eZ,Vnorm);
if norm(Vstrike)==0
Vstrike = eY*Vnorm(3);
end
Vstrike = Vstrike/norm(Vstrike);
Vdip = cross(Vnorm,Vstrike);
% Transform slip vector components from TDCS into EFCS
A = [Vnorm Vstrike Vdip];
[bX,bY,bZ] = CoordTrans(bx,by,bz,A);
% Calculate contribution of angular dislocation pair on each TD side
[u1,v1,w1] = AngSetupFSC(X,Y,Z,bX,bY,bZ,P1,P2,nu); % Side P1P2
[u2,v2,w2] = AngSetupFSC(X,Y,Z,bX,bY,bZ,P2,P3,nu); % Side P2P3
[u3,v3,w3] = AngSetupFSC(X,Y,Z,bX,bY,bZ,P3,P1,nu); % Side P3P1
% Calculate total harmonic function contribution to displacements
ue = u1+u2+u3;
un = v1+v2+v3;
uv = w1+w2+w3;
function [X1,X2,X3]=CoordTrans(x1,x2,x3,A)
% CoordTrans transforms the coordinates of the vectors, from
% x1x2x3 coordinate system to X1X2X3 coordinate system. "A" is the
% transformation matrix, whose columns e1,e2 and e3 are the unit base
% vectors of the x1x2x3. The coordinates of e1,e2 and e3 in A must be given
% in X1X2X3. The transpose of A (i.e., A') will transform the coordinates
% from X1X2X3 into x1x2x3.
x1 = x1(:);
x2 = x2(:);
x3 = x3(:);
r = A*[x1';x2';x3'];
X1 = r(1,:)';
X2 = r(2,:)';
X3 = r(3,:)';
function [trimode]=trimodefinder(x,y,z,p1,p2,p3)
% trimodefinder calculates the normalized barycentric coordinates of
% the points with respect to the TD vertices and specifies the appropriate
% artefact-free configuration of the angular dislocations for the
% calculations. The input matrices x, y and z share the same size and
% correspond to the y, z and x coordinates in the TDCS, respectively. p1,
% p2 and p3 are two-component matrices representing the y and z coordinates
% of the TD vertices in the TDCS, respectively.
% The components of the output (trimode) corresponding to each calculation
% points, are 1 for the first configuration, -1 for the second
% configuration and 0 for the calculation point that lie on the TD sides.
x = x(:);
y = y(:);
z = z(:);
a = ((p2(2)-p3(2)).*(x-p3(1))+(p3(1)-p2(1)).*(y-p3(2)))./...
((p2(2)-p3(2)).*(p1(1)-p3(1))+(p3(1)-p2(1)).*(p1(2)-p3(2)));
b = ((p3(2)-p1(2)).*(x-p3(1))+(p1(1)-p3(1)).*(y-p3(2)))./...
((p2(2)-p3(2)).*(p1(1)-p3(1))+(p3(1)-p2(1)).*(p1(2)-p3(2)));
c = 1-a-b;
trimode = ones(length(x),1);
trimode(a<=0 & b>c & c>a) = -1;
trimode(b<=0 & c>a & a>b) = -1;
trimode(c<=0 & a>b & b>c) = -1;
trimode(a==0 & b>=0 & c>=0) = 0;
trimode(a>=0 & b==0 & c>=0) = 0;
trimode(a>=0 & b>=0 & c==0) = 0;
trimode(trimode==0 & z~=0) = 1;
function [u,v,w]=TDSetupD(x,y,z,alpha,bx,by,bz,nu,TriVertex,SideVec)
% TDSetupD transforms coordinates of the calculation points as well as
% slip vector components from ADCS into TDCS. It then calculates the
% displacements in ADCS and transforms them into TDCS.
% Transformation matrix
A = [[SideVec(3);-SideVec(2)] SideVec(2:3)]';
% Transform coordinates of the calculation points from TDCS into ADCS
r1 = A*[y'-TriVertex(2);z'-TriVertex(3)];
y1 = r1(1,:)';
z1 = r1(2,:)';
% Transform the in-plane slip vector components from TDCS into ADCS
r2 = A*[by;bz];
by1 = r2(1,:)';
bz1 = r2(2,:)';
% Calculate displacements associated with an angular dislocation in ADCS
[u,v0,w0] = AngDisDisp(x,y1,z1,-pi+alpha,bx,by1,bz1,nu);
% Transform displacements from ADCS into TDCS
r3 = A'*[v0';w0'];
v = r3(1,:)';
w = r3(2,:)';
function [ue,un,uv]=AngSetupFSC(X,Y,Z,bX,bY,bZ,PA,PB,nu)
% AngSetupFSC calculates the Free Surface Correction to displacements
% associated with angular dislocation pair on each TD side.
% Calculate TD side vector and the angle of the angular dislocation pair
SideVec = PB-PA;
eZ = [0 0 1]';
beta = acos(-SideVec'*eZ/norm(SideVec));
if abs(beta)<eps || abs(pi-beta)<eps
ue = zeros(length(X),1);
un = zeros(length(X),1);
uv = zeros(length(X),1);
else
ey1 = [SideVec(1:2);0];
ey1 = ey1/norm(ey1);
ey3 = -eZ;
ey2 = cross(ey3,ey1);
A = [ey1,ey2,ey3]; % Transformation matrix
% Transform coordinates from EFCS to the first ADCS
[y1A,y2A,y3A] = CoordTrans(X-PA(1),Y-PA(2),Z-PA(3),A);
% Transform coordinates from EFCS to the second ADCS
[y1AB,y2AB,y3AB] = CoordTrans(SideVec(1),SideVec(2),SideVec(3),A);
y1B = y1A-y1AB;
y2B = y2A-y2AB;
y3B = y3A-y3AB;
% Transform slip vector components from EFCS to ADCS
[b1,b2,b3] = CoordTrans(bX,bY,bZ,A);
% Determine the best arteact-free configuration for the calculation
% points near the free furface
I = (beta*y1A)>=0;
% Configuration I
[v1A(I),v2A(I),v3A(I)] = AngDisDispFSC(y1A(I),y2A(I),y3A(I),...
-pi+beta,b1,b2,b3,nu,-PA(3));
[v1B(I),v2B(I),v3B(I)] = AngDisDispFSC(y1B(I),y2B(I),y3B(I),...
-pi+beta,b1,b2,b3,nu,-PB(3));
% Configuration II
[v1A(~I),v2A(~I),v3A(~I)] = AngDisDispFSC(y1A(~I),y2A(~I),y3A(~I),...
beta,b1,b2,b3,nu,-PA(3));
[v1B(~I),v2B(~I),v3B(~I)] = AngDisDispFSC(y1B(~I),y2B(~I),y3B(~I),...
beta,b1,b2,b3,nu,-PB(3));
% Calculate total Free Surface Correction to displacements in ADCS
v1 = v1B-v1A;
v2 = v2B-v2A;
v3 = v3B-v3A;
% Transform total Free Surface Correction to displacements from ADCS
% to EFCS
[ue,un,uv] = CoordTrans(v1,v2,v3,A');
end
function [u,v,w]=AngDisDisp(x,y,z,alpha,bx,by,bz,nu)
% AngDisDisp calculates the "incomplete" displacements (without the
% Burgers' function contribution) associated with an angular dislocation in
% an elastic full-space.
cosA = cos(alpha);
sinA = sin(alpha);
eta = y*cosA-z*sinA;
zeta = y*sinA+z*cosA;
r = sqrt(x.^2+y.^2+z.^2);
% Avoid complex results for the logarithmic terms
zeta(zeta>r) = r(zeta>r);
z(z>r) = r(z>r);
ux = bx/8/pi/(1-nu)*(x.*y./r./(r-z)-x.*eta./r./(r-zeta));
vx = bx/8/pi/(1-nu)*(eta*sinA./(r-zeta)-y.*eta./r./(r-zeta)+...
y.^2./r./(r-z)+(1-2*nu)*(cosA*log(r-zeta)-log(r-z)));
wx = bx/8/pi/(1-nu)*(eta*cosA./(r-zeta)-y./r-eta.*z./r./(r-zeta)-...
(1-2*nu)*sinA*log(r-zeta));
uy = by/8/pi/(1-nu)*(x.^2*cosA./r./(r-zeta)-x.^2./r./(r-z)-...
(1-2*nu)*(cosA*log(r-zeta)-log(r-z)));
vy = by*x/8/pi/(1-nu).*(y.*cosA./r./(r-zeta)-...
sinA*cosA./(r-zeta)-y./r./(r-z));
wy = by*x/8/pi/(1-nu).*(z*cosA./r./(r-zeta)-cosA^2./(r-zeta)+1./r);
uz = bz*sinA/8/pi/(1-nu).*((1-2*nu)*log(r-zeta)-x.^2./r./(r-zeta));
vz = bz*x*sinA/8/pi/(1-nu).*(sinA./(r-zeta)-y./r./(r-zeta));
wz = bz*x*sinA/8/pi/(1-nu).*(cosA./(r-zeta)-z./r./(r-zeta));
u = ux+uy+uz;
v = vx+vy+vz;
w = wx+wy+wz;
function [v1 v2 v3] = AngDisDispFSC(y1,y2,y3,beta,b1,b2,b3,nu,a)
% AngDisDispFSC calculates the harmonic function contribution to the
% displacements associated with an angular dislocation in an elastic
% half-space.
sinB = sin(beta);
cosB = cos(beta);
cotB = cot(beta);
y3b = y3+2*a;
z1b = y1*cosB+y3b*sinB;
z3b = -y1*sinB+y3b*cosB;
r2b = y1.^2+y2.^2+y3b.^2;
rb = sqrt(r2b);
Fib = 2*atan(-y2./(-(rb+y3b)*cot(beta/2)+y1)); % The Burgers' function
v1cb1 = b1/4/pi/(1-nu)*(-2*(1-nu)*(1-2*nu)*Fib*cotB.^2+(1-2*nu)*y2./...
(rb+y3b).*((1-2*nu-a./rb)*cotB-y1./(rb+y3b).*(nu+a./rb))+(1-2*nu).*...
y2.*cosB*cotB./(rb+z3b).*(cosB+a./rb)+a*y2.*(y3b-a)*cotB./rb.^3+y2.*...
(y3b-a)./(rb.*(rb+y3b)).*(-(1-2*nu)*cotB+y1./(rb+y3b).*(2*nu+a./rb)+...
a*y1./rb.^2)+y2.*(y3b-a)./(rb.*(rb+z3b)).*(cosB./(rb+z3b).*((rb*...
cosB+y3b).*((1-2*nu)*cosB-a./rb).*cotB+2*(1-nu)*(rb*sinB-y1)*cosB)-...
a.*y3b*cosB*cotB./rb.^2));
v2cb1 = b1/4/pi/(1-nu)*((1-2*nu)*((2*(1-nu)*cotB^2-nu)*log(rb+y3b)-(2*...
(1-nu)*cotB^2+1-2*nu)*cosB*log(rb+z3b))-(1-2*nu)./(rb+y3b).*(y1*...
cotB.*(1-2*nu-a./rb)+nu*y3b-a+y2.^2./(rb+y3b).*(nu+a./rb))-(1-2*...
nu).*z1b*cotB./(rb+z3b).*(cosB+a./rb)-a*y1.*(y3b-a)*cotB./rb.^3+...
(y3b-a)./(rb+y3b).*(-2*nu+1./rb.*((1-2*nu).*y1*cotB-a)+y2.^2./(rb.*...
(rb+y3b)).*(2*nu+a./rb)+a*y2.^2./rb.^3)+(y3b-a)./(rb+z3b).*(cosB^2-...
1./rb.*((1-2*nu).*z1b*cotB+a*cosB)+a*y3b.*z1b*cotB./rb.^3-1./(rb.*...
(rb+z3b)).*(y2.^2*cosB^2-a*z1b*cotB./rb.*(rb*cosB+y3b))));
v3cb1 = b1/4/pi/(1-nu)*(2*(1-nu)*(((1-2*nu)*Fib*cotB)+(y2./(rb+y3b).*(2*...
nu+a./rb))-(y2*cosB./(rb+z3b).*(cosB+a./rb)))+y2.*(y3b-a)./rb.*(2*...
nu./(rb+y3b)+a./rb.^2)+y2.*(y3b-a)*cosB./(rb.*(rb+z3b)).*(1-2*nu-...
(rb*cosB+y3b)./(rb+z3b).*(cosB+a./rb)-a*y3b./rb.^2));
v1cb2 = b2/4/pi/(1-nu)*((1-2*nu)*((2*(1-nu)*cotB^2+nu)*log(rb+y3b)-(2*...
(1-nu)*cotB^2+1)*cosB*log(rb+z3b))+(1-2*nu)./(rb+y3b).*(-(1-2*nu).*...
y1*cotB+nu*y3b-a+a*y1*cotB./rb+y1.^2./(rb+y3b).*(nu+a./rb))-(1-2*...
nu)*cotB./(rb+z3b).*(z1b*cosB-a*(rb*sinB-y1)./(rb*cosB))-a*y1.*...
(y3b-a)*cotB./rb.^3+(y3b-a)./(rb+y3b).*(2*nu+1./rb.*((1-2*nu).*y1*...
cotB+a)-y1.^2./(rb.*(rb+y3b)).*(2*nu+a./rb)-a*y1.^2./rb.^3)+(y3b-a)*...
cotB./(rb+z3b).*(-cosB*sinB+a*y1.*y3b./(rb.^3*cosB)+(rb*sinB-y1)./...
rb.*(2*(1-nu)*cosB-(rb*cosB+y3b)./(rb+z3b).*(1+a./(rb*cosB)))));
v2cb2 = b2/4/pi/(1-nu)*(2*(1-nu)*(1-2*nu)*Fib*cotB.^2+(1-2*nu)*y2./...
(rb+y3b).*(-(1-2*nu-a./rb)*cotB+y1./(rb+y3b).*(nu+a./rb))-(1-2*nu)*...
y2*cotB./(rb+z3b).*(1+a./(rb*cosB))-a*y2.*(y3b-a)*cotB./rb.^3+y2.*...
(y3b-a)./(rb.*(rb+y3b)).*((1-2*nu)*cotB-2*nu*y1./(rb+y3b)-a*y1./rb.*...
(1./rb+1./(rb+y3b)))+y2.*(y3b-a)*cotB./(rb.*(rb+z3b)).*(-2*(1-nu)*...
cosB+(rb*cosB+y3b)./(rb+z3b).*(1+a./(rb*cosB))+a*y3b./(rb.^2*cosB)));
v3cb2 = b2/4/pi/(1-nu)*(-2*(1-nu)*(1-2*nu)*cotB*(log(rb+y3b)-cosB*...
log(rb+z3b))-2*(1-nu)*y1./(rb+y3b).*(2*nu+a./rb)+2*(1-nu)*z1b./(rb+...
z3b).*(cosB+a./rb)+(y3b-a)./rb.*((1-2*nu)*cotB-2*nu*y1./(rb+y3b)-a*...
y1./rb.^2)-(y3b-a)./(rb+z3b).*(cosB*sinB+(rb*cosB+y3b)*cotB./rb.*...
(2*(1-nu)*cosB-(rb*cosB+y3b)./(rb+z3b))+a./rb.*(sinB-y3b.*z1b./...
rb.^2-z1b.*(rb*cosB+y3b)./(rb.*(rb+z3b)))));
v1cb3 = b3/4/pi/(1-nu)*((1-2*nu)*(y2./(rb+y3b).*(1+a./rb)-y2*cosB./(rb+...
z3b).*(cosB+a./rb))-y2.*(y3b-a)./rb.*(a./rb.^2+1./(rb+y3b))+y2.*...
(y3b-a)*cosB./(rb.*(rb+z3b)).*((rb*cosB+y3b)./(rb+z3b).*(cosB+a./...
rb)+a.*y3b./rb.^2));
v2cb3 = b3/4/pi/(1-nu)*((1-2*nu)*(-sinB*log(rb+z3b)-y1./(rb+y3b).*(1+a./...
rb)+z1b./(rb+z3b).*(cosB+a./rb))+y1.*(y3b-a)./rb.*(a./rb.^2+1./(rb+...
y3b))-(y3b-a)./(rb+z3b).*(sinB*(cosB-a./rb)+z1b./rb.*(1+a.*y3b./...
rb.^2)-1./(rb.*(rb+z3b)).*(y2.^2*cosB*sinB-a*z1b./rb.*(rb*cosB+y3b))));
v3cb3 = b3/4/pi/(1-nu)*(2*(1-nu)*Fib+2*(1-nu)*(y2*sinB./(rb+z3b).*(cosB+...
a./rb))+y2.*(y3b-a)*sinB./(rb.*(rb+z3b)).*(1+(rb*cosB+y3b)./(rb+...
z3b).*(cosB+a./rb)+a.*y3b./rb.^2));
v1 = v1cb1+v1cb2+v1cb3;
v2 = v2cb1+v2cb2+v2cb3;
v3 = v3cb1+v3cb2+v3cb3;
|
github
|
chaovite/crack_pipe-master
|
TDstressHS.m
|
.m
|
crack_pipe-master/source/TriDisloc3d/TDstressHS.m
| 45,581 |
utf_8
|
d5f7cd8bddd53eda49774969927762a3
|
function [Stress,Strain]=TDstressHS(X,Y,Z,P1,P2,P3,Ss,Ds,Ts,mu,lambda)
% TDstressHS
% Calculates stresses and strains associated with a triangular dislocation
% in an elastic half-space.
%
% TD: Triangular Dislocation
% EFCS: Earth-Fixed Coordinate System
% TDCS: Triangular Dislocation Coordinate System
% ADCS: Angular Dislocation Coordinate System
%
% INPUTS
% X, Y and Z:
% Coordinates of calculation points in EFCS (East, North, Up). X, Y and Z
% must have the same size.
%
% P1,P2 and P3:
% Coordinates of TD vertices in EFCS.
%
% Ss, Ds and Ts:
% TD slip vector components (Strike-slip, Dip-slip, Tensile-slip).
%
% mu and lambda:
% Lame constants.
%
% OUTPUTS
% Stress:
% Calculated stress tensor components in EFCS. The six columns of Stress
% are Sxx, Syy, Szz, Sxy, Sxz and Syz, respectively. The stress components
% have the same unit as Lame constants.
%
% Strain:
% Calculated strain tensor components in EFCS. The six columns of Strain
% are Exx, Eyy, Ezz, Exy, Exz and Eyz, respectively. The strain components
% are dimensionless.
%
%
% Example: Calculate and plot the first component of stress tensor on a
% regular grid.
%
% [X,Y,Z] = meshgrid(-3:.02:3,-3:.02:3,-5);
% [Stress,Strain] = TDstressHS(X,Y,Z,[-1 0 0],[1 -1 -1],[0 1.5 -2],...
% -1,2,3,.33e11,.33e11);
% h = surf(X,Y,reshape(Stress(:,1),size(X)),'edgecolor','none');
% view(2)
% axis equal
% axis tight
% set(gcf,'renderer','painters')
% Reference journal article:
% Nikkhoo M. and Walter T.R., 2015. Triangular dislocation: An analytical,
% artefact-free solution.
% Submitted to Geophysical Journal International
% Copyright (c) 2014 Mehdi Nikkhoo
%
% Permission is hereby granted, free of charge, to any person obtaining a
% copy of this software and associated documentation files
% (the "Software"), to deal in the Software without restriction, including
% without limitation the rights to use, copy, modify, merge, publish,
% distribute, sublicense, and/or sell copies of the Software, and to permit
% persons to whom the Software is furnished to do so, subject to the
% following conditions:
%
% The above copyright notice and this permission notice shall be included
% in all copies or substantial portions of the Software.
%
% THE SOFTWARE 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. IN
% NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
% DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
% OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
% USE OR OTHER DEALINGS IN THE SOFTWARE.
% I appreciate any comments or bug reports.
% Mehdi Nikkhoo
% created: 2013.1.28
% Last modified: 2014.7.30
%
% VolcanoTectonics Research Group
% Section 2.1, Physics of Earthquakes and Volcanoes
% Department 2, Physics of the Earth
% Helmholtz Centre Potsdam
% German Research Centre for Geosciences (GFZ)
%
% email:
% [email protected]
% [email protected]
if any(Z>0 | P1(3)>0 | P2(3)>0 | P3(3)>0)
error('Half-space solution: Z coordinates must be negative!')
end
X = X(:);
Y = Y(:);
Z = Z(:);
P1 = P1(:);
P2 = P2(:);
P3 = P3(:);
% Calculate main dislocation contribution to strains and stresses
[StsMS,StrMS] = TDstressFS(X,Y,Z,P1,P2,P3,Ss,Ds,Ts,mu,lambda);
% Calculate harmonic function contribution to strains and stresses
[StsFSC,StrFSC] = TDstress_HarFunc(X,Y,Z,P1,P2,P3,Ss,Ds,Ts,mu,lambda);
% Calculate image dislocation contribution to strains and stresses
P1(3) = -P1(3);
P2(3) = -P2(3);
P3(3) = -P3(3);
[StsIS,StrIS] = TDstressFS(X,Y,Z,P1,P2,P3,Ss,Ds,Ts,mu,lambda);
if P1(3)==0 && P2(3)==0 && P3(3)==0
StsIS(:,5) = -StsIS(:,5);
StsIS(:,6) = -StsIS(:,6);
StrIS(:,5) = -StrIS(:,5);
StrIS(:,6) = -StrIS(:,6);
end
% Calculate the complete stress and strain tensor components in EFCS
Stress = StsMS+StsIS+StsFSC;
Strain = StrMS+StrIS+StrFSC;
function [Stress,Strain]=TDstressFS(X,Y,Z,P1,P2,P3,Ss,Ds,Ts,mu,lambda)
% TDstressFS
% Calculates stresses and strains associated with a triangular dislocation
% in an elastic full-space.
nu = 1/(1+lambda/mu)/2; % Poisson's ratio
bx = Ts; % Tensile-slip
by = Ss; % Strike-slip
bz = Ds; % Dip-slip
% Calculate unit strike, dip and normal to TD vectors: For a horizontal TD
% as an exception, if the normal vector points upward, the strike and dip
% vectors point Northward and Westward, whereas if the normal vector points
% downward, the strike and dip vectors point Southward and Westward,
% respectively.
Vnorm = cross(P2-P1,P3-P1);
Vnorm = Vnorm/norm(Vnorm);
eY = [0 1 0]';
eZ = [0 0 1]';
Vstrike = cross(eZ,Vnorm);
% For horizontal elements ("Vnorm(3)" adjusts for Northward or Southward
% direction)
if norm(Vstrike)==0
Vstrike = eY*Vnorm(3);
% For horizontal elements in case of half-space calculation!!!
% Correct the strike vector of image dislocation only
if P1(3)>0
Vstrike = -Vstrike;
end
end
Vstrike = Vstrike/norm(Vstrike);
Vdip = cross(Vnorm,Vstrike);
% Transform coordinates and slip vector components from EFCS into TDCS
p1 = zeros(3,1);
p2 = zeros(3,1);
p3 = zeros(3,1);
A = [Vnorm Vstrike Vdip]';
[x,y,z] = CoordTrans(X'-P2(1),Y'-P2(2),Z'-P2(3),A);
[p1(1),p1(2),p1(3)] = CoordTrans(P1(1)-P2(1),P1(2)-P2(2),P1(3)-P2(3),A);
[p3(1),p3(2),p3(3)] = CoordTrans(P3(1)-P2(1),P3(2)-P2(2),P3(3)-P2(3),A);
% Calculate the unit vectors along TD sides in TDCS
e12 = (p2-p1)/norm(p2-p1);
e13 = (p3-p1)/norm(p3-p1);
e23 = (p3-p2)/norm(p3-p2);
% Calculate the TD angles
A = acos(e12'*e13);
B = acos(-e12'*e23);
C = acos(e23'*e13);
% Determine the best arteact-free configuration for each calculation point
Trimode = trimodefinder(y,z,x,p1(2:3),p2(2:3),p3(2:3));
casepLog = Trimode==1;
casenLog = Trimode==-1;
casezLog = Trimode==0;
xp = x(casepLog);
yp = y(casepLog);
zp = z(casepLog);
xn = x(casenLog);
yn = y(casenLog);
zn = z(casenLog);
% Configuration I
if nnz(casepLog)~=0
% Calculate first angular dislocation contribution
[Exx1Tp,Eyy1Tp,Ezz1Tp,Exy1Tp,Exz1Tp,Eyz1Tp] = TDSetupS(xp,yp,zp,A,...
bx,by,bz,nu,p1,-e13);
% Calculate second angular dislocation contribution
[Exx2Tp,Eyy2Tp,Ezz2Tp,Exy2Tp,Exz2Tp,Eyz2Tp] = TDSetupS(xp,yp,zp,B,...
bx,by,bz,nu,p2,e12);
% Calculate third angular dislocation contribution
[Exx3Tp,Eyy3Tp,Ezz3Tp,Exy3Tp,Exz3Tp,Eyz3Tp] = TDSetupS(xp,yp,zp,C,...
bx,by,bz,nu,p3,e23);
end
% Configuration II
if nnz(casenLog)~=0
% Calculate first angular dislocation contribution
[Exx1Tn,Eyy1Tn,Ezz1Tn,Exy1Tn,Exz1Tn,Eyz1Tn] = TDSetupS(xn,yn,zn,A,...
bx,by,bz,nu,p1,e13);
% Calculate second angular dislocation contribution
[Exx2Tn,Eyy2Tn,Ezz2Tn,Exy2Tn,Exz2Tn,Eyz2Tn] = TDSetupS(xn,yn,zn,B,...
bx,by,bz,nu,p2,-e12);
% Calculate third angular dislocation contribution
[Exx3Tn,Eyy3Tn,Ezz3Tn,Exy3Tn,Exz3Tn,Eyz3Tn] = TDSetupS(xn,yn,zn,C,...
bx,by,bz,nu,p3,-e23);
end
% Calculate the strain tensor components in TDCS
if nnz(casepLog)~=0
exx(casepLog,1) = Exx1Tp+Exx2Tp+Exx3Tp;
eyy(casepLog,1) = Eyy1Tp+Eyy2Tp+Eyy3Tp;
ezz(casepLog,1) = Ezz1Tp+Ezz2Tp+Ezz3Tp;
exy(casepLog,1) = Exy1Tp+Exy2Tp+Exy3Tp;
exz(casepLog,1) = Exz1Tp+Exz2Tp+Exz3Tp;
eyz(casepLog,1) = Eyz1Tp+Eyz2Tp+Eyz3Tp;
end
if nnz(casenLog)~=0
exx(casenLog,1) = Exx1Tn+Exx2Tn+Exx3Tn;
eyy(casenLog,1) = Eyy1Tn+Eyy2Tn+Eyy3Tn;
ezz(casenLog,1) = Ezz1Tn+Ezz2Tn+Ezz3Tn;
exy(casenLog,1) = Exy1Tn+Exy2Tn+Exy3Tn;
exz(casenLog,1) = Exz1Tn+Exz2Tn+Exz3Tn;
eyz(casenLog,1) = Eyz1Tn+Eyz2Tn+Eyz3Tn;
end
if nnz(casezLog)~=0
exx(casezLog,1) = nan;
eyy(casezLog,1) = nan;
ezz(casezLog,1) = nan;
exy(casezLog,1) = nan;
exz(casezLog,1) = nan;
eyz(casezLog,1) = nan;
end
% Transform the strain tensor components from TDCS into EFCS
[Exx,Eyy,Ezz,Exy,Exz,Eyz] = TensTrans(exx,eyy,ezz,exy,exz,eyz,...
[Vnorm,Vstrike,Vdip]);
% Calculate the stress tensor components in EFCS
Sxx = 2*mu*Exx+lambda*(Exx+Eyy+Ezz);
Syy = 2*mu*Eyy+lambda*(Exx+Eyy+Ezz);
Szz = 2*mu*Ezz+lambda*(Exx+Eyy+Ezz);
Sxy = 2*mu*Exy;
Sxz = 2*mu*Exz;
Syz = 2*mu*Eyz;
Strain = [Exx,Eyy,Ezz,Exy,Exz,Eyz];
Stress = [Sxx,Syy,Szz,Sxy,Sxz,Syz];
function [Stress,Strain]=TDstress_HarFunc(X,Y,Z,P1,P2,P3,Ss,Ds,Ts,mu,lambda)
% TDstress_HarFunc calculates the harmonic function contribution to the
% strains and stresses associated with a triangular dislocation in a
% half-space. The function cancels the surface normal tractions induced by
% the main and image dislocations.
bx = Ts; % Tensile-slip
by = Ss; % Strike-slip
bz = Ds; % Dip-slip
% Calculate unit strike, dip and normal to TD vectors: For a horizontal TD
% as an exception, if the normal vector points upward, the strike and dip
% vectors point Northward and Westward, whereas if the normal vector points
% downward, the strike and dip vectors point Southward and Westward,
% respectively.
Vnorm = cross(P2-P1,P3-P1);
Vnorm = Vnorm/norm(Vnorm);
eY = [0 1 0]';
eZ = [0 0 1]';
Vstrike = cross(eZ,Vnorm);
if norm(Vstrike)==0
Vstrike = eY*Vnorm(3);
end
Vstrike = Vstrike/norm(Vstrike);
Vdip = cross(Vnorm,Vstrike);
% Transform slip vector components from TDCS into EFCS
A = [Vnorm Vstrike Vdip];
[bX,bY,bZ] = CoordTrans(bx,by,bz,A);
% Calculate contribution of angular dislocation pair on each TD side
[Stress1,Strain1] = AngSetupFSC_S(X,Y,Z,bX,bY,bZ,P1,P2,mu,lambda); % P1P2
[Stress2,Strain2] = AngSetupFSC_S(X,Y,Z,bX,bY,bZ,P2,P3,mu,lambda); % P2P3
[Stress3,Strain3] = AngSetupFSC_S(X,Y,Z,bX,bY,bZ,P3,P1,mu,lambda); % P3P1
% Calculate total harmonic function contribution to strains and stresses
Stress = Stress1+Stress2+Stress3;
Strain = Strain1+Strain2+Strain3;
function [Txx2,Tyy2,Tzz2,Txy2,Txz2,Tyz2]=TensTrans(Txx1,Tyy1,Tzz1,Txy1,...
Txz1,Tyz1,A)
% TensTrans Transforms the coordinates of tensors,from x1y1z1 coordinate
% system to x2y2z2 coordinate system. "A" is the transformation matrix,
% whose columns e1,e2 and e3 are the unit base vectors of the x1y1z1. The
% coordinates of e1,e2 and e3 in A must be given in x2y2z2. The transpose
% of A (i.e., A') does the transformation from x2y2z2 into x1y1z1.
Txx2 = A(1)^2*Txx1+2*A(1)*A(4)*Txy1+2*A(1)*A(7)*Txz1+2*A(4)*A(7)*Tyz1+...
A(4)^2*Tyy1+A(7)^2*Tzz1;
Tyy2 = A(2)^2*Txx1+2*A(2)*A(5)*Txy1+2*A(2)*A(8)*Txz1+2*A(5)*A(8)*Tyz1+...
A(5)^2*Tyy1+A(8)^2*Tzz1;
Tzz2 = A(3)^2*Txx1+2*A(3)*A(6)*Txy1+2*A(3)*A(9)*Txz1+2*A(6)*A(9)*Tyz1+...
A(6)^2*Tyy1+A(9)^2*Tzz1;
Txy2 = A(1)*A(2)*Txx1+(A(1)*A(5)+A(2)*A(4))*Txy1+(A(1)*A(8)+...
A(2)*A(7))*Txz1+(A(8)*A(4)+A(7)*A(5))*Tyz1+A(5)*A(4)*Tyy1+...
A(7)*A(8)*Tzz1;
Txz2 = A(1)*A(3)*Txx1+(A(1)*A(6)+A(3)*A(4))*Txy1+(A(1)*A(9)+...
A(3)*A(7))*Txz1+(A(9)*A(4)+A(7)*A(6))*Tyz1+A(6)*A(4)*Tyy1+...
A(7)*A(9)*Tzz1;
Tyz2 = A(2)*A(3)*Txx1+(A(3)*A(5)+A(2)*A(6))*Txy1+(A(3)*A(8)+...
A(2)*A(9))*Txz1+(A(8)*A(6)+A(9)*A(5))*Tyz1+A(5)*A(6)*Tyy1+...
A(8)*A(9)*Tzz1;
function [X1,X2,X3]=CoordTrans(x1,x2,x3,A)
% CoordTrans transforms the coordinates of the vectors, from
% x1x2x3 coordinate system to X1X2X3 coordinate system. "A" is the
% transformation matrix, whose columns e1,e2 and e3 are the unit base
% vectors of the x1x2x3. The coordinates of e1,e2 and e3 in A must be given
% in X1X2X3. The transpose of A (i.e., A') will transform the coordinates
% from X1X2X3 into x1x2x3.
x1 = x1(:);
x2 = x2(:);
x3 = x3(:);
r = A*[x1';x2';x3'];
X1 = r(1,:)';
X2 = r(2,:)';
X3 = r(3,:)';
function [trimode]=trimodefinder(x,y,z,p1,p2,p3)
% trimodefinder calculates the normalized barycentric coordinates of
% the points with respect to the TD vertices and specifies the appropriate
% artefact-free configuration of the angular dislocations for the
% calculations. The input matrices x, y and z share the same size and
% correspond to the y, z and x coordinates in the TDCS, respectively. p1,
% p2 and p3 are two-component matrices representing the y and z coordinates
% of the TD vertices in the TDCS, respectively.
% The components of the output (trimode) corresponding to each calculation
% points, are 1 for the first configuration, -1 for the second
% configuration and 0 for the calculation point that lie on the TD sides.
x = x(:);
y = y(:);
z = z(:);
a = ((p2(2)-p3(2)).*(x-p3(1))+(p3(1)-p2(1)).*(y-p3(2)))./...
((p2(2)-p3(2)).*(p1(1)-p3(1))+(p3(1)-p2(1)).*(p1(2)-p3(2)));
b = ((p3(2)-p1(2)).*(x-p3(1))+(p1(1)-p3(1)).*(y-p3(2)))./...
((p2(2)-p3(2)).*(p1(1)-p3(1))+(p3(1)-p2(1)).*(p1(2)-p3(2)));
c = 1-a-b;
trimode = ones(length(x),1);
trimode(a<=0 & b>c & c>a) = -1;
trimode(b<=0 & c>a & a>b) = -1;
trimode(c<=0 & a>b & b>c) = -1;
trimode(a==0 & b>=0 & c>=0) = 0;
trimode(a>=0 & b==0 & c>=0) = 0;
trimode(a>=0 & b>=0 & c==0) = 0;
trimode(trimode==0 & z~=0) = 1;
function [exx,eyy,ezz,exy,exz,eyz]=TDSetupS(x,y,z,alpha,bx,by,bz,nu,...
TriVertex,SideVec)
% TDSetupS transforms coordinates of the calculation points as well as
% slip vector components from ADCS into TDCS. It then calculates the
% strains in ADCS and transforms them into TDCS.
% Transformation matrix
A = [[SideVec(3);-SideVec(2)] SideVec(2:3)]';
% Transform coordinates of the calculation points from TDCS into ADCS
r1 = A*[y'-TriVertex(2);z'-TriVertex(3)];
y1 = r1(1,:)';
z1 = r1(2,:)';
% Transform the in-plane slip vector components from TDCS into ADCS
r2 = A*[by;bz];
by1 = r2(1,:)';
bz1 = r2(2,:)';
% Calculate strains associated with an angular dislocation in ADCS
[exx,eyy,ezz,exy,exz,eyz] = AngDisStrain(x,y1,z1,-pi+alpha,bx,by1,bz1,nu);
% Transform strains from ADCS into TDCS
B = [[1 0 0];[zeros(2,1),A']]; % 3x3 Transformation matrix
[exx,eyy,ezz,exy,exz,eyz] = TensTrans(exx,eyy,ezz,exy,exz,eyz,B);
function [Stress,Strain]=AngSetupFSC_S(X,Y,Z,bX,bY,bZ,PA,PB,mu,lambda)
% AngSetupFSC_S calculates the Free Surface Correction to strains and
% stresses associated with angular dislocation pair on each TD side.
nu = 1/(1+lambda/mu)/2; % Poisson's ratio
% Calculate TD side vector and the angle of the angular dislocation pair
SideVec = PB-PA;
eZ = [0 0 1]';
beta = acos(-SideVec'*eZ/norm(SideVec));
if abs(beta)<eps || abs(pi-beta)<eps
Stress = zeros(length(X),6);
Strain = zeros(length(X),6);
else
ey1 = [SideVec(1:2);0];
ey1 = ey1/norm(ey1);
ey3 = -eZ;
ey2 = cross(ey3,ey1);
A = [ey1,ey2,ey3]; % Transformation matrix
% Transform coordinates from EFCS to the first ADCS
[y1A,y2A,y3A] = CoordTrans(X-PA(1),Y-PA(2),Z-PA(3),A);
% Transform coordinates from EFCS to the second ADCS
[y1AB,y2AB,y3AB] = CoordTrans(SideVec(1),SideVec(2),SideVec(3),A);
y1B = y1A-y1AB;
y2B = y2A-y2AB;
y3B = y3A-y3AB;
% Transform slip vector components from EFCS to ADCS
[b1,b2,b3] = CoordTrans(bX,bY,bZ,A);
% Determine the best arteact-free configuration for the calculation
% points near the free furface
I = (beta*y1A)>=0;
% For singularities at surface
v11A = zeros(length(X),1);
v22A = zeros(length(X),1);
v33A = zeros(length(X),1);
v12A = zeros(length(X),1);
v13A = zeros(length(X),1);
v23A = zeros(length(X),1);
v11B = zeros(length(X),1);
v22B = zeros(length(X),1);
v33B = zeros(length(X),1);
v12B = zeros(length(X),1);
v13B = zeros(length(X),1);
v23B = zeros(length(X),1);
% Configuration I
[v11A(I),v22A(I),v33A(I),v12A(I),v13A(I),v23A(I)] = ...
AngDisStrainFSC(-y1A(I),-y2A(I),y3A(I),...
pi-beta,-b1,-b2,b3,nu,-PA(3));
v13A(I) = -v13A(I);
v23A(I) = -v23A(I);
[v11B(I),v22B(I),v33B(I),v12B(I),v13B(I),v23B(I)] = ...
AngDisStrainFSC(-y1B(I),-y2B(I),y3B(I),...
pi-beta,-b1,-b2,b3,nu,-PB(3));
v13B(I) = -v13B(I);
v23B(I) = -v23B(I);
% Configuration II
[v11A(~I),v22A(~I),v33A(~I),v12A(~I),v13A(~I),v23A(~I)] = ...
AngDisStrainFSC(y1A(~I),y2A(~I),y3A(~I),...
beta,b1,b2,b3,nu,-PA(3));
[v11B(~I),v22B(~I),v33B(~I),v12B(~I),v13B(~I),v23B(~I)] = ...
AngDisStrainFSC(y1B(~I),y2B(~I),y3B(~I),...
beta,b1,b2,b3,nu,-PB(3));
% Calculate total Free Surface Correction to strains in ADCS
v11 = v11B-v11A;
v22 = v22B-v22A;
v33 = v33B-v33A;
v12 = v12B-v12A;
v13 = v13B-v13A;
v23 = v23B-v23A;
% Transform total Free Surface Correction to strains from ADCS to EFCS
[Exx,Eyy,Ezz,Exy,Exz,Eyz] = TensTrans(v11,v22,v33,v12,v13,v23,A');
% Calculate total Free Surface Correction to stresses in EFCS
Sxx = 2*mu*Exx+lambda*(Exx+Eyy+Ezz);
Syy = 2*mu*Eyy+lambda*(Exx+Eyy+Ezz);
Szz = 2*mu*Ezz+lambda*(Exx+Eyy+Ezz);
Sxy = 2*mu*Exy;
Sxz = 2*mu*Exz;
Syz = 2*mu*Eyz;
Strain = [Exx,Eyy,Ezz,Exy,Exz,Eyz];
Stress = [Sxx,Syy,Szz,Sxy,Sxz,Syz];
end
function [Exx,Eyy,Ezz,Exy,Exz,Eyz]=AngDisStrain(x,y,z,alpha,bx,by,bz,nu)
% AngDisStrain calculates the strains associated with an angular
% dislocation in an elastic full-space.
sinA = sin(alpha);
cosA = cos(alpha);
eta = y.*cosA-z.*sinA;
zeta = y.*sinA+z.*cosA;
x2 = x.^2;
y2 = y.^2;
z2 = z.^2;
r2 = x2+y2+z2;
r = sqrt(r2);
r3 = r.*r2;
rz = r.*(r-z);
r2z2 = r2.*(r-z).^2;
r3z = r3.*(r-z);
W = zeta-r;
W2 = W.^2;
Wr = W.*r;
W2r = W2.*r;
Wr3 = W.*r3;
W2r2 = W2.*r2;
C = (r*cosA-z)./Wr;
S = (r*sinA-y)./Wr;
% Partial derivatives of the Burgers' function
rFi_rx = (eta./r./(r-zeta)-y./r./(r-z))/4/pi;
rFi_ry = (x./r./(r-z)-cosA*x./r./(r-zeta))/4/pi;
rFi_rz = (sinA*x./r./(r-zeta))/4/pi;
Exx = bx.*(rFi_rx)+...
bx/8/pi/(1-nu)*(eta./Wr+eta.*x2./W2r2-eta.*x2./Wr3+y./rz-...
x2.*y./r2z2-x2.*y./r3z)-...
by*x/8/pi/(1-nu).*(((2*nu+1)./Wr+x2./W2r2-x2./Wr3)*cosA+...
(2*nu+1)./rz-x2./r2z2-x2./r3z)+...
bz*x*sinA/8/pi/(1-nu).*((2*nu+1)./Wr+x2./W2r2-x2./Wr3);
Eyy = by.*(rFi_ry)+...
bx/8/pi/(1-nu)*((1./Wr+S.^2-y2./Wr3).*eta+(2*nu+1)*y./rz-y.^3./r2z2-...
y.^3./r3z-2*nu*cosA*S)-...
by*x/8/pi/(1-nu).*(1./rz-y2./r2z2-y2./r3z+...
(1./Wr+S.^2-y2./Wr3)*cosA)+...
bz*x*sinA/8/pi/(1-nu).*(1./Wr+S.^2-y2./Wr3);
Ezz = bz.*(rFi_rz)+...
bx/8/pi/(1-nu)*(eta./W./r+eta.*C.^2-eta.*z2./Wr3+y.*z./r3+...
2*nu*sinA*C)-...
by*x/8/pi/(1-nu).*((1./Wr+C.^2-z2./Wr3)*cosA+z./r3)+...
bz*x*sinA/8/pi/(1-nu).*(1./Wr+C.^2-z2./Wr3);
Exy = bx.*(rFi_ry)./2+by.*(rFi_rx)./2-...
bx/8/pi/(1-nu).*(x.*y2./r2z2-nu*x./rz+x.*y2./r3z-nu*x*cosA./Wr+...
eta.*x.*S./Wr+eta.*x.*y./Wr3)+...
by/8/pi/(1-nu)*(x2.*y./r2z2-nu*y./rz+x2.*y./r3z+nu*cosA*S+...
x2.*y*cosA./Wr3+x2*cosA.*S./Wr)-...
bz*sinA/8/pi/(1-nu).*(nu*S+x2.*S./Wr+x2.*y./Wr3);
Exz = bx.*(rFi_rz)./2+bz.*(rFi_rx)./2-...
bx/8/pi/(1-nu)*(-x.*y./r3+nu*x*sinA./Wr+eta.*x.*C./Wr+...
eta.*x.*z./Wr3)+...
by/8/pi/(1-nu)*(-x2./r3+nu./r+nu*cosA*C+x2.*z*cosA./Wr3+...
x2*cosA.*C./Wr)-...
bz*sinA/8/pi/(1-nu).*(nu*C+x2.*C./Wr+x2.*z./Wr3);
Eyz = by.*(rFi_rz)./2+bz.*(rFi_ry)./2+...
bx/8/pi/(1-nu).*(y2./r3-nu./r-nu*cosA*C+nu*sinA*S+eta*sinA*cosA./W2-...
eta.*(y*cosA+z*sinA)./W2r+eta.*y.*z./W2r2-eta.*y.*z./Wr3)-...
by*x/8/pi/(1-nu).*(y./r3+sinA*cosA^2./W2-cosA*(y*cosA+z*sinA)./...
W2r+y.*z*cosA./W2r2-y.*z*cosA./Wr3)-...
bz*x*sinA/8/pi/(1-nu).*(y.*z./Wr3-sinA*cosA./W2+(y*cosA+z*sinA)./...
W2r-y.*z./W2r2);
function [v11 v22 v33 v12 v13 v23] = AngDisStrainFSC(y1,y2,y3,beta,...
b1,b2,b3,nu,a)
% AngDisStrainFSC calculates the harmonic function contribution to the
% strains associated with an angular dislocation in an elastic half-space.
sinB = sin(beta);
cosB = cos(beta);
cotB = cot(beta);
y3b = y3+2*a;
z1b = y1*cosB+y3b*sinB;
z3b = -y1*sinB+y3b*cosB;
rb2 = y1.^2+y2.^2+y3b.^2;
rb = sqrt(rb2);
W1 = rb*cosB+y3b;
W2 = cosB+a./rb;
W3 = cosB+y3b./rb;
W4 = nu+a./rb;
W5 = 2*nu+a./rb;
W6 = rb+y3b;
W7 = rb+z3b;
W8 = y3+a;
W9 = 1+a./rb./cosB;
N1 = 1-2*nu;
% Partial derivatives of the Burgers' function
rFib_ry2 = z1b./rb./(rb+z3b)-y1./rb./(rb+y3b); % y2 = x in ADCS
rFib_ry1 = y2./rb./(rb+y3b)-cosB*y2./rb./(rb+z3b); % y1 =y in ADCS
rFib_ry3 = -sinB*y2./rb./(rb+z3b); % y3 = z in ADCS
v11 = b1*(1/4*((-2+2*nu)*N1*rFib_ry1*cotB^2-N1.*y2./W6.^2.*((1-W5)*cotB-...
y1./W6.*W4)./rb.*y1+N1.*y2./W6.*(a./rb.^3.*y1*cotB-1./W6.*W4+y1.^2./...
W6.^2.*W4./rb+y1.^2./W6*a./rb.^3)-N1.*y2*cosB*cotB./W7.^2.*W2.*(y1./...
rb-sinB)-N1.*y2*cosB*cotB./W7*a./rb.^3.*y1-3*a.*y2.*W8*cotB./rb.^5.*...
y1-y2.*W8./rb.^3./W6.*(-N1*cotB+y1./W6.*W5+a.*y1./rb2).*y1-y2.*W8./...
rb2./W6.^2.*(-N1*cotB+y1./W6.*W5+a.*y1./rb2).*y1+y2.*W8./rb./W6.*...
(1./W6.*W5-y1.^2./W6.^2.*W5./rb-y1.^2./W6*a./rb.^3+a./rb2-2*a.*y1.^...
2./rb2.^2)-y2.*W8./rb.^3./W7.*(cosB./W7.*(W1.*(N1*cosB-a./rb)*cotB+...
(2-2*nu).*(rb*sinB-y1)*cosB)-a.*y3b*cosB*cotB./rb2).*y1-y2.*W8./rb./...
W7.^2.*(cosB./W7.*(W1.*(N1*cosB-a./rb)*cotB+(2-2*nu).*(rb*sinB-y1)*...
cosB)-a.*y3b*cosB*cotB./rb2).*(y1./rb-sinB)+y2.*W8./rb./W7.*(-cosB./...
W7.^2.*(W1.*(N1*cosB-a./rb)*cotB+(2-2*nu).*(rb*sinB-y1)*cosB).*(y1./...
rb-sinB)+cosB./W7.*(1./rb*cosB.*y1.*(N1*cosB-a./rb)*cotB+W1*a./rb.^...
3.*y1*cotB+(2-2*nu).*(1./rb*sinB.*y1-1)*cosB)+2*a.*y3b*cosB*cotB./...
rb2.^2.*y1))/pi/(1-nu))+...
b2*(1/4*(N1*(((2-2*nu)*cotB^2+nu)./rb.*y1./W6-((2-2*nu)*cotB^2+1)*...
cosB.*(y1./rb-sinB)./W7)-N1./W6.^2.*(-N1.*y1*cotB+nu.*y3b-a+a.*y1*...
cotB./rb+y1.^2./W6.*W4)./rb.*y1+N1./W6.*(-N1*cotB+a.*cotB./rb-a.*...
y1.^2*cotB./rb.^3+2.*y1./W6.*W4-y1.^3./W6.^2.*W4./rb-y1.^3./W6*a./...
rb.^3)+N1*cotB./W7.^2.*(z1b*cosB-a.*(rb*sinB-y1)./rb./cosB).*(y1./...
rb-sinB)-N1*cotB./W7.*(cosB^2-a.*(1./rb*sinB.*y1-1)./rb./cosB+a.*...
(rb*sinB-y1)./rb.^3./cosB.*y1)-a.*W8*cotB./rb.^3+3*a.*y1.^2.*W8*...
cotB./rb.^5-W8./W6.^2.*(2*nu+1./rb.*(N1.*y1*cotB+a)-y1.^2./rb./W6.*...
W5-a.*y1.^2./rb.^3)./rb.*y1+W8./W6.*(-1./rb.^3.*(N1.*y1*cotB+a).*y1+...
1./rb.*N1*cotB-2.*y1./rb./W6.*W5+y1.^3./rb.^3./W6.*W5+y1.^3./rb2./...
W6.^2.*W5+y1.^3./rb2.^2./W6*a-2*a./rb.^3.*y1+3*a.*y1.^3./rb.^5)-W8*...
cotB./W7.^2.*(-cosB*sinB+a.*y1.*y3b./rb.^3./cosB+(rb*sinB-y1)./rb.*...
((2-2*nu)*cosB-W1./W7.*W9)).*(y1./rb-sinB)+W8*cotB./W7.*(a.*y3b./...
rb.^3./cosB-3*a.*y1.^2.*y3b./rb.^5./cosB+(1./rb*sinB.*y1-1)./rb.*...
((2-2*nu)*cosB-W1./W7.*W9)-(rb*sinB-y1)./rb.^3.*((2-2*nu)*cosB-W1./...
W7.*W9).*y1+(rb*sinB-y1)./rb.*(-1./rb*cosB.*y1./W7.*W9+W1./W7.^2.*...
W9.*(y1./rb-sinB)+W1./W7*a./rb.^3./cosB.*y1)))/pi/(1-nu))+...
b3*(1/4*(N1*(-y2./W6.^2.*(1+a./rb)./rb.*y1-y2./W6*a./rb.^3.*y1+y2*...
cosB./W7.^2.*W2.*(y1./rb-sinB)+y2*cosB./W7*a./rb.^3.*y1)+y2.*W8./...
rb.^3.*(a./rb2+1./W6).*y1-y2.*W8./rb.*(-2*a./rb2.^2.*y1-1./W6.^2./...
rb.*y1)-y2.*W8*cosB./rb.^3./W7.*(W1./W7.*W2+a.*y3b./rb2).*y1-y2.*W8*...
cosB./rb./W7.^2.*(W1./W7.*W2+a.*y3b./rb2).*(y1./rb-sinB)+y2.*W8*...
cosB./rb./W7.*(1./rb*cosB.*y1./W7.*W2-W1./W7.^2.*W2.*(y1./rb-sinB)-...
W1./W7*a./rb.^3.*y1-2*a.*y3b./rb2.^2.*y1))/pi/(1-nu));
v22 = b1*(1/4*(N1*(((2-2*nu)*cotB^2-nu)./rb.*y2./W6-((2-2*nu)*cotB^2+1-...
2*nu)*cosB./rb.*y2./W7)+N1./W6.^2.*(y1*cotB.*(1-W5)+nu.*y3b-a+y2.^...
2./W6.*W4)./rb.*y2-N1./W6.*(a.*y1*cotB./rb.^3.*y2+2.*y2./W6.*W4-y2.^...
3./W6.^2.*W4./rb-y2.^3./W6*a./rb.^3)+N1.*z1b*cotB./W7.^2.*W2./rb.*...
y2+N1.*z1b*cotB./W7*a./rb.^3.*y2+3*a.*y2.*W8*cotB./rb.^5.*y1-W8./...
W6.^2.*(-2*nu+1./rb.*(N1.*y1*cotB-a)+y2.^2./rb./W6.*W5+a.*y2.^2./...
rb.^3)./rb.*y2+W8./W6.*(-1./rb.^3.*(N1.*y1*cotB-a).*y2+2.*y2./rb./...
W6.*W5-y2.^3./rb.^3./W6.*W5-y2.^3./rb2./W6.^2.*W5-y2.^3./rb2.^2./W6*...
a+2*a./rb.^3.*y2-3*a.*y2.^3./rb.^5)-W8./W7.^2.*(cosB^2-1./rb.*(N1.*...
z1b*cotB+a.*cosB)+a.*y3b.*z1b*cotB./rb.^3-1./rb./W7.*(y2.^2*cosB^2-...
a.*z1b*cotB./rb.*W1))./rb.*y2+W8./W7.*(1./rb.^3.*(N1.*z1b*cotB+a.*...
cosB).*y2-3*a.*y3b.*z1b*cotB./rb.^5.*y2+1./rb.^3./W7.*(y2.^2*cosB^2-...
a.*z1b*cotB./rb.*W1).*y2+1./rb2./W7.^2.*(y2.^2*cosB^2-a.*z1b*cotB./...
rb.*W1).*y2-1./rb./W7.*(2.*y2*cosB^2+a.*z1b*cotB./rb.^3.*W1.*y2-a.*...
z1b*cotB./rb2*cosB.*y2)))/pi/(1-nu))+...
b2*(1/4*((2-2*nu)*N1*rFib_ry2*cotB^2+N1./W6.*((W5-1)*cotB+y1./W6.*...
W4)-N1.*y2.^2./W6.^2.*((W5-1)*cotB+y1./W6.*W4)./rb+N1.*y2./W6.*(-a./...
rb.^3.*y2*cotB-y1./W6.^2.*W4./rb.*y2-y2./W6*a./rb.^3.*y1)-N1*cotB./...
W7.*W9+N1.*y2.^2*cotB./W7.^2.*W9./rb+N1.*y2.^2*cotB./W7*a./rb.^3./...
cosB-a.*W8*cotB./rb.^3+3*a.*y2.^2.*W8*cotB./rb.^5+W8./rb./W6.*(N1*...
cotB-2*nu.*y1./W6-a.*y1./rb.*(1./rb+1./W6))-y2.^2.*W8./rb.^3./W6.*...
(N1*cotB-2*nu.*y1./W6-a.*y1./rb.*(1./rb+1./W6))-y2.^2.*W8./rb2./W6.^...
2.*(N1*cotB-2*nu.*y1./W6-a.*y1./rb.*(1./rb+1./W6))+y2.*W8./rb./W6.*...
(2*nu.*y1./W6.^2./rb.*y2+a.*y1./rb.^3.*(1./rb+1./W6).*y2-a.*y1./rb.*...
(-1./rb.^3.*y2-1./W6.^2./rb.*y2))+W8*cotB./rb./W7.*((-2+2*nu)*cosB+...
W1./W7.*W9+a.*y3b./rb2./cosB)-y2.^2.*W8*cotB./rb.^3./W7.*((-2+2*nu)*...
cosB+W1./W7.*W9+a.*y3b./rb2./cosB)-y2.^2.*W8*cotB./rb2./W7.^2.*((-2+...
2*nu)*cosB+W1./W7.*W9+a.*y3b./rb2./cosB)+y2.*W8*cotB./rb./W7.*(1./...
rb*cosB.*y2./W7.*W9-W1./W7.^2.*W9./rb.*y2-W1./W7*a./rb.^3./cosB.*y2-...
2*a.*y3b./rb2.^2./cosB.*y2))/pi/(1-nu))+...
b3*(1/4*(N1*(-sinB./rb.*y2./W7+y2./W6.^2.*(1+a./rb)./rb.*y1+y2./W6*...
a./rb.^3.*y1-z1b./W7.^2.*W2./rb.*y2-z1b./W7*a./rb.^3.*y2)-y2.*W8./...
rb.^3.*(a./rb2+1./W6).*y1+y1.*W8./rb.*(-2*a./rb2.^2.*y2-1./W6.^2./...
rb.*y2)+W8./W7.^2.*(sinB.*(cosB-a./rb)+z1b./rb.*(1+a.*y3b./rb2)-1./...
rb./W7.*(y2.^2*cosB*sinB-a.*z1b./rb.*W1))./rb.*y2-W8./W7.*(sinB*a./...
rb.^3.*y2-z1b./rb.^3.*(1+a.*y3b./rb2).*y2-2.*z1b./rb.^5*a.*y3b.*y2+...
1./rb.^3./W7.*(y2.^2*cosB*sinB-a.*z1b./rb.*W1).*y2+1./rb2./W7.^2.*...
(y2.^2*cosB*sinB-a.*z1b./rb.*W1).*y2-1./rb./W7.*(2.*y2*cosB*sinB+a.*...
z1b./rb.^3.*W1.*y2-a.*z1b./rb2*cosB.*y2)))/pi/(1-nu));
v33 = b1*(1/4*((2-2*nu)*(N1*rFib_ry3*cotB-y2./W6.^2.*W5.*(y3b./rb+1)-...
1/2.*y2./W6*a./rb.^3*2.*y3b+y2*cosB./W7.^2.*W2.*W3+1/2.*y2*cosB./W7*...
a./rb.^3*2.*y3b)+y2./rb.*(2*nu./W6+a./rb2)-1/2.*y2.*W8./rb.^3.*(2*...
nu./W6+a./rb2)*2.*y3b+y2.*W8./rb.*(-2*nu./W6.^2.*(y3b./rb+1)-a./...
rb2.^2*2.*y3b)+y2*cosB./rb./W7.*(1-2*nu-W1./W7.*W2-a.*y3b./rb2)-...
1/2.*y2.*W8*cosB./rb.^3./W7.*(1-2*nu-W1./W7.*W2-a.*y3b./rb2)*2.*...
y3b-y2.*W8*cosB./rb./W7.^2.*(1-2*nu-W1./W7.*W2-a.*y3b./rb2).*W3+y2.*...
W8*cosB./rb./W7.*(-(cosB*y3b./rb+1)./W7.*W2+W1./W7.^2.*W2.*W3+1/2.*...
W1./W7*a./rb.^3*2.*y3b-a./rb2+a.*y3b./rb2.^2*2.*y3b))/pi/(1-nu))+...
b2*(1/4*((-2+2*nu)*N1*cotB*((y3b./rb+1)./W6-cosB.*W3./W7)+(2-2*nu).*...
y1./W6.^2.*W5.*(y3b./rb+1)+1/2.*(2-2*nu).*y1./W6*a./rb.^3*2.*y3b+(2-...
2*nu)*sinB./W7.*W2-(2-2*nu).*z1b./W7.^2.*W2.*W3-1/2.*(2-2*nu).*z1b./...
W7*a./rb.^3*2.*y3b+1./rb.*(N1*cotB-2*nu.*y1./W6-a.*y1./rb2)-1/2.*...
W8./rb.^3.*(N1*cotB-2*nu.*y1./W6-a.*y1./rb2)*2.*y3b+W8./rb.*(2*nu.*...
y1./W6.^2.*(y3b./rb+1)+a.*y1./rb2.^2*2.*y3b)-1./W7.*(cosB*sinB+W1*...
cotB./rb.*((2-2*nu)*cosB-W1./W7)+a./rb.*(sinB-y3b.*z1b./rb2-z1b.*...
W1./rb./W7))+W8./W7.^2.*(cosB*sinB+W1*cotB./rb.*((2-2*nu)*cosB-W1./...
W7)+a./rb.*(sinB-y3b.*z1b./rb2-z1b.*W1./rb./W7)).*W3-W8./W7.*((cosB*...
y3b./rb+1)*cotB./rb.*((2-2*nu)*cosB-W1./W7)-1/2.*W1*cotB./rb.^3.*...
((2-2*nu)*cosB-W1./W7)*2.*y3b+W1*cotB./rb.*(-(cosB*y3b./rb+1)./W7+...
W1./W7.^2.*W3)-1/2*a./rb.^3.*(sinB-y3b.*z1b./rb2-z1b.*W1./rb./W7)*...
2.*y3b+a./rb.*(-z1b./rb2-y3b*sinB./rb2+y3b.*z1b./rb2.^2*2.*y3b-...
sinB.*W1./rb./W7-z1b.*(cosB*y3b./rb+1)./rb./W7+1/2.*z1b.*W1./rb.^3./...
W7*2.*y3b+z1b.*W1./rb./W7.^2.*W3)))/pi/(1-nu))+...
b3*(1/4*((2-2*nu)*rFib_ry3-(2-2*nu).*y2*sinB./W7.^2.*W2.*W3-1/2.*...
(2-2*nu).*y2*sinB./W7*a./rb.^3*2.*y3b+y2*sinB./rb./W7.*(1+W1./W7.*...
W2+a.*y3b./rb2)-1/2.*y2.*W8*sinB./rb.^3./W7.*(1+W1./W7.*W2+a.*y3b./...
rb2)*2.*y3b-y2.*W8*sinB./rb./W7.^2.*(1+W1./W7.*W2+a.*y3b./rb2).*W3+...
y2.*W8*sinB./rb./W7.*((cosB*y3b./rb+1)./W7.*W2-W1./W7.^2.*W2.*W3-...
1/2.*W1./W7*a./rb.^3*2.*y3b+a./rb2-a.*y3b./rb2.^2*2.*y3b))/pi/(1-nu));
v12 = b1/2*(1/4*((-2+2*nu)*N1*rFib_ry2*cotB^2+N1./W6.*((1-W5)*cotB-y1./...
W6.*W4)-N1.*y2.^2./W6.^2.*((1-W5)*cotB-y1./W6.*W4)./rb+N1.*y2./W6.*...
(a./rb.^3.*y2*cotB+y1./W6.^2.*W4./rb.*y2+y2./W6*a./rb.^3.*y1)+N1*...
cosB*cotB./W7.*W2-N1.*y2.^2*cosB*cotB./W7.^2.*W2./rb-N1.*y2.^2*cosB*...
cotB./W7*a./rb.^3+a.*W8*cotB./rb.^3-3*a.*y2.^2.*W8*cotB./rb.^5+W8./...
rb./W6.*(-N1*cotB+y1./W6.*W5+a.*y1./rb2)-y2.^2.*W8./rb.^3./W6.*(-N1*...
cotB+y1./W6.*W5+a.*y1./rb2)-y2.^2.*W8./rb2./W6.^2.*(-N1*cotB+y1./...
W6.*W5+a.*y1./rb2)+y2.*W8./rb./W6.*(-y1./W6.^2.*W5./rb.*y2-y2./W6*...
a./rb.^3.*y1-2*a.*y1./rb2.^2.*y2)+W8./rb./W7.*(cosB./W7.*(W1.*(N1*...
cosB-a./rb)*cotB+(2-2*nu).*(rb*sinB-y1)*cosB)-a.*y3b*cosB*cotB./...
rb2)-y2.^2.*W8./rb.^3./W7.*(cosB./W7.*(W1.*(N1*cosB-a./rb)*cotB+(2-...
2*nu).*(rb*sinB-y1)*cosB)-a.*y3b*cosB*cotB./rb2)-y2.^2.*W8./rb2./...
W7.^2.*(cosB./W7.*(W1.*(N1*cosB-a./rb)*cotB+(2-2*nu).*(rb*sinB-y1)*...
cosB)-a.*y3b*cosB*cotB./rb2)+y2.*W8./rb./W7.*(-cosB./W7.^2.*(W1.*...
(N1*cosB-a./rb)*cotB+(2-2*nu).*(rb*sinB-y1)*cosB)./rb.*y2+cosB./...
W7.*(1./rb*cosB.*y2.*(N1*cosB-a./rb)*cotB+W1*a./rb.^3.*y2*cotB+(2-2*...
nu)./rb*sinB.*y2*cosB)+2*a.*y3b*cosB*cotB./rb2.^2.*y2))/pi/(1-nu))+...
b2/2*(1/4*(N1*(((2-2*nu)*cotB^2+nu)./rb.*y2./W6-((2-2*nu)*cotB^2+1)*...
cosB./rb.*y2./W7)-N1./W6.^2.*(-N1.*y1*cotB+nu.*y3b-a+a.*y1*cotB./rb+...
y1.^2./W6.*W4)./rb.*y2+N1./W6.*(-a.*y1*cotB./rb.^3.*y2-y1.^2./W6.^...
2.*W4./rb.*y2-y1.^2./W6*a./rb.^3.*y2)+N1*cotB./W7.^2.*(z1b*cosB-a.*...
(rb*sinB-y1)./rb./cosB)./rb.*y2-N1*cotB./W7.*(-a./rb2*sinB.*y2./...
cosB+a.*(rb*sinB-y1)./rb.^3./cosB.*y2)+3*a.*y2.*W8*cotB./rb.^5.*y1-...
W8./W6.^2.*(2*nu+1./rb.*(N1.*y1*cotB+a)-y1.^2./rb./W6.*W5-a.*y1.^2./...
rb.^3)./rb.*y2+W8./W6.*(-1./rb.^3.*(N1.*y1*cotB+a).*y2+y1.^2./rb.^...
3./W6.*W5.*y2+y1.^2./rb2./W6.^2.*W5.*y2+y1.^2./rb2.^2./W6*a.*y2+3*...
a.*y1.^2./rb.^5.*y2)-W8*cotB./W7.^2.*(-cosB*sinB+a.*y1.*y3b./rb.^3./...
cosB+(rb*sinB-y1)./rb.*((2-2*nu)*cosB-W1./W7.*W9))./rb.*y2+W8*cotB./...
W7.*(-3*a.*y1.*y3b./rb.^5./cosB.*y2+1./rb2*sinB.*y2.*((2-2*nu)*cosB-...
W1./W7.*W9)-(rb*sinB-y1)./rb.^3.*((2-2*nu)*cosB-W1./W7.*W9).*y2+(rb*...
sinB-y1)./rb.*(-1./rb*cosB.*y2./W7.*W9+W1./W7.^2.*W9./rb.*y2+W1./W7*...
a./rb.^3./cosB.*y2)))/pi/(1-nu))+...
b3/2*(1/4*(N1*(1./W6.*(1+a./rb)-y2.^2./W6.^2.*(1+a./rb)./rb-y2.^2./...
W6*a./rb.^3-cosB./W7.*W2+y2.^2*cosB./W7.^2.*W2./rb+y2.^2*cosB./W7*...
a./rb.^3)-W8./rb.*(a./rb2+1./W6)+y2.^2.*W8./rb.^3.*(a./rb2+1./W6)-...
y2.*W8./rb.*(-2*a./rb2.^2.*y2-1./W6.^2./rb.*y2)+W8*cosB./rb./W7.*...
(W1./W7.*W2+a.*y3b./rb2)-y2.^2.*W8*cosB./rb.^3./W7.*(W1./W7.*W2+a.*...
y3b./rb2)-y2.^2.*W8*cosB./rb2./W7.^2.*(W1./W7.*W2+a.*y3b./rb2)+y2.*...
W8*cosB./rb./W7.*(1./rb*cosB.*y2./W7.*W2-W1./W7.^2.*W2./rb.*y2-W1./...
W7*a./rb.^3.*y2-2*a.*y3b./rb2.^2.*y2))/pi/(1-nu))+...
b1/2*(1/4*(N1*(((2-2*nu)*cotB^2-nu)./rb.*y1./W6-((2-2*nu)*cotB^2+1-...
2*nu)*cosB.*(y1./rb-sinB)./W7)+N1./W6.^2.*(y1*cotB.*(1-W5)+nu.*y3b-...
a+y2.^2./W6.*W4)./rb.*y1-N1./W6.*((1-W5)*cotB+a.*y1.^2*cotB./rb.^3-...
y2.^2./W6.^2.*W4./rb.*y1-y2.^2./W6*a./rb.^3.*y1)-N1*cosB*cotB./W7.*...
W2+N1.*z1b*cotB./W7.^2.*W2.*(y1./rb-sinB)+N1.*z1b*cotB./W7*a./rb.^...
3.*y1-a.*W8*cotB./rb.^3+3*a.*y1.^2.*W8*cotB./rb.^5-W8./W6.^2.*(-2*...
nu+1./rb.*(N1.*y1*cotB-a)+y2.^2./rb./W6.*W5+a.*y2.^2./rb.^3)./rb.*...
y1+W8./W6.*(-1./rb.^3.*(N1.*y1*cotB-a).*y1+1./rb.*N1*cotB-y2.^2./...
rb.^3./W6.*W5.*y1-y2.^2./rb2./W6.^2.*W5.*y1-y2.^2./rb2.^2./W6*a.*y1-...
3*a.*y2.^2./rb.^5.*y1)-W8./W7.^2.*(cosB^2-1./rb.*(N1.*z1b*cotB+a.*...
cosB)+a.*y3b.*z1b*cotB./rb.^3-1./rb./W7.*(y2.^2*cosB^2-a.*z1b*cotB./...
rb.*W1)).*(y1./rb-sinB)+W8./W7.*(1./rb.^3.*(N1.*z1b*cotB+a.*cosB).*...
y1-1./rb.*N1*cosB*cotB+a.*y3b*cosB*cotB./rb.^3-3*a.*y3b.*z1b*cotB./...
rb.^5.*y1+1./rb.^3./W7.*(y2.^2*cosB^2-a.*z1b*cotB./rb.*W1).*y1+1./...
rb./W7.^2.*(y2.^2*cosB^2-a.*z1b*cotB./rb.*W1).*(y1./rb-sinB)-1./rb./...
W7.*(-a.*cosB*cotB./rb.*W1+a.*z1b*cotB./rb.^3.*W1.*y1-a.*z1b*cotB./...
rb2*cosB.*y1)))/pi/(1-nu))+...
b2/2*(1/4*((2-2*nu)*N1.*rFib_ry1*cotB^2-N1.*y2./W6.^2.*((W5-1)*cotB+...
y1./W6.*W4)./rb.*y1+N1.*y2./W6.*(-a./rb.^3.*y1*cotB+1./W6.*W4-y1.^...
2./W6.^2.*W4./rb-y1.^2./W6*a./rb.^3)+N1.*y2*cotB./W7.^2.*W9.*(y1./...
rb-sinB)+N1.*y2*cotB./W7*a./rb.^3./cosB.*y1+3*a.*y2.*W8*cotB./rb.^...
5.*y1-y2.*W8./rb.^3./W6.*(N1*cotB-2*nu.*y1./W6-a.*y1./rb.*(1./rb+1./...
W6)).*y1-y2.*W8./rb2./W6.^2.*(N1*cotB-2*nu.*y1./W6-a.*y1./rb.*(1./...
rb+1./W6)).*y1+y2.*W8./rb./W6.*(-2*nu./W6+2*nu.*y1.^2./W6.^2./rb-a./...
rb.*(1./rb+1./W6)+a.*y1.^2./rb.^3.*(1./rb+1./W6)-a.*y1./rb.*(-1./...
rb.^3.*y1-1./W6.^2./rb.*y1))-y2.*W8*cotB./rb.^3./W7.*((-2+2*nu)*...
cosB+W1./W7.*W9+a.*y3b./rb2./cosB).*y1-y2.*W8*cotB./rb./W7.^2.*((-2+...
2*nu)*cosB+W1./W7.*W9+a.*y3b./rb2./cosB).*(y1./rb-sinB)+y2.*W8*...
cotB./rb./W7.*(1./rb*cosB.*y1./W7.*W9-W1./W7.^2.*W9.*(y1./rb-sinB)-...
W1./W7*a./rb.^3./cosB.*y1-2*a.*y3b./rb2.^2./cosB.*y1))/pi/(1-nu))+...
b3/2*(1/4*(N1*(-sinB*(y1./rb-sinB)./W7-1./W6.*(1+a./rb)+y1.^2./W6.^...
2.*(1+a./rb)./rb+y1.^2./W6*a./rb.^3+cosB./W7.*W2-z1b./W7.^2.*W2.*...
(y1./rb-sinB)-z1b./W7*a./rb.^3.*y1)+W8./rb.*(a./rb2+1./W6)-y1.^2.*...
W8./rb.^3.*(a./rb2+1./W6)+y1.*W8./rb.*(-2*a./rb2.^2.*y1-1./W6.^2./...
rb.*y1)+W8./W7.^2.*(sinB.*(cosB-a./rb)+z1b./rb.*(1+a.*y3b./rb2)-1./...
rb./W7.*(y2.^2*cosB*sinB-a.*z1b./rb.*W1)).*(y1./rb-sinB)-W8./W7.*...
(sinB*a./rb.^3.*y1+cosB./rb.*(1+a.*y3b./rb2)-z1b./rb.^3.*(1+a.*y3b./...
rb2).*y1-2.*z1b./rb.^5*a.*y3b.*y1+1./rb.^3./W7.*(y2.^2*cosB*sinB-a.*...
z1b./rb.*W1).*y1+1./rb./W7.^2.*(y2.^2*cosB*sinB-a.*z1b./rb.*W1).*...
(y1./rb-sinB)-1./rb./W7.*(-a.*cosB./rb.*W1+a.*z1b./rb.^3.*W1.*y1-a.*...
z1b./rb2*cosB.*y1)))/pi/(1-nu));
v13 = b1/2*(1/4*((-2+2*nu)*N1*rFib_ry3*cotB^2-N1.*y2./W6.^2.*((1-W5)*...
cotB-y1./W6.*W4).*(y3b./rb+1)+N1.*y2./W6.*(1/2*a./rb.^3*2.*y3b*cotB+...
y1./W6.^2.*W4.*(y3b./rb+1)+1/2.*y1./W6*a./rb.^3*2.*y3b)-N1.*y2*cosB*...
cotB./W7.^2.*W2.*W3-1/2.*N1.*y2*cosB*cotB./W7*a./rb.^3*2.*y3b+a./...
rb.^3.*y2*cotB-3./2*a.*y2.*W8*cotB./rb.^5*2.*y3b+y2./rb./W6.*(-N1*...
cotB+y1./W6.*W5+a.*y1./rb2)-1/2.*y2.*W8./rb.^3./W6.*(-N1*cotB+y1./...
W6.*W5+a.*y1./rb2)*2.*y3b-y2.*W8./rb./W6.^2.*(-N1*cotB+y1./W6.*W5+...
a.*y1./rb2).*(y3b./rb+1)+y2.*W8./rb./W6.*(-y1./W6.^2.*W5.*(y3b./rb+...
1)-1/2.*y1./W6*a./rb.^3*2.*y3b-a.*y1./rb2.^2*2.*y3b)+y2./rb./W7.*...
(cosB./W7.*(W1.*(N1*cosB-a./rb)*cotB+(2-2*nu).*(rb*sinB-y1)*cosB)-...
a.*y3b*cosB*cotB./rb2)-1/2.*y2.*W8./rb.^3./W7.*(cosB./W7.*(W1.*(N1*...
cosB-a./rb)*cotB+(2-2*nu).*(rb*sinB-y1)*cosB)-a.*y3b*cosB*cotB./...
rb2)*2.*y3b-y2.*W8./rb./W7.^2.*(cosB./W7.*(W1.*(N1*cosB-a./rb)*cotB+...
(2-2*nu).*(rb*sinB-y1)*cosB)-a.*y3b*cosB*cotB./rb2).*W3+y2.*W8./rb./...
W7.*(-cosB./W7.^2.*(W1.*(N1*cosB-a./rb)*cotB+(2-2*nu).*(rb*sinB-y1)*...
cosB).*W3+cosB./W7.*((cosB*y3b./rb+1).*(N1*cosB-a./rb)*cotB+1/2.*W1*...
a./rb.^3*2.*y3b*cotB+1/2.*(2-2*nu)./rb*sinB*2.*y3b*cosB)-a.*cosB*...
cotB./rb2+a.*y3b*cosB*cotB./rb2.^2*2.*y3b))/pi/(1-nu))+...
b2/2*(1/4*(N1*(((2-2*nu)*cotB^2+nu).*(y3b./rb+1)./W6-((2-2*nu)*cotB^...
2+1)*cosB.*W3./W7)-N1./W6.^2.*(-N1.*y1*cotB+nu.*y3b-a+a.*y1*cotB./...
rb+y1.^2./W6.*W4).*(y3b./rb+1)+N1./W6.*(nu-1/2*a.*y1*cotB./rb.^3*2.*...
y3b-y1.^2./W6.^2.*W4.*(y3b./rb+1)-1/2.*y1.^2./W6*a./rb.^3*2.*y3b)+...
N1*cotB./W7.^2.*(z1b*cosB-a.*(rb*sinB-y1)./rb./cosB).*W3-N1*cotB./...
W7.*(cosB*sinB-1/2*a./rb2*sinB*2.*y3b./cosB+1/2*a.*(rb*sinB-y1)./...
rb.^3./cosB*2.*y3b)-a./rb.^3.*y1*cotB+3./2*a.*y1.*W8*cotB./rb.^5*2.*...
y3b+1./W6.*(2*nu+1./rb.*(N1.*y1*cotB+a)-y1.^2./rb./W6.*W5-a.*y1.^2./...
rb.^3)-W8./W6.^2.*(2*nu+1./rb.*(N1.*y1*cotB+a)-y1.^2./rb./W6.*W5-a.*...
y1.^2./rb.^3).*(y3b./rb+1)+W8./W6.*(-1/2./rb.^3.*(N1.*y1*cotB+a)*2.*...
y3b+1/2.*y1.^2./rb.^3./W6.*W5*2.*y3b+y1.^2./rb./W6.^2.*W5.*(y3b./rb+...
1)+1/2.*y1.^2./rb2.^2./W6*a.*2.*y3b+3./2*a.*y1.^2./rb.^5*2.*y3b)+...
cotB./W7.*(-cosB*sinB+a.*y1.*y3b./rb.^3./cosB+(rb*sinB-y1)./rb.*((2-...
2*nu)*cosB-W1./W7.*W9))-W8*cotB./W7.^2.*(-cosB*sinB+a.*y1.*y3b./rb.^...
3./cosB+(rb*sinB-y1)./rb.*((2-2*nu)*cosB-W1./W7.*W9)).*W3+W8*cotB./...
W7.*(a./rb.^3./cosB.*y1-3./2*a.*y1.*y3b./rb.^5./cosB*2.*y3b+1/2./...
rb2*sinB*2.*y3b.*((2-2*nu)*cosB-W1./W7.*W9)-1/2.*(rb*sinB-y1)./rb.^...
3.*((2-2*nu)*cosB-W1./W7.*W9)*2.*y3b+(rb*sinB-y1)./rb.*(-(cosB*y3b./...
rb+1)./W7.*W9+W1./W7.^2.*W9.*W3+1/2.*W1./W7*a./rb.^3./cosB*2.*...
y3b)))/pi/(1-nu))+...
b3/2*(1/4*(N1*(-y2./W6.^2.*(1+a./rb).*(y3b./rb+1)-1/2.*y2./W6*a./...
rb.^3*2.*y3b+y2*cosB./W7.^2.*W2.*W3+1/2.*y2*cosB./W7*a./rb.^3*2.*...
y3b)-y2./rb.*(a./rb2+1./W6)+1/2.*y2.*W8./rb.^3.*(a./rb2+1./W6)*2.*...
y3b-y2.*W8./rb.*(-a./rb2.^2*2.*y3b-1./W6.^2.*(y3b./rb+1))+y2*cosB./...
rb./W7.*(W1./W7.*W2+a.*y3b./rb2)-1/2.*y2.*W8*cosB./rb.^3./W7.*(W1./...
W7.*W2+a.*y3b./rb2)*2.*y3b-y2.*W8*cosB./rb./W7.^2.*(W1./W7.*W2+a.*...
y3b./rb2).*W3+y2.*W8*cosB./rb./W7.*((cosB*y3b./rb+1)./W7.*W2-W1./...
W7.^2.*W2.*W3-1/2.*W1./W7*a./rb.^3*2.*y3b+a./rb2-a.*y3b./rb2.^2*2.*...
y3b))/pi/(1-nu))+...
b1/2*(1/4*((2-2*nu)*(N1*rFib_ry1*cotB-y1./W6.^2.*W5./rb.*y2-y2./W6*...
a./rb.^3.*y1+y2*cosB./W7.^2.*W2.*(y1./rb-sinB)+y2*cosB./W7*a./rb.^...
3.*y1)-y2.*W8./rb.^3.*(2*nu./W6+a./rb2).*y1+y2.*W8./rb.*(-2*nu./W6.^...
2./rb.*y1-2*a./rb2.^2.*y1)-y2.*W8*cosB./rb.^3./W7.*(1-2*nu-W1./W7.*...
W2-a.*y3b./rb2).*y1-y2.*W8*cosB./rb./W7.^2.*(1-2*nu-W1./W7.*W2-a.*...
y3b./rb2).*(y1./rb-sinB)+y2.*W8*cosB./rb./W7.*(-1./rb*cosB.*y1./W7.*...
W2+W1./W7.^2.*W2.*(y1./rb-sinB)+W1./W7*a./rb.^3.*y1+2*a.*y3b./rb2.^...
2.*y1))/pi/(1-nu))+...
b2/2*(1/4*((-2+2*nu)*N1*cotB*(1./rb.*y1./W6-cosB*(y1./rb-sinB)./W7)-...
(2-2*nu)./W6.*W5+(2-2*nu).*y1.^2./W6.^2.*W5./rb+(2-2*nu).*y1.^2./W6*...
a./rb.^3+(2-2*nu)*cosB./W7.*W2-(2-2*nu).*z1b./W7.^2.*W2.*(y1./rb-...
sinB)-(2-2*nu).*z1b./W7*a./rb.^3.*y1-W8./rb.^3.*(N1*cotB-2*nu.*y1./...
W6-a.*y1./rb2).*y1+W8./rb.*(-2*nu./W6+2*nu.*y1.^2./W6.^2./rb-a./rb2+...
2*a.*y1.^2./rb2.^2)+W8./W7.^2.*(cosB*sinB+W1*cotB./rb.*((2-2*nu)*...
cosB-W1./W7)+a./rb.*(sinB-y3b.*z1b./rb2-z1b.*W1./rb./W7)).*(y1./rb-...
sinB)-W8./W7.*(1./rb2*cosB.*y1*cotB.*((2-2*nu)*cosB-W1./W7)-W1*...
cotB./rb.^3.*((2-2*nu)*cosB-W1./W7).*y1+W1*cotB./rb.*(-1./rb*cosB.*...
y1./W7+W1./W7.^2.*(y1./rb-sinB))-a./rb.^3.*(sinB-y3b.*z1b./rb2-...
z1b.*W1./rb./W7).*y1+a./rb.*(-y3b*cosB./rb2+2.*y3b.*z1b./rb2.^2.*y1-...
cosB.*W1./rb./W7-z1b./rb2*cosB.*y1./W7+z1b.*W1./rb.^3./W7.*y1+z1b.*...
W1./rb./W7.^2.*(y1./rb-sinB))))/pi/(1-nu))+...
b3/2*(1/4*((2-2*nu).*rFib_ry1-(2-2*nu).*y2*sinB./W7.^2.*W2.*(y1./rb-...
sinB)-(2-2*nu).*y2*sinB./W7*a./rb.^3.*y1-y2.*W8*sinB./rb.^3./W7.*(1+...
W1./W7.*W2+a.*y3b./rb2).*y1-y2.*W8*sinB./rb./W7.^2.*(1+W1./W7.*W2+...
a.*y3b./rb2).*(y1./rb-sinB)+y2.*W8*sinB./rb./W7.*(1./rb*cosB.*y1./...
W7.*W2-W1./W7.^2.*W2.*(y1./rb-sinB)-W1./W7*a./rb.^3.*y1-2*a.*y3b./...
rb2.^2.*y1))/pi/(1-nu));
v23 = b1/2*(1/4*(N1.*(((2-2*nu)*cotB^2-nu).*(y3b./rb+1)./W6-((2-2*nu)*...
cotB^2+1-2*nu)*cosB.*W3./W7)+N1./W6.^2.*(y1*cotB.*(1-W5)+nu.*y3b-a+...
y2.^2./W6.*W4).*(y3b./rb+1)-N1./W6.*(1/2*a.*y1*cotB./rb.^3*2.*y3b+...
nu-y2.^2./W6.^2.*W4.*(y3b./rb+1)-1/2.*y2.^2./W6*a./rb.^3*2.*y3b)-N1*...
sinB*cotB./W7.*W2+N1.*z1b*cotB./W7.^2.*W2.*W3+1/2.*N1.*z1b*cotB./W7*...
a./rb.^3*2.*y3b-a./rb.^3.*y1*cotB+3./2*a.*y1.*W8*cotB./rb.^5*2.*y3b+...
1./W6.*(-2*nu+1./rb.*(N1.*y1*cotB-a)+y2.^2./rb./W6.*W5+a.*y2.^2./...
rb.^3)-W8./W6.^2.*(-2*nu+1./rb.*(N1.*y1*cotB-a)+y2.^2./rb./W6.*W5+...
a.*y2.^2./rb.^3).*(y3b./rb+1)+W8./W6.*(-1/2./rb.^3.*(N1.*y1*cotB-a)*...
2.*y3b-1/2.*y2.^2./rb.^3./W6.*W5*2.*y3b-y2.^2./rb./W6.^2.*W5.*(y3b./...
rb+1)-1/2.*y2.^2./rb2.^2./W6*a.*2.*y3b-3./2*a.*y2.^2./rb.^5*2.*y3b)+...
1./W7.*(cosB^2-1./rb.*(N1.*z1b*cotB+a.*cosB)+a.*y3b.*z1b*cotB./rb.^...
3-1./rb./W7.*(y2.^2*cosB^2-a.*z1b*cotB./rb.*W1))-W8./W7.^2.*(cosB^2-...
1./rb.*(N1.*z1b*cotB+a.*cosB)+a.*y3b.*z1b*cotB./rb.^3-1./rb./W7.*...
(y2.^2*cosB^2-a.*z1b*cotB./rb.*W1)).*W3+W8./W7.*(1/2./rb.^3.*(N1.*...
z1b*cotB+a.*cosB)*2.*y3b-1./rb.*N1*sinB*cotB+a.*z1b*cotB./rb.^3+a.*...
y3b*sinB*cotB./rb.^3-3./2*a.*y3b.*z1b*cotB./rb.^5*2.*y3b+1/2./rb.^...
3./W7.*(y2.^2*cosB^2-a.*z1b*cotB./rb.*W1)*2.*y3b+1./rb./W7.^2.*(y2.^...
2*cosB^2-a.*z1b*cotB./rb.*W1).*W3-1./rb./W7.*(-a.*sinB*cotB./rb.*W1+...
1/2*a.*z1b*cotB./rb.^3.*W1*2.*y3b-a.*z1b*cotB./rb.*(cosB*y3b./rb+...
1))))/pi/(1-nu))+...
b2/2*(1/4*((2-2*nu)*N1.*rFib_ry3*cotB^2-N1.*y2./W6.^2.*((W5-1)*cotB+...
y1./W6.*W4).*(y3b./rb+1)+N1.*y2./W6.*(-1/2*a./rb.^3*2.*y3b*cotB-y1./...
W6.^2.*W4.*(y3b./rb+1)-1/2.*y1./W6*a./rb.^3*2.*y3b)+N1.*y2*cotB./...
W7.^2.*W9.*W3+1/2.*N1.*y2*cotB./W7*a./rb.^3./cosB*2.*y3b-a./rb.^3.*...
y2*cotB+3./2*a.*y2.*W8*cotB./rb.^5*2.*y3b+y2./rb./W6.*(N1*cotB-2*...
nu.*y1./W6-a.*y1./rb.*(1./rb+1./W6))-1/2.*y2.*W8./rb.^3./W6.*(N1*...
cotB-2*nu.*y1./W6-a.*y1./rb.*(1./rb+1./W6))*2.*y3b-y2.*W8./rb./W6.^...
2.*(N1*cotB-2*nu.*y1./W6-a.*y1./rb.*(1./rb+1./W6)).*(y3b./rb+1)+y2.*...
W8./rb./W6.*(2*nu.*y1./W6.^2.*(y3b./rb+1)+1/2*a.*y1./rb.^3.*(1./rb+...
1./W6)*2.*y3b-a.*y1./rb.*(-1/2./rb.^3*2.*y3b-1./W6.^2.*(y3b./rb+...
1)))+y2*cotB./rb./W7.*((-2+2*nu)*cosB+W1./W7.*W9+a.*y3b./rb2./cosB)-...
1/2.*y2.*W8*cotB./rb.^3./W7.*((-2+2*nu)*cosB+W1./W7.*W9+a.*y3b./...
rb2./cosB)*2.*y3b-y2.*W8*cotB./rb./W7.^2.*((-2+2*nu)*cosB+W1./W7.*...
W9+a.*y3b./rb2./cosB).*W3+y2.*W8*cotB./rb./W7.*((cosB*y3b./rb+1)./...
W7.*W9-W1./W7.^2.*W9.*W3-1/2.*W1./W7*a./rb.^3./cosB*2.*y3b+a./rb2./...
cosB-a.*y3b./rb2.^2./cosB*2.*y3b))/pi/(1-nu))+...
b3/2*(1/4*(N1.*(-sinB.*W3./W7+y1./W6.^2.*(1+a./rb).*(y3b./rb+1)+...
1/2.*y1./W6*a./rb.^3*2.*y3b+sinB./W7.*W2-z1b./W7.^2.*W2.*W3-1/2.*...
z1b./W7*a./rb.^3*2.*y3b)+y1./rb.*(a./rb2+1./W6)-1/2.*y1.*W8./rb.^...
3.*(a./rb2+1./W6)*2.*y3b+y1.*W8./rb.*(-a./rb2.^2*2.*y3b-1./W6.^2.*...
(y3b./rb+1))-1./W7.*(sinB.*(cosB-a./rb)+z1b./rb.*(1+a.*y3b./rb2)-1./...
rb./W7.*(y2.^2*cosB*sinB-a.*z1b./rb.*W1))+W8./W7.^2.*(sinB.*(cosB-...
a./rb)+z1b./rb.*(1+a.*y3b./rb2)-1./rb./W7.*(y2.^2*cosB*sinB-a.*z1b./...
rb.*W1)).*W3-W8./W7.*(1/2*sinB*a./rb.^3*2.*y3b+sinB./rb.*(1+a.*y3b./...
rb2)-1/2.*z1b./rb.^3.*(1+a.*y3b./rb2)*2.*y3b+z1b./rb.*(a./rb2-a.*...
y3b./rb2.^2*2.*y3b)+1/2./rb.^3./W7.*(y2.^2*cosB*sinB-a.*z1b./rb.*...
W1)*2.*y3b+1./rb./W7.^2.*(y2.^2*cosB*sinB-a.*z1b./rb.*W1).*W3-1./...
rb./W7.*(-a.*sinB./rb.*W1+1/2*a.*z1b./rb.^3.*W1*2.*y3b-a.*z1b./rb.*...
(cosB*y3b./rb+1))))/pi/(1-nu))+...
b1/2*(1/4*((2-2*nu).*(N1.*rFib_ry2*cotB+1./W6.*W5-y2.^2./W6.^2.*W5./...
rb-y2.^2./W6*a./rb.^3-cosB./W7.*W2+y2.^2*cosB./W7.^2.*W2./rb+y2.^2*...
cosB./W7*a./rb.^3)+W8./rb.*(2*nu./W6+a./rb2)-y2.^2.*W8./rb.^3.*(2*...
nu./W6+a./rb2)+y2.*W8./rb.*(-2*nu./W6.^2./rb.*y2-2*a./rb2.^2.*y2)+...
W8*cosB./rb./W7.*(1-2*nu-W1./W7.*W2-a.*y3b./rb2)-y2.^2.*W8*cosB./...
rb.^3./W7.*(1-2*nu-W1./W7.*W2-a.*y3b./rb2)-y2.^2.*W8*cosB./rb2./W7.^...
2.*(1-2*nu-W1./W7.*W2-a.*y3b./rb2)+y2.*W8*cosB./rb./W7.*(-1./rb*...
cosB.*y2./W7.*W2+W1./W7.^2.*W2./rb.*y2+W1./W7*a./rb.^3.*y2+2*a.*...
y3b./rb2.^2.*y2))/pi/(1-nu))+...
b2/2*(1/4*((-2+2*nu).*N1*cotB.*(1./rb.*y2./W6-cosB./rb.*y2./W7)+(2-...
2*nu).*y1./W6.^2.*W5./rb.*y2+(2-2*nu).*y1./W6*a./rb.^3.*y2-(2-2*...
nu).*z1b./W7.^2.*W2./rb.*y2-(2-2*nu).*z1b./W7*a./rb.^3.*y2-W8./rb.^...
3.*(N1*cotB-2*nu.*y1./W6-a.*y1./rb2).*y2+W8./rb.*(2*nu.*y1./W6.^2./...
rb.*y2+2*a.*y1./rb2.^2.*y2)+W8./W7.^2.*(cosB*sinB+W1*cotB./rb.*((2-...
2*nu)*cosB-W1./W7)+a./rb.*(sinB-y3b.*z1b./rb2-z1b.*W1./rb./W7))./...
rb.*y2-W8./W7.*(1./rb2*cosB.*y2*cotB.*((2-2*nu)*cosB-W1./W7)-W1*...
cotB./rb.^3.*((2-2*nu)*cosB-W1./W7).*y2+W1*cotB./rb.*(-cosB./rb.*...
y2./W7+W1./W7.^2./rb.*y2)-a./rb.^3.*(sinB-y3b.*z1b./rb2-z1b.*W1./...
rb./W7).*y2+a./rb.*(2.*y3b.*z1b./rb2.^2.*y2-z1b./rb2*cosB.*y2./W7+...
z1b.*W1./rb.^3./W7.*y2+z1b.*W1./rb2./W7.^2.*y2)))/pi/(1-nu))+...
b3/2*(1/4*((2-2*nu).*rFib_ry2+(2-2*nu)*sinB./W7.*W2-(2-2*nu).*y2.^2*...
sinB./W7.^2.*W2./rb-(2-2*nu).*y2.^2*sinB./W7*a./rb.^3+W8*sinB./rb./...
W7.*(1+W1./W7.*W2+a.*y3b./rb2)-y2.^2.*W8*sinB./rb.^3./W7.*(1+W1./...
W7.*W2+a.*y3b./rb2)-y2.^2.*W8*sinB./rb2./W7.^2.*(1+W1./W7.*W2+a.*...
y3b./rb2)+y2.*W8*sinB./rb./W7.*(1./rb*cosB.*y2./W7.*W2-W1./W7.^2.*...
W2./rb.*y2-W1./W7*a./rb.^3.*y2-2*a.*y3b./rb2.^2.*y2))/pi/(1-nu));
|
github
|
chaovite/crack_pipe-master
|
TDdispFS.m
|
.m
|
crack_pipe-master/source/TriDisloc3d/TDdispFS.m
| 10,409 |
utf_8
|
dbf65044c43e2187e8c9eb6f63a395e1
|
function [ue,un,uv]=TDdispFS(X,Y,Z,P1,P2,P3,Ss,Ds,Ts,nu)
% TDdispFS
% Calculates displacements associated with a triangular dislocation in an
% elastic full-space.
%
% TD: Triangular Dislocation
% EFCS: Earth-Fixed Coordinate System
% TDCS: Triangular Dislocation Coordinate System
% ADCS: Angular Dislocation Coordinate System
%
% INPUTS
% X, Y and Z:
% Coordinates of calculation points in EFCS (East, North, Up). X, Y and Z
% must have the same size.
%
% P1,P2 and P3:
% Coordinates of TD vertices in EFCS.
%
% Ss, Ds and Ts:
% TD slip vector components (Strike-slip, Dip-slip, Tensile-slip).
%
% nu:
% Poisson's ratio.
%
% OUTPUTS
% ue, un and uv:
% Calculated displacement vector components in EFCS. ue, un and uv have
% the same unit as Ss, Ds and Ts in the inputs.
%
%
% Example: Calculate and plot the first component of displacement vector
% on a regular grid.
%
% [X,Y,Z] = meshgrid(-3:.02:3,-3:.02:3,2);
% [ue,un,uv] = TDdispFS(X,Y,Z,[-1 0 0],[1 -1 -1],[0 1.5 .5],-1,2,3,.25);
% h = surf(X,Y,reshape(ue,size(X)),'edgecolor','none');
% view(2)
% axis equal
% axis tight
% set(gcf,'renderer','painters')
% Reference journal article:
% Nikkhoo M. and Walter T.R., 2015. Triangular dislocation: An analytical,
% artefact-free solution.
% Submitted to Geophysical Journal International
% Copyright (c) 2014 Mehdi Nikkhoo
%
% Permission is hereby granted, free of charge, to any person obtaining a
% copy of this software and associated documentation files
% (the "Software"), to deal in the Software without restriction, including
% without limitation the rights to use, copy, modify, merge, publish,
% distribute, sublicense, and/or sell copies of the Software, and to permit
% persons to whom the Software is furnished to do so, subject to the
% following conditions:
%
% The above copyright notice and this permission notice shall be included
% in all copies or substantial portions of the Software.
%
% THE SOFTWARE 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. IN
% NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
% DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
% OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
% USE OR OTHER DEALINGS IN THE SOFTWARE.
% I appreciate any comments or bug reports.
% Mehdi Nikkhoo
% created: 2012.5.14
% Last modified: 2014.7.30
%
% VolcanoTectonics Research Group
% Section 2.1, Physics of Earthquakes and Volcanoes
% Department 2, Physics of the Earth
% Helmholtz Centre Potsdam
% German Research Centre for Geosciences (GFZ)
%
% email:
% [email protected]
% [email protected]
bx = Ts; % Tensile-slip
by = Ss; % Strike-slip
bz = Ds; % Dip-slip
X = X(:);
Y = Y(:);
Z = Z(:);
P1 = P1(:);
P2 = P2(:);
P3 = P3(:);
% Calculate unit strike, dip and normal to TD vectors: For a horizontal TD
% as an exception, if the normal vector points upward, the strike and dip
% vectors point Northward and Westward, whereas if the normal vector points
% downward, the strike and dip vectors point Southward and Westward,
% respectively.
Vnorm = cross(P2-P1,P3-P1);
Vnorm = Vnorm/norm(Vnorm);
eY = [0 1 0]';
eZ = [0 0 1]';
Vstrike = cross(eZ,Vnorm);
if norm(Vstrike)==0
Vstrike = eY*Vnorm(3);
end
Vstrike = Vstrike/norm(Vstrike);
Vdip = cross(Vnorm,Vstrike);
% Transform coordinates from EFCS into TDCS
p1 = zeros(3,1);
p2 = zeros(3,1);
p3 = zeros(3,1);
At = [Vnorm Vstrike Vdip]';
[x,y,z] = CoordTrans(X'-P2(1),Y'-P2(2),Z'-P2(3),At);
[p1(1),p1(2),p1(3)] = CoordTrans(P1(1)-P2(1),P1(2)-P2(2),P1(3)-P2(3),At);
[p3(1),p3(2),p3(3)] = CoordTrans(P3(1)-P2(1),P3(2)-P2(2),P3(3)-P2(3),At);
% Calculate the unit vectors along TD sides in TDCS
e12 = (p2-p1)/norm(p2-p1);
e13 = (p3-p1)/norm(p3-p1);
e23 = (p3-p2)/norm(p3-p2);
% Calculate the TD angles
A = acos(e12'*e13);
B = acos(-e12'*e23);
C = acos(e23'*e13);
% Determine the best arteact-free configuration for each calculation point
Trimode = trimodefinder(y,z,x,p1(2:3),p2(2:3),p3(2:3));
casepLog = Trimode==1;
casenLog = Trimode==-1;
casezLog = Trimode==0;
xp = x(casepLog);
yp = y(casepLog);
zp = z(casepLog);
xn = x(casenLog);
yn = y(casenLog);
zn = z(casenLog);
% Configuration I
if nnz(casepLog)~=0
% Calculate first angular dislocation contribution
[u1Tp,v1Tp,w1Tp] = TDSetupD(xp,yp,zp,A,bx,by,bz,nu,p1,-e13);
% Calculate second angular dislocation contribution
[u2Tp,v2Tp,w2Tp] = TDSetupD(xp,yp,zp,B,bx,by,bz,nu,p2,e12);
% Calculate third angular dislocation contribution
[u3Tp,v3Tp,w3Tp] = TDSetupD(xp,yp,zp,C,bx,by,bz,nu,p3,e23);
end
% Configuration II
if nnz(casenLog)~=0
% Calculate first angular dislocation contribution
[u1Tn,v1Tn,w1Tn] = TDSetupD(xn,yn,zn,A,bx,by,bz,nu,p1,e13);
% Calculate second angular dislocation contribution
[u2Tn,v2Tn,w2Tn] = TDSetupD(xn,yn,zn,B,bx,by,bz,nu,p2,-e12);
% Calculate third angular dislocation contribution
[u3Tn,v3Tn,w3Tn] = TDSetupD(xn,yn,zn,C,bx,by,bz,nu,p3,-e23);
end
% Calculate the "incomplete" displacement vector components in TDCS
if nnz(casepLog)~=0
u(casepLog,1) = u1Tp+u2Tp+u3Tp;
v(casepLog,1) = v1Tp+v2Tp+v3Tp;
w(casepLog,1) = w1Tp+w2Tp+w3Tp;
end
if nnz(casenLog)~=0
u(casenLog,1) = u1Tn+u2Tn+u3Tn;
v(casenLog,1) = v1Tn+v2Tn+v3Tn;
w(casenLog,1) = w1Tn+w2Tn+w3Tn;
end
if nnz(casezLog)~=0
u(casezLog,1) = nan;
v(casezLog,1) = nan;
w(casezLog,1) = nan;
end
% Calculate the Burgers' function contribution corresponding to the TD
a = [-x p1(2)-y p1(3)-z];
b = [-x -y -z];
c = [-x p3(2)-y p3(3)-z];
na = sqrt(sum(a.^2,2));
nb = sqrt(sum(b.^2,2));
nc = sqrt(sum(c.^2,2));
Fi = -2*atan2((a(:,1).*(b(:,2).*c(:,3)-b(:,3).*c(:,2))-...
a(:,2).*(b(:,1).*c(:,3)-b(:,3).*c(:,1))+...
a(:,3).*(b(:,1).*c(:,2)-b(:,2).*c(:,1))),...
(na.*nb.*nc+sum(a.*b,2).*nc+sum(a.*c,2).*nb+sum(b.*c,2).*na))/4/pi;
% Calculate the complete displacement vector components in TDCS
u = bx.*Fi+u;
v = by.*Fi+v;
w = bz.*Fi+w;
% Transform the complete displacement vector components from TDCS into EFCS
[ue,un,uv] = CoordTrans(u,v,w,[Vnorm Vstrike Vdip]);
function [X1,X2,X3]=CoordTrans(x1,x2,x3,A)
% CoordTrans transforms the coordinates of the vectors, from
% x1x2x3 coordinate system to X1X2X3 coordinate system. "A" is the
% transformation matrix, whose columns e1,e2 and e3 are the unit base
% vectors of the x1x2x3. The coordinates of e1,e2 and e3 in A must be given
% in X1X2X3. The transpose of A (i.e., A') will transform the coordinates
% from X1X2X3 into x1x2x3.
x1 = x1(:);
x2 = x2(:);
x3 = x3(:);
r = A*[x1';x2';x3'];
X1 = r(1,:)';
X2 = r(2,:)';
X3 = r(3,:)';
function [trimode]=trimodefinder(x,y,z,p1,p2,p3)
% trimodefinder calculates the normalized barycentric coordinates of
% the points with respect to the TD vertices and specifies the appropriate
% artefact-free configuration of the angular dislocations for the
% calculations. The input matrices x, y and z share the same size and
% correspond to the y, z and x coordinates in the TDCS, respectively. p1,
% p2 and p3 are two-component matrices representing the y and z coordinates
% of the TD vertices in the TDCS, respectively.
% The components of the output (trimode) corresponding to each calculation
% points, are 1 for the first configuration, -1 for the second
% configuration and 0 for the calculation point that lie on the TD sides.
x = x(:);
y = y(:);
z = z(:);
a = ((p2(2)-p3(2)).*(x-p3(1))+(p3(1)-p2(1)).*(y-p3(2)))./...
((p2(2)-p3(2)).*(p1(1)-p3(1))+(p3(1)-p2(1)).*(p1(2)-p3(2)));
b = ((p3(2)-p1(2)).*(x-p3(1))+(p1(1)-p3(1)).*(y-p3(2)))./...
((p2(2)-p3(2)).*(p1(1)-p3(1))+(p3(1)-p2(1)).*(p1(2)-p3(2)));
c = 1-a-b;
trimode = ones(length(x),1);
trimode(a<=0 & b>c & c>a) = -1;
trimode(b<=0 & c>a & a>b) = -1;
trimode(c<=0 & a>b & b>c) = -1;
trimode(a==0 & b>=0 & c>=0) = 0;
trimode(a>=0 & b==0 & c>=0) = 0;
trimode(a>=0 & b>=0 & c==0) = 0;
trimode(trimode==0 & z~=0) = 1;
function [u,v,w]=TDSetupD(x,y,z,alpha,bx,by,bz,nu,TriVertex,SideVec)
% TDSetupD transforms coordinates of the calculation points as well as
% slip vector components from ADCS into TDCS. It then calculates the
% displacements in ADCS and transforms them into TDCS.
% Transformation matrix
A = [[SideVec(3);-SideVec(2)] SideVec(2:3)]';
% Transform coordinates of the calculation points from TDCS into ADCS
r1 = A*[y'-TriVertex(2);z'-TriVertex(3)];
y1 = r1(1,:)';
z1 = r1(2,:)';
% Transform the in-plane slip vector components from TDCS into ADCS
r2 = A*[by;bz];
by1 = r2(1,:)';
bz1 = r2(2,:)';
% Calculate displacements associated with an angular dislocation in ADCS
[u,v0,w0] = AngDisDisp(x,y1,z1,-pi+alpha,bx,by1,bz1,nu);
% Transform displacements from ADCS into TDCS
r3 = A'*[v0';w0'];
v = r3(1,:)';
w = r3(2,:)';
function [u,v,w]=AngDisDisp(x,y,z,alpha,bx,by,bz,nu)
% AngDisDisp calculates the "incomplete" displacements (without the
% Burgers' function contribution) associated with an angular dislocation in
% an elastic full-space.
cosA = cos(alpha);
sinA = sin(alpha);
eta = y*cosA-z*sinA;
zeta = y*sinA+z*cosA;
r = sqrt(x.^2+y.^2+z.^2);
% Avoid complex results for the logarithmic terms
zeta(zeta>r) = r(zeta>r);
z(z>r) = r(z>r);
ux = bx/8/pi/(1-nu)*(x.*y./r./(r-z)-x.*eta./r./(r-zeta));
vx = bx/8/pi/(1-nu)*(eta*sinA./(r-zeta)-y.*eta./r./(r-zeta)+...
y.^2./r./(r-z)+(1-2*nu)*(cosA*log(r-zeta)-log(r-z)));
wx = bx/8/pi/(1-nu)*(eta*cosA./(r-zeta)-y./r-eta.*z./r./(r-zeta)-...
(1-2*nu)*sinA*log(r-zeta));
uy = by/8/pi/(1-nu)*(x.^2*cosA./r./(r-zeta)-x.^2./r./(r-z)-...
(1-2*nu)*(cosA*log(r-zeta)-log(r-z)));
vy = by*x/8/pi/(1-nu).*(y.*cosA./r./(r-zeta)-...
sinA*cosA./(r-zeta)-y./r./(r-z));
wy = by*x/8/pi/(1-nu).*(z*cosA./r./(r-zeta)-...
cosA^2./(r-zeta)+1./r);
uz = bz*sinA/8/pi/(1-nu).*((1-2*nu)*log(r-zeta)-x.^2./r./(r-zeta));
vz = bz*x*sinA/8/pi/(1-nu).*(sinA./(r-zeta)-y./r./(r-zeta));
wz = bz*x*sinA/8/pi/(1-nu).*(cosA./(r-zeta)-z./r./(r-zeta));
u = ux+uy+uz;
v = vx+vy+vz;
w = wx+wy+wz;
|
github
|
mangye16/IDE-baseline-Market-1501-master
|
LOMO.m
|
.m
|
IDE-baseline-Market-1501-master/market_evaluation/LOMO_XQDA/code/LOMO.m
| 10,918 |
utf_8
|
20a351130c8001186927d19a29d23814
|
function descriptors = LOMO(images, options)
%% function Descriptors = LOMO(images, options)
% Function for the Local Maximal Occurrence (LOMO) feature extraction
%
% Input:
% <images>: a set of n RGB color images. Size: [h, w, 3, n]
% [optioins]: optional parameters. A structure containing any of the
% following fields:
% numScales: number of pyramid scales in feature extraction. Default: 3
% blockSize: size of the sub-window for histogram counting. Default: 10
% blockStep: sliding step for the sub-windows. Default: 5
% hsvBins: number of bins for HSV channels. Default: [8,8,8]
% tau: the tau parameter in SILTP. Default: 0.3
% R: the radius paramter in SILTP. Specify multiple values for multiscale SILTP. Default: [3, 5]
% numPoints: number of neiborhood points for SILTP encoding. Default: 4
% The above default parameters are good for 128x48 and 160x60 person
% images. You may need to adjust the numScales, blockSize, and R parameters
% for other smaller or higher resolutions.
%
% Output:
% descriptors: the extracted LOMO descriptors. Size: [d, n]
%
% Example:
% I = imread('../images/000_45_a.bmp');
% descriptor = LOMO(I);
%
% Reference:
% Shengcai Liao, Yang Hu, Xiangyu Zhu, and Stan Z. Li. Person
% re-identification by local maximal occurrence representation and metric
% learning. In IEEE Conference on Computer Vision and Pattern Recognition, 2015.
%
% Version: 1.0
% Date: 2015-04-29
%
% Author: Shengcai Liao
% Institute: National Laboratory of Pattern Recognition,
% Institute of Automation, Chinese Academy of Sciences
% Email: [email protected]
%% set parameters
numScales = 3;
blockSize = 10;
blockStep = 5;
hsvBins = [8,8,8];
tau = 0.3;
R = [3, 5];
numPoints = 4;
if nargin >= 2
if isfield(options,'numScales') && ~isempty(options.numScales) && isscalar(options.numScales) && isnumeric(options.numScales) && options.numScales > 0
numScales = options.numScales;
fprintf('numScales = %d.\n', numScales);
end
if isfield(options,'blockSize') && ~isempty(options.blockSize) && isscalar(options.blockSize) && isnumeric(options.blockSize) && options.blockSize > 0
blockSize = options.blockSize;
fprintf('blockSize = %d.\n', blockSize);
end
if isfield(options,'blockStep') && ~isempty(options.blockStep) && isscalar(options.blockStep) && isnumeric(options.blockStep) && options.blockStep > 0
blockStep = options.blockStep;
fprintf('blockStep = %d.\n', blockStep);
end
if isfield(options,'hsvBins') && ~isempty(options.hsvBins) && isvector(options.blockStep) && isnumeric(options.hsvBins) && length(options.hsvBins) == 3 && all(options.hsvBins > 0)
hsvBins = options.hsvBins;
fprintf('hsvBins = [%d, %d, %d].\n', hsvBins);
end
if isfield(options,'tau') && ~isempty(options.tau) && isscalar(options.tau) && isnumeric(options.tau) && options.tau > 0
tau = options.tau;
fprintf('tau = %g.\n', tau);
end
if isfield(options,'R') && ~isempty(options.R) && isnumeric(options.R) && all(options.R > 0)
R = options.R;
fprintf('R = %d.\n', R);
end
if isfield(options,'numPoints') && ~isempty(options.numPoints) && isscalar(options.numPoints) && isnumeric(options.numPoints) && options.numPoints > 0
numPoints = options.numPoints;
fprintf('numPoints = %d.\n', numPoints);
end
end
t0 = tic;
%% extract Joint HSV based LOMO descriptors
fea1 = PyramidMaxJointHist( images, numScales, blockSize, blockStep, hsvBins );
%% extract SILTP based LOMO descriptors
fea2 = [];
for i = 1 : length(R)
fea2 = [fea2; PyramidMaxSILTPHist( images, numScales, blockSize, blockStep, tau, R(i), numPoints )]; %#ok<AGROW>
end
%% finishing
descriptors = [fea1; fea2];
clear Fea1 Fea2
feaTime = toc(t0);
meanTime = feaTime / size(images, 4);
% fprintf('LOMO feature extraction finished. Running time: %.3f seconds in total, %.3f seconds per image.\n', feaTime, meanTime);
end
function descriptors = PyramidMaxJointHist( oriImgs, numScales, blockSize, blockStep, colorBins )
%% PyramidMaxJointHist: HSV based LOMO representation
if nargin == 1
numScales = 3;
blockSize = 10;
blockStep = 5;
colorBins = [8,8,8];
end
totalBins = prod(colorBins);
numImgs = size(oriImgs, 4);
images = zeros(size(oriImgs));
% color transformation
for i = 1 : numImgs
I = oriImgs(:,:,:,i);
I = Retinex(I);
I = rgb2hsv(I);
I(:,:,1) = min( floor( I(:,:,1) * colorBins(1) ), colorBins(1)-1 );
I(:,:,2) = min( floor( I(:,:,2) * colorBins(2) ), colorBins(2)-1 );
I(:,:,3) = min( floor( I(:,:,3) * colorBins(3) ), colorBins(3)-1 );
images(:,:,:,i) = I; % HSV
end
minRow = 1;
minCol = 1;
descriptors = [];
% Scan multi-scale blocks and compute histograms
for i = 1 : numScales
patterns = images(:,:,3,:) * colorBins(2) * colorBins(1) + images(:,:,2,:)*colorBins(1) + images(:,:,1,:); % HSV
patterns = reshape(patterns, [], numImgs);
height = size(images, 1);
width = size(images, 2);
maxRow = height - blockSize + 1;
maxCol = width - blockSize + 1;
[cols,rows] = meshgrid(minCol:blockStep:maxCol, minRow:blockStep:maxRow); % top-left positions
cols = cols(:);
rows = rows(:);
numBlocks = length(cols);
numBlocksCol = length(minCol:blockStep:maxCol);
if numBlocks == 0
break;
end
offset = bsxfun(@plus, (0 : blockSize-1)', (0 : blockSize-1) * height); % offset to the top-left positions. blockSize-by-blockSize
index = sub2ind([height, width], rows, cols);
index = bsxfun(@plus, offset(:), index'); % (blockSize*blockSize)-by-numBlocks
patches = patterns(index(:), :); % (blockSize * blockSize * numBlocks)-by-numImgs
patches = reshape(patches, [], numBlocks * numImgs); % (blockSize * blockSize)-by-(numBlocks * numChannels * numImgs)
fea = hist(patches, 0 : totalBins-1); % totalBins-by-(numBlocks * numImgs)
fea = reshape(fea, [totalBins, numBlocks / numBlocksCol, numBlocksCol, numImgs]);
fea = max(fea, [], 3);
fea = reshape(fea, [], numImgs);
descriptors = [descriptors; fea]; %#ok<AGROW>
if i < numScales
images = ColorPooling(images, 'average');
end
end
descriptors = log(descriptors + 1);
descriptors = normc(descriptors);
end
function outImages = ColorPooling(images, method)
[height, width, numChannels, numImgs] = size(images);
outImages = images;
if mod(height, 2) == 1
outImages(end, :, :, :) = [];
height = height - 1;
end
if mod(width, 2) == 1
outImages(:, end, :, :) = [];
width = width - 1;
end
if height == 0 || width == 0
error('Over scaled image: height=%d, width=%d.', height, width);
end
height = height / 2;
width = width / 2;
outImages = reshape(outImages, 2, height, 2, width, numChannels, numImgs);
outImages = permute(outImages, [2, 4, 5, 6, 1, 3]);
outImages = reshape(outImages, height, width, numChannels, numImgs, 2*2);
if strcmp(method, 'average')
outImages = floor(mean(outImages, 5));
else if strcmp(method, 'max')
outImages = max(outImages, [], 5);
else
error('Error pooling method: %s.', method);
end
end
end
function descriptors = PyramidMaxSILTPHist( oriImgs, numScales, blockSize, blockStep, tau, R, numPoints )
%% PyramidMaxSILTPHist: SILTP based LOMO representation
if nargin == 1
numScales = 3;
blockSize = 10;
blockStep = 5;
tau = 0.3;
R = 5;
numPoints = 4;
end
totalBins = 3^numPoints;
[imgHeight, imgWidth, ~, numImgs] = size(oriImgs);
images = zeros(imgHeight,imgWidth, numImgs);
% Convert gray images
for i = 1 : numImgs
I = oriImgs(:,:,:,i);
I = rgb2gray(I);
images(:,:,i) = double(I) / 255;
end
minRow = 1;
minCol = 1;
descriptors = [];
% Scan multi-scale blocks and compute histograms
for i = 1 : numScales
height = size(images, 1);
width = size(images, 2);
if width < R * 2 + 1
fprintf('Skip scale R = %d, width = %d.\n', R, width);
continue;
end
patterns = SILTP(images, tau, R, numPoints);
patterns = reshape(patterns, [], numImgs);
maxRow = height - blockSize + 1;
maxCol = width - blockSize + 1;
[cols,rows] = meshgrid(minCol:blockStep:maxCol, minRow:blockStep:maxRow); % top-left positions
cols = cols(:);
rows = rows(:);
numBlocks = length(cols);
numBlocksCol = length(minCol:blockStep:maxCol);
if numBlocks == 0
break;
end
offset = bsxfun(@plus, (0 : blockSize-1)', (0 : blockSize-1) * height); % offset to the top-left positions. blockSize-by-blockSize
index = sub2ind([height, width], rows, cols);
index = bsxfun(@plus, offset(:), index'); % (blockSize*blockSize)-by-numBlocks
patches = patterns(index(:), :); % (blockSize * blockSize * numBlocks)-by-numImgs
patches = reshape(patches, [], numBlocks * numImgs); % (blockSize * blockSize)-by-(numBlocks * numChannels * numImgs)
fea = hist(patches, 0:totalBins-1); % totalBins-by-(numBlocks * numImgs)
fea = reshape(fea, [totalBins, numBlocks / numBlocksCol, numBlocksCol, numImgs]);
fea = max(fea, [], 3);
fea = reshape(fea, [], numImgs);
descriptors = [descriptors; fea]; %#ok<AGROW>
if i < numScales
images = Pooling(images, 'average');
end
end
descriptors = log(descriptors + 1);
descriptors = normc(descriptors);
end
function outImages = Pooling(images, method)
[height, width, numImgs] = size(images);
outImages = images;
if mod(height, 2) == 1
outImages(end, :, :) = [];
height = height - 1;
end
if mod(width, 2) == 1
outImages(:, end, :) = [];
width = width - 1;
end
if height == 0 || width == 0
error('Over scaled image: height=%d, width=%d.', height, width);
end
height = height / 2;
width = width / 2;
outImages = reshape(outImages, 2, height, 2, width, numImgs);
outImages = permute(outImages, [2, 4, 5, 1, 3]);
outImages = reshape(outImages, height, width, numImgs, 2*2);
if strcmp(method, 'average')
outImages = mean(outImages, 4);
else if strcmp(method, 'max')
outImages = max(outImages, [], 4);
else
error('Error pooling method: %s.', method);
end
end
end
|
github
|
mangye16/IDE-baseline-Market-1501-master
|
evalData.m
|
.m
|
IDE-baseline-Market-1501-master/market_evaluation/KISSME/toolbox/evalData.m
| 4,143 |
utf_8
|
fa4260fdbaa73509795057250201aece
|
function [ds,rocPlot] = evalData(pairs, ds, params)
% EVALDATA Evaluate results and plot figures
%
% Input:
% pairs - [1xN] struct. N is the number of pairs. Fields: pairs.fold
% pairs.match, pairs.img1, pairs.img2.
% ds - [1xF] data struct. F is the number of folds.
% ds.method.dist is required to compute tpr, fpr, etc.
% params - Parameter struct with the following fields:
% params.title - Title for ROC plot.
% params.saveDir - Directory to which all the plots are saved
%
% Output:
% ds - Augmented result data struct
% rocPlot - handle to the ROC figure
%
% copyright by Martin Koestinger (2011)
% Graz University of Technology
% contact [email protected]
%
% For more information, see <a href="matlab:
% web('http://lrs.icg.tugraz.at/members/koestinger')">the ICG Web site</a>.
%
if ~isfield(params,'title')
params.title = 'ROC';
end
matches = logical([pairs.match]);
%-- EVAL FOLDS --%
un = unique([pairs.fold]);
for c=1:length(un)
testMask = [pairs.fold] == un(c);
% eval fold
names = fieldnames(ds(c));
for nameCounter=1:length(names)
%tpr, fpr
[ds(c).(names{nameCounter}).tpr, ds(c).(names{nameCounter}).fpr] = ...
icg_roc(matches(testMask),-ds(c).(names{nameCounter}).dist);
[ignore, ds(c).(names{nameCounter}).eerIdx] = min(abs(ds(c).(names{nameCounter}).tpr ...
- (1-ds(c).(names{nameCounter}).fpr)));
%eer
ds(c).(names{nameCounter}).eer = ...
ds(c).(names{nameCounter}).tpr(ds(c).(names{nameCounter}).eerIdx);
end
h = myplotroc(ds(c),matches(testMask),names,params);
title(sprintf('%s Fold: %d',params.title, c));
%save figure if save dir is specified
if isfield(params,'saveDir')
exportAndCropFigure(h,sprintf('Fold%d',c),params.saveDir);
end
close;
end
%-- EVAL ALL --%
names = fieldnames(ds);
for nameCounter=1:length(names)
s = [ds.(names{nameCounter})];
ms.(names{nameCounter}).std = std([s.eer]);
ms.(names{nameCounter}).dist = [s.dist];
ms.(names{nameCounter}).se = ms.(names{nameCounter}).std/sqrt(length(un));
[ms.(names{nameCounter}).tpr, ms.(names{nameCounter}).fpr, ms.(names{nameCounter}).thresh] = icg_roc(matches,-[s.dist]);
[ignore, ms.(names{nameCounter}).eerIdx] = min(abs(ms.(names{nameCounter}).tpr ...
- (1-ms.(names{nameCounter}).fpr)));
ms.(names{nameCounter}).eer = ms.(names{nameCounter}).tpr(ms.(names{nameCounter}).eerIdx);
ms.(names{nameCounter}).type = names{nameCounter};
ms.(names{nameCounter}).roccolor = s(1).roccolor;
end
[rocPlot.h,rocPlot.hL] = myplotroc(ms,matches,names,params);
if isfield(params,'saveDir')
exportAndCropFigure(rocPlot.h,'overall.png',params.saveDir);
end
end
%--------------------------------------------------------------------------
function [h,l] = myplotroc(ds,matches,names,params)
legendEntries = cell(1,length(names));
rocColors = prism(length(names)); %hsv(length(names))
for nameCounter=1:length(names)
roccolor = rocColors(nameCounter,:);
if isfield(ds.(names{nameCounter}),'roccolor');
roccolor = ds.(names{nameCounter}).roccolor;
end
%plot roc
if nameCounter==1
h = icg_plotroc(matches,-ds.(names{nameCounter}).dist);
hold on; plot(ds.(names{nameCounter}).fpr,ds.(names{nameCounter}).tpr,'Color',roccolor,'LineWidth',2,'LineStyle','-'); hold off;
else
hold on; plot(ds.(names{nameCounter}).fpr,ds.(names{nameCounter}).tpr,'Color',roccolor,'LineWidth',2,'LineStyle','-'); hold off;
end
legendEntries{nameCounter} = sprintf('%s (%.3f)',upper(names{nameCounter}),ds.(names{nameCounter}).eer);
end
grid on;
ha = get(gca);
set(get(get(ha.Children(end),'Annotation'),'LegendInformation'),'IconDisplayStyle','off');
set(get(get(ha.Children(end-1),'Annotation'),'LegendInformation'),'IconDisplayStyle','off');
l = legend(legendEntries,'Location', 'SouthEast');
drawnow;
end
%--------------------------------------------------------------------------
|
github
|
mangye16/IDE-baseline-Market-1501-master
|
LearnAlgoLMNN.m
|
.m
|
IDE-baseline-Market-1501-master/market_evaluation/KISSME/toolbox/learnAlgos/LearnAlgoLMNN.m
| 2,829 |
utf_8
|
f833d30dfe0476ecab72fc14f7cacc8a
|
%LEARNALGOLMNN Wrapper class to the actual LMNN code
classdef LearnAlgoLMNN < LearnAlgo
properties
p %parameters
s %struct
available
fhanlde
end
properties (Constant)
type = 'lmnn'
end
methods
function obj = LearnAlgoLMNN(p)
if nargin < 1
p = struct();
end
if ~isfield(p,'knn')
p.knn = 1;
end
if ~isfield(p,'maxiter')
p.maxiter = 1000; %std
end
if ~isfield(p,'validation')
p.validation = 0;
end
if ~isfield(p,'roccolor')
p.roccolor = 'k';
end
if ~isfield(p,'quiet')
p.quiet = 1;
end
obj.p = p;
check(obj);
end
function bool = check(obj)
bool = exist('lmnn.m') == 2;
if ~bool
fprintf('Sorry %s not available\n',obj.type);
end
obj.fhanlde = @lmnn;
if isunix && exist('lmnn2.m') == 2;
obj.fhanlde = @lmnn2;
end
obj.available = bool;
end
function s = learnPairwise(obj,X,idxa,idxb,matches)
if ~obj.available
s = struct();
return;
end
obj.p.knn = 1;
X = X(:,[idxa(matches) idxb(matches)]); %m x d
y = [1:sum(matches) 1:sum(matches)];
tic;
[s.L, s.Det] = obj.fhanlde(X,consecutiveLabels(y),obj.p.knn, ...
'maxiter',obj.p.maxiter,'validation',obj.p.validation, ...
'quiet',obj.p.quiet);
s.M = s.L'*s.L;
s.t = toc;
s.learnAlgo = obj;
s.roccolor = obj.p.roccolor;
end
function s = learn(obj,X,y)
if ~obj.available
s = struct();
return;
end
tic;
[s.L, s.Det] = obj.fhanlde(X,consecutiveLabels(y),obj.p.knn, ...
'maxiter', obj.p.maxiter,'validation',obj.p.validation, ...
'quiet',obj.p.quiet);
s.M = s.L'*s.L;
s.t = toc;
s.learnAlgo = obj;
s.roccolor = obj.p.roccolor;
end
function d = dist(obj, s, X, idxa,idxb)
d = cdistM(s.M,X,idxa,idxb);
end
end
end
% lmnn2 needs consecutive integers as labels
function ty = consecutiveLabels(y)
uniqueLabels = unique(y);
ty = zeros(size(y));
for cY=1:length(uniqueLabels)
mask = y == uniqueLabels(cY);
ty(mask ) = cY;
end
end
|
github
|
mangye16/IDE-baseline-Market-1501-master
|
icg_roc.m
|
.m
|
IDE-baseline-Market-1501-master/market_evaluation/KISSME/toolbox/helper/icg_roc.m
| 1,425 |
utf_8
|
11d04e9c4c3db15aa1c3b9b771eff30e
|
function [tpr,fpr,thresh] = icg_roc(tp,confs)
% ICG_ROC computes ROC measures (tpr,fpr)
%
% Input:
% tp - [m x n] matrix of zero-one labels. one row per class.
% confs - [m x n] matrix of classifier scores. one row per class.
%
% Output:
% tpr - true positive rate in interval [0,1], [m x n+1] matrix
% fpr - false positive rate in interval [0,1], [m x n+1] matrix
% confs - thresholds over interval
%
% Example:
% icg_plotroc([ones(1,10) zeros(1,10)],20:-1:1);
% produces a perfect step curve
%
% copyright by Martin Koestinger (2011)
% Graz University of Technology
% contact [email protected]
%
% For more information, see <a href="matlab:
% web('http://lrs.icg.tugraz.at/members/koestinger')">the ICG Web site</a>.
%
m = size(tp,1);
n = size(tp,2);
tpr = zeros(m,n+1);
fpr = zeros(m,n+1);
thresh = zeros(m,n);
for c=1:m
[tpr(c,:),fpr(c,:),thresh(c,:)] = icg_roc_one_class(tp(c,:),confs(c,:));
end
end
function [tpr,fpr,confs] = icg_roc_one_class(tp,confs)
[confs,idx] = sort(confs,'descend');
tps = tp(idx);
% calc recall/precision
tpr = zeros(1,numel(tps));
fpr = zeros(1,numel(tps));
tp = 0;
fp = 0;
tn = sum(tps < 0.5);
fn = numel(tps) - tn;
for i=1:numel(tps)
if tps(i) > 0.5
tp = tp + 1;
fn = fn - 1;
else
fp = fp + 1;
tn = tn - 1;
end
tpr(i) = tp/(tp+fn);
fpr(i) = fp/(fp+tn);
end
fpr = [0 fpr];
tpr = [0 tpr];
end
|
github
|
mangye16/IDE-baseline-Market-1501-master
|
lmnn.m
|
.m
|
IDE-baseline-Market-1501-master/market_evaluation/KISSME/toolbox/lib/LMNN/lmnn.m
| 15,400 |
utf_8
|
cb91112611f161bfe0a081b291878dea
|
function [L,Det]=lmnn(x,y,varargin);
%
% function [L,Det]=lmnn(maxiter,L,x,y,Kg,'Parameter1',Value1,'Parameter2',Value2,...);
%
% Input:
%
% x = input matrix (each column is an input vector)
% y = labels
% (*optional*) L = initial transformation matrix (e.g eye(size(x,1)))
% (*optional*) Kg = attract Kg nearest similar labeled vectos
%
% Parameters:
% stepsize = (default 1e-09)
% tempid = (def 0) saves state every 10 iterations in temp#.mat
% save = (def 0) save the initial computation
% skip = (def 0) loads the initial computation instead of
% recomputing (only works if previous run was on exactly the same data)
% correction = (def 15) how many steps between each update
% The number of impostors are fixed for until next "correction"
% factor = (def 1.1) multiplicative factor by which the
% "correction" gab increases
% obj = (def 1) if 1, solver solves in L, if 0, solver solves in L'*L
% thresho = (def 1e-9) cut off for change in objective function (if
% improvement is less, stop)
% thresha = (def 1e-22) cut off for stepsize, if stepsize is
% smaller stop
% validation = (def 0) fraction of training data to be used as
% validation set (best output is stored in Det.bestL)
% valcount = (def 50) every "valcount" steps do validation
% maxiter = maximum number of iterations (default: 10000)
% scale = (def. 0) if 1, all data gets re-scaled s.t. average
% distance to closest neighbor is 1
% quiet = {0,1} surpress output (default=0)
%
%
% Output:
%
% L = linear transformation xnew=L*x
%
% Det.obj = objective function over time
% Det.nimp = number of impostors over time
% Det.pars = all parameters used in run
% Det.time = time needed for computation
% Det.iter = number of iterations
% Det.verify = verify (results of validation - if used)
%
% Version 1.0
% copyright by Kilian Q. Weinbergerr (2005)
% University of Pennsylvania
% contact [email protected]
%
tempnum=num2str(round(rand(1).*1000));
fprintf('Tempfile: %s\n',tempnum);
fprintf('LMNN stable\n');
if(nargin==0)
help lmnn;
return;
end;
if(length(varargin)>0 & isnumeric(varargin{1}))
% check if neighborhood or L have been passed on
Kg=varargin{1};
fprintf('Setting neighborhood to k=%i\n',Kg);
if(length(varargin)>1 & ~isstr(varargin{2}))
L=varargin{2};
fprintf('Setting initial transformation!\n');
end;
% skip Kgand L parameters
newvarargin={};copy=0;j=1;
for i=1:length(varargin)
if(isstr(varargin{i})) copy=1;end;
if(copy)newvarargin{j}=varargin{i};j=j+1;end;
end;
varargin=newvarargin;
clear('newvarargin','copy');
else
fprintf('Neigborhood size not specified. Setting k=3\n');
Kg=3;
end;
if(exist('L')~=1)
fprintf(['Initial starting point not specified.\nStarting with identity matrix.\n']);
L=eye(size(x,1));
end;
tic
% checks
D=size(L,2);
x=x(1:D,:);
if(size(x,1)>length(L)) error('x and L must have matching dimensions!\n');end;
% set parameters
pars.stepsize=1e-07;
pars.minstepsize=0;
pars.tempid=-1;
pars.save=0;
pars.skip=0;
pars.maxiter=10000;
pars.factor=1.1;
pars.correction=15;
pars.thresho=1e-7;
pars.thresha=1e-22;
pars.ifraction=1;
pars.scale=0;
pars.obj=1;
pars.union=1;
pars.tabularasa=Inf;
pars.quiet=0;
pars.validation=0;
pars.validationstep=50;
pars.earlystopping=0;
pars.aggressive=0;
pars.valcount=50;
pars.stepgrowth=1.01;
pars.reg=0;
pars.weight1=0.5;
pars.maximp=100000;
pars.fifo=0;
pars.guard=0;
pars.graphics=0;
pars=extractpars(varargin,pars);
% verification dataset
%i=randperm(size(x,2));
i=1:size(x,2);
tr=ceil(size(x,2)*(1-pars.validation));
ve=size(x,2)-tr;
xo=x;
yo=y;
x=xo(:,i(1:tr));
y=yo(i(1:tr));
xv=xo(:,i(tr+1:end));
yv=yo(i(tr+1:end));
verify=[];besterr=inf;
clear('xo','yo');
lowesterr=inf;
verify=[];
bestL=L;
if(~pars.quiet)
pars
end;
tempname=sprintf('temp%i.mat',pars.tempid);
% Initializationip
[D,N]=size(x);
fprintf('%i input vectors with %i dimensions\n',N,D);
[gen,NN]=getGenLS(x,y,Kg,pars);
obj=zeros(1,pars.maxiter);
nimp=zeros(1,pars.maxiter);
if(~pars.quiet) fprintf('Total number of genuine pairs: %i\n',size(gen,2));end;
[imp]= checkup(L,x,y,NN(end,:),pars);
if(~pars.quiet)fprintf('Total number of imposture pairs: %i\n',size(imp,2));end;
if(pars.reg==1)
dfG=vec(eye(D));
else
dfG=vec(SOD(x,gen(1,:),gen(2,:)));
end;
% Fifo=zeros(1,size(imp,2));
if(pars.scale)
Lx=L*x;
sc=sqrt(mean(sum( ((Lx-Lx(:,NN(end,:)))).^2)));
L=L./sc;
end;
df=zeros(D^2,1);
correction=pars.correction;
tabularasa=pars.tabularasa;
ifraction=pars.ifraction;
stepsize=pars.stepsize;
lastcor=1;
if(pars.graphics)
hpl=scat(L*x,3,y+0,'size',120);
end;
for nnid=1:Kg; a1{nnid}=[];a2{nnid}=[];end;
df=zeros(size(dfG));
% Main Loop
for iter=1:pars.maxiter
% save old position
Lold=L;dfold=df;
for nnid=1:Kg; a1old{nnid}=a1{nnid};a2old{nnid}=a2{nnid};end;
if(iter>1)L=step(L,mat((dfG.*pars.weight1+df.*(1-pars.weight1))),stepsize,pars);end;
if(~pars.quiet)fprintf('%i.',iter);end;
Lx=L*x;
%Lx2=sum(Lx.^2);
totalactive=0;
if(pars.graphics & mod(iter,10)==0)
set(hpl,'XData',Lx(1,:),'YData',Lx(2,:));
set(hpl,'YData',Lx(3,:));
set(hpl,'CData',y);
axis tight;
drawnow;
end;
g0=cdist(Lx,imp(1,:),imp(2,:));
if(pars.guard) kk=Kg;
else kk=1;
end;
for nnid=kk:Kg
Ni(nnid,1:N)=(sum((Lx-Lx(:,NN(nnid,:))).^2)+1);
end;
g1=Ni(:,imp(1,:));
g2=Ni(:,imp(2,:));
act1=[];act2=[];
if(pars.validation>0 & (mod(iter,pars.validationstep)==0 | iter==1))
verify=[verify Ltest2in(Lx,y,L*xv,yv,Ni,Kg,pars)];
if(verify(end)<=besterr) fprintf('*');besterr=verify(end);bestL= ...
L;Det.bestiter=iter;
end;
if(pars.earlystopping>0 & length(verify)>pars.earlystopping & all(verify(end-pars.earlystopping:end)>besterr)) ...
fprintf('Validation error is no longer improving!\n');break;
end;
end;
clear('Lx','Lx2');
% objv=dfG'*vec((L'*L));
for nnid=Kg:-1:kk
act1=find(g0<g1(nnid,:));
act2=find(g0<g2(nnid,:));
active=[act1 act2];
if(~isempty(a1{nnid}) | ~isempty(a2{nnid}))
try
[plus1,minus1]=sd(act1(:)',a1{nnid}(:)');
[plus2,minus2]=sd(act2(:)',a2{nnid}(:)');
catch
lasterr
keyboard;
end;
else
plus1=act1;plus2=act2;
minus1=[];minus2=[];
end;
% [isminus2,i]=sort(imp(1,minus2));minus2=minus2(i);
MINUS1a=[imp(1,minus1) imp(2,minus2)]; MINUS1b=[imp(1,[plus1 plus2])];
MINUS2a=[NN(nnid,imp(1,minus1)) NN(nnid,imp(2,minus2))]; MINUS2b=[imp(2,[plus1 plus2])];
[isplus2,i]= sort(imp(2,plus2));plus2=plus2(i);
PLUS1a=[imp(1,plus1) isplus2]; PLUS1b=[imp(1,[minus1 minus2])];
PLUS2a=[NN(nnid,imp(1,plus1)) NN(nnid,isplus2)]; PLUS2b=[imp(2,[minus1 minus2])];
loss1=max(g1(nnid,:)-g0,0);
loss2=max(g2(nnid,:)-g0,0);
% ;
[PLUS ,pweight]=count([PLUS1a;PLUS2a]);
[MINUS,mweight]=count([MINUS1a;MINUS2a]);
df2=SODW(x,PLUS(1,:),PLUS(2,:),pweight)-SODW(x,MINUS(1,:),MINUS(2,:),mweight);
df4=SOD(x,PLUS1b,PLUS2b)-SOD(x,MINUS1b,MINUS2b);
df=df+vec(df2+df4);
a1{nnid}=act1;a2{nnid}=act2;
totalactive=totalactive+length(active);
end;
if(any(any(isnan(df))))
fprintf('Gradient has NaN value!\n');
keyboard;
end;
%obj(iter)=objv;
obj(iter)=(dfG.*pars.weight1+df.*(1-pars.weight1))'*vec(L'*L)+totalactive.*(1-pars.weight1);
if(isnan(obj(iter)))
fprintf('Obj is NAN!\n');
keyboard;
end;
nimp(iter)=totalactive;
delta=obj(iter)-obj(max(iter-1,1));
if(~pars.quiet)fprintf([' Obj:%2.2f Nimp:%i Delta:%2.4f max(G):' ...
' %2.4f' ...
' \n '],obj(iter),nimp(iter),delta,max(max(abs(df))));
end;
if(iter>1 & delta>0 & correction~=pars.correction)
stepsize=stepsize*0.5;
fprintf('***correcting stepsize***\n');
if(stepsize<pars.minstepsize) stepsize=pars.minstepsize;end;
if(~pars.aggressive)
L=Lold;
df=dfold;
for nnid=1:Kg; a1{nnid}=a1old{nnid};a2{nnid}=a2old{nnid};end;
obj(iter)=obj(iter-1);
end;
% correction=1;
hitwall=1;
else
if(correction~=pars.correction)stepsize=stepsize*pars.stepgrowth;end;
hitwall=0;
end;
if(iter>10 & (max(abs(diff(obj(iter-3:iter))))<pars.thresho*obj(iter) ...
| stepsize<pars.thresha))
if(pars.correction-correction>=5)
correction=1;
else
switch(pars.obj)
case 0
if(~pars.quiet)fprintf('Stepsize too small. No more progress!\n');end;
break;
case 1
pars.obj=0;
pars.correction=15;
pars.stepsize=1e-9;
correction=min(correction,pars.correction);
if(~pars.quiet | 1)
fprintf('\nVerifying solution! %i\n',obj(iter));
end;
case 3
if(~pars.quiet)fprintf('Stepsize too small. No more progress!\n');end;
break;
end;
end;
end;
if(pars.tempid>=0 & mod(iter,50)==0) time=toc;save(tempname,'L','iter','obj','pars','time','verify');end;
correction=correction-1;
if(correction==0)
if(pars.quiet)fprintf('\n');end;
[Vio]=checkup(L,x,y,NN(nnid,:),pars);
Vio=setdiff(Vio',imp','rows')';
if(pars.maximp<inf)
i=randperm(size(Vio,2));
Vio=Vio(:,i(1:min(pars.maximp,size(Vio,2))));
end;
ol=size(imp,2);
[imp i1 i2]=unique([imp Vio].','rows');
imp=imp.';
if(size(imp,2)~=ol)
for nnid=1:Kg;
a1{nnid}=i2(a1{nnid});
a2{nnid}=i2(a2{nnid});
end;
end;
fprintf('Added %i active constraints. New total: %i\n\n',size(imp,2)-ol,size(imp,2));
if(ifraction<1)
i=1:size(imp,2);
imp=imp(:,i(1:ceil(length(i)*ifraction)));
if(~pars.quiet)fprintf('Only use %2.2f of them.\n',ifraction);end;
ifraction=ifraction+pars.ifraction;
end;
% put next correction a little more into the future if no new impostors were added
if(size(imp,2)-ol<=0)
pars.correction=min(pars.correction*2+2,300);
correction=pars.correction-1;
else
pars.correction=round(pars.correction*pars.factor);
correction=pars.correction;
end;
lastcor=iter;
end;
end;
% Output
Det.obj=obj(1:iter);
Det.nimp=nimp;
Det.pars=pars;
Det.time=toc;
Det.iter=iter;
Det.verify=verify;
if(pars.validation>0)
Det.minL=L;
L=bestL;
Det.verify=verify;
end;
function [err,yy,Value]=Ltest2in(Lx,y,LxT,yTest,Ni,Kg,pars);
% function [err,yy,Value]=Ltest2(L,x,y,xTest,yTest,Kg,varargin);
%
% Initializationip
[D,N]=size(Lx);
Lx2=sum(Lx.^2);
MM=min(y);
y=y-MM+1;
un=unique(y);
Value=zeros(length(un),length(yTest));
B=500;
NTe=size(LxT,2);
for n=1:B:NTe
nn=n:n+min(B-1,NTe-n);
DD=distance(Lx,LxT(:,nn));
for i=1:length(un)
% Main Loopfor iter=1:pars.maxiter
testlabel=un(i);
enemy=find(y~=testlabel);
friend=find(y==testlabel);
Df=mink(DD(friend,:),Kg);
Value(i,nn)=sumiflessv2(DD,Ni(:,enemy),enemy)+sumiflessh2(DD,Df+1,enemy);
if(pars.reg==0)
Value(i,nn)=Value(i,nn)+sum(Df);
end;
end;
end;
fprintf('\n');
[temp,yy]=min(Value);
yy=un(yy)+MM-1;
err=sum(yy~=yTest)./length(yTest);
fprintf('Energy error:%2.2f%%\n',err*100);
function err=validation(Lx,y,LxT,yTest,Ni,Kg);
if(isempty(LxT)) err=0;return;end;
MM=min(y);
y=y-MM+1;
un=unique(y);
Value=zeros(length(un),length(yTest));
B=500;
if(size(Lx,2)>50000) B=250;end;
NTe=size(LxT,2);
for n=1:B:NTe
fprintf('%2.2f%%: ',n/NTe*100);
nn=n:n+min(B-1,NTe-n);
DD=distance(Lx,LxT(:,nn));
for i=1:length(un)
testlabel=un(i);
fprintf('%i.',testlabel+MM-1);
enemy=find(y~=testlabel);
friend=find(y==testlabel);
Df=sort(DD(friend,:));
Value(i,nn)=sum(Df(1:Kg,:))+sumiflessv(DD(enemy,:),Ni(enemy))+sumiflessh(DD(enemy,:),Df(Kg,:));
end;
fprintf('\n');
end;
fprintf('\n');
[temp,yy]=min(Value);
yy=un(yy)+MM-1;
err=sum(yy~=yTest)./length(yTest);
fprintf('Energy error:%2.2f%%\n',err*100);
function L=step(L,G,stepsize,pars);
% do step in gradient direction
if(size(L,1)~=size(L,2)) pars.obj=1;end;
switch(pars.obj)
case 0 % updating Q
Q=L'*L;
Q=Q-stepsize.*G;
case 1 % updating L
G=2.*(L*G);
L=L-stepsize.*G;
return;
case 2 % multiplicative update
Q=L'*L;
Q=Q-stepsize.*G+stepsize^2/4.*G*inv(Q)*G;
return;
case 3
Q=L'*L;
Q=Q-stepsize.*G;
Q=diag(Q);
L=diag(sqrt(max(Q,0)));
return;
otherwise
error('Objective function has to be 0,1,2\n');
end;
% decompose Q
[L,dd]=eig(Q);
dd=real(diag(dd));
L=real(L);
% reassemble Q (ignore negative eigenvalues)
j=find(dd<1e-10);
if(~isempty(j))
if(~pars.quiet)fprintf('[%i]',length(j));end;
end;
dd(j)=0;
[temp,ii]=sort(-dd);
L=L(:,ii);
dd=dd(ii);
% Q=L*diag(dd)*L';
L=(L*diag(sqrt(dd)))';
%for i=1:size(L,1)
% if(L(i,1)~=0) L(i,:)=L(i,:)./sign(L(i,1));end;
%end;
function imp=getImpLS(x,y,Kg,Ki,pars);
[D,N]=size(x);
filename=sprintf('.LSKInn%i.mat',pars.tempid);
if(pars.skip) load(filename);
else
un=unique(y);
Inn=zeros(Ki,N);
for c=un
fprintf('%i nearest imposture neighbors for class %i :',Ki,c);
i=find(y==c);
j=find(y~=c);
nn=LSKnn(x(:,j),x(:,i),1:Ki);
Inn(:,i)=j(nn);
fprintf('\r');
end;
fprintf('\n');
end;
imp=[vec(Inn(1:Ki,:)')'; vec(repmat(1:N,Ki,1)')'];
imp=unique(imp','rows')'; % Delete dublicates
if(pars.save)
save(filename,'Inn');
end;
function [gen,NN]=getGenLS(x,y,Kg,pars);
if(~pars.quiet)fprintf('Computing nearest neighbors ...\n');end;
filename=sprintf('.LSKGnn%i.mat',pars.tempid);
[D,N]=size(x);
if(pars.skip) load(filename);
else
un=unique(y);
Gnn=zeros(Kg,N);
for c=un
fprintf('%i nearest genuine neighbors for class %i:',Kg,c);
i=find(y==c);
nn=LSKnn(x(:,i),x(:,i),2:Kg+1);
Gnn(:,i)=i(nn);
fprintf('\r');
end;
fprintf('\n');
NN=Gnn;
gen1=vec(Gnn(1:Kg,:)')';
gen2=vec(repmat(1:N,Kg,1)')';
gen=[gen1;gen2];
if(pars.save)
save(filename,'gen','NN');
end;
end;
function imp=checkup(L,x,y,NN,pars);
if(~pars.quiet)fprintf('Computing nearest neighbors ...\n');end;
[D,N]=size(x);
Lx=L*x;
Ni=sum((Lx-Lx(:,NN)).^2)+1;
un=unique(y);
imp=[];
index=1:N;
for c=un(1:end-1)
if(~pars.quiet)fprintf('All nearest impostor neighbors for class %i :',c);end;
i=index(find(y(index)==c));
index=index(find(y(index)~=c));
limps=LSImps2(Lx(:,index),Lx(:,i),Ni(index),Ni(i),pars);
if(size(limps,2)>pars.maximp)
ip=randperm(size(limps,2));
ip=ip(1:pars.maximp);
limps=limps(:,ip);
end;
imp=[imp [i(limps(2,:));index(limps(1,:))]];
if(~pars.quiet)fprintf('\r');end;
end;
try
imp=unique(sort(imp)','rows')';
catch
keyboard;
end;
function limps=LSImps2(X1,X2,Thresh1,Thresh2,pars);
B=750;
[D,N2]=size(X2);
N1=size(X1,2);
limps=[];
for i=1:B:N2
BB=min(B,N2-i);
try
newlimps=findimps3Dac(X1,X2(:,i:i+BB), Thresh1,Thresh2(i:i+BB));
if(~isempty(newlimps) & newlimps(end)==0)
[minv,endpoint]=min(min(newlimps));
newlimps=newlimps(:,1:endpoint-1);
end;
newlimps=unique(newlimps','rows')';
% if(~all(all(newlimps==newlimps2))) keyboard;end;
% newlimps2=findimps3D2(X1,X2(:,i:i+BB), Thresh1,Thresh2(i:i+BB));
% newlimps=unique((sort(newlimps))','rows')';
% if(length(newlimps2)~=length(newlimps) | ~all(all(newlimps2==newlimps)))
% keyboard;
%end;
catch
keyboard;
end;
newlimps(2,:)=newlimps(2,:)+i-1;
limps=[limps newlimps];
if(~pars.quiet)fprintf('(%i%%) ',round((i+BB)/N2*100)); end;
end;
if(~pars.quiet)fprintf(' [%i] ',size(limps,2));end;
function NN=LSKnn(X1,X2,ks,pars);
B=750;
[D,N]=size(X2);
NN=zeros(length(ks),N);
DD=zeros(length(ks),N);
for i=1:B:N
BB=min(B,N-i);
fprintf('.');
Dist=distance(X1,X2(:,i:i+BB));
fprintf('.');
[dist,nn]=mink(Dist,max(ks));
clear('Dist');
fprintf('.');
NN(:,i:i+BB)=nn(ks,:);
clear('nn','dist');
fprintf('(%i%%) ',round((i+BB)/N*100));
end;
|
github
|
mangye16/IDE-baseline-Market-1501-master
|
knnclassify.m
|
.m
|
IDE-baseline-Market-1501-master/market_evaluation/KISSME/toolbox/lib/LMNN/knnclassify.m
| 2,559 |
utf_8
|
02d7cf7e68cc0dc6f86bc8765e02e66b
|
function [Eval,Details]=LSevaluate(L,xTr,lTr,xTe,lTe,KK);
% function [Eval,Details]=LSevaluate(L,xTr,yTr,xTe,yTe,Kg);
%
% INPUT:
% L : transformation matrix (learned by LMNN)
% xTr : training vectors (each column is an instance)
% yTr : training labels (row vector!!)
% xTe : test vectors
% yTe : test labels
% Kg : number of nearest neighbors
%
% Good luck!
%
% copyright by Kilian Q. Weinberger, 2006
%
% version 1.1 (04/13/07)
% Little bugfix, couldn't handle single test vectors beforehand.
% Thanks to Karim T. Abou-Moustafa for pointing it out to me.
%
MM=min([lTr lTe]);
if(nargin<6)
KK=1:2:3;
end;
if(length(KK)==1) outputK=ceil(KK/2);KK=1:2:KK;else outputK=1:length(KK);end;
Kn=max(KK);
D=length(L);
xTr=L*xTr(1:D,:);
xTe=L*xTe(1:D,:);
B=700;
[NTr]=size(xTr,2);
[NTe]=size(xTe,2);
Eval=zeros(2,length(KK));
lTr2=zeros(length(KK),NTr);
lTe2=zeros(length(KK),NTe);
iTr=zeros(Kn,NTr);
iTe=zeros(Kn,NTe);
sx1=sum(xTr.^2,1);
sx2=sum(xTe.^2,1);
for i=1:B:max(NTr,NTe)
if(i<=NTr)
BTr=min(B-1,NTr-i);
%Dtr=distance(xTr,xTr(:,i:i+BTr));
Dtr=addh(addv(-2*xTr'*xTr(:,i:i+BTr),sx1),sx1(i:i+BTr));
% [dist,nn]=sort(Dtr);
[dist,nn]=mink(Dtr,Kn+1);
nn=nn(2:Kn+1,:);
lTr2(:,i:i+BTr)=LSKnn2(lTr(nn),KK,MM);
iTr(:,i:i+BTr)=nn;
Eval(1,:)=sum((lTr2(:,1:i+BTr)~=repmat(lTr(1:i+BTr),length(KK),1))',1)./(i+BTr);
end;
if(i<=NTe)
BTe=min(B-1,NTe-i);
Dtr=addh(addv(-2*xTr'*xTe(:,i:i+BTe),sx1),sx2(i:i+BTe));
[dist,nn]=mink(Dtr,Kn);
lTe2(:,i:i+BTe)=LSKnn2(reshape(lTr(nn),max(KK),BTe+1),KK,MM);
iTe(:,i:i+BTe)=nn;
Eval(2,:)=sum((lTe2(:,1:i+BTe)~=repmat(lTe(1:i+BTe),length(KK),1))',1)./(i+BTe);
end;
fprintf('%2.2f%%.:\n',(i+BTr)/max(NTr,NTe)*100);
disp(Eval.*100);
end;
Details.lTe2=lTe2;
Details.lTr2=lTr2;
Details.iTe=iTe;
Details.iTr=iTr;
Eval=Eval(:,outputK);
function yy=LSKnn2(Ni,KK,MM);
% function yy=LSKnn2(Ni,KK,MM);
%
if(nargin<2)
KK=1:2:3;
end;
N=size(Ni,2);
Ni=Ni-MM+1;
classes=unique(unique(Ni))';
%yy=zeros(1,size(Ni,2));
%for i=1:size(Ni,2)
% n=zeros(max(un),1);
% for j=1:size(Ni,1)
% n(Ni(j,i))=n(Ni(j,i))+1;
% end;
% [temp,yy(i)]=max(n);
%end;
T=zeros(length(classes),N,length(KK));
for i=1:length(classes)
c=classes(i);
for k=KK
% NNi=Ni(1:k,:)==c;
% NNi=NNi+(Ni(1,:)==c).*0.01;% give first neighbor tiny advantage
try
T(i,:,k)=sum(Ni(1:k,:)==c,1);
catch
keyboard;
end;
end;
end;
yy=zeros(max(KK),N);
for k=KK
[temp,yy(k,1:N)]=max(T(:,:,k)+T(:,:,1).*0.01);
yy(k,1:N)=classes(yy(k,:));
end;
yy=yy(KK,:);
yy=yy+MM-1;
|
github
|
mangye16/IDE-baseline-Market-1501-master
|
energyclassify.m
|
.m
|
IDE-baseline-Market-1501-master/market_evaluation/KISSME/toolbox/lib/LMNN/energyclassify.m
| 2,926 |
utf_8
|
9155befdcfcd16052c23bbab1cf7b530
|
function [err,yy,Value]=energyclassify(L,x,y,xTest,yTest,Kg,varargin);
% function [err,yy,Value]=energyclassify(L,xTr,yTr,xTe,yTe,Kg,varargin);
%
% INPUT:
% L : transformation matrix (learned by LMNN)
% xTr : training vectors (each column is an instance)
% yTr : training labels (row vector!!)
% xTe : test vectors
% yTe : test labels
% Kg : number of nearest neighbors
%
% Good luck!
%
% copyright by Kilian Q. Weinberger, 2006
% checks
D=length(L);
x=x(1:D,:);
xTest=xTest(1:D,:);
if(size(x,1)>length(L)) error('x and L must have matching dimensions!\n');end;
% set parameters
pars.alpha=1e-09;
pars.tempid=0;
pars.save=0;
pars.speed=10;
pars.skip=0;
pars.factor=1;
pars.correction=15;
pars.prod=0;
pars.thresh=1e-16;
pars.ifraction=1;
pars.scale=0;
pars.obj=0;
pars.union=1;
pars.margin=0;
pars.tabularasa=Inf;
pars.blocksize=500;
pars=extractpars(varargin,pars);
pars
tempname=sprintf('temp%i.mat',pars.tempid);
% Initializationip
[D,N]=size(x);
[gen,NN]=getGenLS(x,y,Kg,pars);
if(pars.scale)
fprintf('Scaling input vectors!\n');
sc=sqrt(mean(sum( ((x-x(:,NN(end,:)))).^2)));
x=x./sc;
xTest=xTest./sc;
end;
Lx=L*x;
Lx2=sum(Lx.^2);
LxT=L*xTest;
for inn=1:Kg
Ni(inn,:)=sum((Lx-Lx(:,NN(inn,:))).^2)+1;
end;
MM=min(y);
y=y-MM+1;
un=unique(y);
Value=zeros(length(un),length(yTest));
B=pars.blocksize;
if(size(x,2)>50000) B=250;end;
NTe=size(xTest,2);
for n=1:B:NTe
fprintf('%2.2f%%: ',n/NTe*100);
nn=n:n+min(B-1,NTe-n);
DD=distance(Lx,LxT(:,nn));
for i=1:length(un)
% Main Loopfor iter=1:maxiter
testlabel=un(i);
fprintf('%i.',testlabel+MM-1);
enemy=find(y~=testlabel);
friend=find(y==testlabel);
Df=mink(DD(friend,:),Kg);
Value(i,nn)=sumiflessv2(DD,Ni(:,enemy),enemy)+sumiflessh2(DD,Df,enemy)+sum(Df);
% Value(i,nn)=sumiflessh2(DD,Df+pars.margin,enemy)+sum(Df);
end;
fprintf('\n');
end;
fprintf('\n');
[temp,yy]=min(Value);
yy=un(yy)+MM-1;
err=sum(yy~=yTest)./length(yTest);
fprintf('Energy error:%2.2f%%\n',err*100);
function [gen,NN]=getGenLS(x,y,Kg,pars);
fprintf('Computing nearest neighbors ...\n');
[D,N]=size(x);
if(pars.skip) load('.LSKGnn.mat');
else
un=unique(y);
Gnn=zeros(Kg,N);
for c=un
fprintf('%i nearest genuine neighbors for class %i:',Kg,c);
i=find(y==c);
nn=LSKnn(x(:,i),x(:,i),2:Kg+1);
Gnn(:,i)=i(nn);
fprintf('\n');
end;
end;
NN=Gnn;
gen1=vec(Gnn(1:Kg,:)')';
gen2=vec(repmat(1:N,Kg,1)')';
gen=[gen1;gen2];
if(pars.save)
save('.LSKGnn.mat','Gnn');
end;
function NN=LSKnn(X1,X2,ks,pars);
B=2000;
[D,N]=size(X2);
NN=zeros(length(ks),N);
DD=zeros(length(ks),N);
for i=1:B:N
BB=min(B,N-i);
fprintf('.');
Dist=distance(X1,X2(:,i:i+BB));
fprintf('.');
% [dist,nn]=sort(Dist);
[dist,nn]=mink(Dist,max(ks));
clear('Dist');
fprintf('.');
% keyboard;
NN(:,i:i+BB)=nn(ks,:);
clear('nn','dist');
fprintf('(%i%%) ',round((i+BB)/N*100));
end;
function v=vec(M);
% vectorizes a matrix
v=M(:);
|
github
|
mangye16/IDE-baseline-Market-1501-master
|
draw_confusion_matrix.m
|
.m
|
IDE-baseline-Market-1501-master/market_evaluation/utils/draw_confusion_matrix.m
| 1,023 |
utf_8
|
a9d55f96cdc7d7b9e03092bd89fe0715
|
% calculate and draw confusion matrix
function [ap_mat, r1_mat] = draw_confusion_matrix(ap, r1, queryCam)
ap_mat = zeros(6, 6);
r1_mat = zeros(6, 6);
count1 = zeros(6, 6);
count2 = zeros(6, 6);
for n = 1:length(queryCam)
for k = 1:6
ap_mat(queryCam(n), k) = ap_mat(queryCam(n), k) + ap(n, k);
if ap(n, k) ~= 0
count1(queryCam(n), k) = count1(queryCam(n), k) + 1;
end
if r1(n, k) >= 0
r1_mat(queryCam(n), k) = r1_mat(queryCam(n), k) + r1(n, k);
count2(queryCam(n), k) = count2(queryCam(n), k) + 1;
end
end
end
num_class = 6;
ap_mat = ap_mat./count1;
name_class{1} = 'Cam1';
name_class{2} = 'Cam2';
name_class{3} = 'Cam3';
name_class{4} = 'Cam4';
name_class{5} = 'Cam5';
name_class{6} = 'Cam6';
draw_cm(ap_mat,name_class,num_class);
r1_mat = r1_mat./count2;
name_class{1} = 'Cam1';
name_class{2} = 'Cam2';
name_class{3} = 'Cam3';
name_class{4} = 'Cam4';
name_class{5} = 'Cam5';
name_class{6} = 'Cam6';
draw_cm(r1_mat,name_class,num_class);
|
github
|
zhangyuygss/WSL-master
|
example_layout.m
|
.m
|
WSL-master/tmp/VOCdevkit/example_layout.m
| 4,470 |
utf_8
|
faaf53dfba2457f3f7e5542cd51ad5fb
|
function example_layout
% change this path if you install the VOC code elsewhere
addpath([cd '/VOCcode']);
% initialize VOC options
VOCinit;
% train and test detector
cls='person';
detector=train(VOCopts,cls); % train detector
test(VOCopts,cls,detector); % test detector
[recall,prec,ap]=VOCevallayout(VOCopts,'comp6',cls,true); % compute and display PR
% train detector
function detector = train(VOCopts,cls)
% load 'train' image set
ids=textread(sprintf(VOCopts.layout.imgsetpath,'train'),'%s');
% extract features and objects
n=0;
tic;
for i=1:length(ids)
% display progress
if toc>1
fprintf('%s: train: %d/%d\n',cls,i,length(ids));
drawnow;
tic;
end
% read annotation
rec=PASreadrecord(sprintf(VOCopts.annopath,ids{i}));
% find objects of class and extract difficult flags for these objects
clsinds=strmatch(cls,{rec.objects(:).class},'exact');
diff=[rec.objects(clsinds).difficult];
hasparts=[rec.objects(clsinds).hasparts];
% assign ground truth class to image
if isempty(clsinds)
gt=-1; % no objects of class
elseif any(~diff&hasparts)
gt=1; % at least one non-difficult object with parts
else
gt=0; % only difficult/objects without parts
end
if gt
% extract features for image
try
% try to load features
load(sprintf(VOCopts.exfdpath,ids{i}),'fd');
catch
% compute and save features
I=imread(sprintf(VOCopts.imgpath,ids{i}));
fd=extractfd(VOCopts,I);
save(sprintf(VOCopts.exfdpath,ids{i}),'fd');
end
n=n+1;
detector(n).fd=fd;
% extract non-difficult objects with parts
detector(n).object=rec.objects(clsinds(~diff&hasparts));
% mark image as positive or negative
detector(n).gt=gt;
end
end
% run detector on test images
function out = test(VOCopts,cls,detector)
% load test set ('val' for development kit)
[ids,gt]=textread(sprintf(VOCopts.layout.imgsetpath,VOCopts.testset),'%s %d');
% apply detector to each image
rec.results.layout=[];
tic;
for i=1:length(ids)
% display progress
if toc>1
fprintf('%s: test: %d/%d\n',cls,i,length(ids));
drawnow;
tic;
end
try
% try to load features
load(sprintf(VOCopts.exfdpath,ids{i}),'fd');
catch
% compute and save features
I=imread(sprintf(VOCopts.imgpath,ids{i}));
fd=extractfd(VOCopts,I);
save(sprintf(VOCopts.exfdpath,ids{i}),'fd');
end
% compute confidence of positive classification and layout
l=detect(VOCopts,detector,fd,ids{i});
if isempty(rec.results.layout)
rec.results.layout=l;
else
rec.results.layout=[rec.results.layout l];
end
end
% write results file
fprintf('saving results...\n');
VOCwritexml(rec,sprintf(VOCopts.layout.respath,'comp6',cls));
% trivial feature extractor: compute mean RGB
function fd = extractfd(VOCopts,I)
fd=squeeze(sum(sum(double(I)))/(size(I,1)*size(I,2)));
% trivial detector: confidence is computed as in example_classifier, and
% bounding boxes of nearest positive training image are output
function layout = detect(VOCopts,detector,fd,imgid)
FD=[detector.fd];
% compute confidence
d=sum(fd.*fd)+sum(FD.*FD)-2*fd'*FD;
dp=min(d([detector.gt]>0));
dn=min(d([detector.gt]<0));
c=dn/(dp+eps);
% copy objects and layout from nearest positive image
pinds=find([detector.gt]>0);
[dp,di]=min(d(pinds));
pind=pinds(di);
BB=[];
for i=1:length(detector(pind).object)
o=detector(pind).object(i);
layout(i).image=imgid;
layout(i).confidence=c;
layout(i).bndbox.xmin=o.bbox(1);
layout(i).bndbox.ymin=o.bbox(2);
layout(i).bndbox.xmax=o.bbox(3);
layout(i).bndbox.ymax=o.bbox(4);
for j=1:length(o.part)
layout(i).part(j).class=o.part(j).class;
layout(i).part(j).bndbox.xmin=o.part(j).bbox(1);
layout(i).part(j).bndbox.ymin=o.part(j).bbox(2);
layout(i).part(j).bndbox.xmax=o.part(j).bbox(3);
layout(i).part(j).bndbox.ymax=o.part(j).bbox(4);
end
end
|
github
|
zhangyuygss/WSL-master
|
example_detector.m
|
.m
|
WSL-master/tmp/VOCdevkit/example_detector.m
| 4,055 |
utf_8
|
940dbf93f88c7210c89a2e4885c0fac2
|
function example_detector
% change this path if you install the VOC code elsewhere
addpath([cd '/VOCcode']);
% initialize VOC options
VOCinit;
% train and test detector for each class
for i=1:VOCopts.nclasses
cls=VOCopts.classes{i};
detector=train(VOCopts,cls); % train detector
test(VOCopts,cls,detector); % test detector
[recall,prec,ap]=VOCevaldet(VOCopts,'comp3',cls,true); % compute and display PR
if i<VOCopts.nclasses
fprintf('press any key to continue with next class...\n');
drawnow;
pause;
end
end
% train detector
function detector = train(VOCopts,cls)
% load 'train' image set
ids=textread(sprintf(VOCopts.imgsetpath,'train'),'%s');
% extract features and bounding boxes
detector.FD=[];
detector.bbox={};
detector.gt=[];
tic;
for i=1:length(ids)
% display progress
if toc>1
fprintf('%s: train: %d/%d\n',cls,i,length(ids));
drawnow;
tic;
end
% read annotation
rec=PASreadrecord(sprintf(VOCopts.annopath,ids{i}));
% find objects of class and extract difficult flags for these objects
clsinds=strmatch(cls,{rec.objects(:).class},'exact');
diff=[rec.objects(clsinds).difficult];
% assign ground truth class to image
if isempty(clsinds)
gt=-1; % no objects of class
elseif any(~diff)
gt=1; % at least one non-difficult object of class
else
gt=0; % only difficult objects
end
if gt
% extract features for image
try
% try to load features
load(sprintf(VOCopts.exfdpath,ids{i}),'fd');
catch
% compute and save features
I=imread(sprintf(VOCopts.imgpath,ids{i}));
fd=extractfd(VOCopts,I);
save(sprintf(VOCopts.exfdpath,ids{i}),'fd');
end
detector.FD(1:length(fd),end+1)=fd;
% extract bounding boxes for non-difficult objects
detector.bbox{end+1}=cat(1,rec.objects(clsinds(~diff)).bbox)';
% mark image as positive or negative
detector.gt(end+1)=gt;
end
end
% run detector on test images
function out = test(VOCopts,cls,detector)
% load test set ('val' for development kit)
[ids,gt]=textread(sprintf(VOCopts.imgsetpath,VOCopts.testset),'%s %d');
% create results file
fid=fopen(sprintf(VOCopts.detrespath,'comp3',cls),'w');
% apply detector to each image
tic;
for i=1:length(ids)
% display progress
if toc>1
fprintf('%s: test: %d/%d\n',cls,i,length(ids));
drawnow;
tic;
end
try
% try to load features
load(sprintf(VOCopts.exfdpath,ids{i}),'fd');
catch
% compute and save features
I=imread(sprintf(VOCopts.imgpath,ids{i}));
fd=extractfd(VOCopts,I);
save(sprintf(VOCopts.exfdpath,ids{i}),'fd');
end
% compute confidence of positive classification and bounding boxes
[c,BB]=detect(VOCopts,detector,fd);
% write to results file
for j=1:length(c)
fprintf(fid,'%s %f %d %d %d %d\n',ids{i},c(j),BB(:,j));
end
end
% close results file
fclose(fid);
% trivial feature extractor: compute mean RGB
function fd = extractfd(VOCopts,I)
fd=squeeze(sum(sum(double(I)))/(size(I,1)*size(I,2)));
% trivial detector: confidence is computed as in example_classifier, and
% bounding boxes of nearest positive training image are output
function [c,BB] = detect(VOCopts,detector,fd)
% compute confidence
d=sum(fd.*fd)+sum(detector.FD.*detector.FD)-2*fd'*detector.FD;
dp=min(d(detector.gt>0));
dn=min(d(detector.gt<0));
c=dn/(dp+eps);
% copy bounding boxes from nearest positive image
pinds=find(detector.gt>0);
[dp,di]=min(d(pinds));
pind=pinds(di);
BB=detector.bbox{pind};
% replicate confidence for each detection
c=ones(size(BB,2),1)*c;
|
github
|
zhangyuygss/WSL-master
|
create_segmentations_from_detections.m
|
.m
|
WSL-master/tmp/VOCdevkit/create_segmentations_from_detections.m
| 3,667 |
utf_8
|
e991547b4a595e58313d5b11c0a91942
|
% Creates segmentation results from detection results.
% CREATE_SEGMENTATIONS_FROM_DETECTIONS(ID) creates segmentations from
% the detection results with identifier ID e.g. 'comp3'. All detections
% will be used, no matter what their confidence level.
%
% CREATE_SEGMENTATIONS_FROM_DETECTIONS(ID, CONFIDENCE) as above, but only
% detections above the specified confidence will be used.
function create_segmentations_from_detections(id,confidence)
if nargin<2
confidence = -inf;
end
% change this path if you install the VOC code elsewhere
addpath([cd '/VOCcode']);
% initialize VOC options
VOCinit;
% load detection results
tic;
imgids={};
for clsnum = 1:VOCopts.nclasses
resultsfile = sprintf(VOCopts.detrespath,id,VOCopts.classes{clsnum});
if ~exist(resultsfile,'file')
error('Could not find detection results file to use to create segmentations (%s not found)',resultsfile);
end
[ids,confs,b1,b2,b3,b4]=textread(resultsfile,'%s %f %f %f %f %f');
BBOXS=[b1 b2 b3 b4];
previd='';
for j=1:numel(ids)
% display progress
if toc>1
fprintf('class %d/%d: load detections: %d/%d\n',clsnum,VOCopts.nclasses,j,numel(ids));
drawnow;
tic;
end
imgid = ids{j};
conf = confs(j);
if ~strcmp(imgid,previd)
ind = strmatch(imgid,imgids,'exact');
end
detinfo.clsnum = clsnum;
detinfo.conf = conf;
detinfo.bbox = BBOXS(j,:);
if isempty(ind)
imgids{end+1}=imgid;
ind = numel(imgids);
detnum=1;
else
detnum = numel(im(ind).det)+1;
end
im(ind).det(detnum) = detinfo;
end
end
% Write out the segmentations
resultsdir = sprintf(VOCopts.seg.clsresdir,id,VOCopts.testset);
resultsdirinst = sprintf(VOCopts.seg.instresdir,id,VOCopts.testset);
if ~exist(resultsdir,'dir')
mkdir(resultsdir);
end
if ~exist(resultsdirinst,'dir')
mkdir(resultsdirinst);
end
cmap = VOClabelcolormap(255);
tic;
for j=1:numel(imgids)
% display progress
if toc>1
fprintf('make segmentation: %d/%d\n',j,numel(imgids));
drawnow;
tic;
end
imname = imgids{j};
classlabelfile = sprintf(VOCopts.seg.clsrespath,id,VOCopts.testset,imname);
instlabelfile = sprintf(VOCopts.seg.instrespath,id,VOCopts.testset,imname);
imgfile = sprintf(VOCopts.imgpath,imname);
imginfo = imfinfo(imgfile);
[instim,classim]= convert_dets_to_image(imginfo.Width, imginfo.Height,im(j).det,confidence);
imwrite(instim,cmap,instlabelfile);
imwrite(classim,cmap,classlabelfile);
% Copy in ground truth - uncomment to copy ground truth segmentations in
% for comparison
% gtlabelfile = [VOCopts.root '/Segmentations(class)/' imname '.png'];
% gtclasslabelfile = sprintf('%s/%d_gt.png',resultsdir,imnums(j));
% copyfile(gtlabelfile,gtclasslabelfile);
end
% Converts a set of detected bounding boxes into an instance-labelled image
% and a class-labelled image
function [instim,classim]=convert_dets_to_image(W,H,dets,confidence)
instim = uint8(zeros([H W]));
classim = uint8(zeros([H W]));
for j=1:numel(dets)
detinfo = dets(j);
if detinfo.conf<confidence
continue
end
bbox = round(detinfo.bbox);
% restrict to fit within image
bbox([1 3]) = min(max(bbox([1 3]),1),W);
bbox([2 4]) = min(max(bbox([2 4]),1),H);
instim(bbox(2):bbox(4),bbox(1):bbox(3)) = j;
classim(bbox(2):bbox(4),bbox(1):bbox(3)) = detinfo.clsnum;
end
|
github
|
zhangyuygss/WSL-master
|
example_segmenter.m
|
.m
|
WSL-master/tmp/VOCdevkit/example_segmenter.m
| 366 |
utf_8
|
811cf1eb98ef8899c06077d47bd601f6
|
% example_segmenter Segmentation algorithm based on detection results.
%
% This segmenter requires that some detection results are present in
% 'Results' e.g. by running 'example_detector'.
%
% Segmentations are generated from detection bounding boxes.
function example_segmenter
VOCinit
create_segmentations_from_detections('comp3',1)
VOCevalseg(VOCopts,'comp3');
|
github
|
zhangyuygss/WSL-master
|
example_classifier.m
|
.m
|
WSL-master/tmp/VOCdevkit/example_classifier.m
| 2,884 |
utf_8
|
4d037fe9f87eb5181d869b1435e95025
|
function example_classifier
% change this path if you install the VOC code elsewhere
addpath([cd '/VOCcode']);
% initialize VOC options
VOCinit;
% train and test classifier for each class
for i=1:VOCopts.nclasses
cls=VOCopts.classes{i};
classifier=train(VOCopts,cls); % train classifier
test(VOCopts,cls,classifier); % test classifier
[recall,prec,ap]=VOCevalcls(VOCopts,'comp1',cls,true); % compute and display PR
if i<VOCopts.nclasses
fprintf('press any key to continue with next class...\n');
drawnow;
pause;
end
end
% train classifier
function classifier = train(VOCopts,cls)
% load 'train' image set for class
[ids,classifier.gt]=textread(sprintf(VOCopts.clsimgsetpath,cls,'train'),'%s %d');
% extract features for each image
classifier.FD=zeros(0,length(ids));
tic;
for i=1:length(ids)
% display progress
if toc>1
fprintf('%s: train: %d/%d\n',cls,i,length(ids));
drawnow;
tic;
end
try
% try to load features
load(sprintf(VOCopts.exfdpath,ids{i}),'fd');
catch
% compute and save features
I=imread(sprintf(VOCopts.imgpath,ids{i}));
fd=extractfd(VOCopts,I);
save(sprintf(VOCopts.exfdpath,ids{i}),'fd');
end
classifier.FD(1:length(fd),i)=fd;
end
% run classifier on test images
function test(VOCopts,cls,classifier)
% load test set ('val' for development kit)
[ids,gt]=textread(sprintf(VOCopts.imgsetpath,VOCopts.testset),'%s %d');
% create results file
fid=fopen(sprintf(VOCopts.clsrespath,'comp1',cls),'w');
% classify each image
tic;
for i=1:length(ids)
% display progress
if toc>1
fprintf('%s: test: %d/%d\n',cls,i,length(ids));
drawnow;
tic;
end
try
% try to load features
load(sprintf(VOCopts.exfdpath,ids{i}),'fd');
catch
% compute and save features
I=imread(sprintf(VOCopts.imgpath,ids{i}));
fd=extractfd(VOCopts,I);
save(sprintf(VOCopts.exfdpath,ids{i}),'fd');
end
% compute confidence of positive classification
c=classify(VOCopts,classifier,fd);
% write to results file
fprintf(fid,'%s %f\n',ids{i},c);
end
% close results file
fclose(fid);
% trivial feature extractor: compute mean RGB
function fd = extractfd(VOCopts,I)
fd=squeeze(sum(sum(double(I)))/(size(I,1)*size(I,2)));
% trivial classifier: compute ratio of L2 distance betweeen
% nearest positive (class) feature vector and nearest negative (non-class)
% feature vector
function c = classify(VOCopts,classifier,fd)
d=sum(fd.*fd)+sum(classifier.FD.*classifier.FD)-2*fd'*classifier.FD;
dp=min(d(classifier.gt>0));
dn=min(d(classifier.gt<0));
c=dn/(dp+eps);
|
github
|
zhangyuygss/WSL-master
|
VOCevalseg.m
|
.m
|
WSL-master/tmp/VOCdevkit/VOCcode/VOCevalseg.m
| 2,709 |
utf_8
|
3d832544dce45b76923c6413db5ca130
|
%VOCEVALSEG Creates a confusion matrix for a set of segmentation results.
% VOCEVALSEG(VOCopts,ID); prints out the per class and overall
% segmentation accuracies.
%
% [ACCURACIES,AVACC,CONF] = VOCEVALSEG(VOCopts,ID) returns the per class
% percentage ACCURACIES, the average accuracy AVACC and the confusion
% matrix CONF.
function [accuracies,avacc,conf,rawcounts] = VOCevalseg(VOCopts,id)
% image test set
[gtids,t]=textread(sprintf(VOCopts.seg.imgsetpath,VOCopts.testset),'%s %d');
% number of labels = number of classes plus one for the background
num = VOCopts.nclasses+1;
confcounts = zeros(num);
count=0;
tic;
for i=1:length(gtids)
% display progress
if toc>1
fprintf('test confusion: %d/%d\n',i,length(gtids));
drawnow;
tic;
end
imname = gtids{i};
% ground truth label file
gtfile = sprintf(VOCopts.seg.clsimgpath,imname);
[gtim,map] = imread(gtfile);
gtim = double(gtim);
% results file
resfile = sprintf(VOCopts.seg.clsrespath,id,VOCopts.testset,imname);
[resim,map] = imread(resfile);
resim = double(resim);
% Check validity of results image
maxlabel = max(resim(:));
if (maxlabel>VOCopts.nclasses),
error('Results image ''%s'' has out of range value %d (the value should be <= %d)',imname,maxlabel,VOCopts.nclasses);
end
szgtim = size(gtim); szresim = size(resim);
if any(szgtim~=szresim)
error('Results image ''%s'' is the wrong size, was %d x %d, should be %d x %d.',imname,szresim(1),szresim(2),szgtim(1),szgtim(2));
end
%pixel locations to include in computation
locs = gtim<255;
% joint histogram
sumim = 1+gtim+resim*num;
hs = histc(sumim(locs),1:num*num);
count = count + numel(find(locs));
confcounts(:) = confcounts(:) + hs(:);
end
% confusion matrix - first index is true label, second is inferred label
conf = zeros(num);
rawcounts = confcounts;
overall_acc = 100*sum(diag(confcounts)) / sum(confcounts(:));
fprintf('Percentage of pixels correctly labelled overall: %6.3f%%\n',overall_acc);
accuracies = zeros(VOCopts.nclasses,1);
fprintf('Percentage of pixels correctly labelled for each class\n');
for j=1:num
rowsum = sum(confcounts(j,:));
if (rowsum>0), conf(j,:) = 100*confcounts(j,:)/rowsum; end;
accuracies(j) = conf(j,j);
clname = 'background';
if (j>1), clname = VOCopts.classes{j-1};end;
fprintf(' %14s: %6.3f%%\n',clname,accuracies(j));
end
accuracies = accuracies(1:end);
avacc = mean(accuracies);
fprintf('-------------------------\n');
fprintf('Average accuracy: %6.3f%%\n',avacc);
|
github
|
zhangyuygss/WSL-master
|
VOClabelcolormap.m
|
.m
|
WSL-master/tmp/VOCdevkit/VOCcode/VOClabelcolormap.m
| 691 |
utf_8
|
0bfcd3122e62038f83e2d64f456d556b
|
% VOCLABELCOLORMAP Creates a label color map such that adjacent indices have different
% colors. Useful for reading and writing index images which contain large indices,
% by encoding them as RGB images.
%
% CMAP = VOCLABELCOLORMAP(N) creates a label color map with N entries.
function cmap = labelcolormap(N)
if nargin==0
N=256
end
cmap = zeros(N,3);
for i=1:N
id = i-1; r=0;g=0;b=0;
for j=0:7
r = bitor(r, bitshift(bitget(id,1),7 - j));
g = bitor(g, bitshift(bitget(id,2),7 - j));
b = bitor(b, bitshift(bitget(id,3),7 - j));
id = bitshift(id,-3);
end
cmap(i,1)=r; cmap(i,2)=g; cmap(i,3)=b;
end
cmap = cmap / 255;
|
github
|
zhangyuygss/WSL-master
|
VOCwritexml.m
|
.m
|
WSL-master/tmp/VOCdevkit/VOCcode/VOCwritexml.m
| 1,166 |
utf_8
|
5eee01a8259554f83bf00cf9cf2992a2
|
function VOCwritexml(rec, path)
fid=fopen(path,'w');
writexml(fid,rec,0);
fclose(fid);
function xml = writexml(fid,rec,depth)
fn=fieldnames(rec);
for i=1:length(fn)
f=rec.(fn{i});
if ~isempty(f)
if isstruct(f)
for j=1:length(f)
fprintf(fid,'%s',repmat(char(9),1,depth));
fprintf(fid,'<%s>\n',fn{i});
writexml(fid,rec.(fn{i})(j),depth+1);
fprintf(fid,'%s',repmat(char(9),1,depth));
fprintf(fid,'</%s>\n',fn{i});
end
else
if ~iscell(f)
f={f};
end
for j=1:length(f)
fprintf(fid,'%s',repmat(char(9),1,depth));
fprintf(fid,'<%s>',fn{i});
if ischar(f{j})
fprintf(fid,'%s',f{j});
elseif isnumeric(f{j})&&numel(f{j})==1
fprintf(fid,'%s',num2str(f{j}));
else
error('unsupported type');
end
fprintf(fid,'</%s>\n',fn{i});
end
end
end
end
|
github
|
zhangyuygss/WSL-master
|
VOCreadrecxml.m
|
.m
|
WSL-master/tmp/VOCdevkit/VOCcode/VOCreadrecxml.m
| 1,767 |
utf_8
|
6dd61b87dc93a2f814399e42610184b1
|
function rec = VOCreadrecxml(path)
x=VOCreadxml(path);
x=x.annotation;
rec=rmfield(x,'object');
rec.size.width=str2double(rec.size.width);
rec.size.height=str2double(rec.size.height);
rec.size.depth=str2double(rec.size.depth);
rec.segmented=strcmp(rec.segmented,'1');
rec.imgname=[x.folder '/JPEGImages/' x.filename];
rec.imgsize=str2double({x.size.width x.size.height x.size.depth});
rec.database=rec.source.database;
for i=1:length(x.object)
rec.objects(i)=xmlobjtopas(x.object(i));
end
function p = xmlobjtopas(o)
p.class=o.name;
if isfield(o,'pose')
if strcmp(o.pose,'Unspecified')
p.view='';
else
p.view=o.pose;
end
else
p.view='';
end
if isfield(o,'truncated')
p.truncated=strcmp(o.truncated,'1');
else
p.truncated=false;
end
if isfield(o,'difficult')
p.difficult=strcmp(o.difficult,'1');
else
p.difficult=false;
end
p.label=['PAS' p.class p.view];
if p.truncated
p.label=[p.label 'Trunc'];
end
if p.difficult
p.label=[p.label 'Difficult'];
end
p.orglabel=p.label;
p.bbox=str2double({o.bndbox.xmin o.bndbox.ymin o.bndbox.xmax o.bndbox.ymax});
p.bndbox.xmin=str2double(o.bndbox.xmin);
p.bndbox.ymin=str2double(o.bndbox.ymin);
p.bndbox.xmax=str2double(o.bndbox.xmax);
p.bndbox.ymax=str2double(o.bndbox.ymax);
if isfield(o,'polygon')
warning('polygon unimplemented');
p.polygon=[];
else
p.polygon=[];
end
if isfield(o,'mask')
warning('mask unimplemented');
p.mask=[];
else
p.mask=[];
end
if isfield(o,'part')&&~isempty(o.part)
p.hasparts=true;
for i=1:length(o.part)
p.part(i)=xmlobjtopas(o.part(i));
end
else
p.hasparts=false;
p.part=[];
end
|
github
|
zhangyuygss/WSL-master
|
VOCxml2struct.m
|
.m
|
WSL-master/tmp/VOCdevkit/VOCcode/VOCxml2struct.m
| 1,920 |
utf_8
|
6a873dba4b24c57e9f86a15ee12ea366
|
function res = VOCxml2struct(xml)
xml(xml==9|xml==10|xml==13)=[];
[res,xml]=parse(xml,1,[]);
function [res,ind]=parse(xml,ind,parent)
res=[];
if ~isempty(parent)&&xml(ind)~='<'
i=findchar(xml,ind,'<');
res=trim(xml(ind:i-1));
ind=i;
[tag,ind]=gettag(xml,i);
if ~strcmp(tag,['/' parent])
error('<%s> closed with <%s>',parent,tag);
end
else
while ind<=length(xml)
[tag,ind]=gettag(xml,ind);
if strcmp(tag,['/' parent])
return
else
[sub,ind]=parse(xml,ind,tag);
if isstruct(sub)
if isfield(res,tag)
n=length(res.(tag));
fn=fieldnames(sub);
for f=1:length(fn)
res.(tag)(n+1).(fn{f})=sub.(fn{f});
end
else
res.(tag)=sub;
end
else
if isfield(res,tag)
if ~iscell(res.(tag))
res.(tag)={res.(tag)};
end
res.(tag){end+1}=sub;
else
res.(tag)=sub;
end
end
end
end
end
function i = findchar(str,ind,chr)
i=[];
while ind<=length(str)
if str(ind)==chr
i=ind;
break
else
ind=ind+1;
end
end
function [tag,ind]=gettag(xml,ind)
if ind>length(xml)
tag=[];
elseif xml(ind)=='<'
i=findchar(xml,ind,'>');
if isempty(i)
error('incomplete tag');
end
tag=xml(ind+1:i-1);
ind=i+1;
else
error('expected tag');
end
function s = trim(s)
for i=1:numel(s)
if ~isspace(s(i))
s=s(i:end);
break
end
end
for i=numel(s):-1:1
if ~isspace(s(i))
s=s(1:i);
break
end
end
|
github
|
zhangyuygss/WSL-master
|
PASreadrectxt.m
|
.m
|
WSL-master/tmp/VOCdevkit/VOCcode/PASreadrectxt.m
| 3,179 |
utf_8
|
3b0bdbeb488c8292a1744dace066bb73
|
function record=PASreadrectxt(filename)
[fd,syserrmsg]=fopen(filename,'rt');
if (fd==-1),
PASmsg=sprintf('Could not open %s for reading',filename);
PASerrmsg(PASmsg,syserrmsg);
end;
matchstrs=initstrings;
record=PASemptyrecord;
notEOF=1;
while (notEOF),
line=fgetl(fd);
notEOF=ischar(line);
if (notEOF),
matchnum=match(line,matchstrs);
switch matchnum,
case 1, [imgname]=strread(line,matchstrs(matchnum).str);
record.imgname=char(imgname);
case 2, [x,y,c]=strread(line,matchstrs(matchnum).str);
record.imgsize=[x y c];
case 3, [database]=strread(line,matchstrs(matchnum).str);
record.database=char(database);
case 4, [obj,lbl,xmin,ymin,xmax,ymax]=strread(line,matchstrs(matchnum).str);
record.objects(obj).label=char(lbl);
record.objects(obj).bbox=[min(xmin,xmax),min(ymin,ymax),max(xmin,xmax),max(ymin,ymax)];
case 5, tmp=findstr(line,' : ');
[obj,lbl]=strread(line(1:tmp),matchstrs(matchnum).str);
record.objects(obj).label=char(lbl);
record.objects(obj).polygon=sscanf(line(tmp+3:end),'(%d, %d) ')';
case 6, [obj,lbl,mask]=strread(line,matchstrs(matchnum).str);
record.objects(obj).label=char(lbl);
record.objects(obj).mask=char(mask);
case 7, [obj,lbl,orglbl]=strread(line,matchstrs(matchnum).str);
lbl=char(lbl);
record.objects(obj).label=lbl;
record.objects(obj).orglabel=char(orglbl);
if strcmp(lbl(max(end-8,1):end),'Difficult')
record.objects(obj).difficult=true;
lbl(end-8:end)=[];
else
record.objects(obj).difficult=false;
end
if strcmp(lbl(max(end-4,1):end),'Trunc')
record.objects(obj).truncated=true;
lbl(end-4:end)=[];
else
record.objects(obj).truncated=false;
end
t=find(lbl>='A'&lbl<='Z');
t=t(t>=4);
if ~isempty(t)
record.objects(obj).view=lbl(t(1):end);
lbl(t(1):end)=[];
else
record.objects(obj).view='';
end
record.objects(obj).class=lbl(4:end);
otherwise, %fprintf('Skipping: %s\n',line);
end;
end;
end;
fclose(fd);
return
function matchnum=match(line,matchstrs)
for i=1:length(matchstrs),
matched(i)=strncmp(line,matchstrs(i).str,matchstrs(i).matchlen);
end;
matchnum=find(matched);
if isempty(matchnum), matchnum=0; end;
if (length(matchnum)~=1),
PASerrmsg('Multiple matches while parsing','');
end;
return
function s=initstrings
s(1).matchlen=14;
s(1).str='Image filename : %q';
s(2).matchlen=10;
s(2).str='Image size (X x Y x C) : %d x %d x %d';
s(3).matchlen=8;
s(3).str='Database : %q';
s(4).matchlen=8;
s(4).str='Bounding box for object %d %q (Xmin, Ymin) - (Xmax, Ymax) : (%d, %d) - (%d, %d)';
s(5).matchlen=7;
s(5).str='Polygon for object %d %q (X, Y)';
s(6).matchlen=5;
s(6).str='Pixel mask for object %d %q : %q';
s(7).matchlen=8;
s(7).str='Original label for object %d %q : %q';
return
|
github
|
cocoanlab/humanfmri_preproc_bids-master
|
humanfmri_c3_make_nuisance_regressors.m
|
.m
|
humanfmri_preproc_bids-master/codes/humanfmri_c3_make_nuisance_regressors.m
| 6,395 |
utf_8
|
f53e212728aa5bea91b2b7a366e20669
|
% ========================================================= %
% Possible combinations %
% --------------------------------------------------------- %
% 1. 24 parameter + spike covatiates + linear drift %
% 2. 24 parameter + spike covariates + WM and CSF + linear %
% drfit %
% 3. linear drift %
% ========================================================= %
function humanfmri_c3_make_nuisance_regressors(preproc_subject_dir,varargin)
% This funtion is for making and saving nuisance mat files using PREPROC
% files.
%
% :Usage:
% humanfmri_c3_make_nuisance_regressors(preproc_subject_dir,varargin)
%
% :Input:
% ::
% - preproc_subject_dir: the subject directory for preprocessed data
% (PREPROC.preproc_outputdir)
%
% :Optional input
% ::
% - 'regressors': parameter you want to include
% (defaults: 'regressors','{'24Move','Spike','WM_CSF'};)
% -> lists of regressors
% 1. {24Move}: 24 movement parameters
% 2. {Spike} : spike covariates
% 3. {WM_CSF}: WM and CSF
%
% - 'img': if you want to estimate WM and CSF in specific imgs, you can
% specify field name in PREPROC struture
% (defaults: 'img','swr_func_bold_files' )
%
%
% :Output:
% ::
% - PREPROC.nuisacne_descriptions
% - PREPROC.nuisance_dir
% - PREPROC.nuisance_files
% - save 'nuisance mat files' in PREPROC.nuisacne_dir
%
%
% :Exmaples:
% - humanfmri_c3_make_nuisance_regressors(preproc_subject_dir,'regressors',{'24Move','Spike','WM_CSF'})
% - humanfmri_c3_make_nuisance_regressors(preproc_subject_dir,'img','swr_func_bold_files')
%
%
% ..
% Author and copyright information:
%
% Copyright (C) Jan 2019 Suhwan Gim
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
% ..
%% parse varagin
do_24params = false;
do_spike_covariates = false;
do_wm_csf = false;
reg_idx = {'24Move','Spike','WM_CSF'}; % defaults
do_specify_img = false;
fieldname = 'swr_func_bold_files';
for i = 1:numel(varargin)
if ischar(varargin{i})
switch varargin{i}
case {'regressors'} % in seconds
reg_idx = varargin{i+1};
case {'img'}
fieldname = varargin{i+1};
do_specify_img = true;
end
end
end
%%
for subj_i = 1:numel(preproc_subject_dir)
% load PREPROC and Print header
subject_dir = preproc_subject_dir{subj_i};
PREPROC = save_load_PREPROC(subject_dir, 'load');
print_header('Make and save nuisance regressors: ', PREPROC.subject_code);
% set the nuisance regressors
disp(':: List of nuisance regresosrs' )
for j = 1:length(reg_idx)
switch reg_idx{j}
case {'24Move','24MoveParams'}
do_24params = true;
disp('- 24 movement parameters');
case {'Spike','Spike_covariates'}
do_spike_covariates = true;
disp('- Spike covariates');
case {'WM_CSF','WMCSF','WhiteMatter_CSF'}
do_wm_csf = true;
disp('- White Matter and CSF');
end
end
disp('----------------------------------------------');
%% set directory
subj_dir = PREPROC.preproc_outputdir;
nuisance_dir = fullfile(subj_dir, 'nuisance_mat');
if ~exist(nuisance_dir, 'dir'), mkdir(nuisance_dir); end
%% make nuisance.mat
% warning('No nuisance files. Please check') input('');
for img_i = 1:numel(PREPROC.nuisance.mvmt_covariates)
R = [];
disp(['Run Number : ' num2str(img_i)]);
disp('-------------------------------------------');
disp(['Nuisance file name: ', sprintf('nuisance_run%d.mat', img_i)]);
disp('-------------------------------------------');
% 1. 24 movement parameters
if do_24params
R = [[PREPROC.nuisance.mvmt_covariates{img_i} PREPROC.nuisance.mvmt_covariates{img_i}.^2 ...
[zeros(1,6); diff(PREPROC.nuisance.mvmt_covariates{img_i})] [zeros(1,6); diff(PREPROC.nuisance.mvmt_covariates{img_i})].^2]];
end
% 2. spike_covariates
if do_spike_covariates
R = [R PREPROC.nuisance.spike_covariates{img_i}];
end
% 3. extract and add WM(value2)_CSF(value3)
if do_wm_csf
if do_specify_img
eval(['images_by_run = PREPROC.' fieldname]);
else %defaults
images_by_run = PREPROC.swr_func_bold_files;
end
[~,img_name]=fileparts(images_by_run{img_i});
disp(['Img File name: ' img_name]);
[~, components] = extract_gray_white_csf(fmri_data(images_by_run{img_i}), 'masks', ...
{'gray_matter_mask.nii', 'canonical_white_matter_thrp5_ero1.nii', ...
'canonical_ventricles_thrp5_ero1.nii'});
R = [R scale(double(components{2})) scale(double(components{3}))];
end
% 4. finally, add linear drift
R = [R zscore((1:size(R,1))')];
% 5. Save
savename{img_i} = fullfile(nuisance_dir, sprintf('nuisance_run%d.mat', img_i));
fprintf('\nsaving... %s\n\n', savename{img_i});
save(savename{img_i}, 'R');
end
reg_idx{length(reg_idx)+1} = 'linear drift';
% Save PROPROC
PREPROC.nuisance_descriptions = reg_idx;
PREPROC.nuisance_dir = nuisance_dir;
PREPROC.nuisance_files = savename;
save_load_PREPROC(subj_dir, 'save', PREPROC); % save PREPROC
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.