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
|
wanghan0501/convolutional_sparse_coding-master
|
cbpdn_rank.m
|
.m
|
convolutional_sparse_coding-master/SparseCode/cbpdn_rank.m
| 11,085 |
utf_8
|
3c32aee454510bbb1b9f2d1f4d422844
|
function [Y, optinf] = cbpdn_rank(D, S, lambda, opt)
% cbpdn -- Convolutional Basis Pursuit DeNoising
%
% argmin_{x_m} (1/2)||\sum_m d_m * x_m - s||_2^2 +
% lambda \sum_m ||x_m||_1
%
% The solution is computed using an ADMM approach (see
% boyd-2010-distributed) with efficient solution of the main
% linear systems (see wohlberg-2014-efficient).
%
% Usage:
% [Y, optinf] = cbpdn(D, S, lambda, opt);
%
% Input:
% D Dictionary filter set (3D array)
% S Input image
% lambda Regularization parameter
% opt Algorithm parameters structure
%
% Output:
% Y Dictionary coefficient map set (3D array)
% optinf Details of optimisation
%
%
% Options structure fields:
% Verbose Flag determining whether iteration status is displayed.
% Fields are iteration number, functional value,
% data fidelity term, l1 regularisation term, and
% primal and dual residuals (see Sec. 3.3 of
% boyd-2010-distributed). The value of rho is also
% displayed if options request that it is automatically
% adjusted.
% MaxMainIter Maximum main iterations
% AbsStopTol Absolute convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% RelStopTol Relative convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% L1Weight Weighting array for coefficients in l1 norm of X
% Y0 Initial value for Y
% U0 Initial value for U
% rho ADMM penalty parameter
% AutoRho Flag determining whether rho is automatically updated
% (see Sec. 3.4.1 of boyd-2010-distributed)
% AutoRhoPeriod Iteration period on which rho is updated
% RhoRsdlRatio Primal/dual residual ratio in rho update test
% RhoScaling Multiplier applied to rho when updated
% AutoRhoScaling Flag determining whether RhoScaling value is
% adaptively determined (see wohlberg-2015-adaptive). If
% enabled, RhoScaling specifies a maximum allowed
% multiplier instead of a fixed multiplier.
% RhoRsdlTarget Residual ratio targeted by auto rho update policy.
% StdResiduals Flag determining whether standard residual definitions
% (see Sec 3.3 of boyd-2010-distributed) are used instead
% of normalised residuals (see wohlberg-2015-adaptive)
% RelaxParam Relaxation parameter (see Sec. 3.4.3 of
% boyd-2010-distributed)
% NonNegCoef Flag indicating whether solution should be forced to
% be non-negative
% NoBndryCross Flag indicating whether all solution coefficients
% corresponding to filters crossing the image boundary
% should be forced to zero.
% AuxVarObj Flag determining whether objective function is computed
% using the auxiliary (split) variable
% HighMemSolve Use more memory for a slightly faster solution
%
%
% Author: Brendt Wohlberg <[email protected]> Modified: 2015-07-30
%
% This file is part of the SPORCO library. Details of the copyright
% and user license can be found in the 'Copyright' and 'License' files
% distributed with the library.
if nargin < 4,
opt = [];
end
checkopt(opt, defaultopts([]));
opt = defaultopts(opt);
% Set up status display for verbose operation
hstr = 'Itn Fnc DFid l1 r s ';
sfms = '%4d %9.2e %9.2e %9.2e %9.2e %9.2e';
nsep = 54;
if opt.AutoRho,
hstr = [hstr ' rho '];
sfms = [sfms ' %9.2e'];
nsep = nsep + 10;
end
if opt.Verbose && opt.MaxMainIter > 0,
disp(hstr);
disp(char('-' * ones(1,nsep)));
end
% Collapsing of trailing singleton dimensions greatly complicates
% handling of both SMV and MMV cases. The simplest approach would be
% if S could always be reshaped to 4d, with dimensions consisting of
% image rows, image cols, a single dimensional placeholder for number
% of filters, and number of measurements, but in the single
% measurement case the third dimension is collapsed so that the array
% is only 3d.
if size(S,3) > 1 && size(S,4) == 1,
xsz = [size(S,1) size(S,2) size(D,3) size(S,3)];
hrm = [1 1 1 size(S,3)];
% Insert singleton 3rd dimension (for number of filters) so that
% 4th dimension is number of images in input s volume
S = reshape(S, [size(S,1) size(S,2) 1 size(S,3)]);
else
xsz = [size(S,1) size(S,2) size(D,3) size(S,4)];
hrm = 1;
end
xrm = [1 1 size(D,3)];
% Start timer
tstart = tic;
% Compute filters in DFT domain
Df = fft2(D, size(S,1), size(S,2));
% Convolve-sum and its Hermitian transpose
Dop = @(x) sum(bsxfun(@times, Df, x), 3);
DHop = @(x) bsxfun(@times, conj(Df), x);
% Compute signal in DFT domain
Sf = fft2(S);
% S convolved with all filters in DFT domain
DSf = DHop(Sf);
% Default lambda is 1/10 times the lambda value beyond which the
% solution is a zero vector
if nargin < 3 | isempty(lambda),
b = ifft2(DHop(Sf), 'symmetric');
lambda = 0.1*max(vec(abs(b)));
end
% Set up algorithm parameters and initialise variables
rho = opt.rho;
if isempty(rho), rho = 50*lambda+1; end;
if isempty(opt.RhoRsdlTarget),
if opt.StdResiduals,
opt.RhoRsdlTarget = 1;
else
opt.RhoRsdlTarget = 1 + (18.3).^(log10(lambda) + 1);
end
end
if opt.HighMemSolve,
C = bsxfun(@rdivide, Df, sum(Df.*conj(Df), 3) + rho);
else
C = [];
end
Nx = prod(xsz);
optinf = struct('itstat', [], 'opt', opt);
r = Inf;
s = Inf;
epri = 0;
edua = 0;
% Initialise main working variables
X = [];
if isempty(opt.Y0),
Y = zeros(xsz);
else
Y = opt.Y0;
end
Yprv = Y;
if isempty(opt.U0),
if isempty(opt.Y0),
U = zeros(xsz);
else
U = (lambda/rho)*sign(Y);
end
else
U = opt.U0;
end
% Main loop
k = 1;
while k <= opt.MaxMainIter && (r > epri | s > edua),
% Solve X subproblem
Xf = solvedbi_sm(Df, rho, DSf + rho*fft2(Y - U), C);
X = ifft2(Xf, 'symmetric');
% See pg. 21 of boyd-2010-distributed
if opt.RelaxParam == 1,
Xr = X;
else
Xr = opt.RelaxParam*X + (1-opt.RelaxParam)*Y;
end
% Solve Y subproblem
%Y = shrink(Xr + U, (lambda/rho)*opt.L1Weight);
% Y = shrink(Xr + U, (lambda/rho)*opt.L1Weight);
Y = Do(lambda/rho, Xr+U);
if opt.NonNegCoef,
Y(Y < 0) = 0;
end
if opt.NoBndryCross,
Y((end-size(D,1)+2):end,:,:,:) = 0;
Y(:,(end-size(D,1)+2):end,:,:) = 0;
end
% Update dual variable
U = U + Xr - Y;
% Compute data fidelity term in Fourier domain (note normalisation)
if opt.AuxVarObj,
Yf = fft2(Y); % This represents unnecessary computational cost
Jdf = sum(vec(abs(sum(bsxfun(@times,Df,Yf),3)-Sf).^2))/(2*xsz(1)*xsz(2));
Jl1 = sum(abs(vec(bsxfun(@times, opt.L1Weight, Y))));
Jl1=trace(sqrt(X*X'));
for i=1:size(X,3)
cc=X(:,:,i)'*X(:,:,i);
cc=sqrt(cc);
Jl1=Jl1+trace(cc);
end
else
Jdf = sum(vec(abs(sum(bsxfun(@times,Df,Xf),3)-Sf).^2))/(2*xsz(1)*xsz(2));
Jl1 = sum(abs(vec(bsxfun(@times, opt.L1Weight, X))));
Jl1=0;
for i=1:size(X,3)
cc=X(:,:,i)'*X(:,:,i);
cc=sqrt(cc);
Jl1=Jl1+trace(cc);
end
end
Jfn = Jdf + lambda*Jl1;
nX = norm(X(:)); nY = norm(Y(:)); nU = norm(U(:));
if opt.StdResiduals,
% See pp. 19-20 of boyd-2010-distributed
r = norm(vec(X - Y));
s = norm(vec(rho*(Yprv - Y)));
epri = sqrt(Nx)*opt.AbsStopTol+max(nX,nY)*opt.RelStopTol;
edua = sqrt(Nx)*opt.AbsStopTol+rho*nU*opt.RelStopTol;
else
% See wohlberg-2015-adaptive
r = norm(vec(X - Y))/max(nX,nY);
s = norm(vec(Yprv - Y))/nU;
epri = sqrt(Nx)*opt.AbsStopTol/max(nX,nY)+opt.RelStopTol;
edua = sqrt(Nx)*opt.AbsStopTol/(rho*nU)+opt.RelStopTol;
end
% Record and display iteration details
tk = toc(tstart);
optinf.itstat = [optinf.itstat; [k Jfn Jdf Jl1 r s epri edua rho tk]];
if opt.Verbose,
if opt.AutoRho,
disp(sprintf(sfms, k, Jfn, Jdf, Jl1, r, s, rho));
else
disp(sprintf(sfms, k, Jfn, Jdf, Jl1, r, s));
end
end
% See wohlberg-2015-adaptive and pp. 20-21 of boyd-2010-distributed
if opt.AutoRho,
if k ~= 1 && mod(k, opt.AutoRhoPeriod) == 0,
if opt.AutoRhoScaling,
rhomlt = sqrt(r/(s*opt.RhoRsdlTarget));
if rhomlt < 1, rhomlt = 1/rhomlt; end
if rhomlt > opt.RhoScaling, rhomlt = opt.RhoScaling; end
else
rhomlt = opt.RhoScaling;
end
rsf = 1;
if r > opt.RhoRsdlTarget*opt.RhoRsdlRatio*s, rsf = rhomlt; end
if s > (opt.RhoRsdlRatio/opt.RhoRsdlTarget)*r, rsf = 1/rhomlt; end
rho = rsf*rho;
U = U/rsf;
if opt.HighMemSolve && rsf ~= 1,
C = bsxfun(@rdivide, Df, sum(Df.*conj(Df), 3) + rho);
end
end
end
Yprv = Y;
k = k + 1;
end
% Record run time and working variables
optinf.runtime = toc(tstart);
optinf.X = X;
optinf.Xf = Xf;
optinf.Y = Y;
optinf.U = U;
optinf.lambda = lambda;
optinf.rho = rho;
% End status display for verbose operation
if opt.Verbose && opt.MaxMainIter > 0,
disp(char('-' * ones(1,nsep)));
end
return
function u = vec(v)
u = v(:);
return
function u = shrink(v, lambda)
if isscalar(lambda),
u = sign(v).*max(0, abs(v) - lambda);
else
u = sign(v).*max(0, bsxfun(@minus, abs(v), lambda));
end
return
function r = Do(tau, X)
% shrinkage operator for singular values
for i=1:size(X,3)
for j=1:size(X,4)
[U, S, V] = svd(X(:,:,i,j), 'econ');
r(:,:,i,j)= U*So(tau, S)*V';
end
end
return
function r = So(tau, X)
% shrinkage operator
r = sign(X) .* max(abs(X) - tau, 0);
return
function opt = defaultopts(opt)
if ~isfield(opt,'Verbose'),
opt.Verbose = 0;
end
if ~isfield(opt,'MaxMainIter'),
opt.MaxMainIter = 1000;
end
if ~isfield(opt,'AbsStopTol'),
opt.AbsStopTol = 0;
end
if ~isfield(opt,'RelStopTol'),
opt.RelStopTol = 1e-4;
end
if ~isfield(opt,'L1Weight'),
opt.L1Weight = 1;
end
if ~isfield(opt,'Y0'),
opt.Y0 = [];
end
if ~isfield(opt,'U0'),
opt.U0 = [];
end
if ~isfield(opt,'rho'),
opt.rho = [];
end
if ~isfield(opt,'AutoRho'),
opt.AutoRho = 1;
end
if ~isfield(opt,'AutoRhoPeriod'),
opt.AutoRhoPeriod = 1;
end
if ~isfield(opt,'RhoRsdlRatio'),
opt.RhoRsdlRatio = 1.2;
end
if ~isfield(opt,'RhoScaling'),
opt.RhoScaling = 100;
end
if ~isfield(opt,'AutoRhoScaling'),
opt.AutoRhoScaling = 1;
end
if ~isfield(opt,'RhoRsdlTarget'),
opt.RhoRsdlTarget = [];
end
if ~isfield(opt,'StdResiduals'),
opt.StdResiduals = 0;
end
if ~isfield(opt,'RelaxParam'),
opt.RelaxParam = 1.8;
end
if ~isfield(opt,'NonNegCoef'),
opt.NonNegCoef = 0;
end
if ~isfield(opt,'NoBndryCross'),
opt.NoBndryCross = 0;
end
if ~isfield(opt,'AuxVarObj'),
opt.AuxVarObj = 0;
end
if ~isfield(opt,'HighMemSolve'),
opt.HighMemSolve = 0;
end
return
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
cbpdn_low_sparse.m
|
.m
|
convolutional_sparse_coding-master/SparseCode/cbpdn_low_sparse.m
| 11,314 |
utf_8
|
676fce8f71b3f64551bb909163b73533
|
function [Y, optinf] = cbpdn_low_sparse(D, S, lambda_s, lambda_r,opt)
% cbpdn -- Convolutional Basis Pursuit DeNoising
%
% argmin_{x_m} (1/2)||\sum_m d_m * x_m - s||_2^2 +
% lambda \sum_m ||x_m||_1
%
% The solution is computed using an ADMM approach (see
% boyd-2010-distributed) with efficient solution of the main
% linear systems (see wohlberg-2014-efficient).
%
% Usage:
% [Y, optinf] = cbpdn(D, S, lambda, opt);
%
% Input:
% D Dictionary filter set (3D array)
% S Input image
% lambda Regularization parameter
% opt Algorithm parameters structure
%
% Output:
% Y Dictionary coefficient map set (3D array)
% optinf Details of optimisation
%
%
% Options structure fields:
% Verbose Flag determining whether iteration status is displayed.
% Fields are iteration number, functional value,
% data fidelity term, l1 regularisation term, and
% primal and dual residuals (see Sec. 3.3 of
% boyd-2010-distributed). The value of rho is also
% displayed if options request that it is automatically
% adjusted.
% MaxMainIter Maximum 2(D, size(X,1), size(X,2)), fft2(X)),3), ...
% AbsStopTol Absolute convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% RelStopTol Relative convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% L1Weight Weighting array for coefficients in l1 norm of X
% Y0 Initial value for Y
% U0 Initial value for U
% rho ADMM penalty parameter
% AutoRho Flag determining whether rho is automatically updated
% (see Sec. 3.4.1 of boyd-2010-distributed)
% AutoRhoPeriod Iteration period on which rho is updated
% RhoRsdlRatio Primal/dual residual ratio in rho update test
% RhoScaling Multiplier applied to rho when updated
% AutoRhoScaling Flag determining whether RhoScaling value is
% adaptively determined (see wohlberg-2015-adaptive). If
% enabled, RhoScaling specifies a maximum allowed
% multiplier instead of a fixed multiplier.
% RhoRsdlTarget Residual ratio targeted by auto rho update policy.
% StdResiduals Flag determining whether standard residual definitions
% (see Sec 3.3 of boyd-2010-distributed) are used instead
% of normalised residuals (see wohlberg-2015-adaptive)
% RelaxParam Relaxation parameter (see Sec. 3.4.3 of
% boyd-2010-distributed)
% NonNegCoef Flag indicating whether solution should be forced to
% be non-negative
% NoBndryCross Flag indicating whether all solution coefficients
% corresponding to filters crossing the image boundary
% should be forced to zero.
% AuxVarObj Flag determining whether objective function is computed
% using the auxiliary (split) variable
% HighMemSolve Use more memory for a slightly faster solution
%
%
% Author: Brendt Wohlberg <[email protected]> Modified: 2015-07-30
%
% This file is part of the SPORCO library. Details of the copyright
% and user license can be found in the 'Copyright' and 'License' files
% distributed with the library.
lambda=lambda_s;
if nargin < 4,
opt = [];
end
checkopt(opt, defaultopts([]));
opt = defaultopts(opt);
% Set up status display for verbose operation
hstr = 'Itn Fnc DFid l1 r s ';
sfms = '%4d %9.2e %9.2e %9.2e %9.2e %9.2e';
nsep = 54;
if opt.AutoRho,
hstr = [hstr ' rho '];
sfms = [sfms ' %9.2e'];
nsep = nsep + 10;
end
if opt.Verbose && opt.MaxMainIter > 0,
disp(hstr);
disp(char('-' * ones(1,nsep)));
end
% Collapsing of trailing singleton dimensions greatly complicates
% handling of both SMV and MMV cases. The simplest approach would be
% if S could always be reshaped to 4d, with dimensions consisting of
% image rows, image cols, a single dimensional placeholder for number
% of filters, and number of measurements, but in the single
% measurement case the third dimension is collapsed so that the array
% is only 3d.
if size(S,3) > 1 && size(S,4) == 1,
xsz = [size(S,1) size(S,2) size(D,3) size(S,3)];
hrm = [1 1 1 size(S,3)];
% Insert singleton 3rd dimension (for number of filters) so that
% 4th dimension is number of images in input s volume
S = reshape(S, [size(S,1) size(S,2) 1 size(S,3)]);
else
xsz = [size(S,1) size(S,2) size(D,3) size(S,4)];
hrm = 1;
end
xrm = [1 1 size(D,3)];
% Start timer
tstart = tic;
% Compute filters in DFT domain
Df = fft2(D, size(S,1), size(S,2));
% Convolve-sum and its Hermitian transpose
Dop = @(x) sum(bsxfun(@times, Df, x), 3);
DHop = @(x) bsxfun(@times, conj(Df), x);
% Compute signal in DFT domain
Sf = fft2(S);
% S convolved with all filters in DFT domain
DSf = DHop(Sf);
% Default lambda is 1/10 times the lambda value beyond which the
% solution is a zero vector
if nargin < 3 | isempty(lambda),
b = ifft2(DHop(Sf), 'symmetric');
lambda = 0.1*max(vec(abs(b)));
end
% Set up algorithm parameters and initialise variables
rho = opt.rho;
if isempty(rho), rho = 50*lambda+1; end;
if isempty(opt.RhoRsdlTarget),
if opt.StdResiduals,
opt.RhoRsdlTarget = 1;
else
opt.RhoRsdlTarget = 1 + (18.3).^(log10(lambda) + 1);
end
end
if opt.HighMemSolve,
C = bsxfun(@rdivide, Df, sum(Df.*conj(Df), 3) + rho);
else
C = [];
end
Nx = prod(xsz);
optinf = struct('itstat', [], 'opt', opt);
r = Inf;
s = Inf;
epri = 0;
edua = 0;
% Initialise main working variables
X = [];
if isempty(opt.Y0),
Y = zeros(xsz);
else
Y = opt.Y0;
end
Yprv = Y;
if isempty(opt.U0),
if isempty(opt.Y0),
U1 = zeros(xsz);
U2 = zeros(xsz);
else
U1 = (lambda/rho)*sign(Y);
U2 = (lambda/rho)*sign(Y);
end
else
U1 = opt.U0;
U2 = opt.U0;
end
% Main loop
k = 1;
while k <= opt.MaxMainIter && (r > epri | s > edua),
% Solve X subproblem
Xf_1 = solvedbi_sm(Df, rho, DSf + rho*fft2(Y - U1), C);
X = ifft2(Xf_1, 'symmetric');
% See pg. 21 of boyd-2010-distributed
if opt.RelaxParam == 1,
Xr_1 = X;
else
Xr_1 = opt.RelaxParam*X + (1-opt.RelaxParam)*Y;
end
% Solve Y subproblem
%Y = shrink(Xr + U, (lambda/rho)*opt.L1Weight);
Xr_2 = Do(lambda_r/rho, Y-U2);
if opt.NonNegCoef,
Xr_2(Y < 0) = 0;
end
if opt.NoBndryCross,
Xr_2((end-size(D,1)+2):end,:,:,:) = 0;
Xr_2(:,(end-size(D,1)+2):end,:,:) = 0;
end
Y = shrink((Xr_1+Xr_2)/2 + (U1+U2)/2, (2*lambda_s/rho)*opt.L1Weight);
% Update dual variable
U1 = U1 + Xr_1 - Y;
U2 = U2 + Xr_2 - Y;
% Compute data fidelity term in Fourier domain (note normalisation)
if opt.AuxVarObj,
Yf = fft2(Y); % This represents unnecessary computational cost
Jdf = sum(vec(abs(sum(bsxfun(@times,Df,Yf),3)-Sf).^2))/(2*xsz(1)*xsz(2));
Jl1 = sum(abs(vec(bsxfun(@times, opt.L1Weight, Y))));
for i=1:size(Y,Y)
cc=Y(:,:,i)'*Y(:,:,i);
cc=sqrt(cc);
Jl1=Jl1+trace(cc);
end
else
Jdf = sum(vec(abs(sum(bsxfun(@times,Df,Xf_1),3)-Sf).^2))/(2*xsz(1)*xsz(2));
Js1 = sum(abs(vec(bsxfun(@times, opt.L1Weight, Y))));
Jl1=0;
for i=1:size(Y,3)
cc=Y(:,:,i)'*Y(:,:,i);
cc=sqrt(cc);
Jl1=Jl1+trace(cc);
end
end
Jfn = Jdf + lambda_r*Jl1+lambda_s*Js1;
nX = norm(X(:)); nY = norm(Y(:)); nU = norm((U1(:)+U2(:))/2);
if opt.StdResiduals,
% See pp. 19-20 of boyd-2010-distributed
r = norm(vec(X - Y));
s = norm(vec(rho*(Yprv - Y)));
epri = sqrt(Nx)*opt.AbsStopTol+max(nX,nY)*opt.RelStopTol;
edua = sqrt(Nx)*opt.AbsStopTol+rho*nU*opt.RelStopTol;
else
% See wohlberg-2015-adaptive
r = norm(vec(X - Y))/max(nX,nY);
s = norm(vec(Yprv - Y))/nU;
epri = sqrt(Nx)*opt.AbsStopTol/max(nX,nY)+opt.RelStopTol;
edua = sqrt(Nx)*opt.AbsStopTol/(rho*nU)+opt.RelStopTol;
end
% Record and display iteration details
tk = toc(tstart);
optinf.itstat = [optinf.itstat; [k Jfn Jdf Jl1 r s epri edua rho tk]];
if opt.Verbose,
if opt.AutoRho,
disp(sprintf(sfms, k, Jfn, Jdf, Jl1, r, s, rho));
else
disp(sprintf(sfms, k, Jfn, Jdf, Jl1, r, s));
end
end
% See wohlberg-2015-adaptive and pp. 20-21 of boyd-2010-distributed
if opt.AutoRho,
if k ~= 1 && mod(k, opt.AutoRhoPeriod) == 0,
if opt.AutoRhoScaling,
rhomlt = sqrt(r/(s*opt.RhoRsdlTarget));
if rhomlt < 1, rhomlt = 1/rhomlt; end
if rhomlt > opt.RhoScaling, rhomlt = opt.RhoScaling; end
else
rhomlt = opt.RhoScaling;
end
rsf = 1;
if r > opt.RhoRsdlTarget*opt.RhoRsdlRatio*s, rsf = rhomlt; end
if s > (opt.RhoRsdlRatio/opt.RhoRsdlTarget)*r, rsf = 1/rhomlt; end
rho = rsf*rho;
U = (U1+U2)/2/rsf;
if opt.HighMemSolve && rsf ~= 1,
C = bsxfun(@rdivide, Df, sum(Df.*conj(Df), 3) + rho);
end
end
end
Yprv = Y;
k = k + 1;
end
% Record run time and working variables
optinf.runtime = toc(tstart);
optinf.X = X;
optinf.Xf = Xf_1;
optinf.Y = Y;
optinf.U = U;
optinf.lambda = lambda;
optinf.rho = rho;
% End status display for verbose operation
if opt.Verbose && opt.MaxMainIter > 0,
disp(char('-' * ones(1,nsep)));
end
return
function u = vec(v)
u = v(:);
return
function u = shrink(v, lambda)
if isscalar(lambda),
u = sign(v).*max(0, abs(v) - lambda);
else
u = sign(v).*max(0, bsxfun(@minus, abs(v), lambda));
end
return
function r = Do(tau, X)
% shrinkage operator for singular values
for i=1:size(X,3)
for j=1:size(X,4)
[U, S, V] = svd(X(:,:,i,j), 'econ');
r(:,:,i,j)= U*So(tau, S)*V';
end
end
return
function r = So(tau, X)
% shrinkage operator
r = sign(X) .* max(abs(X) - tau, 0);
return
function opt = defaultopts(opt)
if ~isfield(opt,'Verbose'),
opt.Verbose = 0;
end
if ~isfield(opt,'MaxMainIter'),
opt.MaxMainIter = 1000;
end
if ~isfield(opt,'AbsStopTol'),
opt.AbsStopTol = 0;
end
if ~isfield(opt,'RelStopTol'),
opt.RelStopTol = 1e-4;
end
if ~isfield(opt,'L1Weight'),
opt.L1Weight = 1;
end
if ~isfield(opt,'Y0'),
opt.Y0 = [];
end
if ~isfield(opt,'U0'),
opt.U0 = [];
end
if ~isfield(opt,'rho'),
opt.rho = [];
end
if ~isfield(opt,'AutoRho'),
opt.AutoRho = 1;
end
if ~isfield(opt,'AutoRhoPeriod'),
opt.AutoRhoPeriod = 1;
end
if ~isfield(opt,'RhoRsdlRatio'),
opt.RhoRsdlRatio = 1.2;
end
if ~isfield(opt,'RhoScaling'),
opt.RhoScaling = 100;
end
if ~isfield(opt,'AutoRhoScaling'),
opt.AutoRhoScaling = 1;
end
if ~isfield(opt,'RhoRsdlTarget'),
opt.RhoRsdlTarget = [];
end
if ~isfield(opt,'StdResiduals'),
opt.StdResiduals = 0;
end
if ~isfield(opt,'RelaxParam'),
opt.RelaxParam = 1.8;
end
if ~isfield(opt,'NonNegCoef'),
opt.NonNegCoef = 0;
end
if ~isfield(opt,'NoBndryCross'),
opt.NoBndryCross = 0;
end
if ~isfield(opt,'AuxVarObj'),
opt.AuxVarObj = 0;
end
if ~isfield(opt,'HighMemSolve'),
opt.HighMemSolve = 0;
end
return
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
celnet_gpu.m
|
.m
|
convolutional_sparse_coding-master/SparseCode/celnet_gpu.m
| 12,262 |
utf_8
|
3bfe8fecce50ec8ea826ac2b286c605d
|
function [Y, optinf] = celnet_gpu(D, S, lambda, mu, opt)
% celnet_gpu -- Convolutional Elastic Net (GPU version)
%
% argmin_{x_m} (1/2)||\sum_m d_m * x_m - s||_2^2 +
% lambda \sum_m ||x_m||_1 + (mu/2) \sum_m ||x_m||_2^2
%
% The solution is computed using an ADMM approach (see
% boyd-2010-distributed) with efficient solution of the main
% linear systems (see wohlberg-2016-efficient).
%
% Usage:
% [Y, optinf] = celnet_gpu(D, S, lambda, mu, opt)
%
% Input:
% D Dictionary filter set (3D array)
% s Input image
% lambda Regularization parameter (l1)
% mu Regularization parameter (l2)
% opt Algorithm parameters structure
%
% Output:
% Y Dictionary coefficient map set (3D array)
% optinf Details of optimisation
%
%
% Options structure fields:
% Verbose Flag determining whether iteration status is displayed.
% Fields are iteration number, functional value,
% data fidelity term, l1 regularisation term, l2
% regularisation term, and primal and dual residuals
% (see Sec. 3.3 of boyd-2010-distributed). The value of
% rho is also displayed if options request that it is
% automatically adjusted.
% MaxMainIter Maximum main iterations
% AbsStopTol Absolute convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% RelStopTol Relative convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% L1Weight Weighting array for coefficients in l1 norm of X.
% Array should have the same dimensions as X, but the
% first two dimensions may be of unit size, corresponding
% to a weighting that varies with filter index but is
% spatially constant.
% L2Weight Weighting array for l2 norm of X. Array should have
% dimensions corresponding to the non-spatial dimensions
% of X since spatial weighting is no possible (i.e.
% weighting varies only with filter and sample index).
% Y0 Initial value for Y
% U0 Initial value for U
% rho ADMM penalty parameter
% AutoRho Flag determining whether rho is automatically updated
% (see Sec. 3.4.1 of boyd-2010-distributed)
% AutoRhoPeriod Iteration period on which rho is updated
% RhoRsdlRatio Primal/dual residual ratio in rho update test
% RhoScaling Multiplier applied to rho when updated
% AutoRhoScaling Flag determining whether RhoScaling value is
% adaptively determined (see wohlberg-2015-adaptive). If
% enabled, RhoScaling specifies a maximum allowed
% multiplier instead of a fixed multiplier.
% RhoRsdlTarget Residual ratio targeted by auto rho update policy.
% StdResiduals Flag determining whether standard residual definitions
% (see Sec 3.3 of boyd-2010-distributed) are used instead
% of normalised residuals (see wohlberg-2015-adaptive)
% RelaxParam Relaxation parameter (see Sec. 3.4.3 of
% boyd-2010-distributed)
% NoBndryCross Flag indicating whether all solution coefficients
% corresponding to filters crossing the image boundary
% should be forced to zero.
% AuxVarObj Flag determining whether objective function is computed
% using the auxiliary (split) variable
% HighMemSolve Use more memory for a slightly faster solution
%
%
% Authors: Brendt Wohlberg <[email protected]>
% Ping-Keng Jao <[email protected]>
% Modified: 2015-12-18
%
% This file is part of the SPORCO library. Details of the copyright
% and user license can be found in the 'License' file distributed with
% the library.
gS = gpuArray(S);
gD = gpuArray(D);
glambda = gpuArray(lambda);
if nargin < 5,
opt = [];
end
if nargin < 4,
gmu = gpuArray(0);
else
gmu = gpuArray(mu);
end
checkopt(opt, defaultopts([]));
opt = defaultopts(opt);
% Set up status display for verbose operation
hstr = 'Itn Fnc DFid l1 l2 r s ';
sfms = '%4d %9.2e %9.2e %9.2e %9.2e %9.2e %9.2e';
nsep = 64;
if opt.AutoRho,
hstr = [hstr ' rho '];
sfms = [sfms ' %9.2e'];
nsep = nsep + 10;
end
if opt.Verbose && opt.MaxMainIter > 0,
disp(hstr);
disp(char('-' * ones(1,nsep)));
end
% Start timer
tstart = tic;
% Collapsing of trailing singleton dimensions greatly complicates
% handling of both SMV and MMV cases. The simplest approach would be
% if S could always be reshaped to 4d, with dimensions consisting of
% image rows, image cols, a single dimensional placeholder for number
% of filters, and number of measurements, but in the single
% measurement case the third dimension is collapsed so that the array
% is only 3d.
if size(S,3) > 1,
xsz = [size(S,1) size(S,2) size(D,3) size(S,3)];
% Insert singleton 3rd dimension (for number of filters) so that
% 4th dimension is number of images in input s volume
S = reshape(S, [size(S,1) size(S,2) 1 size(S,3)]);
else
xsz = [size(S,1) size(S,2) size(D,3) 1];
end
% Compute filters in DFT domain
gDf = fft2(gD, size(S,1), size(S,2));
% Convolve-sum and its Hermitian transpose
gDop = @(x) sum(bsxfun(@times, gDf, x), 3);
gDHop = @(x) bsxfun(@times, conj(gDf), x);
% Compute signal in DFT domain
gSf = fft2(gS);
% S convolved with all filters in DFT domain
gDSf = gDHop(gSf);
% Set up l2 weight array
if isscalar(opt.L2Weight),
gwl2 = gpuArray(opt.L2Weight);
else
gwl2 = gpuArray(reshape(opt.L2Weight, [1 1 size(opt.L2Weight,1) ...
size(opt.L2Weight,2)]));
end
% Default lambda is 1/10 times the lambda value beyond which the
% solution is a zero vector
if nargin < 3 | isempty(glambda),
gb = ifft2(gDHop(gSf), 'symmetric');
glambda = 0.1*max(vec(abs(gb)));
end
% Set up algorithm parameters and initialise variables
grho = gpuArray(opt.rho);
if isempty(grho), grho = 50*glambda+1; end;
gmwr = gmu*gwl2 + grho;
if isempty(opt.RhoRsdlTarget),
if opt.StdResiduals,
opt.RhoRsdlTarget = 1;
else
opt.RhoRsdlTarget = 1 + (18.3).^(log10(glambda) + 1);
end
end
if opt.HighMemSolve,
gcn = bsxfun(@rdivide, gDf, gmwr);
gcd = sum(gDf.*bsxfun(@rdivide, conj(gDf), gmu*gwl2 + grho), 3) + 1.0;
gC = bsxfun(@rdivide, gcn, gcd);
clear cn cd;
else
C = [];
end
gNx = prod(gpuArray(xsz));
optinf = struct('itstat', [], 'opt', opt);
gr = gpuArray(Inf);
gs = gpuArray(Inf);
gepri = gpuArray(0);
gedua = gpuArray(0);
% Initialise main working variables
% X = [];
if isempty(opt.Y0),
gY = gpuArray.zeros(xsz);
else
gY = gpuArray(opt.Y0);
end
gYprv = gY;
if isempty(opt.U0),
if isempty(opt.Y0),
gU = gpuArray.zeros(xsz);
else
gU = (glambda/grho)*sign(gY);
end
else
gU = gpuArray(opt.U0);
end
% Main loop
k = 1;
while k <= opt.MaxMainIter & (gr > gepri | gs > gedua),
% Solve X subproblem
gXf = solvedbd_sm(gDf, gmwr, gDSf + grho*fft2(gY - gU), gC);
gX = ifft2(gXf, 'symmetric');
% See pg. 21 of boyd-2010-distributed
if opt.RelaxParam == 1,
gXr = gX;
else
gXr = opt.RelaxParam*gX + (1-opt.RelaxParam)*gY;
end
% Solve Y subproblem
gY = shrink(gXr + gU, (glambda/grho)*opt.L1Weight);
if opt.NoBndryCross,
gY((end-size(gD,1)+2):end,:,:,:) = 0;
gY(:,(end-size(gD,1)+2):end,:,:) = 0;
end
% Update dual variable
gU = gU + gXr - gY;
% Compute data fidelity term in Fourier domain (note normalisation)
if opt.AuxVarObj,
gYf = fft2(gY); % This represents unnecessary computational cost
gJdf = sum(vec(abs(sum(bsxfun(@times,gDf,gYf),3)-gSf).^2)) / ...
(2*xsz(1)*xsz(2));
gJl1 = sum(abs(vec(bsxfun(@times, opt.L1Weight, gY))));
gJl2 = sum(vec(gwl2.*sum(sum(gY.^2, 1),2)))/2;
else
gJdf = sum(vec(abs(sum(bsxfun(@times,gDf,gXf),3)-gSf).^2)) / ...
(2*xsz(1)*xsz(2));
gJl1 = sum(abs(vec(bsxfun(@times, opt.L1Weight, gX))));
gJl2 = sum(vec(gwl2.*sum(sum(gX.^2, 1),2)))/2;
end
gJfn = gJdf + glambda*gJl1 + gmu*gJl2;
gnX = norm(gX(:)); gnY = norm(gY(:)); gnU = norm(gU(:));
if opt.StdResiduals,
% See pp. 19-20 of boyd-2010-distributed
gr = norm(vec(gX - gY));
gs = norm(vec(grho*(gYprv - gY)));
gepri = sqrt(gNx)*opt.AbsStopTol+max(gnX,gnY)*opt.RelStopTol;
gedua = sqrt(gNx)*opt.AbsStopTol+grho*gnU*opt.RelStopTol;
else
% See wohlberg-2015-adaptive
gr = norm(vec(gX - gY))/max(gnX,gnY);
gs = norm(vec(gYprv - gY))/gnU;
gepri = sqrt(gNx)*opt.AbsStopTol/max(gnX,gnY)+opt.RelStopTol;
gedua = sqrt(gNx)*opt.AbsStopTol/(grho*gnU)+opt.RelStopTol;
end
% Record and display iteration details
tk = toc(tstart);
optinf.itstat = [optinf.itstat; [k gather(gJfn) gather(gJdf) gather(gJl1) ...
gather(gJl2) gather(gr) gather(gs) gather(gepri) ...
gather(gedua) gather(grho) tk]];
if opt.Verbose,
if opt.AutoRho,
disp(sprintf(sfms, k, gather(gJfn), gather(gJdf), gather(gJl1), ...
gather(gJl2), gather(gr), gather(gs), gather(grho)));
else
disp(sprintf(sfms, k, gather(gJfn), gather(gJdf), gather(gJl1), ...
gather(gJl2), gather(gr), gather(gs)));
end
end
% See wohlberg-2015-adaptive and pp. 20-21 of boyd-2010-distributed
if opt.AutoRho,
if k ~= 1 && mod(k, opt.AutoRhoPeriod) == 0,
if opt.AutoRhoScaling,
grhomlt = sqrt(gr/(gs*opt.RhoRsdlTarget));
if grhomlt < 1, grhomlt = 1/grhomlt; end
if grhomlt > opt.RhoScaling, grhomlt = opt.RhoScaling; end
else
rhomlt = opt.RhoScaling;
end
grsf = 1;
if gr > opt.RhoRsdlTarget*opt.RhoRsdlRatio*gs, grsf = grhomlt; end
if gs > (opt.RhoRsdlRatio/opt.RhoRsdlTarget)*gr, grsf = 1/grhomlt; end
grho = grsf*grho;
gU = gU/grsf;
if opt.HighMemSolve && grsf ~= 1,
gmwr = gmu*gwl2 + grho;
gcn = bsxfun(@rdivide, gDf, gmwr);
gcd = sum(gDf.*bsxfun(@rdivide, conj(gDf), gmwr), 3) + 1.0;
gC = bsxfun(@rdivide, gcn, gcd);
clear gcn gcd;
end
end
end
gYprv = gY;
k = k + 1;
end
% Record run time and working variables
optinf.runtime = toc(tstart);
optinf.X = gather(gX);
optinf.Xf = gather(gXf);
optinf.Y = gather(gY);
optinf.U = gather(gU);
optinf.lambda = gather(glambda);
optinf.mu = gather(mu);
optinf.rho = gather(grho);
Y = gather(gY);
if opt.Verbose && opt.MaxMainIter > 0,
disp(char('-' * ones(1,nsep)));
end
return
function u = vec(v)
u = v(:);
return
function u = shrink(v, lambda)
if isscalar(lambda),
u = sign(v).*max(0, abs(v) - lambda);
else
u = sign(v).*max(0, bsxfun(@minus, abs(v), lambda));
end
return
function opt = defaultopts(opt)
if ~isfield(opt,'Verbose'),
opt.Verbose = 0;
end
if ~isfield(opt,'MaxMainIter'),
opt.MaxMainIter = 1000;
end
if ~isfield(opt,'AbsStopTol'),
opt.AbsStopTol = 0;
end
if ~isfield(opt,'RelStopTol'),
opt.RelStopTol = 1e-4;
end
if ~isfield(opt,'L1Weight'),
opt.L1Weight = 1;
end
if ~isfield(opt,'L2Weight'),
opt.L2Weight = 1;
end
if ~isfield(opt,'Y0'),
opt.Y0 = [];
end
if ~isfield(opt,'U0'),
opt.U0 = [];
end
if ~isfield(opt,'rho'),
opt.rho = [];
end
if ~isfield(opt,'AutoRho'),
opt.AutoRho = 1;
end
if ~isfield(opt,'AutoRhoPeriod'),
opt.AutoRhoPeriod = 1;
end
if ~isfield(opt,'RhoRsdlRatio'),
opt.RhoRsdlRatio = 1.2;
end
if ~isfield(opt,'RhoScaling'),
opt.RhoScaling = 100;
end
if ~isfield(opt,'AutoRhoScaling'),
opt.AutoRhoScaling = 1;
end
if ~isfield(opt,'RhoRsdlTarget'),
opt.RhoRsdlTarget = [];
end
if ~isfield(opt,'StdResiduals'),
opt.StdResiduals = 0;
end
if ~isfield(opt,'RelaxParam'),
opt.RelaxParam = 1.8;
end
if ~isfield(opt,'NoBndryCross'),
opt.NoBndryCross = 0;
end
if ~isfield(opt,'AuxVarObj'),
opt.AuxVarObj = 0;
end
if ~isfield(opt,'HighMemSolve'),
opt.HighMemSolve = 0;
end
return
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
cbpdnms.m
|
.m
|
convolutional_sparse_coding-master/SparseCode/cbpdnms.m
| 10,773 |
utf_8
|
106a9b0dc6d99d787c98deb2b7f52d58
|
function [X, optinf] = cbpdnms(D, S, lambda, opt)
% cbpdnms -- Convolutional Basis Pursuit DeNoising (Mask Simulation)
%
% argmin_{x_k} (1/2)||W (\sum_k d_k * x_k - s)||_2^2 +
% lambda \sum_k ||x_k||_1
%
% The solution is computed using an ADMM approach (see
% boyd-2010-distributed) with efficient solution of the main
% linear systems (see wohlberg-2016-efficient and
% wohlberg-2016-boundary).
%
% Usage:
% [X, optinf] = cbpdnms(D, S, lambda, opt)
%
% Input:
% D Dictionary filter set (3D array)
% S Input image
% lambda Regularization parameter
% opt Algorithm parameters structure
%
% Output:
% X Dictionary coefficient map set (3D array)
% optinf Details of optimisation
%
%
% Options structure fields:
% Verbose Flag determining whether iteration status is displayed.
% Fields are iteration number, functional value,
% data fidelity term, l1 regularisation term, and
% primal and dual residuals (see Sec. 3.3 of
% boyd-2010-distributed). The value of rho is also
% displayed if options request that it is automatically
% adjusted.
% MaxMainIter Maximum main iterations
% AbsStopTol Absolute convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% RelStopTol Relative convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% L1Weight Weighting array for coefficients in l1 norm of X
% Y0 Initial value for Y
% U0 Initial value for U
% rho ADMM penalty parameter
% AutoRho Flag determining whether rho is automatically updated
% (see Sec. 3.4.1 of boyd-2010-distributed)
% AutoRhoPeriod Iteration period on which rho is updated
% RhoRsdlRatio Primal/dual residual ratio in rho update test
% RhoScaling Multiplier applied to rho when updated
% AutoRhoScaling Flag determining whether RhoScaling value is
% adaptively determined (see wohlberg-2015-adaptive). If
% enabled, RhoScaling specifies a maximum allowed
% multiplier instead of a fixed multiplier.
% RhoRsdlTarget Residual ratio targeted by auto rho update policy.
% StdResiduals Flag determining whether standard residual definitions
% (see Sec 3.3 of boyd-2010-distributed) are used instead
% of normalised residuals (see wohlberg-2015-adaptive)
% RelaxParam Relaxation parameter (see Sec. 3.4.3 of
% boyd-2010-distributed)
% NoBndryCross Flag indicating whether all solution coefficients
% corresponding to filters crossing the image boundary
% should be forced to zero.
% AuxVarObj Flag determining whether objective function is computed
% using the auxiliary (split) variable
% HighMemSolve Use more memory for a slightly faster solution
% W Synthesis spatial weighting matrix
%
%
% Author: Brendt Wohlberg <[email protected]> Modified: 2016-05-10
%
% This file is part of the SPORCO library. Details of the copyright
% and user license can be found in the 'License' file distributed with
% the library.
if nargin < 4,
opt = [];
end
checkopt(opt, defaultopts([]));
opt = defaultopts(opt);
% Set up status display for verbose operation
hstr = 'Itn Fnc DFid l1 r s ';
sfms = '%4d %9.2e %9.2e %9.2e %9.2e %9.2e';
nsep = 54;
if opt.AutoRho,
hstr = [hstr ' rho '];
sfms = [sfms ' %9.2e'];
nsep = nsep + 10;
end
if opt.Verbose && opt.MaxMainIter > 0,
disp(hstr);
disp(char('-' * ones(1,nsep)));
end
% Start timer
tstart = tic;
% Insert impulse filter into dictionary
imp = zeros(size(D,1), size(D,2), 1);
imp(1,1,1) = 1.0;
Di = cat(3, D, imp);
% Collapsing of trailing singleton dimensions greatly complicates
% handling of both SMV and MMV cases. The simplest approach would be
% if s could always be reshaped to 4d, with dimensions consisting of
% image rows, image cols, a single dimensional placeholder for number
% of filters, and number of measurements, but in the single
% measurement case the third dimension is collapsed so that the array
% is only 3d.
if size(S,3) > 1 && size(S,4) == 1,
xsz = [size(S,1) size(S,2) size(Di,3) size(S,3)];
% Insert singleton 3rd dimension (for number of filters) so that
% 4th dimension is number of images in input s volume
S = reshape(S, [size(S,1) size(S,2) 1 size(S,3)]);
if ~isscalar(opt.W) & ndims(opt.W) > 2,
opt.W = reshape(opt.W, [size(opt.W,1) size(opt.W,2) 1 size(opt.W,3)]);
end
else
xsz = [size(S,1) size(S,2) size(Di,3) size(S,4)];
end
IYW = 1.0 - opt.W;
% Compute filters in DFT domain
Df = fft2(Di, size(S,1), size(S,2));
% Convolve-sum and its Hermitian transpose
Dop = @(x) sum(bsxfun(@times, Df, x), 3);
DHop = @(x) bsxfun(@times, conj(Df), x);
% Compute signal in DFT domain
Sf = fft2(S);
% S convolved with all filters in DFT domain
DSf = DHop(Sf);
% Default lambda is 1/10 times the lambda value beyond which the
% solution is a zero vector
if nargin < 3 | isempty(lambda),
b = ifft2(DHop(Sf), 'symmetric');
lambda = 0.1*max(vec(abs(b)));
end
% Set up algorithm parameters and initialise variables
rho = opt.rho;
if isempty(rho), rho = 50*lambda+1; end;
if isempty(opt.RhoRsdlTarget),
if opt.StdResiduals,
opt.RhoRsdlTarget = 1;
else
opt.RhoRsdlTarget = 1 + (18.3).^(log10(lambda) + 1);
end
end
if opt.HighMemSolve,
C = bsxfun(@rdivide, Df, sum(Df.*conj(Df), 3) + rho);
else
C = [];
end
Nx = prod(xsz);
optinf = struct('itstat', [], 'opt', opt);
r = Inf;
s = Inf;
epri = 0;
edua = 0;
% Initialise main working variables
X = [];
if isempty(opt.Y0),
Y = zeros(xsz);
else
Y = opt.Y0;
end
Yprv = Y;
if isempty(opt.U0),
if isempty(opt.Y0),
U = zeros(xsz);
else
U = (lambda/rho)*sign(Y);
end
else
U = opt.U0;
end
% Main loop
k = 1;
while k <= opt.MaxMainIter && (r > epri | s > edua),
% Solve X subproblem
Xf = solvedbi_sm(Df, rho, DSf + rho*fft2(Y - U), C);
X = ifft2(Xf, 'symmetric');
% See pg. 21 of boyd-2010-distributed
if opt.RelaxParam == 1,
Xr = X;
else
Xr = opt.RelaxParam*X + (1-opt.RelaxParam)*Y;
end
% Solve Y subproblem
Y(:,:,1:(end-1),:) = shrink(Xr(:,:,1:(end-1),:) + U(:,:,1:(end-1),:), ...
(lambda/rho)*opt.L1Weight);
Y(:,:,end,:) = bsxfun(@times, IYW, Xr(:,:,end,:) + U(:,:,end,:));
if opt.NoBndryCross,
Y((end-size(D,1)+2):end,:,1:(end-1),:) = 0;
Y(:,(end-size(D,2)+2):end,1:(end-1),:) = 0;
end
% Update dual variable
U = U + Xr - Y;
% Compute data fidelity term in Fourier domain (note normalisation)
if opt.AuxVarObj,
Yf = fft2(Y); % This represents unnecessary computational cost
Jdf = sum(vec(abs(sum(bsxfun(@times,Df,Yf),3)-Sf).^2))/(2*xsz(1)*xsz(2));
Jl1 = sum(abs(vec(bsxfun(@times, opt.L1Weight, Y(:,:,1:(end-1),:)))));
else
Jdf = sum(vec(abs(sum(bsxfun(@times,Df,Xf),3)-Sf).^2))/(2*xsz(1)*xsz(2));
Jl1 = sum(abs(vec(bsxfun(@times, opt.L1Weight, X(:,:,1:(end-1),:)))));
end
Jfn = Jdf + lambda*Jl1;
nX = norm(X(:)); nY = norm(Y(:)); nU = norm(U(:));
if opt.StdResiduals,
% See pp. 19-20 of boyd-2010-distributed
r = norm(vec(X - Y));
s = norm(vec(rho*(Yprv - Y)));
epri = sqrt(Nx)*opt.AbsStopTol+max(nX,nY)*opt.RelStopTol;
edua = sqrt(Nx)*opt.AbsStopTol+rho*nU*opt.RelStopTol;
else
% See wohlberg-2015-adaptive
r = norm(vec(X - Y))/max(nX,nY);
s = norm(vec(Yprv - Y))/nU;
epri = sqrt(Nx)*opt.AbsStopTol/max(nX,nY)+opt.RelStopTol;
edua = sqrt(Nx)*opt.AbsStopTol/(rho*nU)+opt.RelStopTol;
end
% Record and display iteration details
tk = toc(tstart);
optinf.itstat = [optinf.itstat; [k Jfn Jdf Jl1 r s epri edua rho tk]];
if opt.Verbose,
if opt.AutoRho,
disp(sprintf(sfms, k, Jfn, Jdf, Jl1, r, s, rho));
else
disp(sprintf(sfms, k, Jfn, Jdf, Jl1, r, s));
end
end
% See wohlberg-2015-adaptive and pp. 20-21 of boyd-2010-distributed
if opt.AutoRho,
if k ~= 1 && mod(k, opt.AutoRhoPeriod) == 0,
if opt.AutoRhoScaling,
rhomlt = sqrt(r/(s*opt.RhoRsdlTarget));
if rhomlt < 1, rhomlt = 1/rhomlt; end
if rhomlt > opt.RhoScaling, rhomlt = opt.RhoScaling; end
else
rhomlt = opt.RhoScaling;
end
rsf = 1;
if r > opt.RhoRsdlTarget*opt.RhoRsdlRatio*s, rsf = rhomlt; end
if s > (opt.RhoRsdlRatio/opt.RhoRsdlTarget)*r, rsf = 1/rhomlt; end
rho = rsf*rho;
U = U/rsf;
if opt.HighMemSolve && rsf ~= 1,
C = bsxfun(@rdivide, Df, sum(Df.*conj(Df), 3) + rho);
end
end
end
Yprv = Y;
k = k + 1;
end
% Record run time and working variables
optinf.runtime = toc(tstart);
optinf.X = X;
optinf.Xf = Xf;
optinf.Y = Y;
optinf.U = U;
optinf.lambda = lambda;
optinf.rho = rho;
if opt.Verbose && opt.MaxMainIter > 0,
disp(char('-' * ones(1,nsep)));
end
% Remove coefficient map for impulse filter
X = X(:,:,1:(end-1), :);
return
function u = vec(v)
u = v(:);
return
function u = shrink(v, lambda)
if isscalar(lambda),
u = sign(v).*max(0, abs(v) - lambda);
else
u = sign(v).*max(0, bsxfun(@minus, abs(v), lambda));
end
return
function opt = defaultopts(opt)
if ~isfield(opt,'Verbose'),
opt.Verbose = 0;
end
if ~isfield(opt,'MaxMainIter'),
opt.MaxMainIter = 1000;
end
if ~isfield(opt,'AbsStopTol'),
opt.AbsStopTol = 0;
end
if ~isfield(opt,'RelStopTol'),
opt.RelStopTol = 1e-4;
end
if ~isfield(opt,'L1Weight'),
opt.L1Weight = 1;
end
if ~isfield(opt,'Y0'),
opt.Y0 = [];
end
if ~isfield(opt,'U0'),
opt.U0 = [];
end
if ~isfield(opt,'rho'),
opt.rho = [];
end
if ~isfield(opt,'AutoRho'),
opt.AutoRho = 1;
end
if ~isfield(opt,'AutoRhoPeriod'),
opt.AutoRhoPeriod = 1;
end
if ~isfield(opt,'RhoRsdlRatio'),
opt.RhoRsdlRatio = 1.2;
end
if ~isfield(opt,'RhoScaling'),
opt.RhoScaling = 100;
end
if ~isfield(opt,'AutoRhoScaling'),
opt.AutoRhoScaling = 1;
end
if ~isfield(opt,'RhoRsdlTarget'),
opt.RhoRsdlTarget = [];
end
if ~isfield(opt,'StdResiduals'),
opt.StdResiduals = 1;
end
if ~isfield(opt,'RelaxParam'),
opt.RelaxParam = 1.8;
end
if ~isfield(opt,'NoBndryCross'),
opt.NoBndryCross = 0;
end
if ~isfield(opt,'AuxVarObj'),
opt.AuxVarObj = 0;
end
if ~isfield(opt,'HighMemSolve'),
opt.HighMemSolve = 0;
end
if ~isfield(opt,'W'),
opt.W = 1.0;
end
return
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
cbpdnmd.m
|
.m
|
convolutional_sparse_coding-master/SparseCode/cbpdnmd.m
| 10,799 |
utf_8
|
b23bbc7e352dd855e43948e1868c0ff1
|
function [X, optinf] = cbpdnmd(D, S, lambda, opt)
% cbpdnmd -- Convolutional Basis Pursuit DeNoising (Mask Decoupling)
%
% argmin_{x_k} (1/2)||W \sum_k d_k * x_k - s||_2^2 +
% lambda \sum_k ||x_k||_1
%
% The solution is computed using an ADMM approach (see
% boyd-2010-distributed) with efficient solution of the main
% linear systems (see wohlberg-2016-efficient and
% wohlberg-2016-boundary).
%
% Usage:
% [Y, optinf] = cbpdnmd(D, S, lambda, opt)
%
% Input:
% D Dictionary filter set (3D array)
% S Input image
% lambda Regularization parameter
% opt Algorithm parameters structure
%
% Output:
% Y Dictionary coefficient map set (3D array)
% optinf Details of optimisation
%
%
% Options structure fields:
% Verbose Flag determining whether iteration status is displayed.
% Fields are iteration number, functional value,
% data fidelity term, l1 regularisation term, and
% primal and dual residuals (see Sec. 3.3 of
% boyd-2010-distributed). The value of rho is also
% displayed if options request that it is automatically
% adjusted.
% MaxMainIter Maximum main iterations
% AbsStopTol Absolute convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% RelStopTol Relative convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% L1Weight Weighting array for coefficients in l1 norm of X
% Y0 Initial value for Y
% U0 Initial value for U
% rho ADMM penalty parameter
% AutoRho Flag determining whether rho is automatically updated
% (see Sec. 3.4.1 of boyd-2010-distributed)
% AutoRhoPeriod Iteration period on which rho is updated
% RhoRsdlRatio Primal/dual residual ratio in rho update test
% RhoScaling Multiplier applied to rho when updated
% AutoRhoScaling Flag determining whether RhoScaling value is
% adaptively determined (see wohlberg-2015-adaptive). If
% enabled, RhoScaling specifies a maximum allowed
% multiplier instead of a fixed multiplier.
% RhoRsdlTarget Residual ratio targeted by auto rho update policy.
% StdResiduals Flag determining whether standard residual definitions
% (see Sec 3.3 of boyd-2010-distributed) are used instead
% of normalised residuals (see wohlberg-2015-adaptive)
% RelaxParam Relaxation parameter (see Sec. 3.4.3 of
% boyd-2010-distributed)
% NoBndryCross Flag indicating whether all solution coefficients
% corresponding to filters crossing the image boundary
% should be forced to zero.
% AuxVarObj Flag determining whether objective function is computed
% using the auxiliary (split) variable
% HighMemSolve Use more memory for a slightly faster solution
% W Synthesis spatial weighting matrix
%
%
% Author: Brendt Wohlberg <[email protected]> Modified: 2016-06-30
%
% This file is part of the SPORCO library. Details of the copyright
% and user license can be found in the 'License' file distributed with
% the library.
if nargin < 4,
opt = [];
end
checkopt(opt, defaultopts([]));
opt = defaultopts(opt);
% Set up status display for verbose operation
hstr = 'Itn Fnc DFid l1 r s ';
sfms = '%4d %9.2e %9.2e %9.2e %9.2e %9.2e';
nsep = 54;
if opt.AutoRho,
hstr = [hstr ' rho '];
sfms = [sfms ' %9.2e'];
nsep = nsep + 10;
end
if opt.Verbose && opt.MaxMainIter > 0,
disp(hstr);
disp(char('-' * ones(1,nsep)));
end
% Start timer
tstart = tic;
% Collapsing of trailing singleton dimensions greatly complicates
% handling of both SMV and MMV cases. The simplest approach would be
% if S could always be reshaped to 4d, with dimensions consisting of
% image rows, image cols, a single dimensional placeholder for number
% of filters, and number of measurements, but in the single
% measurement case the third dimension is collapsed so that the array
% is only 3d.
if size(S,3) > 1 && size(S,4) == 1,
xsz = [size(S,1) size(S,2) size(D,3) size(S,3)];
% Insert singleton 3rd dimension (for number of filters) so that
% 4th dimension is number of images in input s volume
S = reshape(S, [size(S,1) size(S,2) 1 size(S,3)]);
if ~isscalar(opt.W) & ndims(opt.W) > 2,
opt.W = reshape(opt.W, [size(opt.W,1) size(opt.W,2) 1 size(opt.W,3)]);
end
else
xsz = [size(S,1) size(S,2) size(D,3) size(S,4)];
end
K = size(S,4);
W = opt.W;
WS = bsxfun(@times, W, S);
% Compute filters in DFT domain
Df = fft2(D, size(S,1), size(S,2));
% Convolve-sum and its Hermitian transpose
Dop = @(x) sum(bsxfun(@times, Df, x), 3);
DHop = @(x) bsxfun(@times, conj(Df), x);
% Set up algorithm parameters and initialise variables
rho = opt.rho;
if isempty(rho), rho = 50*lambda+1; end;
if isempty(opt.RhoRsdlTarget),
if opt.StdResiduals,
opt.RhoRsdlTarget = 1;
else
opt.RhoRsdlTarget = 1 + (18.3).^(log10(lambda) + 1);
end
end
if opt.HighMemSolve,
C = bsxfun(@rdivide, Df, sum(Df.*conj(Df), 3) + 1.0);
else
C = [];
end
Nx = prod(xsz);
Ny = prod(xsz + [0 0 1 0]);
optinf = struct('itstat', [], 'opt', opt);
r = Inf;
s = Inf;
epri = 0;
edua = 0;
% Initialise main working variables
X = [];
if isempty(opt.Y0),
Y = zeros(xsz + [0 0 1 0]);
Y(:,:,end,:) = S;
else
Y = opt.Y0;
end
Yprv = Y;
if isempty(opt.U0),
if isempty(opt.Y0),
U = zeros(xsz + [0 0 1 0]);
else
U(:,:,1:(end-1),:) = (lambda/rho)*sign(Y(:,:,1:(end-1),:));
U(:,:,end,:) = bsxfun(@times, W, (bsxfun(@times, W, Y(:,:,end,:)) - S))/rho;
end
else
U = opt.U0;
end
% Main loop
k = 1;
while k <= opt.MaxMainIter && (r > epri | s > edua),
% Solve X subproblem
YUf = fft2(Y - U);
YU0f = YUf(:,:,1:(end-1),:);
YU1f = YUf(:,:,end,:);
Xf = solvedbi_sm(Df, 1.0, DHop(YU1f) + YU0f, C);
X = ifft2(Xf, 'symmetric');
DX = ifft2(sum(bsxfun(@times, Df, Xf), 3), 'symmetric');
% See pg. 21 of boyd-2010-distributed
AX = cat(3, X, DX);
if opt.RelaxParam ~= 1.0,
AX = opt.RelaxParam*AX + (1-opt.RelaxParam)*Y;
end
% Solve Y subproblem
Y(:,:,1:(end-1),:) = shrink(AX(:,:,1:(end-1),:) + U(:,:,1:(end-1),:), ...
(lambda/rho)*opt.L1Weight);
if opt.NoBndryCross,
Y((end-size(D,1)+2):end,:,1:(end-1),:) = 0;
Y(:,(end-size(D,2)+2):end,1:(end-1),:) = 0;
end
Y(:,:,end,:) = bsxfun(@rdivide,(WS + rho*(DX+U(:,:,end,:))),...
((W.^2) + rho));
% Update dual variable
U = U + AX - Y;
% Compute data fidelity term in Fourier domain (note normalisation)
if opt.AuxVarObj,
Jdf = sum(vec(abs(bsxfun(@times, W, Y(:,:,end,:)) - S).^2))/2;
Jl1 = sum(abs(vec(bsxfun(@times, opt.L1Weight, Y(:,:,1:(end-1),:)))));
else
Jdf = sum(vec(abs(bsxfun(@times, W, DX) - S).^2))/2;
Jl1 = sum(abs(vec(bsxfun(@times, opt.L1Weight, X))));
end
Jfn = Jdf + lambda*Jl1;
% This is computationally expensive for diagnostic information
U0 = U(:,:,1:(end-1),:);
U1 = U(:,:,end,:);
U1f = fft2(U1);
ATU0 = U0;
ATU1 = ifft2(DHop(U1f), 'symmetric');
nX = norm(X(:)); nY = norm(Y(:));
nU0 = norm(U0(:)); nU1 = norm(U1(:));
if opt.StdResiduals,
% See pp. 19-20 of boyd-2010-distributed
r = norm(vec(AX - Y));
s = rho*norm(vec(ATU0 + ATU1));
epri = sqrt(Ny)*opt.AbsStopTol+max(nX,nY)*opt.RelStopTol;
edua = sqrt(Nx)*opt.AbsStopTol+rho*max(nU0,nU1)*opt.RelStopTol;
else
% See wohlberg-2015-adaptive
r = norm(vec(AX - Y))/max(nX,nY);
s = norm(vec(ATU0 + ATU1))/max(nU0,nU1);
epri = sqrt(Ny)*opt.AbsStopTol/max(nX,nY)+opt.RelStopTol;
edua = sqrt(Nx)*opt.AbsStopTol/(rho*max(nU0,nU1))+opt.RelStopTol;
end
% Record and display iteration details
tk = toc(tstart);
optinf.itstat = [optinf.itstat; [k Jfn Jdf Jl1 r s epri edua rho tk]];
if opt.Verbose,
if opt.AutoRho,
disp(sprintf(sfms, k, Jfn, Jdf, Jl1, r, s, rho));
else
disp(sprintf(sfms, k, Jfn, Jdf, Jl1, r, s));
end
end
% See wohlberg-2015-adaptive and pp. 20-21 of boyd-2010-distributed
if opt.AutoRho,
if k ~= 1 && mod(k, opt.AutoRhoPeriod) == 0,
if opt.AutoRhoScaling,
rhomlt = sqrt(r/(s*opt.RhoRsdlTarget));
if rhomlt < 1, rhomlt = 1/rhomlt; end
if rhomlt > opt.RhoScaling, rhomlt = opt.RhoScaling; end
else
rhomlt = opt.RhoScaling;
end
rsf = 1;
if r > opt.RhoRsdlTarget*opt.RhoRsdlRatio*s, rsf = rhomlt; end
if s > (opt.RhoRsdlRatio/opt.RhoRsdlTarget)*r, rsf = 1/rhomlt; end
rho = rsf*rho;
U = U/rsf;
if opt.HighMemSolve && rsf ~= 1,
C = bsxfun(@rdivide, Df, sum(Df.*conj(Df), 3) + 1.0);
end
end
end
Yprv = Y;
k = k + 1;
end
% Record run time and working variables
optinf.runtime = toc(tstart);
optinf.X = X;
optinf.Xf = Xf;
optinf.Y = Y;
optinf.U = U;
optinf.lambda = lambda;
optinf.rho = rho;
if opt.Verbose && opt.MaxMainIter > 0,
disp(char('-' * ones(1,nsep)));
end
return
function u = vec(v)
u = v(:);
return
function u = shrink(v, lambda)
if isscalar(lambda),
u = sign(v).*max(0, abs(v) - lambda);
else
u = sign(v).*max(0, bsxfun(@minus, abs(v), lambda));
end
return
function opt = defaultopts(opt)
if ~isfield(opt,'Verbose'),
opt.Verbose = 0;
end
if ~isfield(opt,'MaxMainIter'),
opt.MaxMainIter = 1000;
end
if ~isfield(opt,'AbsStopTol'),
opt.AbsStopTol = 0;
end
if ~isfield(opt,'RelStopTol'),
opt.RelStopTol = 1e-4;
end
if ~isfield(opt,'L1Weight'),
opt.L1Weight = 1;
end
if ~isfield(opt,'Y0'),
opt.Y0 = [];
end
if ~isfield(opt,'U0'),
opt.U0 = [];
end
if ~isfield(opt,'rho'),
opt.rho = [];
end
if ~isfield(opt,'AutoRho'),
opt.AutoRho = 1;
end
if ~isfield(opt,'AutoRhoPeriod'),
opt.AutoRhoPeriod = 1;
end
if ~isfield(opt,'RhoRsdlRatio'),
opt.RhoRsdlRatio = 1.2;
end
if ~isfield(opt,'RhoScaling'),
opt.RhoScaling = 100;
end
if ~isfield(opt,'AutoRhoScaling'),
opt.AutoRhoScaling = 1;
end
if ~isfield(opt,'RhoRsdlTarget'),
opt.RhoRsdlTarget = [];
end
if ~isfield(opt,'StdResiduals'),
opt.StdResiduals = 1;
end
if ~isfield(opt,'RelaxParam'),
opt.RelaxParam = 1.8;
end
if ~isfield(opt,'NoBndryCross'),
opt.NoBndryCross = 0;
end
if ~isfield(opt,'AuxVarObj'),
opt.AuxVarObj = 0;
end
if ~isfield(opt,'HighMemSolve'),
opt.HighMemSolve = 0;
end
if ~isfield(opt,'W'),
opt.W = 1.0;
end
return
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
bpdnjnt.m
|
.m
|
convolutional_sparse_coding-master/SparseCode/bpdnjnt.m
| 8,880 |
utf_8
|
c1bc97667469900f3e6bd14cb3ac45fe
|
function [Y, optinf] = bpdnjnt(D, S, lambda, mu, opt)
% bpdnjnt -- Basis Pursuit DeNoising with l2,1 joint sparsity
%
% argmin_X (1/2)||D*X - s||_F^2 + lambda*||X||_1 +
% mu*||X||_{2,1}
%
% The solution is computed using the ADMM approach (see
% boyd-2010-distributed for details).
%
% Usage:
% [Y, optinf] = bpdnjnt(D, S, lambda, mu, opt)
%
% Input:
% D Dictionary matrix
% S Signal vector (or matrix)
% lambda Regularization parameter
% mu l2,1 regularization parameter
% opt Options/algorithm parameters structure (see below)
%
% Output:
% Y Dictionary coefficient vector (or matrix)
% optinf Details of optimisation
%
%
% Options structure fields:
% Verbose Flag determining whether iteration status is displayed.
% Fields are iteration number, functional value,
% data fidelity term, l1 regularisation term, l2,1
% regularisation term, and primal and dual residuals
% (see Sec. 3.3 of boyd-2010-distributed). The value of
% rho is also displayed if options request that it is
% automatically adjusted.
% MaxMainIter Maximum main iterations
% AbsStopTol Absolute convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% RelStopTol Relative convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% L1Weight Weighting array for coefficients in l1 norm of X
% Y0 Initial value for Y
% U0 Initial value for U
% rho ADMM penalty parameter
% AutoRho Flag determining whether rho is automatically updated
% (see Sec. 3.4.1 of boyd-2010-distributed)
% AutoRhoPeriod Iteration period on which rho is updated
% RhoRsdlRatio Primal/dual residual ratio in rho update test
% RhoScaling Multiplier applied to rho when updated
% AutoRhoScaling Flag determining whether RhoScaling value is
% adaptively determined (see wohlberg-2015-adaptive). If
% enabled, RhoScaling specifies a maximum allowed
% multiplier instead of a fixed multiplier.
% RhoRsdlTarget Residual ratio targeted by auto rho update policy.
% StdResiduals Flag determining whether standard residual definitions
% (see Sec 3.3 of boyd-2010-distributed) are used instead
% of normalised residuals (see wohlberg-2015-adaptive)
% RelaxParam Relaxation parameter (see Sec. 3.4.3 of
% boyd-2010-distributed)
% AuxVarObj Flag determining whether objective function is computed
% using the auxiliary (split) variable
%
%
% Author: Brendt Wohlberg <[email protected]> Modified: 2015-07-10
%
% This file is part of the SPORCO library. Details of the copyright
% and user license can be found in the 'Copyright' and 'License' files
% distributed with the library.
if nargin < 5,
opt = [];
end
checkopt(opt, defaultopts([]));
opt = defaultopts(opt);
% Set up status display for verbose operation
hstr = 'Itn Fnc DFid l1 l2,1 r s ';
sfms = '%4d %9.2e %9.2e %9.2e %9.2e %9.2e %9.2e';
nsep = 64;
if opt.AutoRho,
hstr = [hstr ' rho '];
sfms = [sfms ' %9.2e'];
nsep = nsep + 10;
end
if opt.Verbose && opt.MaxMainIter > 0,
disp(hstr);
disp(char('-' * ones(1,nsep)));
end
% Start timer
tstart = tic;
% Set up algorithm parameters and initialise variables
rho = opt.rho;
if isempty(rho), rho = 50*lambda+1; end;
[Nr, Nc] = size(D);
Nm = size(S,2);
Nx = Nc*Nm;
DTS = D'*S;
[luL, luU] = factorise(D, rho);
optinf = struct('itstat', [], 'opt', opt);
r = Inf;
s = Inf;
epri = 0;
edua = 0;
% Initialise main working variables
X = [];
if isempty(opt.Y0),
Y = zeros(Nc,Nm);
else
Y = opt.Y0;
end
Yprv = Y;
if isempty(opt.U0),
if isempty(opt.Y0),
U = zeros(Nc,Nm);
else
U = (lambda/rho)*sign(Y);
end
else
U = opt.U0;
end
% Main loop
k = 1;
while k <= opt.MaxMainIter && (r > epri | s > edua),
% Solve X subproblem
X = linsolve(D, rho, luL, luU, DTS + rho*(Y - U));
% See pg. 21 of boyd-2010-distributed
if opt.RelaxParam == 1,
Xr = X;
else
Xr = opt.RelaxParam*X + (1-opt.RelaxParam)*Y;
end
% Solve Y subproblem
Y = shrink21(Xr + U, lambda/rho, mu/rho, opt.L1Weight);
% Update dual variable
U = U + Xr - Y;
% Objective function and convergence measures
if opt.AuxVarObj,
Jdf = sum(vec(abs(D*Y - S).^2))/2;
Jl1 = sum(abs(vec(bsxfun(@times, opt.L1Weight, Y))));
Jl21 = sum(sqrt(sum(Y.^2,2)));
else
Jdf = sum(vec(abs(D*X - S).^2))/2;
Jl1 = sum(abs(vec(bsxfun(@times, opt.L1Weight, X))));
Jl21 = sum(sqrt(sum(X.^2,2)));
end
Jfn = Jdf + lambda*Jl1 + mu*Jl21;
nX = norm(X(:)); nY = norm(Y(:)); nU = norm(U(:));
if opt.StdResiduals,
% See pp. 19-20 of boyd-2010-distributed
r = norm(vec(X - Y));
s = norm(vec(rho*(Yprv - Y)));
epri = sqrt(Nx)*opt.AbsStopTol+max(nX,nY)*opt.RelStopTol;
edua = sqrt(Nx)*opt.AbsStopTol+rho*nU*opt.RelStopTol;
else
% See wohlberg-2015-adaptive
r = norm(vec(X - Y))/max(nX,nY);
s = norm(vec(Yprv - Y))/nU;
epri = sqrt(Nx)*opt.AbsStopTol/max(nX,nY)+opt.RelStopTol;
edua = sqrt(Nx)*opt.AbsStopTol/(rho*nU)+opt.RelStopTol;
end
% Record and display iteration details
tk = toc(tstart);
optinf.itstat = [optinf.itstat;[k Jfn Jdf Jl1 Jl21 r s epri edua rho tk]];
if opt.Verbose,
if opt.AutoRho,
disp(sprintf(sfms, k, Jfn, Jdf, Jl1, Jl21, r, s, rho));
else
disp(sprintf(sfms, k, Jfn, Jdf, Jl1, Jl21, r, s));
end
end
% See wohlberg-2015-adaptive and pp. 20-21 of boyd-2010-distributed
if opt.AutoRho,
if k ~= 1 && mod(k, opt.AutoRhoPeriod) == 0,
if opt.AutoRhoScaling,
rhomlt = sqrt(r/(s*opt.RhoRsdlTarget));
if rhomlt < 1, rhomlt = 1/rhomlt; end
if rhomlt > opt.RhoScaling, rhomlt = opt.RhoScaling; end
else
rhomlt = opt.RhoScaling;
end
rsf = 1;
if r > opt.RhoRsdlTarget*opt.RhoRsdlRatio*s, rsf = rhomlt; end
if s > (opt.RhoRsdlRatio/opt.RhoRsdlTarget)*r, rsf = 1/rhomlt; end
rho = rsf*rho;
U = U/rsf;
if rsf ~= 1,
[luL, luU] = factorise(D, rho);
end
end
end
Yprv = Y;
k = k + 1;
end
% Record run time and working variables
optinf.runtime = toc(tstart);
optinf.X = X;
optinf.Y = Y;
optinf.U = U;
optinf.lambda = lambda;
optinf.rho = rho;
% End status display for verbose operation
if opt.Verbose && opt.MaxMainIter > 0,
disp(char('-' * ones(1,nsep)));
end
return
function u = vec(v)
u = v(:);
return
function u = shrink1_scalars(v, a)
u = sign(v).*max(0, abs(v) - a);
return
function U = shrink2_row_vectors(V, a)
n2v = sqrt(sum(V.^2,2));
n2v(n2v == 0) = 1;
U = bsxfun(@times, V, shrink1_scalars(n2v, a)./n2v);
return
function U = shrink21(V, a, b, W1)
if nargin < 4 || isempty(W1),
W1 = 1;
end
% See wohlberg-2012-local and chartrand-2013-nonconvex
U = shrink2_row_vectors(shrink1_scalars(V, W1 .* a), b);
return
function [L,U] = factorise(A, c)
[N,M] = size(A);
% If N < M it is cheaper to factorise A*A' + cI and then use the
% matrix inversion lemma to compute the inverse of A'*A + cI
if N >= M,
[L,U] = lu(A'*A + c*eye(M,M));
else
[L,U] = lu(A*A' + c*eye(N,N));
end
return
function x = linsolve(A, c, L, U, b)
[N,M] = size(A);
if N >= M,
x = U \ (L \ b);
else
x = (b - A'*(U \ (L \ (A*b))))/c;
end
return
function opt = defaultopts(opt)
if ~isfield(opt,'Verbose'),
opt.Verbose = 0;
end
if ~isfield(opt,'MaxMainIter'),
opt.MaxMainIter = 1000;
end
if ~isfield(opt,'AbsStopTol'),
opt.AbsStopTol = 0;
end
if ~isfield(opt,'RelStopTol'),
opt.RelStopTol = 1e-4;
end
if ~isfield(opt,'L1Weight'),
opt.L1Weight = 1;
end
if ~isfield(opt,'Y0'),
opt.Y0 = [];
end
if ~isfield(opt,'U0'),
opt.U0 = [];
end
if ~isfield(opt,'rho'),
opt.rho = [];
end
if ~isfield(opt,'AutoRho'),
opt.AutoRho = 1;
end
if ~isfield(opt,'AutoRhoPeriod'),
opt.AutoRhoPeriod = 10;
end
if ~isfield(opt,'RhoRsdlRatio'),
opt.RhoRsdlRatio = 1.2;
end
if ~isfield(opt,'RhoScaling'),
opt.RhoScaling = 100;
end
if ~isfield(opt,'AutoRhoScaling'),
opt.AutoRhoScaling = 1;
end
if ~isfield(opt,'RhoRsdlTarget'),
opt.RhoRsdlTarget = 1;
end
if ~isfield(opt,'StdResiduals'),
opt.StdResiduals = 0;
end
if ~isfield(opt,'RelaxParam'),
opt.RelaxParam = 1.8;
end
if ~isfield(opt,'AuxVarObj'),
opt.AuxVarObj = 1;
end
return
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
celnet.m
|
.m
|
convolutional_sparse_coding-master/SparseCode/celnet.m
| 11,532 |
utf_8
|
bc859bf5ebdd67452a48f16c23415b26
|
function [Y, optinf] = celnet(D, S, lambda, mu, opt)
% celnet -- Convolutional Elastic Net
%
% argmin_{x_m} (1/2)||\sum_m d_m * x_m - s||_2^2 +
% lambda \sum_m ||x_m||_1 + (mu/2) \sum_m ||x_m||_2^2
%
% The solution is computed using an ADMM approach (see
% boyd-2010-distributed) with efficient solution of the main
% linear systems (see wohlberg-2014-efficient).
%
% Usage:
% [Y, optinf] = celnet(D, S, lambda, mu, opt)
%
% Input:
% D Dictionary filter set (3D array)
% s Input image
% lambda Regularization parameter (l1)
% mu Regularization parameter (l2)
% opt Algorithm parameters structure
%
% Output:
% Y Dictionary coefficient map set (3D array)
% optinf Details of optimisation
%
%
% Options structure fields:
% Verbose Flag determining whether iteration status is displayed.
% Fields are iteration number, functional value,
% data fidelity term, l1 regularisation term, l2
% regularisation term, and primal and dual residuals
% (see Sec. 3.3 of boyd-2010-distributed). The value of
% rho is also displayed if options request that it is
% automatically adjusted.
% MaxMainIter Maximum main iterations
% AbsStopTol Absolute convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% RelStopTol Relative convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% L1Weight Weighting array for coefficients in l1 norm of X.
% Array should have the same dimensions as X, but the
% first two dimensions may be of unit size, corresponding
% to a weighting that varies with filter index but is
% spatially constant.
% L2Weight Weighting array for l2 norm of X. Array should have
% dimensions corresponding to the non-spatial dimensions
% of X since spatial weighting is not possible (i.e.
% weighting varies only with filter and sample index).
% Y0 Initial value for Y
% U0 Initial value for U
% rho ADMM penalty parameter
% AutoRho Flag determining whether rho is automatically updated
% (see Sec. 3.4.1 of boyd-2010-distributed)
% AutoRhoPeriod Iteration period on which rho is updated
% RhoRsdlRatio Primal/dual residual ratio in rho update test
% RhoScaling Multiplier applied to rho when updated
% AutoRhoScaling Flag determining whether RhoScaling value is
% adaptively determined (see wohlberg-2015-adaptive). If
% enabled, RhoScaling specifies a maximum allowed
% multiplier instead of a fixed multiplier.
% RhoRsdlTarget Residual ratio targeted by auto rho update policy.
% StdResiduals Flag determining whether standard residual definitions
% (see Sec 3.3 of boyd-2010-distributed) are used instead
% of normalised residuals (see wohlberg-2015-adaptive)
% RelaxParam Relaxation parameter (see Sec. 3.4.3 of
% boyd-2010-distributed)
% NoBndryCross Flag indicating whether all solution coefficients
% corresponding to filters crossing the image boundary
% should be forced to zero.
% AuxVarObj Flag determining whether objective function is computed
% using the auxiliary (split) variable
% HighMemSolve Use more memory for a slightly faster solution
%
%
% Author: Brendt Wohlberg <[email protected]> Modified: 2015-08-13
%
% This file is part of the SPORCO library. Details of the copyright
% and user license can be found in the 'Copyright' and 'License' files
% distributed with the library.
if nargin < 5,
opt = [];
end
if nargin < 4,
mu = 0;
end
checkopt(opt, defaultopts([]));
opt = defaultopts(opt);
% Set up status display for verbose operation
hstr = 'Itn Fnc DFid l1 l2 r s ';
sfms = '%4d %9.2e %9.2e %9.2e %9.2e %9.2e %9.2e';
nsep = 64;
if opt.AutoRho,
hstr = [hstr ' rho '];
sfms = [sfms ' %9.2e'];
nsep = nsep + 10;
end
if opt.Verbose && opt.MaxMainIter > 0,
disp(hstr);
disp(char('-' * ones(1,nsep)));
end
% Start timer
tstart = tic;
% Collapsing of trailing singleton dimensions greatly complicates
% handling of both SMV and MMV cases. The simplest approach would be
% if S could always be reshaped to 4d, with dimensions consisting of
% image rows, image cols, a single dimensional placeholder for number
% of filters, and number of measurements, but in the single
% measurement case the third dimension is collapsed so that the array
% is only 3d.
if size(S,3) > 1,
xsz = [size(S,1) size(S,2) size(D,3) size(S,3)];
hrm = [1 1 1 size(S,3)];
% Insert singleton 3rd dimension (for number of filters) so that
% 4th dimension is number of images in input s volume
S = reshape(S, [size(S,1) size(S,2) 1 size(S,3)]);
else
xsz = [size(S,1) size(S,2) size(D,3) 1];
hrm = 1;
end
xrm = [1 1 size(D,3)];
% Compute filters in DFT domain
Df = fft2(D, size(S,1), size(S,2));
% Convolve-sum and its Hermitian transpose
Dop = @(x) sum(bsxfun(@times, Df, x), 3);
DHop = @(x) bsxfun(@times, conj(Df), x);
% Compute signal in DFT domain
Sf = fft2(S);
% S convolved with all filters in DFT domain
DSf = DHop(Sf);
% Set up l2 weight array
if isscalar(opt.L2Weight),
wl2 = opt.L2Weight;
else
wl2 = reshape(opt.L2Weight, [1 1 size(opt.L2Weight,1) size(opt.L2Weight,2)]);
end
% Default lambda is 1/10 times the lambda value beyond which the
% solution is a zero vector
if nargin < 3 | isempty(lambda),
b = ifft2(DHop(Sf), 'symmetric');
lambda = 0.1*max(vec(abs(b)));
end
% Set up algorithm parameters and initialise variables
rho = opt.rho;
if isempty(rho), rho = 50*lambda+1; end;
mwr = mu*wl2 + rho;
if isempty(opt.RhoRsdlTarget),
if opt.StdResiduals,
opt.RhoRsdlTarget = 1;
else
opt.RhoRsdlTarget = 1 + (18.3).^(log10(lambda) + 1);
end
end
if opt.HighMemSolve,
C = compute_dbd_sm_C(Df, mwr);
else
C = [];
end
Nx = prod(xsz);
optinf = struct('itstat', [], 'opt', opt);
r = Inf;
s = Inf;
epri = 0;
edua = 0;
% Initialise main working variables
X = [];
if isempty(opt.Y0),
Y = zeros(xsz);
else
Y = opt.Y0;
end
Yprv = Y;
if isempty(opt.U0),
if isempty(opt.Y0),
U = zeros(xsz);
else
U = (lambda/rho)*sign(Y);
end
else
U = opt.U0;
end
% Main loop
k = 1;
while k <= opt.MaxMainIter && (r > epri | s > edua),
% Solve X subproblem
Xf = solvedbd_sm(Df, mwr, DSf + rho*fft2(Y - U), C);
X = ifft2(Xf, 'symmetric');
% See pg. 21 of boyd-2010-distributed
if opt.RelaxParam == 1,
Xr = X;
else
Xr = opt.RelaxParam*X + (1-opt.RelaxParam)*Y;
end
% Solve Y subproblem
Y = shrink(Xr + U, (lambda/rho)*opt.L1Weight);
if opt.NoBndryCross,
Y((end-size(D,1)+2):end,:,:,:) = 0;
Y(:,(end-size(D,1)+2):end,:,:) = 0;
end
% Update dual variable
U = U + Xr - Y;
% Compute functional value
if opt.AuxVarObj,
Yf = fft2(Y); % This represents unnecessary computational cost
% Compute data fidelity term in Fourier domain (note normalisation)
Jdf = sum(vec(abs(sum(bsxfun(@times,Df,Yf),3)-Sf).^2))/(2*xsz(1)*xsz(2));
Jl1 = sum(abs(vec(bsxfun(@times, opt.L1Weight, Y))));
Jl2 = sum(vec(wl2.*sum(sum(Y.^2, 1),2)))/2;
else
% Compute data fidelity term in Fourier domain (note normalisation)
Jdf = sum(vec(abs(sum(bsxfun(@times,Df,Xf),3)-Sf).^2))/(2*xsz(1)*xsz(2));
Jl1 = sum(abs(vec(bsxfun(@times, opt.L1Weight, X))));
Jl2 = sum(vec(wl2.*sum(sum(X.^2, 1),2)))/2;
end
Jfn = Jdf + lambda*Jl1 + mu*Jl2;
nX = norm(X(:)); nY = norm(Y(:)); nU = norm(U(:));
if opt.StdResiduals,
% See pp. 19-20 of boyd-2010-distributed
r = norm(vec(X - Y));
s = norm(vec(rho*(Yprv - Y)));
epri = sqrt(Nx)*opt.AbsStopTol+max(nX,nY)*opt.RelStopTol;
edua = sqrt(Nx)*opt.AbsStopTol+rho*nU*opt.RelStopTol;
else
% See wohlberg-2015-adaptive
r = norm(vec(X - Y))/max(nX,nY);
s = norm(vec(Yprv - Y))/nU;
epri = sqrt(Nx)*opt.AbsStopTol/max(nX,nY)+opt.RelStopTol;
edua = sqrt(Nx)*opt.AbsStopTol/(rho*nU)+opt.RelStopTol;
end
% Record and display iteration details
tk = toc(tstart);
optinf.itstat = [optinf.itstat; [k Jfn Jdf Jl1 Jl2 r s epri edua rho tk]];
if opt.Verbose,
if opt.AutoRho,
disp(sprintf(sfms, k, Jfn, Jdf, Jl1, Jl2, r, s, rho));
else
disp(sprintf(sfms, k, Jfn, Jdf, Jl1, Jl2, r, s));
end
end
% See wohlberg-2015-adaptive and pp. 20-21 of boyd-2010-distributed
if opt.AutoRho,
if k ~= 1 && mod(k, opt.AutoRhoPeriod) == 0,
if opt.AutoRhoScaling,
rhomlt = sqrt(r/(s*opt.RhoRsdlTarget));
if rhomlt < 1, rhomlt = 1/rhomlt; end
if rhomlt > opt.RhoScaling, rhomlt = opt.RhoScaling; end
else
rhomlt = opt.RhoScaling;
end
rsf = 1;
if r > opt.RhoRsdlTarget*opt.RhoRsdlRatio*s, rsf = rhomlt; end
if s > (opt.RhoRsdlRatio/opt.RhoRsdlTarget)*r, rsf = 1/rhomlt; end
rho = rsf*rho;
U = U/rsf;
if rsf ~= 1,
mwr = mu*wl2 + rho;
if opt.HighMemSolve,
C = compute_dbd_sm_C(Df, mwr);
end
end
end
end
Yprv = Y;
k = k + 1;
end
% Record run time and working variables
optinf.runtime = toc(tstart);
optinf.X = X;
optinf.Xf = Xf;
optinf.Y = Y;
optinf.U = U;
optinf.lambda = lambda;
optinf.mu = mu;
optinf.rho = rho;
if opt.Verbose && opt.MaxMainIter > 0,
disp(char('-' * ones(1,nsep)));
end
return
function u = vec(v)
u = v(:);
return
function u = shrink(v, lambda)
if isscalar(lambda),
u = sign(v).*max(0, abs(v) - lambda);
else
u = sign(v).*max(0, bsxfun(@minus, abs(v), lambda));
end
return
function C = compute_dbd_sm_C(Df, mwr)
cn = bsxfun(@rdivide, Df, mwr);
cd = sum(bsxfun(@times, Df, bsxfun(@rdivide, conj(Df), mwr)), 3) + 1.0;
C = bsxfun(@rdivide, cn, cd);
clear cn cd;
return
function opt = defaultopts(opt)
if ~isfield(opt,'Verbose'),
opt.Verbose = 0;
end
if ~isfield(opt,'MaxMainIter'),
opt.MaxMainIter = 1000;
end
if ~isfield(opt,'AbsStopTol'),
opt.AbsStopTol = 0;
end
if ~isfield(opt,'RelStopTol'),
opt.RelStopTol = 1e-4;
end
if ~isfield(opt,'L1Weight'),
opt.L1Weight = 1;
end
if ~isfield(opt,'L2Weight'),
opt.L2Weight = 1;
end
if ~isfield(opt,'Y0'),
opt.Y0 = [];
end
if ~isfield(opt,'U0'),
opt.U0 = [];
end
if ~isfield(opt,'rho'),
opt.rho = [];
end
if ~isfield(opt,'AutoRho'),
opt.AutoRho = 1;
end
if ~isfield(opt,'AutoRhoPeriod'),
opt.AutoRhoPeriod = 1;
end
if ~isfield(opt,'RhoRsdlRatio'),
opt.RhoRsdlRatio = 1.2;
end
if ~isfield(opt,'RhoScaling'),
opt.RhoScaling = 100;
end
if ~isfield(opt,'AutoRhoScaling'),
opt.AutoRhoScaling = 1;
end
if ~isfield(opt,'RhoRsdlTarget'),
opt.RhoRsdlTarget = [];
end
if ~isfield(opt,'StdResiduals'),
opt.StdResiduals = 0;
end
if ~isfield(opt,'RelaxParam'),
opt.RelaxParam = 1.8;
end
if ~isfield(opt,'NoBndryCross'),
opt.NoBndryCross = 0;
end
if ~isfield(opt,'AuxVarObj'),
opt.AuxVarObj = 0;
end
if ~isfield(opt,'HighMemSolve'),
opt.HighMemSolve = 0;
end
return
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
cbpdn.m
|
.m
|
convolutional_sparse_coding-master/SparseCode/cbpdn.m
| 10,413 |
utf_8
|
27738234c72ea3eb346577080e7e8640
|
function [Y, optinf] = cbpdn(D, S, lambda, opt)
% cbpdn -- Convolutional Basis Pursuit DeNoising
%
% argmin_{x_m} (1/2)||\sum_m d_m * x_m - s||_2^2 +
% lambda \sum_m ||x_m||_1
%
% The solution is computed using an ADMM approach (see
% boyd-2010-distributed) with efficient solution of the main
% linear systems (see wohlberg-2014-efficient).
%
% Usage:
% [Y, optinf] = cbpdn(D, S, lambda, opt);
%
% Input:
% D Dictionary filter set (3D array)
% S Input image
% lambda Regularization parameter
% opt Algorithm parameters structure
%
% Output:
% Y Dictionary coefficient map set (3D array)
% optinf Details of optimisation
%
%
% Options structure fields:
% Verbose Flag determining whether iteration status is displayed.
% Fields are iteration number, functional value,
% data fidelity term, l1 regularisation term, and
% primal and dual residuals (see Sec. 3.3 of
% boyd-2010-distributed). The value of rho is also
% displayed if options request that it is automatically
% adjusted.
% MaxMainIter Maximum main iterations
% AbsStopTol Absolute convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% RelStopTol Relative convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% L1Weight Weighting array for coefficients in l1 norm of X
% Y0 Initial value for Y
% U0 Initial value for U
% rho ADMM penalty parameter
% AutoRho Flag determining whether rho is automatically updated
% (see Sec. 3.4.1 of boyd-2010-distributed)
% AutoRhoPeriod Iteration period on which rho is updated
% RhoRsdlRatio Primal/dual residual ratio in rho update test
% RhoScaling Multiplier applied to rho when updated
% AutoRhoScaling Flag determining whether RhoScaling value is
% adaptively determined (see wohlberg-2015-adaptive). If
% enabled, RhoScaling specifies a maximum allowed
% multiplier instead of a fixed multiplier.
% RhoRsdlTarget Residual ratio targeted by auto rho update policy.
% StdResiduals Flag determining whether standard residual definitions
% (see Sec 3.3 of boyd-2010-distributed) are used instead
% of normalised residuals (see wohlberg-2015-adaptive)
% RelaxParam Relaxation parameter (see Sec. 3.4.3 of
% boyd-2010-distributed)
% NonNegCoef Flag indicating whether solution should be forced to
% be non-negative
% NoBndryCross Flag indicating whether all solution coefficients
% corresponding to filters crossing the image boundary
% should be forced to zero.
% AuxVarObj Flag determining whether objective function is computed
% using the auxiliary (split) variable
% HighMemSolve Use more memory for a slightly faster solution
%
%
% Author: Brendt Wohlberg <[email protected]> Modified: 2015-07-30
%
% This file is part of the SPORCO library. Details of the copyright
% and user license can be found in the 'Copyright' and 'License' files
% distributed with the library.
if nargin < 4,
opt = [];
end
checkopt(opt, defaultopts([]));
opt = defaultopts(opt);
% Set up status display for verbose operation
hstr = 'Itn Fnc DFid l1 r s ';
sfms = '%4d %9.2e %9.2e %9.2e %9.2e %9.2e';
nsep = 54;
if opt.AutoRho,
hstr = [hstr ' rho '];
sfms = [sfms ' %9.2e'];
nsep = nsep + 10;
end
if opt.Verbose && opt.MaxMainIter > 0,
disp(hstr);
disp(char('-' * ones(1,nsep)));
end
% Collapsing of trailing singleton dimensions greatly complicates
% handling of both SMV and MMV cases. The simplest approach would be
% if S could always be reshaped to 4d, with dimensions consisting of
% image rows, image cols, a single dimensional placeholder for number
% of filters, and number of measurements, but in the single
% measurement case the third dimension is collapsed so that the array
% is only 3d.
if size(S,3) > 1 && size(S,4) == 1,
xsz = [size(S,1) size(S,2) size(D,3) size(S,3)];
hrm = [1 1 1 size(S,3)];
% Insert singleton 3rd dimension (for number of filters) so that
% 4th dimension is number of images in input s volume
S = reshape(S, [size(S,1) size(S,2) 1 size(S,3)]);
else
xsz = [size(S,1) size(S,2) size(D,3) size(S,4)];
hrm = 1;
end
xrm = [1 1 size(D,3)];
% Start timer
tstart = tic;
% Compute filters in DFT domain
Df = fft2(D, size(S,1), size(S,2));
% Convolve-sum and its Hermitian transpose
Dop = @(x) sum(bsxfun(@times, Df, x), 3);
DHop = @(x) bsxfun(@times, conj(Df), x);
% Compute signal in DFT domain
Sf = fft2(S);
% S convolved with all filters in DFT domain
DSf = DHop(Sf);
% Default lambda is 1/10 times the lambda value beyond which the
% solution is a zero vector
if nargin < 3 | isempty(lambda),
b = ifft2(DHop(Sf), 'symmetric');
lambda = 0.1*max(vec(abs(b)));
end
% Set up algorithm parameters and initialise variables
rho = opt.rho;
if isempty(rho), rho = 50*lambda+1; end;
if isempty(opt.RhoRsdlTarget),
if opt.StdResiduals,
opt.RhoRsdlTarget = 1;
else
opt.RhoRsdlTarget = 1 + (18.3).^(log10(lambda) + 1);
end
end
if opt.HighMemSolve,
C = bsxfun(@rdivide, Df, sum(Df.*conj(Df), 3) + rho);
else
C = [];
end
Nx = prod(xsz);
optinf = struct('itstat', [], 'opt', opt);
r = Inf;
s = Inf;
epri = 0;
edua = 0;
% Initialise main working variables
X = [];
if isempty(opt.Y0),
Y = zeros(xsz);
else
Y = opt.Y0;
end
Yprv = Y;
if isempty(opt.U0),
if isempty(opt.Y0),
U = zeros(xsz);
else
U = (lambda/rho)*sign(Y);
end
else
U = opt.U0;
end
% Main loop
k = 1;
while k <= opt.MaxMainIter && (r > epri | s > edua),
% Solve X subproblem
Xf = solvedbi_sm(Df, rho, DSf + rho*fft2(Y - U), C);
X = ifft2(Xf, 'symmetric');
% See pg. 21 of boyd-2010-distributed
if opt.RelaxParam == 1,
Xr = X;
else
Xr = opt.RelaxParam*X + (1-opt.RelaxParam)*Y;
end
% Solve Y subproblem
Y = shrink(Xr + U, (lambda/rho)*opt.L1Weight);
if opt.NonNegCoef,
Y(Y < 0) = 0;
end
if opt.NoBndryCross,
Y((end-size(D,1)+2):end,:,:,:) = 0;
Y(:,(end-size(D,1)+2):end,:,:) = 0;
end
% Update dual variable
U = U + Xr - Y;
% Compute data fidelity term in Fourier domain (note normalisation)
if opt.AuxVarObj,
Yf = fft2(Y); % This represents unnecessary computational cost
Jdf = sum(vec(abs(sum(bsxfun(@times,Df,Yf),3)-Sf).^2))/(2*xsz(1)*xsz(2));
Jl1 = sum(abs(vec(bsxfun(@times, opt.L1Weight, Y))));
else
Jdf = sum(vec(abs(sum(bsxfun(@times,Df,Xf),3)-Sf).^2))/(2*xsz(1)*xsz(2));
Jl1 = sum(abs(vec(bsxfun(@times, opt.L1Weight, X))));
end
Jfn = Jdf + lambda*Jl1;
nX = norm(X(:)); nY = norm(Y(:)); nU = norm(U(:));
if opt.StdResiduals,
% See pp. 19-20 of boyd-2010-distributed
r = norm(vec(X - Y));
s = norm(vec(rho*(Yprv - Y)));
epri = sqrt(Nx)*opt.AbsStopTol+max(nX,nY)*opt.RelStopTol;
edua = sqrt(Nx)*opt.AbsStopTol+rho*nU*opt.RelStopTol;
else
% See wohlberg-2015-adaptive
r = norm(vec(X - Y))/max(nX,nY);
s = norm(vec(Yprv - Y))/nU;
epri = sqrt(Nx)*opt.AbsStopTol/max(nX,nY)+opt.RelStopTol;
edua = sqrt(Nx)*opt.AbsStopTol/(rho*nU)+opt.RelStopTol;
end
% Record and display iteration details
tk = toc(tstart);
optinf.itstat = [optinf.itstat; [k Jfn Jdf Jl1 r s epri edua rho tk]];
if opt.Verbose,
if opt.AutoRho,
disp(sprintf(sfms, k, Jfn, Jdf, Jl1, r, s, rho));
else
disp(sprintf(sfms, k, Jfn, Jdf, Jl1, r, s));
end
end
% See wohlberg-2015-adaptive and pp. 20-21 of boyd-2010-distributed
if opt.AutoRho,
if k ~= 1 && mod(k, opt.AutoRhoPeriod) == 0,
if opt.AutoRhoScaling,
rhomlt = sqrt(r/(s*opt.RhoRsdlTarget));
if rhomlt < 1, rhomlt = 1/rhomlt; end
if rhomlt > opt.RhoScaling, rhomlt = opt.RhoScaling; end
else
rhomlt = opt.RhoScaling;
end
rsf = 1;
if r > opt.RhoRsdlTarget*opt.RhoRsdlRatio*s, rsf = rhomlt; end
if s > (opt.RhoRsdlRatio/opt.RhoRsdlTarget)*r, rsf = 1/rhomlt; end
rho = rsf*rho;
U = U/rsf;
if opt.HighMemSolve && rsf ~= 1,
C = bsxfun(@rdivide, Df, sum(Df.*conj(Df), 3) + rho);
end
end
end
Yprv = Y;
k = k + 1;
end
% Record run time and working variables
optinf.runtime = toc(tstart);
optinf.X = X;
optinf.Xf = Xf;
optinf.Y = Y;
optinf.U = U;
optinf.lambda = lambda;
optinf.rho = rho;
% End status display for verbose operation
if opt.Verbose && opt.MaxMainIter > 0,
disp(char('-' * ones(1,nsep)));
end
return
function u = vec(v)
u = v(:);
return
function u = shrink(v, lambda)
if isscalar(lambda),
u = sign(v).*max(0, abs(v) - lambda);
else
u = sign(v).*max(0, bsxfun(@minus, abs(v), lambda));
end
return
function opt = defaultopts(opt)
if ~isfield(opt,'Verbose'),
opt.Verbose = 0;
end
if ~isfield(opt,'MaxMainIter'),
opt.MaxMainIter = 1000;
end
if ~isfield(opt,'AbsStopTol'),
opt.AbsStopTol = 0;
end
if ~isfield(opt,'RelStopTol'),
opt.RelStopTol = 1e-4;
end
if ~isfield(opt,'L1Weight'),
opt.L1Weight = 1;
end
if ~isfield(opt,'Y0'),
opt.Y0 = [];
end
if ~isfield(opt,'U0'),
opt.U0 = [];
end
if ~isfield(opt,'rho'),
opt.rho = [];
end
if ~isfield(opt,'AutoRho'),
opt.AutoRho = 1;
end
if ~isfield(opt,'AutoRhoPeriod'),
opt.AutoRhoPeriod = 1;
end
if ~isfield(opt,'RhoRsdlRatio'),
opt.RhoRsdlRatio = 1.2;
end
if ~isfield(opt,'RhoScaling'),
opt.RhoScaling = 100;
end
if ~isfield(opt,'AutoRhoScaling'),
opt.AutoRhoScaling = 1;
end
if ~isfield(opt,'RhoRsdlTarget'),
opt.RhoRsdlTarget = [];
end
if ~isfield(opt,'StdResiduals'),
opt.StdResiduals = 0;
end
if ~isfield(opt,'RelaxParam'),
opt.RelaxParam = 1.8;
end
if ~isfield(opt,'NonNegCoef'),
opt.NonNegCoef = 0;
end
if ~isfield(opt,'NoBndryCross'),
opt.NoBndryCross = 0;
end
if ~isfield(opt,'AuxVarObj'),
opt.AuxVarObj = 0;
end
if ~isfield(opt,'HighMemSolve'),
opt.HighMemSolve = 0;
end
return
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
elnet.m
|
.m
|
convolutional_sparse_coding-master/SparseCode/elnet.m
| 8,513 |
utf_8
|
ad0ba145ba80323e93f2f1cfabdbfb88
|
function [Y, optinf] = elnet(D, S, lambda, mu, opt)
% elnet -- Elastic Net
%
% argmin_x (1/2)||D*x - s||_2^2 + lambda*||x||_1 + (mu/2) ||x||_2^2
%
% The solution is computed using the ADMM approach (see
% boyd-2010-distributed for details).
%
% Usage:
% [Y, optinf] = elnet(D, S, lambda, mu, opt)
%
% Input:
% D Dictionary matrix
% S Signal vector (or matrix)
% lambda Regularization parameter (l1)
% mu Regularization parameter (l2)
% opt Options/algorithm parameters structure (see below)
%
% Output:
% Y Dictionary coefficient vector (or matrix)
% optinf Details of optimisation
%
%
% Options structure fields:
% Verbose Flag determining whether iteration status is displayed.
% Fields are iteration number, functional value,
% data fidelity term, l1 regularisation term, l2
% regularisation term, and primal and dual residuals
% (see Sec. 3.3 of boyd-2010-distributed). The value of
% rho is also displayed if options request that it is
% automatically adjusted.
% MaxMainIter Maximum main iterations
% AbsStopTol Absolute convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% RelStopTol Relative convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% L1Weight Weighting array for coefficients in l1 norm of X
% Y0 Initial value for Y
% U0 Initial value for U
% rho ADMM penalty parameter
% AutoRho Flag determining whether rho is automatically updated
% (see Sec. 3.4.1 of boyd-2010-distributed)
% AutoRhoPeriod Iteration period on which rho is updated
% RhoRsdlRatio Primal/dual residual ratio in rho update test
% RhoScaling Multiplier applied to rho when updated
% AutoRhoScaling Flag determining whether RhoScaling value is
% adaptively determined (see wohlberg-2015-adaptive). If
% enabled, RhoScaling specifies a maximum allowed
% multiplier instead of a fixed multiplier.
% RhoRsdlTarget Residual ratio targeted by auto rho update policy.
% StdResiduals Flag determining whether standard residual definitions
% (see Sec 3.3 of boyd-2010-distributed) are used instead
% of normalised residuals (see wohlberg-2015-adaptive)
% RelaxParam Relaxation parameter (see Sec. 3.4.3 of
% boyd-2010-distributed)
% AuxVarObj Flag determining whether objective function is computed
% using the auxiliary (split) variable
%
%
% Author: Brendt Wohlberg <[email protected]> Modified: 2015-07-24
%
% This file is part of the SPORCO library. Details of the copyright
% and user license can be found in the 'Copyright' and 'License' files
% distributed with the library.
if nargin < 5,
opt = [];
end
checkopt(opt, defaultopts([]));
opt = defaultopts(opt);
% Set up status display for verbose operation
hstr = 'Itn Fnc DFid l1 l2 r s ';
sfms = '%4d %9.2e %9.2e %9.2e %9.2e %9.2e %9.2e';
nsep = 64;
if opt.AutoRho,
hstr = [hstr ' rho '];
sfms = [sfms ' %9.2e'];
nsep = nsep + 10;
end
if opt.Verbose && opt.MaxMainIter > 0,
disp(hstr);
disp(char('-' * ones(1,nsep)));
end
% Start timer
tstart = tic;
% Set up algorithm parameters and initialise variables
rho = opt.rho;
if isempty(rho), rho = 50*lambda+1; end;
[Nr, Nc] = size(D);
Nm = size(S,2);
Nx = Nc*Nm;
DTS = D'*S;
[luL, luU] = factorise(D, mu + rho);
optinf = struct('itstat', [], 'opt', opt);
r = Inf;
s = Inf;
epri = 0;
edua = 0;
% Initialise main working variables
X = [];
if isempty(opt.Y0),
Y = zeros(Nc,Nm);
else
Y = opt.Y0;
end
Yprv = Y;
if isempty(opt.U0),
if isempty(opt.Y0),
U = zeros(Nc,Nm);
else
U = (lambda/rho)*sign(Y);
end
else
U = opt.U0;
end
% Main loop
k = 1;
while k <= opt.MaxMainIter && (r > epri | s > edua),
% Solve X subproblem
X = linsolve(D, mu + rho, luL, luU, DTS + rho*(Y - U));
% See pg. 21 of boyd-2010-distributed
if opt.RelaxParam == 1,
Xr = X;
else
Xr = opt.RelaxParam*X + (1-opt.RelaxParam)*Y;
end
% Solve Y subproblem
Y = shrink(Xr + U, (lambda/rho)*opt.L1Weight);
% Update dual variable
U = U + Xr - Y;
% Objective function and convergence measures
if opt.AuxVarObj,
Jdf = sum(vec(abs(D*Y - S).^2))/2;
Jl1 = sum(abs(vec(bsxfun(@times, opt.L1Weight, Y))));
Jl2 = sum(abs(vec(Y)).^2);
else
Jdf = sum(vec(abs(D*X - S).^2))/2;
Jl1 = sum(abs(vec(bsxfun(@times, opt.L1Weight, X))));
Jl2 = sum(abs(vec(X)).^2);
end
Jfn = Jdf + lambda*Jl1 + (mu/2)*Jl2;
nX = norm(X(:)); nY = norm(Y(:)); nU = norm(U(:));
if opt.StdResiduals,
% See pp. 19-20 of boyd-2010-distributed
r = norm(vec(X - Y));
s = norm(vec(rho*(Yprv - Y)));
epri = sqrt(Nx)*opt.AbsStopTol+max(nX,nY)*opt.RelStopTol;
edua = sqrt(Nx)*opt.AbsStopTol+rho*nU*opt.RelStopTol;
else
% See wohlberg-2015-adaptive
r = norm(vec(X - Y))/max(nX,nY);
s = norm(vec(Yprv - Y))/nU;
epri = sqrt(Nx)*opt.AbsStopTol/max(nX,nY)+opt.RelStopTol;
edua = sqrt(Nx)*opt.AbsStopTol/(rho*nU)+opt.RelStopTol;
end
% Record and display iteration details
tk = toc(tstart);
optinf.itstat = [optinf.itstat; [k Jfn Jdf Jl1 Jl2 r s epri edua rho tk]];
if opt.Verbose,
if opt.AutoRho,
disp(sprintf(sfms, k, Jfn, Jdf, Jl1, Jl2, r, s, rho));
else
disp(sprintf(sfms, k, Jfn, Jdf, Jl1, Jl2, r, s));
end
end
% See wohlberg-2015-adaptive and pp. 20-21 of boyd-2010-distributed
if opt.AutoRho,
if k ~= 1 && mod(k, opt.AutoRhoPeriod) == 0,
if opt.AutoRhoScaling,
rhomlt = sqrt(r/(s*opt.RhoRsdlTarget));
if rhomlt < 1, rhomlt = 1/rhomlt; end
if rhomlt > opt.RhoScaling, rhomlt = opt.RhoScaling; end
else
rhomlt = opt.RhoScaling;
end
rsf = 1;
if r > opt.RhoRsdlTarget*opt.RhoRsdlRatio*s, rsf = rhomlt; end
if s > (opt.RhoRsdlRatio/opt.RhoRsdlTarget)*r, rsf = 1/rhomlt; end
rho = rsf*rho;
U = U/rsf;
if rsf ~= 1,
[luL, luU] = factorise(D, mu + rho);
end
end
end
Yprv = Y;
k = k + 1;
end
% Record run time and working variables
optinf.runtime = toc(tstart);
optinf.X = X;
optinf.Y = Y;
optinf.U = U;
optinf.lambda = lambda;
optinf.rho = rho;
optinf.mu = mu;
% End status display for verbose operation
if opt.Verbose && opt.MaxMainIter > 0,
disp(char('-' * ones(1,nsep)));
end
return
function u = vec(v)
u = v(:);
return
function u = shrink(v, lambda)
if isscalar(lambda),
u = sign(v).*max(0, abs(v) - lambda);
else
u = sign(v).*max(0, bsxfun(@minus, abs(v), lambda));
end
return
function [L,U] = factorise(A, c)
[N,M] = size(A);
% If N < M it is cheaper to factorise A*A' + cI and then use the
% matrix inversion lemma to compute the inverse of A'*A + cI
if N >= M,
[L,U] = lu(A'*A + c*eye(M,M));
else
[L,U] = lu(A*A' + c*eye(N,N));
end
return
function x = linsolve(A, c, L, U, b)
[N,M] = size(A);
if N >= M,
x = U \ (L \ b);
else
x = (b - A'*(U \ (L \ (A*b))))/c;
end
return
function opt = defaultopts(opt)
if ~isfield(opt,'Verbose'),
opt.Verbose = 0;
end
if ~isfield(opt,'MaxMainIter'),
opt.MaxMainIter = 1000;
end
if ~isfield(opt,'AbsStopTol'),
opt.AbsStopTol = 0;
end
if ~isfield(opt,'RelStopTol'),
opt.RelStopTol = 1e-4;
end
if ~isfield(opt,'L1Weight'),
opt.L1Weight = 1;
end
if ~isfield(opt,'Y0'),
opt.Y0 = [];
end
if ~isfield(opt,'U0'),
opt.U0 = [];
end
if ~isfield(opt,'rho'),
opt.rho = [];
end
if ~isfield(opt,'AutoRho'),
opt.AutoRho = 1;
end
if ~isfield(opt,'AutoRhoPeriod'),
opt.AutoRhoPeriod = 10;
end
if ~isfield(opt,'RhoRsdlRatio'),
opt.RhoRsdlRatio = 1.2;
end
if ~isfield(opt,'RhoScaling'),
opt.RhoScaling = 100;
end
if ~isfield(opt,'AutoRhoScaling'),
opt.AutoRhoScaling = 1;
end
if ~isfield(opt,'RhoRsdlTarget'),
opt.RhoRsdlTarget = 1;
end
if ~isfield(opt,'StdResiduals'),
opt.StdResiduals = 0;
end
if ~isfield(opt,'RelaxParam'),
opt.RelaxParam = 1.8;
end
if ~isfield(opt,'AuxVarObj'),
opt.AuxVarObj = 1;
end
return
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
cbpdn_gpu.m
|
.m
|
convolutional_sparse_coding-master/SparseCode/cbpdn_gpu.m
| 10,916 |
utf_8
|
e6b2b039c00e53be0b0eacdf0428f4ea
|
function [Y, optinf] = cbpdn_gpu(D, S, lambda, opt)
% cbpdn_gpu -- Convolutional Basis Pursuit DeNoising (GPU version)
%
% argmin_{x_m} (1/2)||\sum_m d_m * x_m - s||_2^2 +
% lambda \sum_m ||x_m||_1
%
% The solution is computed using an ADMM approach (see
% boyd-2010-distributed) with efficient solution of the main
% linear systems (see wohlberg-2016-efficient).
%
% Usage:
% [Y, optinf] = cbpdn_gpu(D, S, lambda, opt);
%
% Input:
% D Dictionary filter set (3D array)
% S Input image
% lambda Regularization parameter
% opt Algorithm parameters structure
%
% Output:
% Y Dictionary coefficient map set (3D array)
% optinf Details of optimisation
%
%
% Options structure fields:
% Verbose Flag determining whether iteration status is displayed.
% Fields are iteration number, functional value,
% data fidelity term, l1 regularisation term, and
% primal and dual residuals (see Sec. 3.3 of
% boyd-2010-distributed). The value of rho is also
% displayed if options request that it is automatically
% adjusted.
% MaxMainIter Maximum main iterations
% AbsStopTol Absolute convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% RelStopTol Relative convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% L1Weight Weighting array for coefficients in l1 norm of X
% Y0 Initial value for Y
% U0 Initial value for U
% rho ADMM penalty parameter
% AutoRho Flag determining whether rho is automatically updated
% (see Sec. 3.4.1 of boyd-2010-distributed)
% AutoRhoPeriod Iteration period on which rho is updated
% RhoRsdlRatio Primal/dual residual ratio in rho update test
% RhoScaling Multiplier applied to rho when updated
% AutoRhoScaling Flag determining whether RhoScaling value is
% adaptively determined (see wohlberg-2015-adaptive). If
% enabled, RhoScaling specifies a maximum allowed
% multiplier instead of a fixed multiplier.
% RhoRsdlTarget Residual ratio targeted by auto rho update policy.
% StdResiduals Flag determining whether standard residual definitions
% (see Sec 3.3 of boyd-2010-distributed) are used instead
% of normalised residuals (see wohlberg-2015-adaptive)
% RelaxParam Relaxation parameter (see Sec. 3.4.3 of
% boyd-2010-distributed)
% NoBndryCross Flag indicating whether all solution coefficients
% corresponding to filters crossing the image boundary
% should be forced to zero.
% AuxVarObj Flag determining whether objective function is computed
% using the auxiliary (split) variable
% HighMemSolve Use more memory for a slightly faster solution
%
%
% Authors: Brendt Wohlberg <[email protected]>
% Ping-Keng Jao <[email protected]>
% Modified: 2015-12-28
%
% This file is part of the SPORCO library. Details of the copyright
% and user license can be found in the 'License' file distributed with
% the library.
gS = gpuArray(S);
gD = gpuArray(D);
glambda = gpuArray(lambda);
if nargin < 4,
opt = [];
end
checkopt(opt, defaultopts([]));
opt = defaultopts(opt);
% Set up status display for verbose operation
hstr = 'Itn Fnc DFid l1 r s ';
sfms = '%4d %9.2e %9.2e %9.2e %9.2e %9.2e';
nsep = 54;
if opt.AutoRho,
hstr = [hstr ' rho '];
sfms = [sfms ' %9.2e'];
nsep = nsep + 10;
end
if opt.Verbose && opt.MaxMainIter > 0,
disp(hstr);
disp(char('-' * ones(1,nsep)));
end
% Collapsing of trailing singleton dimensions greatly complicates
% handling of both SMV and MMV cases. The simplest approach would be
% if S could always be reshaped to 4d, with dimensions consisting of
% image rows, image cols, a single dimensional placeholder for number
% of filters, and number of measurements, but in the single
% measurement case the third dimension is collapsed so that the array
% is only 3d.
if size(S,3) > 1 && size(S,4) == 1,
xsz = [size(S,1) size(S,2) size(D,3) size(S,3)];
% Insert singleton 3rd dimension (for number of filters) so that
% 4th dimension is number of images in input s volume
gS = reshape(gS, [size(S,1) size(S,2) 1 size(S,3)]);
else
xsz = [size(S,1) size(S,2) size(D,3) size(S,4)];
end
% Start timer
tstart = tic;
% Compute filters in DFT domain
gDf = fft2(gD, size(S,1), size(S,2));
% Convolve-sum and its Hermitian transpose
gDop = @(x) sum(bsxfun(@times, gDf, x), 3);
gDHop = @(x) bsxfun(@times, conj(gDf), x);
% Compute signal in DFT domain
gSf = fft2(gS);
% S convolved with all filters in DFT domain
gDSf = gDHop(gSf);
% Default lambda is 1/10 times the lambda value beyond which the
% solution is a zero vector
if nargin < 3 | isempty(lambda),
gb = ifft2(DHop(gSf), 'symmetric');
glambda = 0.1*max(vec(abs(gb)));
end
% Set up algorithm parameters and initialise variables
grho = gpuArray(opt.rho);
if isempty(grho), grho = 50*glambda+1; end;
if isempty(opt.RhoRsdlTarget),
if opt.StdResiduals,
opt.RhoRsdlTarget = 1;
else
opt.RhoRsdlTarget = 1 + (18.3).^(log10(gather(glambda)) + 1);
end
end
if opt.HighMemSolve,
gC = bsxfun(@rdivide, gDf, sum(gDf.*conj(gDf), 3) + grho);
else
gC = [];
end
gNx = prod(gpuArray(xsz));
optinf = struct('itstat', [], 'opt', opt);
gr = gpuArray(Inf);
gs = gpuArray(Inf);
gepri = gpuArray(0);
gedua = gpuArray(0);
% Initialise main working variables
% X = [];
if isempty(opt.Y0),
% gY = zeros(xsz, 'gpuArray');
gY = gpuArray.zeros(xsz);
else
gY = gpuArray(opt.Y0);
end
gYprv = gY;
if isempty(opt.U0),
if isempty(opt.Y0),
% gU = zeros(xsz, 'gpuArray');
gU = gpuArray.zeros(xsz);
else
gU = (glambda/grho)*sign(gY);
end
else
gU = gpuArray(opt.U0);
end
% Main loop
k = 1;
while k <= opt.MaxMainIter & (gr > gepri | gs > gedua),
% Solve X subproblem
gXf = solvedbi_sm(gDf, grho, gDSf + grho*fft2(gY - gU), gC);
gX = ifft2(gXf, 'symmetric');
% See pg. 21 of boyd-2010-distributed
if opt.RelaxParam == 1,
gXr = gX;
else
gXr = opt.RelaxParam*gX + (1-opt.RelaxParam)*gY;
end
% Solve Y subproblem
gY = shrink(gXr + gU, (glambda/grho)*opt.L1Weight);
if opt.NoBndryCross,
gY((end-size(gD,1)+2):end,:,:,:) = 0;
gY(:,(end-size(gD,2)+2):end,:,:) = 0;
end
% Update dual variable
gU = gU + gXr - gY;
% Compute data fidelity term in Fourier domain (note normalisation)
if opt.AuxVarObj,
gYf = fft2(gY); % This represents unnecessary computational cost
gJdf = sum(vec(abs(sum(bsxfun(@times,gDf,gYf),3)-gSf).^2)) / ...
(2*xsz(1)*xsz(2));
gJl1 = sum(abs(vec(bsxfun(@times, opt.L1Weight, gY))));
else
gJdf = sum(vec(abs(sum(bsxfun(@times,gDf,gXf),3)-gSf).^2)) / ...
(2*xsz(1)*xsz(2));
gJl1 = sum(abs(vec(bsxfun(@times, opt.L1Weight, gX))));
end
gJfn = gJdf + glambda*gJl1;
gnX = norm(gX(:)); gnY = norm(gY(:)); gnU = norm(gU(:));
if opt.StdResiduals,
% See pp. 19-20 of boyd-2010-distributed
gr = norm(vec(gX - gY));
gs = norm(vec(grho*(gYprv - gY)));
gepri = sqrt(gNx)*opt.AbsStopTol+max(gnX,gnY)*opt.RelStopTol;
gedua = sqrt(gNx)*opt.AbsStopTol+grho*gnU*opt.RelStopTol;
else
% See wohlberg-2015-adaptive
gr = norm(vec(gX - gY))/max(gnX,gnY);
gs = norm(vec(gYprv - gY))/gnU;
gepri = sqrt(gNx)*opt.AbsStopTol/max(gnX,gnY)+opt.RelStopTol;
gedua = sqrt(gNx)*opt.AbsStopTol/(grho*gnU)+opt.RelStopTol;
end
% Record and display iteration details
tk = toc(tstart);
optinf.itstat = [optinf.itstat; [k gather(gJfn) gather(gJdf) gather(gJl1) ...
gather(gr) gather(gs) gather(gepri) gather(gedua) grho tk]];
if opt.Verbose,
if opt.AutoRho,
disp(sprintf(sfms, k, gather(gJfn), gather(gJdf), gather(gJl1), ...
gather(gr), gather(gs), grho));
else
disp(sprintf(sfms, k, gather(gJfn), gather(gJdf), gather(gJl1), ...
gather(gr), gather(gs)));
end
end
% See wohlberg-2015-adaptive and pp. 20-21 of boyd-2010-distributed
if opt.AutoRho,
if k ~= 1 && mod(k, opt.AutoRhoPeriod) == 0,
if opt.AutoRhoScaling,
grhomlt = sqrt(gr/(gs*opt.RhoRsdlTarget));
if grhomlt < 1, grhomlt = 1/grhomlt; end
if grhomlt > opt.RhoScaling, grhomlt = opt.RhoScaling; end
else
grhomlt = opt.RhoScaling;
end
grsf = 1;
if gr > opt.RhoRsdlTarget*opt.RhoRsdlRatio*gs, grsf = grhomlt; end
if gs > (opt.RhoRsdlRatio/opt.RhoRsdlTarget)*gr, grsf = 1/grhomlt; end
grho = grsf*grho;
gU = gU/grsf;
if opt.HighMemSolve && grsf ~= 1,
gC = bsxfun(@rdivide, gDf, sum(gDf.*conj(gDf), 3) + grho);
end
end
end
gYprv = gY;
k = k + 1;
end
% Record run time and working variables
optinf.runtime = toc(tstart);
optinf.X = gather(gX);
optinf.Xf = gather(gXf);
optinf.Y = gather(gY);
optinf.U = gather(gU);
optinf.lambda = gather(glambda);
optinf.rho = gather(grho);
Y = gather(gY);
% End status display for verbose operation
if opt.Verbose && opt.MaxMainIter > 0,
disp(char('-' * ones(1,nsep)));
end
return
function u = vec(v)
u = v(:);
return
function u = shrink(v, lambda)
if isscalar(lambda),
u = sign(v).*max(0, abs(v) - lambda);
else
u = sign(v).*max(0, bsxfun(@minus, abs(v), lambda));
end
return
function opt = defaultopts(opt)
if ~isfield(opt,'Verbose'),
opt.Verbose = 0;
end
if ~isfield(opt,'MaxMainIter'),
opt.MaxMainIter = 1000;
end
if ~isfield(opt,'AbsStopTol'),
opt.AbsStopTol = 0;
end
if ~isfield(opt,'RelStopTol'),
opt.RelStopTol = 1e-4;
end
if ~isfield(opt,'L1Weight'),
opt.L1Weight = 1;
end
if ~isfield(opt,'Y0'),
opt.Y0 = [];
end
if ~isfield(opt,'U0'),
opt.U0 = [];
end
if ~isfield(opt,'rho'),
opt.rho = [];
end
if ~isfield(opt,'AutoRho'),
opt.AutoRho = 1;
end
if ~isfield(opt,'AutoRhoPeriod'),
opt.AutoRhoPeriod = 1;
end
if ~isfield(opt,'RhoRsdlRatio'),
opt.RhoRsdlRatio = 1.2;
end
if ~isfield(opt,'RhoScaling'),
opt.RhoScaling = 100;
end
if ~isfield(opt,'AutoRhoScaling'),
opt.AutoRhoScaling = 1;
end
if ~isfield(opt,'RhoRsdlTarget'),
opt.RhoRsdlTarget = [];
end
if ~isfield(opt,'StdResiduals'),
opt.StdResiduals = 0;
end
if ~isfield(opt,'RelaxParam'),
opt.RelaxParam = 1.8;
end
if ~isfield(opt,'NoBndryCross'),
opt.NoBndryCross = 0;
end
if ~isfield(opt,'AuxVarObj'),
opt.AuxVarObj = 0;
end
if ~isfield(opt,'HighMemSolve'),
opt.HighMemSolve = 0;
end
return
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
cbpdnjnt.m
|
.m
|
convolutional_sparse_coding-master/SparseCode/cbpdnjnt.m
| 11,491 |
utf_8
|
4159f4569e221507f7cf594135d490d7
|
function [Y, optinf] = cbpdnjnt(D, S, lambda, mu, opt)
% cbpdnjnt -- Convolutional Basis Pursuit DeNoising with Joint Sparsity
%
% argmin_{x_k} (1/2)||\sum_k d_k * x_k - s||_2^2 +
% lambda \sum_k ||x_k||_1 +
% mu ||{x_k}||_{2,1}
%
% The solution is computed using an ADMM approach (see
% boyd-2010-distributed) with efficient solution of the main
% linear systems (see wohlberg-2016-efficient and
% wohlberg-2016-convolutional).
%
% Note: Multi-channel images are represented by stacking the
% channels on the 3rd dimension of input array S. Since this
% is also the dimension used for stacking multiple images,
% multiple multi-channel images are are not handled properly
% with respect to the l2,1 norm.
%
% Usage:
% [Y, optinf] = cbpdnjnt(D, S, lambda, mu, opt)
%
% Input:
% D Dictionary filter set (3D array)
% S Input image
% lambda l1 regularization parameter
% mu l2,1 regularization parameter
% opt Algorithm parameters structure
%
% Output:
% Y Dictionary coefficient map set (3D array)
% optinf Details of optimisation
%
%
% Options structure fields:
% Verbose Flag determining whether iteration status is displayed.
% Fields are iteration number, functional value,
% data fidelity term, l1 regularisation term, l2,1
% regularisation term, and primal and dual residuals
% (see Sec. 3.3 of boyd-2010-distributed). The value of
% rho is also displayed if options request that it is
% automatically adjusted.
% MaxMainIter Maximum main iterations
% AbsStopTol Absolute convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% RelStopTol Relative convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% L1Weight Weighting array for coefficients in l1 norm of X
% L21Weight Weighting array for coefficients in l2,1 norm of X
% Y0 Initial value for Y
% U0 Initial value for U
% rho ADMM penalty parameter
% AutoRho Flag determining whether rho is automatically updated
% (see Sec. 3.4.1 of boyd-2010-distributed)
% AutoRhoPeriod Iteration period on which rho is updated
% RhoRsdlRatio Primal/dual residual ratio in rho update test
% RhoScaling Multiplier applied to rho when updated
% AutoRhoScaling Flag determining whether RhoScaling value is
% adaptively determined (see wohlberg-2015-adaptive). If
% enabled, RhoScaling specifies a maximum allowed
% multiplier instead of a fixed multiplier.
% RhoRsdlTarget Residual ratio targeted by auto rho update policy.
% StdResiduals Flag determining whether standard residual definitions
% (see Sec 3.3 of boyd-2010-distributed) are used instead
% of normalised residuals (see wohlberg-2015-adaptive)
% RelaxParam Relaxation parameter (see Sec. 3.4.3 of
% boyd-2010-distributed)
% NonNegCoef Flag indicating whether solution should be forced to
% be non-negative
% NoBndryCross Flag indicating whether all solution coefficients
% corresponding to filters crossing the image boundary
% should be forced to zero.
% AuxVarObj Flag determining whether objective function is computed
% using the auxiliary (split) variable
% HighMemSolve Use more memory for a slightly faster solution
%
%
% Author: Brendt Wohlberg <[email protected]> Modified: 2016-07-01
%
% This file is part of the SPORCO library. Details of the copyright
% and user license can be found in the 'License' file distributed with
% the library.
if nargin < 5,
opt = [];
end
checkopt(opt, defaultopts([]));
opt = defaultopts(opt);
% Set up status display for verbose operation
hstr = 'Itn Fnc DFid l1 l2,1 r s ';
sfms = '%4d %9.2e %9.2e %9.2e %9.2e %9.2e %9.2e';
nsep = 64;
if opt.AutoRho,
hstr = [hstr ' rho '];
sfms = [sfms ' %9.2e'];
nsep = nsep + 10;
end
if opt.Verbose && opt.MaxMainIter > 0,
disp(hstr);
disp(char('-' * ones(1,nsep)));
end
% Start timer
tstart = tic;
% Collapsing of trailing singleton dimensions greatly complicates
% handling of both SMV and MMV cases. The simplest approach would be
% if S could always be reshaped to 4d, with dimensions consisting of
% image rows, image cols, a single dimensional placeholder for number
% of filters, and number of measurements, but in the single
% measurement case the third dimension is collapsed so that the array
% is only 3d.
if size(S,3) > 1,
xsz = [size(S,1) size(S,2) size(D,3) size(S,3)];
hrm = [1 1 1 size(S,3)];
% Insert singleton 3rd dimension (for number of filters) so that
% 4th dimension is number of images in input s volume
S = reshape(S, [size(S,1) size(S,2) 1 size(S,3)]);
else
xsz = [size(S,1) size(S,2) size(D,3) 1];
hrm = 1;
end
xrm = [1 1 size(D,3)];
% Compute filters in DFT domain
Df = fft2(D, size(S,1), size(S,2));
% Convolve-sum and its Hermitian transpose
Dop = @(x) sum(bsxfun(@times, Df, x), 3);
DHop = @(x) bsxfun(@times, conj(Df), x);
% Compute signal in DFT domain
Sf = fft2(S);
% S convolved with all filters in DFT domain
DSf = DHop(Sf);
% Set up algorithm parameters and initialise variables
rho = opt.rho;
if isempty(rho), rho = 50*lambda+1; end;
if isempty(opt.RhoRsdlTarget),
if opt.StdResiduals,
opt.RhoRsdlTarget = 1;
else
opt.RhoRsdlTarget = 1 + (18.3).^(log10(lambda) + 1);
end
end
if opt.HighMemSolve,
C = bsxfun(@rdivide, Df, sum(Df.*conj(Df), 3) + rho);
else
C = [];
end
Nx = prod(xsz);
optinf = struct('itstat', [], 'opt', opt);
r = Inf;
s = Inf;
epri = 0;
edua = 0;
% Initialise main working variables
X = [];
if isempty(opt.Y0),
Y = zeros(xsz, class(S));
else
Y = opt.Y0;
end
Yprv = Y;
if isempty(opt.U0),
if isempty(opt.Y0),
U = zeros(xsz, class(S));
else
U = (lambda/rho)*sign(Y);
end
else
U = opt.U0;
end
% Main loop
k = 1;
while k <= opt.MaxMainIter && (r > epri | s > edua),
% Solve X subproblem
Xf = solvedbi_sm(Df, rho, DSf + rho*fft2(Y - U), C);
X = ifft2(Xf, 'symmetric');
% See pg. 21 of boyd-2010-distributed
if opt.RelaxParam == 1,
Xr = X;
else
Xr = opt.RelaxParam*X + (1-opt.RelaxParam)*Y;
end
% Solve Y subproblem
Y = shrink21(Xr + U, lambda/rho, mu/rho, opt.L1Weight, opt.L21Weight);
if opt.NonNegCoef,
Y(Y < 0) = 0;
end
if opt.NoBndryCross,
Y((end-size(D,1)+2):end,:,:,:) = 0;
Y(:,(end-size(D,2)+2):end,:,:) = 0;
end
% Update dual variable
U = U + Xr - Y;
% Compute data fidelity term in Fourier domain (note normalisation)
if opt.AuxVarObj,
Yf = fft2(Y); % This represents unnecessary computational cost
Jdf = sum(vec(abs(sum(bsxfun(@times,Df,Yf),3)-Sf).^2))/(2*xsz(1)*xsz(2));
Jl1 = sum(abs(vec(bsxfun(@times, opt.L1Weight, Y))));
Jl21 = sum(sqrt(vec(sum(bsxfun(@times, opt.L21Weight, Y).^2, 4))));
else
Jdf = sum(vec(abs(sum(bsxfun(@times,Df,Xf),3)-Sf).^2))/(2*xsz(1)*xsz(2));
Jl1 = sum(abs(vec(bsxfun(@times, opt.L1Weight, X))));
Jl21 = sum(sqrt(vec(sum(bsxfun(@times, opt.L21Weight, X).^2, 4))));
end
Jfn = Jdf + lambda*Jl1 + mu*Jl21;
nX = norm(X(:)); nY = norm(Y(:)); nU = norm(U(:));
if opt.StdResiduals,
% See pp. 19-20 of boyd-2010-distributed
r = norm(vec(X - Y));
s = norm(vec(rho*(Yprv - Y)));
epri = sqrt(Nx)*opt.AbsStopTol+max(nX,nY)*opt.RelStopTol;
edua = sqrt(Nx)*opt.AbsStopTol+rho*nU*opt.RelStopTol;
else
% See wohlberg-2015-adaptive
r = norm(vec(X - Y))/max(nX,nY);
s = norm(vec(Yprv - Y))/nU;
epri = sqrt(Nx)*opt.AbsStopTol/max(nX,nY)+opt.RelStopTol;
edua = sqrt(Nx)*opt.AbsStopTol/(rho*nU)+opt.RelStopTol;
end
% Record and display iteration details
tk = toc(tstart);
optinf.itstat = [optinf.itstat; [k Jfn Jdf Jl1 Jl21 r s epri edua rho tk]];
if opt.Verbose,
if opt.AutoRho,
disp(sprintf(sfms, k, Jfn, Jdf, Jl1, Jl21, r, s, rho));
else
disp(sprintf(sfms, k, Jfn, Jdf, Jl1, Jl21, r, s));
end
end
% See wohlberg-2015-adaptive and pp. 20-21 of boyd-2010-distributed
if opt.AutoRho,
if k ~= 1 && mod(k, opt.AutoRhoPeriod) == 0,
if opt.AutoRhoScaling,
rhomlt = sqrt(r/(s*opt.RhoRsdlTarget));
if rhomlt < 1, rhomlt = 1/rhomlt; end
if rhomlt > opt.RhoScaling, rhomlt = opt.RhoScaling; end
else
rhomlt = opt.RhoScaling;
end
rsf = 1;
if r > opt.RhoRsdlTarget*opt.RhoRsdlRatio*s, rsf = rhomlt; end
if s > (opt.RhoRsdlRatio/opt.RhoRsdlTarget)*r, rsf = 1/rhomlt; end
rho = rsf*rho;
U = U/rsf;
if opt.HighMemSolve && rsf ~= 1,
C = bsxfun(@rdivide, Df, sum(Df.*conj(Df), 3) + rho);
end
end
end
Yprv = Y;
k = k + 1;
end
% Record run time and working variables
optinf.runtime = toc(tstart);
optinf.X = X;
optinf.Y = Y;
optinf.U = U;
optinf.lambda = lambda;
optinf.rho = rho;
% End status display for verbose operation
if opt.Verbose && opt.MaxMainIter > 0,
disp(char('-' * ones(1,nsep)));
end
return
function u = vec(v)
u = v(:);
return
function u = shrink1_scalars(v, a)
if isscalar(a),
u = sign(v).*max(0, abs(v) - a);
else
u = sign(v).*max(0, bsxfun(@minus, abs(v), a));
end
return
function U = shrink2_row_vectors(V, a)
n2v = sqrt(sum(V.^2, 4));
n2v(n2v == 0) = 1;
if isscalar(a),
U = bsxfun(@times, V, max(0, n2v - a)./n2v);
else
U = bsxfun(@times, V, max(0, bsxfun(@minus, n2v, a))./n2v);
end
return
function U = shrink21(V, a, b, W1, W2)
if nargin < 4 || isempty(W1),
W1 = 1;
end
% See wohlberg-2012-local and chartrand-2013-nonconvex
U = shrink2_row_vectors(shrink1_scalars(V, W1 .* a), W2 .* b);
return
function opt = defaultopts(opt)
if ~isfield(opt,'Verbose'),
opt.Verbose = 0;
end
if ~isfield(opt,'MaxMainIter'),
opt.MaxMainIter = 1000;
end
if ~isfield(opt,'AbsStopTol'),
opt.AbsStopTol = 0;
end
if ~isfield(opt,'RelStopTol'),
opt.RelStopTol = 1e-4;
end
if ~isfield(opt,'L1Weight'),
opt.L1Weight = 1;
end
if ~isfield(opt,'L21Weight'),
opt.L21Weight = 1;
end
if ~isfield(opt,'Y0'),
opt.Y0 = [];
end
if ~isfield(opt,'U0'),
opt.U0 = [];
end
if ~isfield(opt,'rho'),
opt.rho = [];
end
if ~isfield(opt,'AutoRho'),
opt.AutoRho = 1;
end
if ~isfield(opt,'AutoRhoPeriod'),
opt.AutoRhoPeriod = 1;
end
if ~isfield(opt,'RhoRsdlRatio'),
opt.RhoRsdlRatio = 1.2;
end
if ~isfield(opt,'RhoScaling'),
opt.RhoScaling = 100;
end
if ~isfield(opt,'AutoRhoScaling'),
opt.AutoRhoScaling = 1;
end
if ~isfield(opt,'RhoRsdlTarget'),
opt.RhoRsdlTarget = [];
end
if ~isfield(opt,'StdResiduals'),
opt.StdResiduals = 0;
end
if ~isfield(opt,'RelaxParam'),
opt.RelaxParam = 1.8;
end
if ~isfield(opt,'NonNegCoef'),
opt.NonNegCoef = 0;
end
if ~isfield(opt,'NoBndryCross'),
opt.NoBndryCross = 0;
end
if ~isfield(opt,'AuxVarObj'),
opt.AuxVarObj = 0;
end
if ~isfield(opt,'HighMemSolve'),
opt.HighMemSolve = 0;
end
return
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
bpdngrp.m
|
.m
|
convolutional_sparse_coding-master/SparseCode/bpdngrp.m
| 9,332 |
utf_8
|
7b8f97e92c355ae6a5ab23882c88b226
|
function [Y, optinf] = bpdngrp(D, S, lambda, mu, g, opt)
% bpdngrp -- Basis Pursuit DeNoising with l2,1 group sparsity
%
% argmin_x (1/2)||D*x - s||_2^2 + lambda*||x||_1 +
% mu * \sum_l ||G_l(x)||_2
%
% The solution is computed using the ADMM approach (see
% boyd-2010-distributed for details).
%
% Usage:
% [Y, optinf] = bpdngrp(D, S, lambda, mu, g, opt)
%
% Input:
% D Dictionary matrix
% S Signal vector (or matrix)
% lambda Regularization parameter
% mu l2,1 regularization parameter
% g Vector containing index values indicating the
% group number for each dictionary element. The
% first group index is 1 (0 indicates no group).
% Number must be contiguous. Overlapping groups
% are not supported.
% opt Options/algorithm parameters structure (see below)
%
% Output:
% Y Dictionary coefficient vector (or matrix)
% optinf Details of optimisation
%
%
% Options structure fields:
% Verbose Flag determining whether iteration status is displayed.
% Fields are iteration number, functional value,
% data fidelity term, l1 regularisation term, l2,1
% regularisation term, and primal and dual residuals
% (see Sec. 3.3 of boyd-2010-distributed). The value of
% rho is also displayed if options request that it is
% automatically adjusted.
% MaxMainIter Maximum main iterations
% AbsStopTol Absolute convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% RelStopTol Relative convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% Y0 Initial value for Y
% U0 Initial value for U
% rho ADMM penalty parameter
% AutoRho Flag determining whether rho is automatically updated
% (see Sec. 3.4.1 of boyd-2010-distributed)
% AutoRhoPeriod Iteration period on which rho is updated
% RhoRsdlRatio Primal/dual residual ratio in rho update test
% RhoScaling Multiplier applied to rho when updated
% AutoRhoScaling Flag determining whether RhoScaling value is
% adaptively determined (see wohlberg-2015-adaptive). If
% enabled, RhoScaling specifies a maximum allowed
% multiplier instead of a fixed multiplier.
% RhoRsdlTarget Residual ratio targeted by auto rho update policy.
% StdResiduals Flag determining whether standard residual definitions
% (see Sec 3.3 of boyd-2010-distributed) are used instead
% of normalised residuals (see wohlberg-2015-adaptive)
% RelaxParam Relaxation parameter (see Sec. 3.4.3 of
% boyd-2010-distributed)
% AuxVarObj Flag determining whether objective function is computed
% using the auxiliary (split) variable
%
%
% Author: Brendt Wohlberg <[email protected]> Modified: 2015-07-10
%
% This file is part of the SPORCO library. Details of the copyright
% and user license can be found in the 'Copyright' and 'License' files
% distributed with the library.
if nargin < 6,
opt = [];
end
checkopt(opt, defaultopts([]));
opt = defaultopts(opt);
% Set up status display for verbose operation
hstr = 'Itn Fnc DFid l1 l2,1 r s ';
sfms = '%4d %9.2e %9.2e %9.2e %9.2e %9.2e %9.2e';
nsep = 64;
if opt.AutoRho,
hstr = [hstr ' rho '];
sfms = [sfms ' %9.2e'];
nsep = nsep + 10;
end
if opt.Verbose && opt.MaxMainIter > 0,
disp(hstr);
disp(char('-' * ones(1,nsep)));
end
% Start timer
tstart = tic;
% Set up algorithm parameters and initialise variables
rho = opt.rho;
if isempty(rho), rho = 50*lambda+1; end;
[Nr, Nc] = size(D);
Nm = size(S,2);
Nx = Nc*Nm;
Ng = max(g);
DTS = D'*S;
[luL, luU] = factorise(D, rho);
optinf = struct('itstat', [], 'opt', opt);
r = Inf;
s = Inf;
epri = 0;
edua = 0;
% Initialise main working variables
X = [];
if isempty(opt.Y0),
Y = zeros(Nc,Nm);
else
Y = opt.Y0;
end
Yprv = Y;
if isempty(opt.U0),
if isempty(opt.Y0),
U = zeros(Nc,Nm);
else
U = (lambda/rho)*sign(Y);
end
else
U = opt.U0;
end
% Main loop
k = 1;
while k <= opt.MaxMainIter && (r > epri | s > edua),
% Solve X subproblem
X = linsolve(D, rho, luL, luU, DTS + rho*(Y - U));
% See pg. 21 of boyd-2010-distributed
if opt.RelaxParam == 1,
Xr = X;
else
Xr = opt.RelaxParam*X + (1-opt.RelaxParam)*Y;
end
% Solve Y subproblem
Y = shrink_groups(Xr + U, g, Ng, lambda/rho, mu/rho);
% Update dual variable
U = U + Xr - Y;
% Objective function and convergence measures
if opt.AuxVarObj,
Jdf = sum(vec(abs(D*Y - S).^2))/2;
Jl1 = sum(abs(vec(Y)));
Jl21 = norm21(Y, g, Ng);
else
Jdf = sum(vec(abs(D*X - S).^2))/2;
Jl1 = sum(abs(vec(X)));
Jl21 = norm21(X, g, Ng);
end
Jfn = Jdf + lambda*Jl1 + mu*Jl21;
nX = norm(X(:)); nY = norm(Y(:)); nU = norm(U(:));
if opt.StdResiduals,
% See pp. 19-20 of boyd-2010-distributed
r = norm(vec(X - Y));
s = norm(vec(rho*(Yprv - Y)));
epri = sqrt(Nx)*opt.AbsStopTol+max(nX,nY)*opt.RelStopTol;
edua = sqrt(Nx)*opt.AbsStopTol+rho*nU*opt.RelStopTol;
else
% See wohlberg-2015-adaptive
r = norm(vec(X - Y))/max(nX,nY);
s = norm(vec(Yprv - Y))/nU;
epri = sqrt(Nx)*opt.AbsStopTol/max(nX,nY)+opt.RelStopTol;
edua = sqrt(Nx)*opt.AbsStopTol/(rho*nU)+opt.RelStopTol;
end
% Record and display iteration details
tk = toc(tstart);
optinf.itstat = [optinf.itstat;[k Jfn Jdf Jl1 Jl21 r s epri edua rho tk]];
if opt.Verbose,
if opt.AutoRho,
disp(sprintf(sfms, k, Jfn, Jdf, Jl1, Jl21, r, s, rho));
else
disp(sprintf(sfms, k, Jfn, Jdf, Jl1, Jl21, r, s));
end
end
% See wohlberg-2015-adaptive and pp. 20-21 of boyd-2010-distributed
if opt.AutoRho,
if k ~= 1 && mod(k, opt.AutoRhoPeriod) == 0,
if opt.AutoRhoScaling,
rhomlt = sqrt(r/(s*opt.RhoRsdlTarget));
if rhomlt < 1, rhomlt = 1/rhomlt; end
if rhomlt > opt.RhoScaling, rhomlt = opt.RhoScaling; end
else
rhomlt = opt.RhoScaling;
end
rsf = 1;
if r > opt.RhoRsdlTarget*opt.RhoRsdlRatio*s, rsf = rhomlt; end
if s > (opt.RhoRsdlRatio/opt.RhoRsdlTarget)*r, rsf = 1/rhomlt; end
rho = rsf*rho;
U = U/rsf;
if rsf ~= 1,
[luL, luU] = factorise(D, rho);
end
end
end
Yprv = Y;
k = k + 1;
end
% Record run time and working variables
optinf.runtime = toc(tstart);
optinf.X = X;
optinf.Y = Y;
optinf.U = U;
optinf.lambda = lambda;
optinf.rho = rho;
% End status display for verbose operation
if opt.Verbose && opt.MaxMainIter > 0,
disp(char('-' * ones(1,nsep)));
end
return
function u = vec(v)
u = v(:);
return
function u = shrink1(v, a)
u = sign(v).*max(0, abs(v) - a);
return
function U = shrink2_col_vec(V, a)
% Additional complexity here allows simultaenous shrinkage of a
% set of column vectors
n2v = sqrt(sum(V.^2,1));
n2v(n2v == 0) = 1;
U = bsxfun(@times, V, max(0, n2v - a)./n2v);
return
function U = shrink21(V, a, b)
% See wohlberg-2012-local and chartrand-2013-nonconvex
U = shrink2_col_vec(shrink1(V, a), b);
return
function U = shrink_groups(V, g, Ng, a, b)
U = zeros(size(V));
U(g==0,:) = shrink1(V(g==0,:), a);
for l = 1:Ng,
U(g==l,:) = shrink21(V(g==l,:), a, b);
end
return
function x = norm21(u, g, Ng)
x = 0;
for l = 1:Ng,
x = x + sqrt(sum(u(g==l,:).^2, 1));
end
x = sum(x); % In case u is a matrix (i.e. not a column vector)
return
function [L,U] = factorise(A, c)
[N,M] = size(A);
% If N < M it is cheaper to factorise A*A' + cI and then use the
% matrix inversion lemma to compute the inverse of A'*A + cI
if N >= M,
[L,U] = lu(A'*A + c*eye(M,M));
else
[L,U] = lu(A*A' + c*eye(N,N));
end
return
function x = linsolve(A, c, L, U, b)
[N,M] = size(A);
if N >= M,
x = U \ (L \ b);
else
x = (b - A'*(U \ (L \ (A*b))))/c;
end
return
function opt = defaultopts(opt)
if ~isfield(opt,'Verbose'),
opt.Verbose = 0;
end
if ~isfield(opt,'MaxMainIter'),
opt.MaxMainIter = 1000;
end
if ~isfield(opt,'AbsStopTol'),
opt.AbsStopTol = 0;
end
if ~isfield(opt,'RelStopTol'),
opt.RelStopTol = 1e-4;
end
if ~isfield(opt,'Y0'),
opt.Y0 = [];
end
if ~isfield(opt,'U0'),
opt.U0 = [];
end
if ~isfield(opt,'rho'),
opt.rho = [];
end
if ~isfield(opt,'AutoRho'),
opt.AutoRho = 1;
end
if ~isfield(opt,'AutoRhoPeriod'),
opt.AutoRhoPeriod = 10;
end
if ~isfield(opt,'RhoRsdlRatio'),
opt.RhoRsdlRatio = 1.2;
end
if ~isfield(opt,'RhoScaling'),
opt.RhoScaling = 100;
end
if ~isfield(opt,'AutoRhoScaling'),
opt.AutoRhoScaling = 1;
end
if ~isfield(opt,'RhoRsdlTarget'),
opt.RhoRsdlTarget = 1;
end
if ~isfield(opt,'StdResiduals'),
opt.StdResiduals = 0;
end
if ~isfield(opt,'RelaxParam'),
opt.RelaxParam = 1.8;
end
if ~isfield(opt,'AuxVarObj'),
opt.AuxVarObj = 1;
end
return
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
bpdndl.m
|
.m
|
convolutional_sparse_coding-master/DictLearn/bpdndl.m
| 12,682 |
utf_8
|
3d5b1793a1a5f558609c6b25c38299ec
|
function [G, Y, optinf] = bpdndl(D0, S, lambda, opt)
% bpdndl -- BPDN Dictionary Learning
%
% argmin_{D,X} (1/2)||D X - S||_2^2 + lambda ||X||_1
%
% The solution is computed using Augmented Lagrangian methods
% (see boyd-2010-distributed for details).
%
% Usage:
% [D, X, optinf] = bpdndl(D0, S, lambda, opt)
%
% Input:
% D0 Initial dictionary
% S Input image
% lambda Regularization parameter
% opt Options/algorithm parameters structure (see below)
%
% Output:
% D Dictionary
% X Coefficients
% optinf Details of optimisation
%
%
% Options structure fields:
% Verbose Flag determining whether iteration status is displayed.
% Fields are iteration number, functional value,
% data fidelity term, l1 regularisation term, and
% primal and dual residuals (see Sec. 3.3 of
% boyd-2010-distributed). The values of rho and sigma
% are also displayed if options request that they are
% automatically adjusted.
% MaxMainIter Maximum main iterations
% AbsStopTol Absolute convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% RelStopTol Relative convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% L1Weight Weight matrix for L1 norm
% Y0 Initial value for Y
% U0 Initial value for U
% G0 Initial value for G (overrides D0 if specified)
% H0 Initial value for H
% rho Augmented Lagrangian penalty parameter
% AutoRho Flag determining whether rho is automatically updated
% (see Sec. 3.4.1 of boyd-2010-distributed)
% AutoRhoPeriod Iteration period on which rho is updated
% RhoRsdlRatio Primal/dual residual ratio in rho update test
% RhoScaling Multiplier applied to rho when updated
% AutoRhoScaling Flag determining whether RhoScaling value is
% adaptively determined (see wohlberg-2015-adaptive). If
% enabled, RhoScaling specifies a maximum allowed
% multiplier instead of a fixed multiplier
% sigma Augmented Lagrangian penalty parameter
% AutoSigma Flag determining whether sigma is automatically
% updated (see Sec. 3.4.1 of boyd-2010-distributed)
% AutoSigmaPeriod Iteration period on which sigma is updated
% SigmaRsdlRatio Primal/dual residual ratio in sigma update test
% SigmaScaling Multiplier applied to sigma when updated
% AutoSigmaScaling Flag determining whether SigmaScaling value is
% adaptively determined (see wohlberg-2015-adaptive). If
% enabled, SigmaScaling specifies a maximum allowed
% multiplier instead of a fixed multiplier.
% StdResiduals Flag determining whether standard residual definitions
% (see Sec 3.3 of boyd-2010-distributed) are used instead
% of normalised residuals (see wohlberg-2015-adaptive)
% XRelaxParam Relaxation parameter (see Sec. 3.4.3 of
% boyd-2010-distributed) for X update
% DRelaxParam Relaxation parameter (see Sec. 3.4.3 of
% boyd-2010-distributed) for D update
% NonNegCoef Flag indicating whether solution should be forced to
% be non-negative
% AuxVarObj Flag determining whether objective function is computed
% using the auxiliary (split) variable
% ZeroMean Force learned dictionary entries to be zero-mean
%
%
% Author: Brendt Wohlberg <[email protected]> Modified: 2015-07-30
%
% This file is part of the SPORCO library. Details of the copyright
% and user license can be found in the 'Copyright' and 'License' files
% distributed with the library.
if nargin < 4,
opt = [];
end
checkopt(opt, defaultopts([]));
opt = defaultopts(opt);
Nx = size(D0,2)*size(S,2);
Nd = prod(size(D0));
% Set up status display for verbose operation
hstr = ['Itn Fnc DFid l1 Cnstr '...
'r(X) s(X) r(D) s(D) '];
sfms = '%4d %9.2e %9.2e %9.2e %9.2e %9.2e %9.2e %9.2e %9.2e';
nsep = 84;
if opt.AutoRho,
hstr = [hstr ' rho '];
sfms = [sfms ' %9.2e'];
nsep = nsep + 10;
end
if opt.AutoSigma,
hstr = [hstr ' sigma '];
sfms = [sfms ' %9.2e'];
nsep = nsep + 10;
end
if opt.Verbose && opt.MaxMainIter > 0,
disp(hstr);
disp(char('-' * ones(1,nsep)));
end
% Mean removal and normalisation projections
Pzmn = @(x) bsxfun(@minus, x, mean(x,1));
Pnrm = @(x) normalise(x);
% Projection of dictionary filters onto constraint set
if opt.ZeroMean,
Pcn = @(x) Pnrm(Pzmn(x));
else
Pcn = @(x) Pnrm(x);
end
% Start timer
tstart = tic;
% Project initial dictionary onto constraint set
D = Pnrm(D0);
% Set up algorithm parameters and initialise variables
rho = opt.rho;
if isempty(rho), rho = 50*lambda+1; end;
sigma = opt.sigma;
if isempty(sigma), sigma = size(S,2)/200; end;
optinf = struct('itstat', [], 'opt', opt);
rx = Inf;
sx = Inf;
rd = Inf;
sd = Inf;
eprix = 0;
eduax = 0;
eprid = 0;
eduad = 0;
% Initialise main working variables
X = [];
if isempty(opt.Y0),
Y = zeros(size(D,2), size(S,2));
else
Y = opt.Y0;
end
Yprv = Y;
if isempty(opt.U0),
if isempty(opt.Y0),
U = zeros(size(D,2), size(S,2), class(S));
else
U = (lambda/rho)*sign(Y);
end
else
U = opt.U0;
end
if isempty(opt.G0),
G = D;
else
G = opt.G0;
end
Gprv = G;
if isempty(opt.H0),
if isempty(opt.G0),
H = zeros(size(G), class(S));
else
H = G;
end
else
H = opt.H0;
end
GS = G'*S;
% Main loop
k = 1;
while k <= opt.MaxMainIter && (rx > eprix|sx > eduax|rd > eprid|sd >eduad),
% Solve X subproblem, using G as the dictionary for improved stability
[luLx, luUx] = factorise(G, rho);
X = linsolveX(G, rho, luLx, luUx, GS + rho*(Y - U));
% See pg. 21 of boyd-2010-distributed
if opt.XRelaxParam == 1,
Xr = X;
else
Xr = opt.XRelaxParam*X + (1-opt.XRelaxParam)*Y;
end
% Solve Y subproblem
Y = shrink(Xr + U, (lambda/rho)*opt.L1Weight);
if opt.NonNegCoef,
Y(Y < 0) = 0;
end
SY = S*Y';
% Update dual variable corresponding to X, Y
U = U + Xr - Y;
% Compute primal and dual residuals and stopping thresholds for X update
nX = norm(X(:)); nY = norm(Y(:)); nU = norm(U(:));
if opt.StdResiduals,
% See pp. 19-20 of boyd-2010-distributed
rx = norm(vec(X - Y));
sx = norm(vec(rho*(Yprv - Y)));
eprix = sqrt(Nx)*opt.AbsStopTol+max(nX,nY)*opt.RelStopTol;
eduax = sqrt(Nx)*opt.AbsStopTol+rho*nU*opt.RelStopTol;
else
% See wohlberg-2015-adaptive
rx = norm(vec(X - Y))/max(nX,nY);
sx = norm(vec(Yprv - Y))/nU;
eprix = sqrt(Nx)*opt.AbsStopTol/max(nX,nY)+opt.RelStopTol;
eduax = sqrt(Nx)*opt.AbsStopTol/(rho*nU)+opt.RelStopTol;
end
% Solve D subproblem, using Y as the coefficients for improved stability
[luLd, luUd] = factorise(Y, sigma);
D = linsolveD(Y, sigma, luLd, luUd, SY + sigma*(G - H));
% See pg. 21 of boyd-2010-distributed
if opt.DRelaxParam == 1,
Dr = D;
else
Dr = opt.DRelaxParam*D + (1-opt.DRelaxParam)*G;
end
% Solve G subproblem
G = Pcn(Dr + H);
GS = G'*S;
% Update dual variable corresponding to D, G
H = H + Dr - G;
% Compute primal and dual residuals and stopping thresholds for D update
nD = norm(D(:)); nG = norm(G(:)); nH = norm(H(:));
if opt.StdResiduals,
% See pp. 19-20 of boyd-2010-distributed
rd = norm(vec(D - G));
sd = norm(vec(sigma*(Gprv - G)));
eprid = sqrt(Nd)*opt.AbsStopTol+max(nD,nG)*opt.RelStopTol;
eduad = sqrt(Nd)*opt.AbsStopTol+sigma*nH*opt.RelStopTol;
else
% See wohlberg-2015-adaptive
rd = norm(vec(D - G))/max(nD,nG);
sd = norm(vec(Gprv - G))/nH;
eprid = sqrt(Nd)*opt.AbsStopTol/max(nD,nG)+opt.RelStopTol;
eduad = sqrt(Nd)*opt.AbsStopTol/(sigma*nH)+opt.RelStopTol;
end
% Objective function
if opt.AuxVarObj,
Jdf = sum(vec(abs(G*Y - S).^2))/2;
Jl1 = sum(abs(vec(opt.L1Weight .* Y)));
else
Jdf = sum(vec(abs(D*X - S).^2))/2;
Jl1 = sum(abs(vec(opt.L1Weight .* X)));
end
Jfn = Jdf + lambda*Jl1;
Jcn = norm(vec(Pcn(D) - D));
% Record and display iteration details
tk = toc(tstart);
optinf.itstat = [optinf.itstat; ...
[k Jfn Jdf Jl1 rx sx rd sd eprix eduax eprid eduad rho sigma tk]];
if opt.Verbose,
dvc = [k Jfn Jdf Jl1 Jcn rx sx rd sd];
if opt.AutoRho,
dvc = [dvc rho];
end
if opt.AutoSigma,
dvc = [dvc sigma];
end
disp(sprintf(sfms, dvc));
end
% See wohlberg-2015-adaptive and pp. 20-21 of boyd-2010-distributed
if opt.AutoRho,
if k ~= 1 && mod(k, opt.AutoRhoPeriod) == 0,
if opt.AutoRhoScaling,
rhomlt = sqrt(rx/sx);
if rhomlt < 1, rhomlt = 1/rhomlt; end
if rhomlt > opt.RhoScaling, rhomlt = opt.RhoScaling; end
else
rhomlt = opt.RhoScaling;
end
rsf = 1;
if rx > opt.RhoRsdlRatio*sx, rsf = rhomlt; end
if sx > opt.RhoRsdlRatio*rx, rsf = 1/rhomlt; end
rho = rsf*rho;
U = U/rsf;
end
end
if opt.AutoSigma,
if k ~= 1 && mod(k, opt.AutoSigmaPeriod) == 0,
if opt.AutoSigmaScaling,
sigmlt = sqrt(rd/sd);
if sigmlt < 1, sigmlt = 1/sigmlt; end
if sigmlt > opt.SigmaScaling, sigmlt = opt.SigmaScaling; end
else
sigmlt = opt.SigmaScaling;
end
ssf = 1;
if rd > opt.SigmaRsdlRatio*sd, ssf = sigmlt; end
if sd > opt.SigmaRsdlRatio*rd, ssf = 1/sigmlt; end
sigma = ssf*sigma;
H = H/ssf;
end
end
Yprv = Y;
Gprv = G;
k = k + 1;
end
% Record run time and working variables
optinf.runtime = toc(tstart);
optinf.X = X;
optinf.Y = Y;
optinf.U = U;
optinf.D = D;
optinf.G = G;
optinf.H = H;
optinf.lambda = lambda;
optinf.rho = rho;
optinf.sigma = sigma;
if opt.Verbose && opt.MaxMainIter > 0,
disp(char('-' * ones(1,nsep)));
end
return
function u = vec(v)
u = v(:);
return
function u = shrink(v, lambda)
u = sign(v).*max(0, abs(v) - lambda);
return
function u = normalise(v)
vn = sqrt(sum(v.^2, 1));
vn(vn == 0) = 1;
u = bsxfun(@rdivide, v, vn);
return
function [L,U] = factorise(A, c)
[N,M] = size(A);
% If N < M it is cheaper to factorise A*A' + cI and then use the
% matrix inversion lemma to compute the inverse of A'*A + cI
if N >= M,
[L,U] = lu(A'*A + c*eye(M,M));
else
[L,U] = lu(A*A' + c*eye(N,N));
end
return
function x = linsolveX(A, c, L, U, b)
[N,M] = size(A);
if N >= M,
x = U \ (L \ b);
else
x = (b - A'*(U \ (L \ (A*b))))/c;
end
return
function x = linsolveD(A, c, L, U, b)
[N,M] = size(A);
if N >= M,
x = (b - (((b*A) / U) / L)*A')/c;
else
x = (b / U) / L;
end
return
function opt = defaultopts(opt)
if ~isfield(opt,'Verbose'),
opt.Verbose = 0;
end
if ~isfield(opt,'MaxMainIter'),
opt.MaxMainIter = 1000;
end
if ~isfield(opt,'AbsStopTol'),
opt.AbsStopTol = 1e-6;
end
if ~isfield(opt,'RelStopTol'),
opt.RelStopTol = 1e-4;
end
if ~isfield(opt,'L1Weight'),
opt.L1Weight = 1;
end
if ~isfield(opt,'Y0'),
opt.Y0 = [];
end
if ~isfield(opt,'U0'),
opt.U0 = [];
end
if ~isfield(opt,'G0'),
opt.G0 = [];
end
if ~isfield(opt,'H0'),
opt.H0 = [];
end
if ~isfield(opt,'rho'),
opt.rho = [];
end
if ~isfield(opt,'AutoRho'),
opt.AutoRho = 0;
end
if ~isfield(opt,'AutoRhoPeriod'),
opt.AutoRhoPeriod = 10;
end
if ~isfield(opt,'RhoRsdlRatio'),
opt.RhoRsdlRatio = 10;
end
if ~isfield(opt,'RhoScaling'),
opt.RhoScaling = 2;
end
if ~isfield(opt,'AutoRhoScaling'),
opt.AutoRhoScaling = 0;
end
if ~isfield(opt,'sigma'),
opt.sigma = [];
end
if ~isfield(opt,'AutoSigma'),
opt.AutoSigma = 0;
end
if ~isfield(opt,'AutoSigmaPeriod'),
opt.AutoSigmaPeriod = 10;
end
if ~isfield(opt,'SigmaRsdlRatio'),
opt.SigmaRsdlRatio = 10;
end
if ~isfield(opt,'SigmaScaling'),
opt.SigmaScaling = 2;
end
if ~isfield(opt,'AutoSigmaScaling'),
opt.AutoSigmaScaling = 0;
end
if ~isfield(opt,'StdResiduals'),
opt.StdResiduals = 0;
end
if ~isfield(opt,'XRelaxParam'),
opt.XRelaxParam = 1;
end
if ~isfield(opt,'DRelaxParam'),
opt.DRelaxParam = 1;
end
if ~isfield(opt,'NonNegCoef'),
opt.NonNegCoef = 0;
end
if ~isfield(opt,'AuxVarObj'),
opt.AuxVarObj = 1;
end
if ~isfield(opt,'ZeroMean'),
opt.ZeroMean = 0;
end
return
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
cbpdndl_rank.m
|
.m
|
convolutional_sparse_coding-master/DictLearn/cbpdndl_rank.m
| 16,753 |
utf_8
|
33a940c2af3c9d287304d391f84c4fd1
|
function [D, Y, optinf] = cbpdndl_rank(D0, S, lambda, opt)
% cbpdndl_rank -- Convolutional BPDN Dictionary Learning
%
% argmin_{x_m,d_m} (1/2) \sum_k ||\sum_m d_m * x_k,m - s_k||_2^2 +
% lambda \sum_k \sum_m ||x_k,m||_1
%
% The solution is computed using Augmented Lagrangian methods
% (see boyd-2010-distributed) with efficient solution of the
% main linear systems (see wohlberg-2014-efficient).
%
% Usage:
% [D, Y, optinf] = cbpdndl_rank(D0, S, lambda, opt)
%
% Input:
% D0 Initial dictionary
% S Input images
% lambda Regularization parameter
% opt Options/algorithm parameters structure (see below)
%
% Output:
% D Dictionary filter set (3D array)
% X Coefficient maps (4D array)
% optinf Details of optimisation
%
%
% Options structure fields:
% Verbose Flag determining whether iteration status is displayed.
% Fields are iteration number, functional value,
% data fidelity term, l1 regularisation term, and
% primal and dual residuals (see Sec. 3.3 of
% boyd-2010-distributed). The values of rho and sigma
% are also displayed if options request that they are
% automatically adjusted.
% MaxMainIter Maximum main iterations
% AbsStopTol Absolute convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% RelStopTol Relative convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% L1Weight Weight array for L1 norm
% Y0 Initial value for Y
% U0 Initial value for U
% G0 Initial value for G (overrides D0 if specified)
% H0 Initial value for H
% rho Augmented Lagrangian penalty parameter
% AutoRho Flag determining whether rho is automatically updated
% (see Sec. 3.4.1 of boyd-2010-distributed)
% AutoRhoPeriod Iteration period on which rho is updated
% RhoRsdlRatio Primal/dual residual ratio in rho update test
% RhoScaling Multiplier applied to rho when updated
% AutoRhoScaling Flag determining whether RhoScaling value is
% adaptively determined (see wohlberg-2015-adaptive). If
% enabled, RhoScaling specifies a maximum allowed
% multiplier instead of a fixed multiplier
% sigma Augmented Lagrangian penalty parameter
% AutoSigma Flag determining whether sigma is automatically
% updated (see Sec. 3.4.1 of boyd-2010-distributed)
% AutoSigmaPeriod Iteration period on which sigma is updated
% SigmaRsdlRatio Primal/dual residual ratio in sigma update test
% SigmaScaling Multiplier applied to sigma when updated
% AutoSigmaScaling Flag determining whether SigmaScaling value is
% adaptively determined (see wohlberg-2015-adaptive). If
% enabled, SigmaScaling specifies a maximum allowed
% multiplier instead of a fixed multiplier.
% StdResiduals Flag determining whether standard residual definitions
% (see Sec 3.3 of boyd-2010-distributed) are used instead
% of normalised residuals (see wohlberg-2015-adaptive)
% XRelaxParam Relaxation parameter (see Sec. 3.4.3 of
% boyd-2010-distributed) for X update
% DRelaxParam Relaxation parameter (see Sec. 3.4.3 of
% boyd-2010-distributed) for D update
% LinSolve Linear solver for main problem: 'SM' or 'CG'
% MaxCGIter Maximum CG iterations when using CG solver
% CGTol CG tolerance when using CG solver
% CGTolAuto Flag determining use of automatic CG tolerance
% CGTolFactor Factor by which primal residual is divided to obtain CG
% tolerance, when automatic tolerance is active
% NoBndryCross Flag indicating whether all solution coefficients
% corresponding to filters crossing the image boundary
% should be forced to zero.
% DictFilterSizes Array of size 2 x M where each column specifies the
% filter size (rows x columns) of the corresponding
% dictionary filter
% NonNegCoef Flag indicating whether solution should be forced to
% be non-negative
% ZeroMean Force learned dictionary entries to be zero-mean
%
%
% Author: Brendt Wohlberg <[email protected]> Modified: 2015-08-05
%
% This file is part of the SPORCO library. Details of the copyright
% and user license can be found in the 'Copyright' and 'License' files
% distributed with the library.
if nargin < 4,
opt = [];
end
checkopt(opt, defaultopts([]));
opt = defaultopts(opt);
% Set up status display for verbose operation
hstr = ['Itn Fnc DFid l1 Cnstr '...
'r(X) s(X) r(D) s(D) '];
sfms = '%4d %9.2e %9.2e %9.2e %9.2e %9.2e %9.2e %9.2e %9.2e';
nsep = 84;
if opt.AutoRho,
hstr = [hstr ' rho '];
sfms = [sfms ' %9.2e'];
nsep = nsep + 10;
end
if opt.AutoSigma,
hstr = [hstr ' sigma '];
sfms = [sfms ' %9.2e'];
nsep = nsep + 10;
end
if opt.Verbose && opt.MaxMainIter > 0,
disp(hstr);
disp(char('-' * ones(1,nsep)));
end
% Collapsing of trailing singleton dimensions greatly complicates
% handling of both SMV and MMV cases. The simplest approach would be
% if S could always be reshaped to 4d, with dimensions consisting of
% image rows, image cols, a single dimensional placeholder for number
% of filters, and number of measurements, but in the single
% measurement case the third dimension is collapsed so that the array
% is only 3d.
if size(S,3) > 1,
xsz = [size(S,1) size(S,2) size(D0,3) size(S,3)];
hrm = [1 1 1 size(S,3)];
% Insert singleton 3rd dimension (for number of filters) so that
% 4th dimension is number of images in input s volume
S = reshape(S, [size(S,1) size(S,2) 1 size(S,3)]);
else
xsz = [size(S,1) size(S,2) size(D0,3) 1];
hrm = 1;
end
xrm = [1 1 size(D0,3)];
Nx = prod(xsz);
Nd = prod(xsz(1:2))*size(D0,3);
cgt = opt.CGTol;
% Dictionary size may be specified when learning multiscale
% dictionary
if isempty(opt.DictFilterSizes),
dsz = [size(D0,1) size(D0,2)];
else
dsz = opt.DictFilterSizes;
end
% Mean removal and normalisation projections
Pzmn = @(x) bsxfun(@minus, x, mean(mean(x,1),2));
Pnrm = @(x) bsxfun(@rdivide, x, sqrt(sum(sum(x.^2, 1), 2)));
% Projection of filter to full image size and its transpose
% (zero-pad and crop respectively)
Pzp = @(x) zpad(x, xsz(1:2));
PzpT = @(x) bcrop(x, dsz);
% Projection of dictionary filters onto constraint set
if opt.ZeroMean,
Pcn = @(x) Pnrm(Pzp(Pzmn(PzpT(x))));
else
Pcn = @(x) Pnrm(Pzp(PzpT(x)));
end
% Start timer
tstart = tic;
% Project initial dictionary onto constraint set
D = Pnrm(D0);
% Compute signal in DFT domain
Sf = fft2(S);
% Set up algorithm parameters and initialise variables
rho = opt.rho;
if isempty(rho), rho = 50*lambda+1; end;
if opt.AutoRho,
asgr = opt.RhoRsdlRatio;
asgm = opt.RhoScaling;
end
sigma = opt.sigma;
if isempty(sigma), sigma = size(S,3); end;
if opt.AutoSigma,
asdr = opt.SigmaRsdlRatio;
asdm = opt.SigmaScaling;
end
optinf = struct('itstat', [], 'opt', opt);
rx = Inf;
sx = Inf;
rd = Inf;
sd = Inf;
eprix = 0;
eduax = 0;
eprid = 0;
eduad = 0;
% Initialise main working variables
X = [];
if isempty(opt.Y0),
Y = zeros(xsz, class(S));
else
Y = opt.Y0;
end
Yprv = Y;
if isempty(opt.U0),
if isempty(opt.Y0),
U = zeros(xsz, class(S));
else
U = (lambda/rho)*sign(Y);
end
else
U = opt.U0;
end
Df = [];
if isempty(opt.G0),
G = Pzp(D);
else
G = opt.G0;
end
Gprv = G;
if isempty(opt.H0),
if isempty(opt.G0),
H = zeros(size(G), class(S));
else
H = G;
end
else
H = opt.H0;
end
Gf = fft2(G, size(S,1), size(S,2));
GSf = bsxfun(@times, conj(Gf), Sf);
% Main loop
k = 1;
while k <= opt.MaxMainIter && (rx > eprix|sx > eduax|rd > eprid|sd >eduad),
% Solve X subproblem. It would be simpler and more efficient (since the
% DFT is already available) to solve for X using the main dictionary
% variable D as the dictionary, but this appears to be unstable. Instead,
% use the projected dictionary variable G
Xf = solvedbi_sm(Gf, rho, GSf + rho*fft2(Y - U));
X = ifft2(Xf, 'symmetric');
clear Xf Gf GSf;
% See pg. 21 of boyd-2010-distributed
if opt.XRelaxParam == 1,
Xr = X;
else
Xr = opt.XRelaxParam*X + (1-opt.XRelaxParam)*Y;
end
% Solve Y subproblem
% Y = shrink(Xr + U, (lambda/rho)*opt.L1Weight);
Y = Do(lambda/rho, Xr+U);
if opt.NonNegCoef,
Y(Y < 0) = 0;
end
if opt.NoBndryCross,
Y((end-max(dsz(1,:)) +2):end,:,:,:) = 0;
Y(:,(end-max(dsz(2,:))+2):end,:,:) = 0;
end
Yf = fft2(Y);
YSf = sum(bsxfun(@times, conj(Yf), Sf), 4);
% Update dual variable corresponding to X, Y
U = U + Xr - Y;
clear Xr;
% Compute primal and dual residuals and stopping thresholds for X update
nX = norm(X(:)); nY = norm(Y(:)); nU = norm(U(:));
if opt.StdResiduals,
% See pp. 19-20 of boyd-2010-distributed
rx = norm(vec(X - Y));
sx = norm(vec(rho*(Yprv - Y)));
eprix = sqrt(Nx)*opt.AbsStopTol+max(nX,nY)*opt.RelStopTol;
eduax = sqrt(Nx)*opt.AbsStopTol+rho*nU*opt.RelStopTol;
else
% See wohlberg-2015-adaptive
rx = norm(vec(X - Y))/max(nX,nY);
sx = norm(vec(Yprv - Y))/nU;
eprix = sqrt(Nx)*opt.AbsStopTol/max(nX,nY)+opt.RelStopTol;
eduax = sqrt(Nx)*opt.AbsStopTol/(rho*nU)+opt.RelStopTol;
end
clear X;
% Compute l1 norm of Y
Jl1 = sum(abs(vec(bsxfun(@times, opt.L1Weight, Y))));
% Update record of previous step Y
Yprv = Y;
% Solve D subproblem. Similarly, it would be simpler and more efficient to
% solve for D using the main coefficient variable X as the coefficients,
% but it appears to be more stable to use the shrunk coefficient variable Y
if strcmp(opt.LinSolve, 'SM'),
Df = solvemdbi_ism(Yf, sigma, YSf + sigma*fft2(G - H));
else
[Df, cgst] = solvemdbi_cg(Yf, sigma, YSf + sigma*fft2(G - H), ...
cgt, opt.MaxCGIter, Df(:));
end
clear YSf;
D = ifft2(Df, 'symmetric');
if strcmp(opt.LinSolve, 'SM'), clear Df; end
% See pg. 21 of boyd-2010-distributed
if opt.DRelaxParam == 1,
Dr = D;
else
Dr = opt.DRelaxParam*D + (1-opt.DRelaxParam)*G;
end
% Solve G subproblem
G = Pcn(Dr + H);
Gf = fft2(G);
GSf = bsxfun(@times, conj(Gf), Sf);
% Update dual variable corresponding to D, G
H = H + Dr - G;
clear Dr;
% Compute primal and dual residuals and stopping thresholds for D update
nD = norm(D(:)); nG = norm(G(:)); nH = norm(H(:));
if opt.StdResiduals,
% See pp. 19-20 of boyd-2010-distributed
rd = norm(vec(D - G));
sd = norm(vec(sigma*(Gprv - G)));
eprid = sqrt(Nd)*opt.AbsStopTol+max(nD,nG)*opt.RelStopTol;
eduad = sqrt(Nd)*opt.AbsStopTol+sigma*nH*opt.RelStopTol;
else
% See wohlberg-2015-adaptive
rd = norm(vec(D - G))/max(nD,nG);
sd = norm(vec(Gprv - G))/nH;
eprid = sqrt(Nd)*opt.AbsStopTol/max(nD,nG)+opt.RelStopTol;
eduad = sqrt(Nd)*opt.AbsStopTol/(sigma*nH)+opt.RelStopTol;
end
% Apply CG auto tolerance policy if enabled
if opt.CGTolAuto && (rd/opt.CGTolFactor) < cgt,
cgt = rd/opt.CGTolFactor;
end
% Compute measure of D constraint violation
Jcn = norm(vec(Pcn(D) - D));
clear D;
% Update record of previous step G
Gprv = G;
% Compute data fidelity term in Fourier domain (note normalisation)
Jdf = sum(vec(abs(sum(bsxfun(@times,Gf,Yf),3)-Sf).^2))/(2*xsz(1)*xsz(2));
clear Yf;
Jfn = Jdf + lambda*Jl1;
% Record and display iteration details
tk = toc(tstart);
optinf.itstat = [optinf.itstat;...
[k Jfn Jdf Jl1 rx sx rd sd eprix eduax eprid eduad rho sigma tk]];
if opt.Verbose,
dvc = [k, Jfn, Jdf, Jl1, Jcn, rx, sx, rd, sd];
if opt.AutoRho,
dvc = [dvc rho];
end
if opt.AutoSigma,
dvc = [dvc sigma];
end
disp(sprintf(sfms, dvc));
end
% See wohlberg-2015-adaptive and pp. 20-21 of boyd-2010-distributed
if opt.AutoRho,
if k ~= 1 && mod(k, opt.AutoRhoPeriod) == 0,
if opt.AutoRhoScaling,
rhomlt = sqrt(rx/sx);
if rhomlt < 1, rhomlt = 1/rhomlt; end
if rhomlt > opt.RhoScaling, rhomlt = opt.RhoScaling; end
else
rhomlt = opt.RhoScaling;
end
rsf = 1;
if rx > opt.RhoRsdlRatio*sx, rsf = rhomlt; end
if sx > opt.RhoRsdlRatio*rx, rsf = 1/rhomlt; end
rho = rsf*rho;
U = U/rsf;
end
end
if opt.AutoSigma,
if k ~= 1 && mod(k, opt.AutoSigmaPeriod) == 0,
if opt.AutoSigmaScaling,
sigmlt = sqrt(rd/sd);
if sigmlt < 1, sigmlt = 1/sigmlt; end
if sigmlt > opt.SigmaScaling, sigmlt = opt.SigmaScaling; end
else
sigmlt = opt.SigmaScaling;
end
ssf = 1;
if rd > opt.SigmaRsdlRatio*sd, ssf = sigmlt; end
if sd > opt.SigmaRsdlRatio*rd, ssf = 1/sigmlt; end
sigma = ssf*sigma;
H = H/ssf;
end
end
k = k + 1;
end
D = PzpT(G);
% Record run time and working variables
optinf.runtime = toc(tstart);
optinf.Y = Y;
optinf.U = U;
optinf.G = G;
optinf.H = H;
optinf.lambda = lambda;
optinf.rho = rho;
optinf.sigma = sigma;
optinf.cgt = cgt;
if exist('cgst'), optinf.cgst = cgst; end
if opt.Verbose && opt.MaxMainIter > 0,
disp(char('-' * ones(1,nsep)));
end
return
function u = vec(v)
u = v(:);
return
function u = shrink(v, lambda)
if isscalar(lambda),
u = sign(v).*max(0, abs(v) - lambda);
else
u = sign(v).*max(0, bsxfun(@minus, abs(v), lambda));
end
return
function r = Do(tau, X)
% shrinkage operator for singular values
for i=1:size(X,3)
for j=1:size(X,4)
[U, S, V] = svd(X(:,:,i,j), 'econ');
r(:,:,i,j)= U*So(tau, S)*V';
end
end
return
function r = So(tau, X)
% shrinkage operator
r = sign(X) .* max(abs(X) - tau, 0);
return
function u = zpad(v, sz)
u = zeros(sz(1), sz(2), size(v,3), size(v,4), class(v));
u(1:size(v,1), 1:size(v,2),:,:) = v;
return
function u = bcrop(v, sz)
if numel(sz) <= 2,
if numel(sz) == 1
cs = [sz sz];
else
cs = sz;
end
u = v(1:cs(1), 1:cs(2), :);
else
cs = max(sz,[],2);
u = zeros(cs(1), cs(2), size(v,3), class(v));
for k = 1:size(v,3),
u(1:sz(1,k), 1:sz(2,k), k) = v(1:sz(1,k), 1:sz(2,k), k);
end
end
return
function opt = defaultopts(opt)
if ~isfield(opt,'Verbose'),
opt.Verbose = 0;
end
if ~isfield(opt,'MaxMainIter'),
opt.MaxMainIter = 1000;
end
if ~isfield(opt,'AbsStopTol'),
opt.AbsStopTol = 1e-6;
end
if ~isfield(opt,'RelStopTol'),
opt.RelStopTol = 1e-4;
end
if ~isfield(opt,'L1Weight'),
opt.L1Weight = 1;
end
if ~isfield(opt,'Y0'),
opt.Y0 = [];
end
if ~isfield(opt,'U0'),
opt.U0 = [];
end
if ~isfield(opt,'G0'),
opt.G0 = [];
end
if ~isfield(opt,'H0'),
opt.H0 = [];
end
if ~isfield(opt,'rho'),
opt.rho = [];
end
if ~isfield(opt,'AutoRho'),
opt.AutoRho = 0;
end
if ~isfield(opt,'AutoRhoPeriod'),
opt.AutoRhoPeriod = 10;
end
if ~isfield(opt,'RhoRsdlRatio'),
opt.RhoRsdlRatio = 10;
end
if ~isfield(opt,'RhoScaling'),
opt.RhoScaling = 2;
end
if ~isfield(opt,'AutoRhoScaling'),
opt.AutoRhoScaling = 0;
end
if ~isfield(opt,'sigma'),
opt.sigma = [];
end
if ~isfield(opt,'AutoSigma'),
opt.AutoSigma = 0;
end
if ~isfield(opt,'AutoSigmaPeriod'),
opt.AutoSigmaPeriod = 10;
end
if ~isfield(opt,'SigmaRsdlRatio'),
opt.SigmaRsdlRatio = 10;
end
if ~isfield(opt,'SigmaScaling'),
opt.SigmaScaling = 2;
end
if ~isfield(opt,'AutoSigmaScaling'),
opt.AutoSigmaScaling = 0;
end
if ~isfield(opt,'StdResiduals'),
opt.StdResiduals = 0;
end
if ~isfield(opt,'XRelaxParam'),
opt.XRelaxParam = 1;
end
if ~isfield(opt,'DRelaxParam'),
opt.DRelaxParam = 1;
end
if ~isfield(opt,'LinSolve'),
opt.LinSolve = 'SM';
end
if ~isfield(opt,'MaxCGIter'),
opt.MaxCGIter = 1000;
end
if ~isfield(opt,'CGTol'),
opt.CGTol = 1e-3;
end
if ~isfield(opt,'CGTolAuto'),
opt.CGTolAuto = 0;
end
if ~isfield(opt,'CGTolAutoFactor'),
opt.CGTolFactor = 50;
end
if ~isfield(opt,'NoBndryCross'),
opt.NoBndryCross = 0;
end
if ~isfield(opt,'DictFilterSizes'),
opt.DictFilterSizes = [];
end
if ~isfield(opt,'NonNegCoef'),
opt.NonNegCoef = 0;
end
if ~isfield(opt,'ZeroMean'),
opt.ZeroMean = 0;
end
return
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
cbpdndl_rank_gpu.m
|
.m
|
convolutional_sparse_coding-master/DictLearn/cbpdndl_rank_gpu.m
| 17,919 |
utf_8
|
dc940180f1ad1ba4b8b672ccf6bd04fc
|
function [D, Y, optinf] = cbpdndl_rank_gpu(D0, S, lambda, opt)
% cbpdndl_rank_gpu -- Convolutional BPDN Dictionary Learning
%
% argmin_{x_m,d_m} (1/2) \sum_k ||\sum_m d_m * x_k,m - s_k||_2^2 +
% lambda \sum_k \sum_m ||x_k,m||_1
%
% The solution is computed using Augmented Lagrangian methods
% (see boyd-2010-distributed) with efficient solution of the
% main linear systems (see wohlberg-2014-efficient).
%
% Usage:
% [D, Y, optinf] = cbpdndl_rank_gpu(D0, S, lambda, opt)
%
% Input:
% D0 Initial dictionary
% S Input images
% lambda Regularization parameter
% opt Options/algorithm parameters structure (see below)
%
% Output:
% D Dictionary filter set (3D array)
% X Coefficient maps (4D array)
% optinf Details of optimisation
%
%
% Options structure fields:
% Verbose Flag determining whether iteration status is displayed.
% Fields are iteration number, functional value,
% data fidelity term, l1 regularisation term, and
% primal and dual residuals (see Sec. 3.3 of
% boyd-2010-distributed). The values of rho and sigma
% are also displayed if options request that they are
% automatically adjusted.
% MaxMainIter Maximum main iterations
% AbsStopTol Absolute convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% RelStopTol Relative convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% L1Weight Weight array for L1 norm
% Y0 Initial value for Y
% U0 Initial value for U
% G0 Initial value for G (overrides D0 if specified)
% H0 Initial value for H
% rho Augmented Lagrangian penalty parameter
% AutoRho Flag determining whether rho is automatically updated
% (see Sec. 3.4.1 of boyd-2010-distributed)
% AutoRhoPeriod Iteration period on which rho is updated
% RhoRsdlRatio Primal/dual residual ratio in rho update test
% RhoScaling Multiplier applied to rho when updated
% AutoRhoScaling Flag determining whether RhoScaling value is
% adaptively determined (see wohlberg-2015-adaptive). If
% enabled, RhoScaling specifies a maximum allowed
% multiplier instead of a fixed multiplier
% sigma Augmented Lagrangian penalty parameter
% AutoSigma Flag determining whether sigma is automatically
% updated (see Sec. 3.4.1 of boyd-2010-distributed)
% AutoSigmaPeriod Iteration period on which sigma is updated
% SigmaRsdlRatio Primal/dual residual ratio in sigma update test
% SigmaScaling Multiplier applied to sigma when updated
% AutoSigmaScaling Flag determining whether SigmaScaling value is
% adaptively determined (see wohlberg-2015-adaptive). If
% enabled, SigmaScaling specifies a maximum allowed
% multiplier instead of a fixed multiplier.
% StdResiduals Flag determining whether standard residual definitions
% (see Sec 3.3 of boyd-2010-distributed) are used instead
% of normalised residuals (see wohlberg-2015-adaptive)
% XRelaxParam Relaxation parameter (see Sec. 3.4.3 of
% boyd-2010-distributed) for X update
% DRelaxParam Relaxation parameter (see Sec. 3.4.3 of
% boyd-2010-distributed) for D update
% LinSolve Linear solver for main problem: 'SM' or 'CG'
% MaxCGIter Maximum CG iterations when using CG solver
% CGTol CG tolerance when using CG solver
% CGTolAuto Flag determining use of automatic CG tolerance
% CGTolFactor Factor by which primal residual is divided to obtain CG
% tolerance, when automatic tolerance is active
% NoBndryCross Flag indicating whether all solution coefficients
% corresponding to filters crossing the image boundary
% should be forced to zero.
% DictFilterSizes Array of size 2 x M where each column specifies the
% filter size (rows x columns) of the corresponding
% dictionary filter
% NonNegCoef Flag indicating whether solution should be forced to
% be non-negative
% ZeroMean Force learned dictionary entries to be zero-mean
%
%
% Author: Brendt Wohlberg <[email protected]> Modified: 2015-08-05
%
% This file is part of the SPORCO library. Details of the copyright
% and user license can be found in the 'Copyright' and 'License' files
% distributed with the library.
gS = gpuArray(S);
gD = gpuArray(D0);
glambda = gpuArray(lambda);
if nargin < 4,
opt = [];
end
checkopt(opt, defaultopts([]));
opt = defaultopts(opt);
% Set up status display for verbose operation
hstr = ['Itn Fnc DFid l1 Cnstr '...
'r(X) s(X) r(D) s(D) '];
sfms = '%4d %9.2e %9.2e %9.2e %9.2e %9.2e %9.2e %9.2e %9.2e';
nsep = 84;
if opt.AutoRho,
hstr = [hstr ' rho '];
sfms = [sfms ' %9.2e'];
nsep = nsep + 10;
end
if opt.AutoSigma,
hstr = [hstr ' sigma '];
sfms = [sfms ' %9.2e'];
nsep = nsep + 10;
end
if opt.Verbose && opt.MaxMainIter > 0
disp(hstr);
disp(char('-' * ones(1,nsep)));
end
% Collapsing of trailing singleton dimensions greatly complicates
% handling of both SMV and MMV cases. The simplest approach would be
% if S could always be reshaped to 4d, with dimensions consisting of
% image rows, image cols, a single dimensional placeholder for number
% of filters, and number of measurements, but in the single
% measurement case the third dimension is collapsed so that the array
% is only 3d.
if size(S,3) > 1
xsz = [size(S,1) size(S,2) size(D0,3) size(S,3)];
hrm = [1 1 1 size(S,3)];
% Insert singleton 3rd dimension (for number of filters) so that
% 4th dimension is number of images in input s volume
gS = gpuArray(reshape(gS, [size(S,1) size(S,2) 1 size(S,3)]));
else
xsz = [size(S,1) size(S,2) size(D0,3) 1];
hrm = 1;
end
xrm = [1 1 size(D0,3)];
gxrm = gpuArray(xrm);
gNx = gpuArray(prod(xsz));
gNd = gpuArray(prod(xsz(1:2))*size(D0,3));cgt = opt.CGTol;
gcgt = gpuArray(opt.CGTol);
% Dictionary size may be specified when learning multiscale
% dictionary
if isempty(opt.DictFilterSizes),
dsz = [size(D0,1) size(D0,2)];
else
dsz = opt.DictFilterSizes;
end
% Mean removal and normalisation projections
Pzmn = @(x) bsxfun(@minus, x, mean(mean(x,1),2));
Pnrm = @(x) bsxfun(@rdivide, x, sqrt(sum(sum(x.^2, 1), 2)));
% Projection of filter to full image size and its transpose
% (zero-pad and crop respectively)
Pzp = @(x) zpad(x, xsz(1:2));
PzpT = @(x) bcrop(x, dsz);
% Projection of dictionary filters onto constraint set
if opt.ZeroMean,
Pcn = @(x) Pnrm(Pzp(Pzmn(PzpT(x))));
else
Pcn = @(x) Pnrm(Pzp(PzpT(x)));
end
% Start timer
tstart = tic;
% Project initial dictionary onto constraint set
% D = Pnrm(D0);
gD = Pnrm(gD);
% Compute signal in DFT domain
gSf = fft2(gS);
% Set up algorithm parameters and initialise variables
grho = gpuArray(opt.rho);
if isempty(grho), grho = 50*glambda+1; end;
if opt.AutoRho,
asgr = opt.RhoRsdlRatio;
asgm = opt.RhoScaling;
end
gsigma = gpuArray(opt.sigma);
if isempty(gsigma), gsigma = gpuArray(size(S,3)); end;
if opt.AutoSigma,
asdr = opt.SigmaRsdlRatio;
asdm = opt.SigmaScaling;
end
optinf = struct('itstat', [], 'opt', opt);
grx = gpuArray(Inf);
gsx = gpuArray(Inf);
grd = gpuArray(Inf);
gsd = gpuArray(Inf);
geprix = gpuArray(0);
geduax = gpuArray(0);
geprid = gpuArray(0);
geduad = gpuArray(0);
% Initialise main working variables
if isempty(opt.Y0),
gY = gpuArray.zeros(xsz, class(S));
else
gY = gpuArray(opt.Y0);
end
gYprv = gY;
if isempty(opt.U0)
if isempty(opt.Y0)
gU = gpuArray.zeros(xsz, class(S));
else
gU = (glambda/grho)*sign(gY);
end
else
gU = gpuArray(opt.U0);
end
if isempty(opt.G0),
gG = Pzp(gD);
else
gG = gpuArray(opt.G0);
end
gGprv = gG;
if isempty(opt.H0),
if isempty(opt.G0),
gH = gpuArray.zeros(size(gG), class(S));
else
gH = gG;
end
else
gH = gpuArray(opt.H0);
end
gGf = fft2(gG, size(S,1), size(S,2));
gGSf = bsxfun(@times, conj(gGf), gSf);
% Main loop
k = 1;
while k <= opt.MaxMainIter && (grx > geprix|gsx > geduax|...
grd > geprid|gsd >geduad),
% Solve X subproblem. It would be simpler and more efficient (since the
% DFT is already available) to solve for X using the main dictionary
% variable D as the dictionary, but this appears to be unstable. Instead,
% use the projected dictionary variable G
gXf = solvedbi_sm(gGf, grho, gGSf + grho*fft2(gY - gU));
gX = ifft2(gXf, 'symmetric');
clear gXf gGf gGSf;
% See pg. 21 of boyd-2010-distributed
if opt.XRelaxParam == 1,
gXr = gX;
else
gXr = opt.XRelaxParam*gX + (1-opt.XRelaxParam)*gY;
end
% Solve Y subproblem
gY = Do(glambda/grho, gXr+gU);
if opt.NonNegCoef,
gY(gY < 0) = 0;
end
if opt.NoBndryCross,
gY((end-max(dsz(1,:)) +2):end,:,:,:) = 0;
gY(:,(end-max(dsz(2,:))+2):end,:,:) = 0;
end
gYf = fft2(gY);
gYSf = sum(bsxfun(@times, conj(gYf), gSf), 4);
% Update dual variable corresponding to X, Y
gU =gU + gXr - gY;
clear gXr;
% Compute primal and dual residuals and stopping thresholds for X update
gnX = norm(gX(:)); gnY = norm(gY(:)); gnU = norm(gU(:));
if opt.StdResiduals,
% See pp. 19-20 of boyd-2010-distributed
grx = norm(vec(gX - gY));
gsx = norm(vec(grho*(gYprv - gY)));
geprix = sqrt(gNx)*opt.AbsStopTol+max(gnX,gnY)*opt.RelStopTol;
geduax = sqrt(gNx)*opt.AbsStopTol+grho*gnU*opt.RelStopTol;
else
% See wohlberg-2015-adaptive
grx = norm(vec(gX - gY))/max(gnX,gnY);
gsx = norm(vec(gYprv - gY))/gnU;
geprix = sqrt(gNx)*opt.AbsStopTol/max(gnX,gnY)+opt.RelStopTol;
geduax = sqrt(gNx)*opt.AbsStopTol/(grho*gnU)+opt.RelStopTol;
end
clear gX;
% Compute l1 norm of Y
gJl1 = sum(abs(vec(opt.L1Weight .* gY)));
% Update record of previous step Y
gYprv = gY;
% Solve D subproblem. Similarly, it would be simpler and more efficient to
% solve for D using the main coefficient variable X as the coefficients,
% but it appears to be more stable to use the shrunk coefficient variable Y
if strcmp(opt.LinSolve, 'SM'),
gDf = solvemdbi_ism_gpu(gYf, gsigma, gYSf + gsigma*fft2(gG - gH));
else
[gDf, gcgst] = solvemdbi_cg(gYf, gsigma, gYSf + gsigma*fft2(gG - gH), ...
gcgt, opt.MaxCGIter, gDf(:));
end
clear YSf;
gD = ifft2(gDf, 'symmetric');
if strcmp(opt.LinSolve, 'SM'), clear gDf; end
% See pg. 21 of boyd-2010-distributed
if opt.DRelaxParam == 1,
gDr = gD;
else
gDr = opt.DRelaxParam*gD + (1-opt.DRelaxParam)*gG;
end
% Solve G subproblem
gG = Pcn(gDr + gH);
gGf = fft2(gG);
gGSf = bsxfun(@times, conj(gGf), gSf);
% Update dual variable corresponding to D, G
gH = gH + gDr - gG;
clear gDr;
% Compute primal and dual residuals and stopping thresholds for D update
gnD = norm(gD(:)); gnG = norm(gG(:)); gnH = norm(gH(:));
if opt.StdResiduals,
% See pp. 19-20 of boyd-2010-distributed
grd = norm(vec(gD - gG));
gsd = norm(vec(sigma*(gGprv - gG)));
geprid = sqrt(gNd)*opt.AbsStopTol+max(gnD,gnG)*opt.RelStopTol;
geduad = sqrt(gNd)*opt.AbsStopTol+gsigma*gnH*opt.RelStopTol;
else
% See wohlberg-2015-adaptive
grd = norm(vec(gD - gG))/max(gnD,gnG);
gsd = norm(vec(gGprv - gG))/gnH;
geprid = sqrt(gNd)*opt.AbsStopTol/max(gnD,gnG)+opt.RelStopTol;
geduad = sqrt(gNd)*opt.AbsStopTol/(gsigma*gnH)+opt.RelStopTol;
end
% Apply CG auto tolerance policy if enabled
if opt.CGTolAuto && (grd/opt.CGTolFactor) < gcgt,
gcgt = grd/opt.CGTolFactor;
end
% Compute measure of D constraint violation
gJcn = norm(vec(Pcn(gD) - gD));
clear gD;
% Update record of previous step G
gGprv = gG;
% Compute data fidelity term in Fourier domain (note normalisation)
gJdf = sum(vec(abs(sum(bsxfun(@times,gGf,gYf),3)-gSf).^2))/(2*xsz(1)*xsz(2));
clear gYf;
gJfn = gJdf + glambda*gJl1;
% Record and display iteration details
tk = toc(tstart);
optinf.itstat = [optinf.itstat;...
[k gather(gJfn) gather(gJdf) gather(gJl1) gather(grx) gather(gsx)...
gather(grd) gather(gsd) gather(geprix) gather(geduax) gather(geprid)...
gather(geduad) gather(grho) gather(gsigma) tk]];
if opt.Verbose
dvc = [k, gather(gJfn), gather(gJdf), gather(gJl1) gather(gJcn), ...
gather(grx), gather(gsx), gather(grd), gather(gsd)];
if opt.AutoRho,
dvc = [dvc gather(grho)];
end
if opt.AutoSigma,
dvc = [dvc gather(gsigma)];
end
disp(sprintf(sfms, dvc));
end
% See wohlberg-2015-adaptive and pp. 20-21 of boyd-2010-distributed
if opt.AutoRho,
if k ~= 1 && mod(k, opt.AutoRhoPeriod) == 0,
if opt.AutoRhoScaling,
grhomlt = sqrt(grx/gsx);
if grhomlt < 1, grhomlt = 1/grhomlt; end
if grhomlt > opt.RhoScaling, grhomlt = gpuArray(opt.RhoScaling); end
else
grhomlt = gpuArray(opt.RhoScaling);
end
grsf = 1;
if grx > opt.RhoRsdlRatio*gsx, grsf = grhomlt; end
if gsx > opt.RhoRsdlRatio*grx, grsf = 1/grhomlt; end
grho = grsf*grho;
gU = gU/grsf;
end
end
if opt.AutoSigma,
if k ~= 1 && mod(k, opt.AutoSigmaPeriod) == 0,
if opt.AutoSigmaScaling,
gsigmlt = sqrt(grd/gsd);
if gsigmlt < 1, gsigmlt = 1/gsigmlt; end
if gsigmlt > opt.SigmaScaling, gsigmlt = gpuArray(opt.SigmaScaling); end
else
gsigmlt = gpuArray(opt.SigmaScaling);
end
gssf = gpuArray(1);
if grd > opt.SigmaRsdlRatio*gsd, gssf = gsigmlt; end
if gsd > opt.SigmaRsdlRatio*grd, gssf = 1/gsigmlt; end
gsigma = gssf*gsigma;
gH = gH/gssf;
end
end
k = k + 1;
end
gD = PzpT(gG);
% Record run time and working variables
optinf.runtime = toc(tstart);
optinf.Y = gather(gY);
optinf.U = gather(gU);
optinf.G = gather(gG);
optinf.H = gather(gH);
optinf.lambda = gather(glambda);
optinf.rho = gather(grho);
optinf.sigma = gather(gsigma);
optinf.cgt = gather(gcgt);
if exist('gcgst'), optinf.cgst = gather(gcgst); end
D = gather(gD);
Y = optinf.Y;
if opt.Verbose && opt.MaxMainIter > 0,
disp(char('-' * ones(1,nsep)));
end
return
function u = vec(v)
u = v(:);
return
function u = shrink(v, lambda)
u = sign(v).*max(0, abs(v) - lambda);
return
function u = zpad(v, sz)
% u = zeros(sz(1), sz(2), size(v,3), size(v,4), class(v));
u = gpuArray.zeros(sz(1), sz(2), size(v,3), size(v,4));
u(1:size(v,1), 1:size(v,2),:,:) = v;
return
function u = bcrop(v, sz)
if numel(sz) <= 2,
if numel(sz) == 1
cs = [sz sz];
else
cs = sz;
end
u = v(1:cs(1), 1:cs(2), :);
else
if size(sz,1) < size(sz,2), sz = sz'; end
cs = max(sz);
% u = zeros(cs(1), cs(2), size(v,3), class(v));
u = gpuArray.zeros(cs(1), cs(2), size(v,3));
for k = 1:size(v,3),
u(1:sz(k,1), 1:sz(k,2), k) = v(1:sz(k,1), 1:sz(k,2), k);
end
end
return
function opt = defaultopts(opt)
if ~isfield(opt,'Verbose')
opt.Verbose = 0;
end
if ~isfield(opt,'MaxMainIter'),
opt.MaxMainIter = 1000;
end
if ~isfield(opt,'AbsStopTol'),
opt.AbsStopTol = 1e-6;
end
if ~isfield(opt,'RelStopTol'),
opt.RelStopTol = 1e-4;
end
if ~isfield(opt,'L1Weight'),
opt.L1Weight = 1;
end
if ~isfield(opt,'Y0'),
opt.Y0 = [];
end
if ~isfield(opt,'U0'),
opt.U0 = [];
end
if ~isfield(opt,'G0'),
opt.G0 = [];
end
if ~isfield(opt,'H0'),
opt.H0 = [];
end
if ~isfield(opt,'rho'),
opt.rho = [];
end
if ~isfield(opt,'AutoRho'),
opt.AutoRho = 0;
end
if ~isfield(opt,'AutoRhoPeriod'),
opt.AutoRhoPeriod = 10;
end
if ~isfield(opt,'RhoRsdlRatio'),
opt.RhoRsdlRatio = 10;
end
if ~isfield(opt,'RhoScaling'),
opt.RhoScaling = 2;
end
if ~isfield(opt,'AutoRhoScaling'),
opt.AutoRhoScaling = 0;
end
if ~isfield(opt,'sigma'),
opt.sigma = [];
end
if ~isfield(opt,'AutoSigma'),
opt.AutoSigma = 0;
end
if ~isfield(opt,'AutoSigmaPeriod'),
opt.AutoSigmaPeriod = 10;
end
if ~isfield(opt,'SigmaRsdlRatio'),
opt.SigmaRsdlRatio = 10;
end
if ~isfield(opt,'SigmaScaling'),
opt.SigmaScaling = 2;
end
if ~isfield(opt,'AutoSigmaScaling'),
opt.AutoSigmaScaling = 0;
end
if ~isfield(opt,'StdResiduals'),
opt.StdResiduals = 0;
end
if ~isfield(opt,'XRelaxParam'),
opt.XRelaxParam = 1;
end
if ~isfield(opt,'DRelaxParam'),
opt.DRelaxParam = 1;
end
if ~isfield(opt,'LinSolve'),
opt.LinSolve = 'SM';
end
if ~isfield(opt,'MaxCGIter'),
opt.MaxCGIter = 1000;
end
if ~isfield(opt,'CGTol'),
opt.CGTol = 1e-3;
end
if ~isfield(opt,'CGTolAuto'),
opt.CGTolAuto = 0;
end
if ~isfield(opt,'CGTolAutoFactor'),
opt.CGTolFactor = 50;
end
if ~isfield(opt,'NoBndryCross'),
opt.NoBndryCross = 0;
end
if ~isfield(opt,'DictFilterSizes'),
opt.DictFilterSizes = [];
end
if ~isfield(opt,'ZeroMean'),
opt.ZeroMean = 0;
end
return
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
cbpdndl.m
|
.m
|
convolutional_sparse_coding-master/DictLearn/cbpdndl.m
| 16,388 |
utf_8
|
960792294ced2b7a9f82104bc944bdeb
|
function [D, Y, optinf] = cbpdndl(D0, S, lambda, opt)
% cbpdndl -- Convolutional BPDN Dictionary Learning
%
% argmin_{x_m,d_m} (1/2) \sum_k ||\sum_m d_m * x_k,m - s_k||_2^2 +
% lambda \sum_k \sum_m ||x_k,m||_1
%
% The solution is computed using Augmented Lagrangian methods
% (see boyd-2010-distributed) with efficient solution of the
% main linear systems (see wohlberg-2014-efficient).
%
% Usage:
% [D, Y, optinf] = cbpdndl(D0, S, lambda, opt)
%
% Input:
% D0 Initial dictionary
% S Input images
% lambda Regularization parameter
% opt Options/algorithm parameters structure (see below)
%
% Output:
% D Dictionary filter set (3D array)
% X Coefficient maps (4D array)
% optinf Details of optimisation
%
%
% Options structure fields:
% Verbose Flag determining whether iteration status is displayed.
% Fields are iteration number, functional value,
% data fidelity term, l1 regularisation term, and
% primal and dual residuals (see Sec. 3.3 of
% boyd-2010-distributed). The values of rho and sigma
% are also displayed if options request that they are
% automatically adjusted.
% MaxMainIter Maximum main iterations
% AbsStopTol Absolute convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% RelStopTol Relative convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% L1Weight Weight array for L1 norm
% Y0 Initial value for Y
% U0 Initial value for U
% G0 Initial value for G (overrides D0 if specified)
% H0 Initial value for H
% rho Augmented Lagrangian penalty parameter
% AutoRho Flag determining whether rho is automatically updated
% (see Sec. 3.4.1 of boyd-2010-distributed)
% AutoRhoPeriod Iteration period on which rho is updated
% RhoRsdlRatio Primal/dual residual ratio in rho update test
% RhoScaling Multiplier applied to rho when updated
% AutoRhoScaling Flag determining whether RhoScaling value is
% adaptively determined (see wohlberg-2015-adaptive). If
% enabled, RhoScaling specifies a maximum allowed
% multiplier instead of a fixed multiplier
% sigma Augmented Lagrangian penalty parameter
% AutoSigma Flag determining whether sigma is automatically
% updated (see Sec. 3.4.1 of boyd-2010-distributed)
% AutoSigmaPeriod Iteration period on which sigma is updated
% SigmaRsdlRatio Primal/dual residual ratio in sigma update test
% SigmaScaling Multiplier applied to sigma when updated
% AutoSigmaScaling Flag determining whether SigmaScaling value is
% adaptively determined (see wohlberg-2015-adaptive). If
% enabled, SigmaScaling specifies a maximum allowed
% multiplier instead of a fixed multiplier.
% StdResiduals Flag determining whether standard residual definitions
% (see Sec 3.3 of boyd-2010-distributed) are used instead
% of normalised residuals (see wohlberg-2015-adaptive)
% XRelaxParam Relaxation parameter (see Sec. 3.4.3 of
% boyd-2010-distributed) for X update
% DRelaxParam Relaxation parameter (see Sec. 3.4.3 of
% boyd-2010-distributed) for D update
% LinSolve Linear solver for main problem: 'SM' or 'CG'
% MaxCGIter Maximum CG iterations when using CG solver
% CGTol CG tolerance when using CG solver
% CGTolAuto Flag determining use of automatic CG tolerance
% CGTolFactor Factor by which primal residual is divided to obtain CG
% tolerance, when automatic tolerance is active
% NoBndryCross Flag indicating whether all solution coefficients
% corresponding to filters crossing the image boundary
% should be forced to zero.
% DictFilterSizes Array of size 2 x M where each column specifies the
% filter size (rows x columns) of the corresponding
% dictionary filter
% NonNegCoef Flag indicating whether solution should be forced to
% be non-negative
% ZeroMean Force learned dictionary entries to be zero-mean
%
%
% Author: Brendt Wohlberg <[email protected]> Modified: 2015-08-05
%
% This file is part of the SPORCO library. Details of the copyright
% and user license can be found in the 'Copyright' and 'License' files
% distributed with the library.
if nargin < 4,
opt = [];
end
checkopt(opt, defaultopts([]));
opt = defaultopts(opt);
% Set up status display for verbose operation
hstr = ['Itn Fnc DFid l1 Cnstr '...
'r(X) s(X) r(D) s(D) '];
sfms = '%4d %9.2e %9.2e %9.2e %9.2e %9.2e %9.2e %9.2e %9.2e';
nsep = 84;
if opt.AutoRho,
hstr = [hstr ' rho '];
sfms = [sfms ' %9.2e'];
nsep = nsep + 10;
end
if opt.AutoSigma,
hstr = [hstr ' sigma '];
sfms = [sfms ' %9.2e'];
nsep = nsep + 10;
end
if opt.Verbose && opt.MaxMainIter > 0,
disp(hstr);
disp(char('-' * ones(1,nsep)));
end
% Collapsing of trailing singleton dimensions greatly complicates
% handling of both SMV and MMV cases. The simplest approach would be
% if S could always be reshaped to 4d, with dimensions consisting of
% image rows, image cols, a single dimensional placeholder for number
% of filters, and number of measurements, but in the single
% measurement case the third dimension is collapsed so that the array
% is only 3d.
if size(S,3) > 1,
xsz = [size(S,1) size(S,2) size(D0,3) size(S,3)];
hrm = [1 1 1 size(S,3)];
% Insert singleton 3rd dimension (for number of filters) so that
% 4th dimension is number of images in input s volume
S = reshape(S, [size(S,1) size(S,2) 1 size(S,3)]);
else
xsz = [size(S,1) size(S,2) size(D0,3) 1];
hrm = 1;
end
xrm = [1 1 size(D0,3)];
Nx = prod(xsz);
Nd = prod(xsz(1:2))*size(D0,3);
cgt = opt.CGTol;
% Dictionary size may be specified when learning multiscale
% dictionary
if isempty(opt.DictFilterSizes),
dsz = [size(D0,1) size(D0,2)];
else
dsz = opt.DictFilterSizes;
end
% Mean removal and normalisation projections
Pzmn = @(x) bsxfun(@minus, x, mean(mean(x,1),2));
Pnrm = @(x) bsxfun(@rdivide, x, sqrt(sum(sum(x.^2, 1), 2)));
% Projection of filter to full image size and its transpose
% (zero-pad and crop respectively)
Pzp = @(x) zpad(x, xsz(1:2));
PzpT = @(x) bcrop(x, dsz);
% Projection of dictionary filters onto constraint set
if opt.ZeroMean,
Pcn = @(x) Pnrm(Pzp(Pzmn(PzpT(x))));
else
Pcn = @(x) Pnrm(Pzp(PzpT(x)));
end
% Start timer
tstart = tic;
% Project initial dictionary onto constraint set
D = Pnrm(D0);
% Compute signal in DFT domain
Sf = fft2(S);
% Set up algorithm parameters and initialise variables
rho = opt.rho;
if isempty(rho), rho = 50*lambda+1; end;
if opt.AutoRho,
asgr = opt.RhoRsdlRatio;
asgm = opt.RhoScaling;
end
sigma = opt.sigma;
if isempty(sigma), sigma = size(S,3); end;
if opt.AutoSigma,
asdr = opt.SigmaRsdlRatio;
asdm = opt.SigmaScaling;
end
optinf = struct('itstat', [], 'opt', opt);
rx = Inf;
sx = Inf;
rd = Inf;
sd = Inf;
eprix = 0;
eduax = 0;
eprid = 0;
eduad = 0;
% Initialise main working variables
X = [];
if isempty(opt.Y0),
Y = zeros(xsz, class(S));
else
Y = opt.Y0;
end
Yprv = Y;
if isempty(opt.U0),
if isempty(opt.Y0),
U = zeros(xsz, class(S));
else
U = (lambda/rho)*sign(Y);
end
else
U = opt.U0;
end
Df = [];
if isempty(opt.G0),
G = Pzp(D);
else
G = opt.G0;
end
Gprv = G;
if isempty(opt.H0),
if isempty(opt.G0),
H = zeros(size(G), class(S));
else
H = G;
end
else
H = opt.H0;
end
Gf = fft2(G, size(S,1), size(S,2));
GSf = bsxfun(@times, conj(Gf), Sf);
% Main loop
k = 1;
while k <= opt.MaxMainIter && (rx > eprix|sx > eduax|rd > eprid|sd >eduad),
% Solve X subproblem. It would be simpler and more efficient (since the
% DFT is already available) to solve for X using the main dictionary
% variable D as the dictionary, but this appears to be unstable. Instead,
% use the projected dictionary variable G
Xf = solvedbi_sm(Gf, rho, GSf + rho*fft2(Y - U));
X = ifft2(Xf, 'symmetric');
clear Xf Gf GSf;
% See pg. 21 of boyd-2010-distributed
if opt.XRelaxParam == 1,
Xr = X;
else
Xr = opt.XRelaxParam*X + (1-opt.XRelaxParam)*Y;
end
% Solve Y subproblem
Y = shrink(Xr + U, (lambda/rho)*opt.L1Weight);
if opt.NonNegCoef,
Y(Y < 0) = 0;
end
if opt.NoBndryCross,
Y((end-max(dsz(1,:)) +2):end,:,:,:) = 0;
Y(:,(end-max(dsz(2,:))+2):end,:,:) = 0;
end
Yf = fft2(Y);
YSf = sum(bsxfun(@times, conj(Yf), Sf), 4);
% Update dual variable corresponding to X, Y
U = U + Xr - Y;
clear Xr;
% Compute primal and dual residuals and stopping thresholds for X update
nX = norm(X(:)); nY = norm(Y(:)); nU = norm(U(:));
if opt.StdResiduals,
% See pp. 19-20 of boyd-2010-distributed
rx = norm(vec(X - Y));
sx = norm(vec(rho*(Yprv - Y)));
eprix = sqrt(Nx)*opt.AbsStopTol+max(nX,nY)*opt.RelStopTol;
eduax = sqrt(Nx)*opt.AbsStopTol+rho*nU*opt.RelStopTol;
else
% See wohlberg-2015-adaptive
rx = norm(vec(X - Y))/max(nX,nY);
sx = norm(vec(Yprv - Y))/nU;
eprix = sqrt(Nx)*opt.AbsStopTol/max(nX,nY)+opt.RelStopTol;
eduax = sqrt(Nx)*opt.AbsStopTol/(rho*nU)+opt.RelStopTol;
end
clear X;
% Compute l1 norm of Y
Jl1 = sum(abs(vec(bsxfun(@times, opt.L1Weight, Y))));
% Update record of previous step Y
Yprv = Y;
% Solve D subproblem. Similarly, it would be simpler and more efficient to
% solve for D using the main coefficient variable X as the coefficients,
% but it appears to be more stable to use the shrunk coefficient variable Y
if strcmp(opt.LinSolve, 'SM'),
Df = solvemdbi_ism(Yf, sigma, YSf + sigma*fft2(G - H));
else
[Df, cgst] = solvemdbi_cg(Yf, sigma, YSf + sigma*fft2(G - H), ...
cgt, opt.MaxCGIter, Df(:));
end
clear YSf;
D = ifft2(Df, 'symmetric');
if strcmp(opt.LinSolve, 'SM'), clear Df; end
% See pg. 21 of boyd-2010-distributed
if opt.DRelaxParam == 1,
Dr = D;
else
Dr = opt.DRelaxParam*D + (1-opt.DRelaxParam)*G;
end
% Solve G subproblem
G = Pcn(Dr + H);
Gf = fft2(G);
GSf = bsxfun(@times, conj(Gf), Sf);
% Update dual variable corresponding to D, G
H = H + Dr - G;
clear Dr;
% Compute primal and dual residuals and stopping thresholds for D update
nD = norm(D(:)); nG = norm(G(:)); nH = norm(H(:));
if opt.StdResiduals,
% See pp. 19-20 of boyd-2010-distributed
rd = norm(vec(D - G));
sd = norm(vec(sigma*(Gprv - G)));
eprid = sqrt(Nd)*opt.AbsStopTol+max(nD,nG)*opt.RelStopTol;
eduad = sqrt(Nd)*opt.AbsStopTol+sigma*nH*opt.RelStopTol;
else
% See wohlberg-2015-adaptive
rd = norm(vec(D - G))/max(nD,nG);
sd = norm(vec(Gprv - G))/nH;
eprid = sqrt(Nd)*opt.AbsStopTol/max(nD,nG)+opt.RelStopTol;
eduad = sqrt(Nd)*opt.AbsStopTol/(sigma*nH)+opt.RelStopTol;
end
% Apply CG auto tolerance policy if enabled
if opt.CGTolAuto && (rd/opt.CGTolFactor) < cgt,
cgt = rd/opt.CGTolFactor;
end
% Compute measure of D constraint violation
Jcn = norm(vec(Pcn(D) - D));
clear D;
% Update record of previous step G
Gprv = G;
% Compute data fidelity term in Fourier domain (note normalisation)
Jdf = sum(vec(abs(sum(bsxfun(@times,Gf,Yf),3)-Sf).^2))/(2*xsz(1)*xsz(2));
clear Yf;
Jfn = Jdf + lambda*Jl1;
% Record and display iteration details
tk = toc(tstart);
optinf.itstat = [optinf.itstat;...
[k Jfn Jdf Jl1 rx sx rd sd eprix eduax eprid eduad rho sigma tk]];
if opt.Verbose,
dvc = [k, Jfn, Jdf, Jl1, Jcn, rx, sx, rd, sd];
if opt.AutoRho,
dvc = [dvc rho];
end
if opt.AutoSigma,
dvc = [dvc sigma];
end
disp(sprintf(sfms, dvc));
end
% See wohlberg-2015-adaptive and pp. 20-21 of boyd-2010-distributed
if opt.AutoRho,
if k ~= 1 && mod(k, opt.AutoRhoPeriod) == 0,
if opt.AutoRhoScaling,
rhomlt = sqrt(rx/sx);
if rhomlt < 1, rhomlt = 1/rhomlt; end
if rhomlt > opt.RhoScaling, rhomlt = opt.RhoScaling; end
else
rhomlt = opt.RhoScaling;
end
rsf = 1;
if rx > opt.RhoRsdlRatio*sx, rsf = rhomlt; end
if sx > opt.RhoRsdlRatio*rx, rsf = 1/rhomlt; end
rho = rsf*rho;
U = U/rsf;
end
end
if opt.AutoSigma,
if k ~= 1 && mod(k, opt.AutoSigmaPeriod) == 0,
if opt.AutoSigmaScaling,
sigmlt = sqrt(rd/sd);
if sigmlt < 1, sigmlt = 1/sigmlt; end
if sigmlt > opt.SigmaScaling, sigmlt = opt.SigmaScaling; end
else
sigmlt = opt.SigmaScaling;
end
ssf = 1;
if rd > opt.SigmaRsdlRatio*sd, ssf = sigmlt; end
if sd > opt.SigmaRsdlRatio*rd, ssf = 1/sigmlt; end
sigma = ssf*sigma;
H = H/ssf;
end
end
k = k + 1;
end
D = PzpT(G);
% Record run time and working variables
optinf.runtime = toc(tstart);
optinf.Y = Y;
optinf.U = U;
optinf.G = G;
optinf.H = H;
optinf.lambda = lambda;
optinf.rho = rho;
optinf.sigma = sigma;
optinf.cgt = cgt;
if exist('cgst'), optinf.cgst = cgst; end
if opt.Verbose && opt.MaxMainIter > 0,
disp(char('-' * ones(1,nsep)));
end
return
function u = vec(v)
u = v(:);
return
function u = shrink(v, lambda)
if isscalar(lambda),
u = sign(v).*max(0, abs(v) - lambda);
else
u = sign(v).*max(0, bsxfun(@minus, abs(v), lambda));
end
return
function u = zpad(v, sz)
u = zeros(sz(1), sz(2), size(v,3), size(v,4), class(v));
u(1:size(v,1), 1:size(v,2),:,:) = v;
return
function u = bcrop(v, sz)
if numel(sz) <= 2,
if numel(sz) == 1
cs = [sz sz];
else
cs = sz;
end
u = v(1:cs(1), 1:cs(2), :);
else
cs = max(sz,[],2);
u = zeros(cs(1), cs(2), size(v,3), class(v));
for k = 1:size(v,3),
u(1:sz(1,k), 1:sz(2,k), k) = v(1:sz(1,k), 1:sz(2,k), k);
end
end
return
function opt = defaultopts(opt)
if ~isfield(opt,'Verbose'),
opt.Verbose = 0;
end
if ~isfield(opt,'MaxMainIter'),
opt.MaxMainIter = 1000;
end
if ~isfield(opt,'AbsStopTol'),
opt.AbsStopTol = 1e-6;
end
if ~isfield(opt,'RelStopTol'),
opt.RelStopTol = 1e-4;
end
if ~isfield(opt,'L1Weight'),
opt.L1Weight = 1;
end
if ~isfield(opt,'Y0'),
opt.Y0 = [];
end
if ~isfield(opt,'U0'),
opt.U0 = [];
end
if ~isfield(opt,'G0'),
opt.G0 = [];
end
if ~isfield(opt,'H0'),
opt.H0 = [];
end
if ~isfield(opt,'rho'),
opt.rho = [];
end
if ~isfield(opt,'AutoRho'),
opt.AutoRho = 0;
end
if ~isfield(opt,'AutoRhoPeriod'),
opt.AutoRhoPeriod = 10;
end
if ~isfield(opt,'RhoRsdlRatio'),
opt.RhoRsdlRatio = 10;
end
if ~isfield(opt,'RhoScaling'),
opt.RhoScaling = 2;
end
if ~isfield(opt,'AutoRhoScaling'),
opt.AutoRhoScaling = 0;
end
if ~isfield(opt,'sigma'),
opt.sigma = [];
end
if ~isfield(opt,'AutoSigma'),
opt.AutoSigma = 0;
end
if ~isfield(opt,'AutoSigmaPeriod'),
opt.AutoSigmaPeriod = 10;
end
if ~isfield(opt,'SigmaRsdlRatio'),
opt.SigmaRsdlRatio = 10;
end
if ~isfield(opt,'SigmaScaling'),
opt.SigmaScaling = 2;
end
if ~isfield(opt,'AutoSigmaScaling'),
opt.AutoSigmaScaling = 0;
end
if ~isfield(opt,'StdResiduals'),
opt.StdResiduals = 0;
end
if ~isfield(opt,'XRelaxParam'),
opt.XRelaxParam = 1;
end
if ~isfield(opt,'DRelaxParam'),
opt.DRelaxParam = 1;
end
if ~isfield(opt,'LinSolve'),
opt.LinSolve = 'SM';
end
if ~isfield(opt,'MaxCGIter'),
opt.MaxCGIter = 1000;
end
if ~isfield(opt,'CGTol'),
opt.CGTol = 1e-3;
end
if ~isfield(opt,'CGTolAuto'),
opt.CGTolAuto = 0;
end
if ~isfield(opt,'CGTolAutoFactor'),
opt.CGTolFactor = 50;
end
if ~isfield(opt,'NoBndryCross'),
opt.NoBndryCross = 0;
end
if ~isfield(opt,'DictFilterSizes'),
opt.DictFilterSizes = [];
end
if ~isfield(opt,'NonNegCoef'),
opt.NonNegCoef = 0;
end
if ~isfield(opt,'ZeroMean'),
opt.ZeroMean = 0;
end
return
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
cbpdndl_low_sparse.m
|
.m
|
convolutional_sparse_coding-master/DictLearn/cbpdndl_low_sparse.m
| 17,151 |
utf_8
|
faf23526a0c9e3f8ce9c36ebb102696a
|
function [D, Y, optinf] = cbpdndl_low_sparse(D0, S, lambda_r,lambda_s, opt)
% cbpdndl -- Convolutional BPDN Dictionary Learning
%
% argmin_{x_m,d_m} (1/2) \sum_k ||\sum_m d_m * x_k,m - s_k||_2^2 +
% lambda \sum_k \sum_m ||x_k,m||_1
%
% The solution is computed using Augmented Lagrangian methods
% (see boyd-2010-distributed) with efficient solution of the
% main linear systems (see wohlberg-2014-efficient).
%
% Usage:
% [D, Y, optinf] = cbpdndl(D0, S, lambda, opt)
%
% Input:
% D0 Initial dictionary
% S Input images
% lambda Regularization parameter
% opt Options/algorithm parameters structure (see below)
%
% Output:
% D Dictionary filter set (3D array)
% X Coefficient maps (4D array)
% optinf Details of optimisation
%
%
% Options structure fields:
% Verbose Flag determining whether iteration status is displayed.
% Fields are iteration number, functional value,
% data fidelity term, l1 regularisation term, and
% primal and dual residuals (see Sec. 3.3 of
% boyd-2010-distributed). The values of rho and sigma
% are also displayed if options request that they are
% automatically adjusted.
% MaxMainIter Maximum main iterations
% AbsStopTol Absolute convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% RelStopTol Relative convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% L1Weight Weight array for L1 norm
% Y0 Initial value for Y
% U0 Initial value for U
% G0 Initial value for G (overrides D0 if specified)
% H0 Initial value for H
% rho Augmented Lagrangian penalty parameter
% AutoRho Flag determining whether rho is automatically updated
% (see Sec. 3.4.1 of boyd-2010-distributed)
% AutoRhoPeriod Iteration period on which rho is updated
% RhoRsdlRatio Primal/dual residual ratio in rho update test
% RhoScaling Multiplier applied to rho when updated
% AutoRhoScaling Flag determining whether RhoScaling value is
% adaptively determined (see wohlberg-2015-adaptive). If
% enabled, RhoScaling specifies a maximum allowed
% multiplier instead of a fixed multiplier
% sigma Augmented Lagrangian penalty parameter
% AutoSigma Flag determining whether sigma is automatically
% updated (see Sec. 3.4.1 of boyd-2010-distributed)
% AutoSigmaPeriod Iteration period on which sigma is updated
% SigmaRsdlRatio Primal/dual residual ratio in sigma update test
% SigmaScaling Multiplier applied to sigma when updated
% AutoSigmaScaling Flag determining whether SigmaScaling value is
% adaptively determined (see wohlberg-2015-adaptive). If
% enabled, SigmaScaling specifies a maximum allowed
% multiplier instead of a fixed multiplier.
% StdResiduals Flag determining whether standard residual definitions
% (see Sec 3.3 of boyd-2010-distributed) are used instead
% of normalised residuals (see wohlberg-2015-adaptive)
% XRelaxParam Relaxation parameter (see Sec. 3.4.3 of
% boyd-2010-distributed) for X update
% DRelaxParam Relaxation parameter (see Sec. 3.4.3 of
% boyd-2010-distributed) for D update
% LinSolve Linear solver for main problem: 'SM' or 'CG'
% MaxCGIter Maximum CG iterations when using CG solver
% CGTol CG tolerance when using CG solver
% CGTolAuto Flag determining use of automatic CG tolerance
% CGTolFactor Factor by which primal residual is divided to obtain CG
% tolerance, when automatic tolerance is active
% NoBndryCross Flag indicating whether all solution coefficients
% corresponding to filters crossing the image boundary
% should be forced to zero.
% DictFilterSizes Array of size 2 x M where each column specifies the
% filter size (rows x columns) of the corresponding
% dictionary filter
% NonNegCoef Flag indicating whether solution should be forced to
% be non-negative
% ZeroMean Force learned dictionary entries to be zero-mean
%
%
% Author: Brendt Wohlberg <[email protected]> Modified: 2015-08-05
%
% This file is part of the SPORCO library. Details of the copyright
% and user license can be found in the 'Copyright' and 'License' files
% distributed with the library.
lambda=lambda_s;
if nargin < 4,
opt = [];
end
checkopt(opt, defaultopts([]));
opt = defaultopts(opt);
% Set up status display for verbose operation
hstr = ['Itn Fnc DFid l1 low1 '...
'r(X) s(X) r(D) s(D) '];
sfms = '%4d %9.2e %9.2e %9.2e %9.2e %9.2e %9.2e %9.2e %9.2e';
nsep = 84;
if opt.AutoRho,
hstr = [hstr ' rho '];
sfms = [sfms ' %9.2e'];
nsep = nsep + 10;
end
if opt.AutoSigma,
hstr = [hstr ' sigma '];
sfms = [sfms ' %9.2e'];
nsep = nsep + 10;
end
if opt.Verbose && opt.MaxMainIter > 0,
disp(hstr);
disp(char('-' * ones(1,nsep)));
end
% Collapsing of trailing singleton dimensions greatly complicates
% handling of both SMV and MMV cases. The simplest approach would be
% if S could always be reshaped to 4d, with dimensions consisting of
% image rows, image cols, a single dimensional placeholder for number
% of filters, and number of measurements, but in the single
% measurement case the third dimension is collapsed so that the array
% is only 3d.
if size(S,3) > 1,
xsz = [size(S,1) size(S,2) size(D0,3) size(S,3)];
hrm = [1 1 1 size(S,3)];
% Insert singleton 3rd dimension (for number of filters) so that
% 4th dimension is number of images in input s volume
S = reshape(S, [size(S,1) size(S,2) 1 size(S,3)]);
else
xsz = [size(S,1) size(S,2) size(D0,3) 1];
hrm = 1;
end
xrm = [1 1 size(D0,3)];
Nx = prod(xsz);
Nd = prod(xsz(1:2))*size(D0,3);
cgt = opt.CGTol;
% Dictionary size may be specified when learning multiscale
% dictionary
if isempty(opt.DictFilterSizes),
dsz = [size(D0,1) size(D0,2)];
else
dsz = opt.DictFilterSizes;
end
% Mean removal and normalisation projections
Pzmn = @(x) bsxfun(@minus, x, mean(mean(x,1),2));
Pnrm = @(x) bsxfun(@rdivide, x, sqrt(sum(sum(x.^2, 1), 2)));
% Projection of filter to full image size and its transpose
% (zero-pad and crop respectively)
Pzp = @(x) zpad(x, xsz(1:2));
PzpT = @(x) bcrop(x, dsz);
% Projection of dictionary filters onto constraint set
if opt.ZeroMean,
Pcn = @(x) Pnrm(Pzp(Pzmn(PzpT(x))));
else
Pcn = @(x) Pnrm(Pzp(PzpT(x)));
end
% Start timer
tstart = tic;
% Project initial dictionary onto constraint set
D = Pnrm(D0);
% Compute signal in DFT domain
Sf = fft2(S);
% Set up algorithm parameters and initialise variables
rho = opt.rho;
if isempty(rho), rho = 50*lambda+1; end;
if opt.AutoRho,
asgr = opt.RhoRsdlRatio;
asgm = opt.RhoScaling;
end
sigma = opt.sigma;
if isempty(sigma), sigma = size(S,3); end;
if opt.AutoSigma,
asdr = opt.SigmaRsdlRatio;
asdm = opt.SigmaScaling;
end
optinf = struct('itstat', [], 'opt', opt);
rx = Inf;
sx = Inf;
rd = Inf;
sd = Inf;
eprix = 0;
eduax = 0;
eprid = 0;
eduad = 0;
% Initialise main working variables
X_1 = [];
if isempty(opt.Y0),
Y = zeros(xsz, class(S));
else
Y = opt.Y0;
end
Yprv = Y;
if isempty(opt.U0),
if isempty(opt.Y0),
U_1 = zeros(xsz, class(S));
U_2 = zeros(xsz, class(S));
else
U_1 = (lambda/rho)*sign(Y);
U_2 = (lambda/rho)*sign(Y);
end
else
U_1 = opt.U0;
U_2 = opt.U0;
end
Df = [];
if isempty(opt.G0),
G = Pzp(D);
else
G = opt.G0;
end
Gprv = G;
if isempty(opt.H0),
if isempty(opt.G0),
H = zeros(size(G), class(S));
else
H = G;
end
else
H = opt.H0;
end
Gf = fft2(G, size(S,1), size(S,2));
GSf = bsxfun(@times, conj(Gf), Sf);
% Main loop
k = 1;
while k <= opt.MaxMainIter && (rx > eprix|sx > eduax|rd > eprid|sd >eduad),
% Solve X subproblem. It would be simpler and more efficient (since the
% DFT is already available) to solve for X using the main dictionary
% variable D as the dictionary, but this appears to be unstable. Instead,
% use the projected dictionary variable G
Xf_1 = solvedbi_sm(Gf, rho, GSf + rho*fft2(Y - U_1));
X_1 = ifft2(Xf_1, 'symmetric');
clear Xf Gf GSf;
% See pg. 21 of boyd-2010-distributed
if opt.XRelaxParam == 1,
Xr_1 = X_1;
else
Xr_1 = opt.XRelaxParam*X_1 + (1-opt.XRelaxParam)*Y;
end
%Update low_rank coefficient
Xr_2 = Do(lambda_r/rho, Y-U_2);
% Solve Y subproblem
Y = shrink((Xr_1+Xr_2)/2 + (U_1+U_2)/2, (2*lambda_s/rho)*opt.L1Weight);
if opt.NonNegCoef,
Y(Y < 0) = 0;
end
if opt.NoBndryCross,
Y((end-max(dsz(1,:)) +2):end,:,:,:) = 0;
Y(:,(end-max(dsz(2,:))+2):end,:,:) = 0;
end
Yf = fft2(Y);
YSf = sum(bsxfun(@times, conj(Yf), Sf), 4);
% Update dual variable corresponding to X, Y
U_1 = U_1 + Xr_1 - Y;
U_2 = U_2 + Xr_2 - Y;
clear Xr;
% Compute primal and dual residuals and stopping thresholds for X update
nX = norm(X_1(:)); nY = norm(Y(:)); nU = norm((U_1(:)+U_2(:)/2));
if opt.StdResiduals,
% See pp. 19-20 of boyd-2010-distributed
rx = norm(vec(X_1 - Y));
sx = norm(vec(rho*(Yprv - Y)));
eprix = sqrt(Nx)*opt.AbsStopTol+max(nX,nY)*opt.RelStopTol;
eduax = sqrt(Nx)*opt.AbsStopTol+rho*nU*opt.RelStopTol;
else
% See wohlberg-2015-adaptive
rx = norm(vec(X_1 - Y))/max(nX,nY);
sx = norm(vec(Yprv - Y))/nU;
eprix = sqrt(Nx)*opt.AbsStopTol/max(nX,nY)+opt.RelStopTol;
eduax = sqrt(Nx)*opt.AbsStopTol/(rho*nU)+opt.RelStopTol;
end
clear X;
% Compute l1 norm of Y
Jl1 = sum(abs(vec(bsxfun(@times, opt.L1Weight, Y))));
low1=0;
for i=1:size(Y,3)
cc=Y(:,:,i)'*Y(:,:,i);
cc=sqrt(cc);
low1=low1+trace(cc);
end
% Update record of previous step Y
Yprv = Y;
% Solve D subproblem. Similarly, it would be simpler and more efficient to
% solve for D using the main coefficient variable X as the coefficients,
% but it appears to be more stable to use the shrunk coefficient variable Y
if strcmp(opt.LinSolve, 'SM'),
Df = solvemdbi_ism(Yf, sigma, YSf + sigma*fft2(G - H));
else
[Df, cgst] = solvemdbi_cg(Yf, sigma, YSf + sigma*fft2(G - H), ...
cgt, opt.MaxCGIter, Df(:));
end
clear YSf;
D = ifft2(Df, 'symmetric');
if strcmp(opt.LinSolve, 'SM'), clear Df; end
% See pg. 21 of boyd-2010-distributed
if opt.DRelaxParam == 1,
Dr = D;
else
Dr = opt.DRelaxParam*D + (1-opt.DRelaxParam)*G;
end
% Solve G subproblem
G = Pcn(Dr + H);
Gf = fft2(G);
GSf = bsxfun(@times, conj(Gf), Sf);
% Update dual variable corresponding to D, G
H = H + Dr - G;
clear Dr;
% Compute primal and dual residuals and stopping thresholds for D update
nD = norm(D(:)); nG = norm(G(:)); nH = norm(H(:));
if opt.StdResiduals,
% See pp. 19-20 of boyd-2010-distributed
rd = norm(vec(D - G));
sd = norm(vec(sigma*(Gprv - G)));
eprid = sqrt(Nd)*opt.AbsStopTol+max(nD,nG)*opt.RelStopTol;
eduad = sqrt(Nd)*opt.AbsStopTol+sigma*nH*opt.RelStopTol;
else
% See wohlberg-2015-adaptive
rd = norm(vec(D - G))/max(nD,nG);
sd = norm(vec(Gprv - G))/nH;
eprid = sqrt(Nd)*opt.AbsStopTol/max(nD,nG)+opt.RelStopTol;
eduad = sqrt(Nd)*opt.AbsStopTol/(sigma*nH)+opt.RelStopTol;
end
% Apply CG auto tolerance policy if enabled
if opt.CGTolAuto && (rd/opt.CGTolFactor) < cgt,
cgt = rd/opt.CGTolFactor;
end
% Compute measure of D constraint violation
Jcn = norm(vec(Pcn(D) - D));
clear D;
% Update record of previous step G
Gprv = G;
% Compute data fidelity term in Fourier domain (note normalisation)
Jdf = sum(vec(abs(sum(bsxfun(@times,Gf,Yf),3)-Sf).^2))/(2*xsz(1)*xsz(2));
clear Yf;
Jfn = Jdf + lambda_s*Jl1+lambda_r*low1;
% Record and display iteration details
tk = toc(tstart);
optinf.itstat = [optinf.itstat;...
[k Jfn Jdf Jl1 low1 sx rd sd eprix eduax eprid eduad rho sigma tk]];
if opt.Verbose,
dvc = [k, Jfn, Jdf, Jl1, low1, rx, sx, rd, sd];
if opt.AutoRho,
dvc = [dvc rho];
end
if opt.AutoSigma,
dvc = [dvc sigma];
end
disp(sprintf(sfms, dvc));
end
% See wohlberg-2015-adaptive and pp. 20-21 of boyd-2010-distributed
if opt.AutoRho,
if k ~= 1 && mod(k, opt.AutoRhoPeriod) == 0,
if opt.AutoRhoScaling,
rhomlt = sqrt(rx/sx);
if rhomlt < 1, rhomlt = 1/rhomlt; end
if rhomlt > opt.RhoScaling, rhomlt = opt.RhoScaling; end
else
rhomlt = opt.RhoScaling;
end
rsf = 1;
if rx > opt.RhoRsdlRatio*sx, rsf = rhomlt; end
if sx > opt.RhoRsdlRatio*rx, rsf = 1/rhomlt; end
rho = rsf*rho;
U = (U_1+U_2)/2/rsf;
end
end
if opt.AutoSigma,
if k ~= 1 && mod(k, opt.AutoSigmaPeriod) == 0,
if opt.AutoSigmaScaling,
sigmlt = sqrt(rd/sd);
if sigmlt < 1, sigmlt = 1/sigmlt; end
if sigmlt > opt.SigmaScaling, sigmlt = opt.SigmaScaling; end
else
sigmlt = opt.SigmaScaling;
end
ssf = 1;
if rd > opt.SigmaRsdlRatio*sd, ssf = sigmlt; end
if sd > opt.SigmaRsdlRatio*rd, ssf = 1/sigmlt; end
sigma = ssf*sigma;
H = H/ssf;
end
end
k = k + 1;
end
D = PzpT(G);
% Record run time and working variables
optinf.runtime = toc(tstart);
optinf.Y = Y;
optinf.U = U;
optinf.G = G;
optinf.H = H;
optinf.lambda = lambda;
optinf.rho = rho;
optinf.sigma = sigma;
optinf.cgt = cgt;
if exist('cgst'), optinf.cgst = cgst; end
if opt.Verbose && opt.MaxMainIter > 0,
disp(char('-' * ones(1,nsep)));
end
return
function u = vec(v)
u = v(:);
return
function r = Do(tau, X)
% shrinkage operator for singular values
for i=1:size(X,3)
for j=1:size(X,4)
[U, S, V] = svd(X(:,:,i,j), 'econ');
r(:,:,i,j)= U*So(tau, S)*V';
end
end
return
function r = So(tau, X)
% shrinkage operator
r = sign(X) .* max(abs(X) - tau, 0);
return
function u = shrink(v, lambda)
if isscalar(lambda),
u = sign(v).*max(0, abs(v) - lambda);
else
u = sign(v).*max(0, bsxfun(@minus, abs(v), lambda));
end
return
function u = zpad(v, sz)
u = zeros(sz(1), sz(2), size(v,3), size(v,4), class(v));
u(1:size(v,1), 1:size(v,2),:,:) = v;
return
function u = bcrop(v, sz)
if numel(sz) <= 2,
if numel(sz) == 1
cs = [sz sz];
else
cs = sz;
end
u = v(1:cs(1), 1:cs(2), :);
else
cs = max(sz,[],2);
u = zeros(cs(1), cs(2), size(v,3), class(v));
for k = 1:size(v,3),
u(1:sz(1,k), 1:sz(2,k), k) = v(1:sz(1,k), 1:sz(2,k), k);
end
end
return
function opt = defaultopts(opt)
if ~isfield(opt,'Verbose'),
opt.Verbose = 0;
end
if ~isfield(opt,'MaxMainIter'),
opt.MaxMainIter = 1000;
end
if ~isfield(opt,'AbsStopTol'),
opt.AbsStopTol = 1e-6;
end
if ~isfield(opt,'RelStopTol'),
opt.RelStopTol = 1e-4;
end
if ~isfield(opt,'L1Weight'),
opt.L1Weight = 1;
end
if ~isfield(opt,'Y0'),
opt.Y0 = [];
end
if ~isfield(opt,'U0'),
opt.U0 = [];
end
if ~isfield(opt,'G0'),
opt.G0 = [];
end
if ~isfield(opt,'H0'),
opt.H0 = [];
end
if ~isfield(opt,'rho'),
opt.rho = [];
end
if ~isfield(opt,'AutoRho'),
opt.AutoRho = 0;
end
if ~isfield(opt,'AutoRhoPeriod'),
opt.AutoRhoPeriod = 10;
end
if ~isfield(opt,'RhoRsdlRatio'),
opt.RhoRsdlRatio = 10;
end
if ~isfield(opt,'RhoScaling'),
opt.RhoScaling = 2;
end
if ~isfield(opt,'AutoRhoScaling'),
opt.AutoRhoScaling = 0;
end
if ~isfield(opt,'sigma'),
opt.sigma = [];
end
if ~isfield(opt,'AutoSigma'),
opt.AutoSigma = 0;
end
if ~isfield(opt,'AutoSigmaPeriod'),
opt.AutoSigmaPeriod = 10;
end
if ~isfield(opt,'SigmaRsdlRatio'),
opt.SigmaRsdlRatio = 10;
end
if ~isfield(opt,'SigmaScaling'),
opt.SigmaScaling = 2;
end
if ~isfield(opt,'AutoSigmaScaling'),
opt.AutoSigmaScaling = 0;
end
if ~isfield(opt,'StdResiduals'),
opt.StdResiduals = 0;
end
if ~isfield(opt,'XRelaxParam'),
opt.XRelaxParam = 1;
end
if ~isfield(opt,'DRelaxParam'),
opt.DRelaxParam = 1;
end
if ~isfield(opt,'LinSolve'),
opt.LinSolve = 'SM';
end
if ~isfield(opt,'MaxCGIter'),
opt.MaxCGIter = 1000;
end
if ~isfield(opt,'CGTol'),
opt.CGTol = 1e-3;
end
if ~isfield(opt,'CGTolAuto'),
opt.CGTolAuto = 0;
end
if ~isfield(opt,'CGTolAutoFactor'),
opt.CGTolFactor = 50;
end
if ~isfield(opt,'NoBndryCross'),
opt.NoBndryCross = 0;
end
if ~isfield(opt,'DictFilterSizes'),
opt.DictFilterSizes = [];
end
if ~isfield(opt,'NonNegCoef'),
opt.NonNegCoef = 0;
end
if ~isfield(opt,'ZeroMean'),
opt.ZeroMean = 0;
end
return
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
cbpdndlms.m
|
.m
|
convolutional_sparse_coding-master/DictLearn/cbpdndlms.m
| 17,080 |
utf_8
|
e4996dd9887a46268c0d4abd8b6077b5
|
function [D, Y, optinf] = cbpdndlms(D0, S, lambda, opt)
% cbpdndlms -- Convolutional BPDN Dictionary Learning (Mask Simulation)
%
% argmin_{x_m,d_m} (1/2) \sum_k ||W \sum_m d_m * x_k,m - s_k||_2^2 +
% lambda \sum_k \sum_m ||x_k,m||_1
%
% The solution is computed using Augmented Lagrangian methods
% (see boyd-2010-distributed) with efficient solution of the main
% linear systems (see wohlberg-2016-efficient and
% wohlberg-2016-boundary).
%
% Usage:
% [D, Y, optinf] = cbpdndlms(D0, S, lambda, opt)
%
% Input:
% D0 Initial dictionary
% S Input images
% lambda Regularization parameter
% opt Options/algorithm parameters structure (see below)
%
% Output:
% D Dictionary filter set (3D array)
% X Coefficient maps (4D array)
% optinf Details of optimisation
%
%
% Options structure fields:
% Verbose Flag determining whether iteration status is displayed.
% Fields are iteration number, functional value,
% data fidelity term, l1 regularisation term, and
% primal and dual residuals (see Sec. 3.3 of
% boyd-2010-distributed). The values of rho and sigma
% are also displayed if options request that they are
% automatically adjusted.
% MaxMainIter Maximum main iterations
% AbsStopTol Absolute convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% RelStopTol Relative convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% L1Weight Weight array for L1 norm
% Y0 Initial value for Y
% U0 Initial value for U
% G0 Initial value for G (overrides D0 if specified)
% H0 Initial value for H
% rho Augmented Lagrangian penalty parameter
% AutoRho Flag determining whether rho is automatically updated
% (see Sec. 3.4.1 of boyd-2010-distributed)
% AutoRhoPeriod Iteration period on which rho is updated
% RhoRsdlRatio Primal/dual residual ratio in rho update test
% RhoScaling Multiplier applied to rho when updated
% AutoRhoScaling Flag determining whether RhoScaling value is
% adaptively determined (see wohlberg-2015-adaptive). If
% enabled, RhoScaling specifies a maximum allowed
% multiplier instead of a fixed multiplier
% sigma Augmented Lagrangian penalty parameter
% AutoSigma Flag determining whether sigma is automatically
% updated (see Sec. 3.4.1 of boyd-2010-distributed)
% AutoSigmaPeriod Iteration period on which sigma is updated
% SigmaRsdlRatio Primal/dual residual ratio in sigma update test
% SigmaScaling Multiplier applied to sigma when updated
% AutoSigmaScaling Flag determining whether SigmaScaling value is
% adaptively determined (see wohlberg-2015-adaptive). If
% enabled, SigmaScaling specifies a maximum allowed
% multiplier instead of a fixed multiplier.
% StdResiduals Flag determining whether standard residual definitions
% (see Sec 3.3 of boyd-2010-distributed) are used instead
% of normalised residuals (see wohlberg-2015-adaptive)
% XRelaxParam Relaxation parameter (see Sec. 3.4.3 of
% boyd-2010-distributed) for X update
% DRelaxParam Relaxation parameter (see Sec. 3.4.3 of
% boyd-2010-distributed) for D update
% LinSolve Linear solver for main problem: 'SM' or 'CG'
% MaxCGIter Maximum CG iterations when using CG solver
% CGTol CG tolerance when using CG solver
% CGTolAuto Flag determining use of automatic CG tolerance
% CGTolFactor Factor by which primal residual is divided to obtain CG
% tolerance, when automatic tolerance is active
% NoBndryCross Flag indicating whether all solution coefficients
% corresponding to filters crossing the image boundary
% should be forced to zero.
% DictFilterSizes Array of size 2 x M where each column specifies the
% filter size (rows x columns) of the corresponding
% dictionary filter
% NonNegCoef Flag indicating whether solution should be forced to
% be non-negative
% ZeroMean Force learned dictionary entries to be zero-mean
% W Synthesis spatial weighting matrix
%
%
% Author: Brendt Wohlberg <[email protected]> Modified: 2016-05-10
%
% This file is part of the SPORCO library. Details of the copyright
% and user license can be found in the 'License' file distributed with
% the library.
if nargin < 4,
opt = [];
end
checkopt(opt, defaultopts([]));
opt = defaultopts(opt);
% Set up status display for verbose operation
hstr = ['Itn Fnc DFid l1 Cnstr '...
'r(X) s(X) r(D) s(D) '];
sfms = '%4d %9.2e %9.2e %9.2e %9.2e %9.2e %9.2e %9.2e %9.2e';
nsep = 84;
if opt.AutoRho,
hstr = [hstr ' rho '];
sfms = [sfms ' %9.2e'];
nsep = nsep + 10;
end
if opt.AutoSigma,
hstr = [hstr ' sigma '];
sfms = [sfms ' %9.2e'];
nsep = nsep + 10;
end
if opt.Verbose && opt.MaxMainIter > 0,
disp(hstr);
disp(char('-' * ones(1,nsep)));
end
% Start timer
tstart = tic;
% Mean removal and normalisation projections
Pzmn = @(x) bsxfun(@minus, x, mean(mean(x,1),2));
Pnrm = @(x) bsxfun(@rdivide, x, sqrt(sum(sum(x.^2, 1), 2)));
% Collapsing of trailing singleton dimensions greatly complicates
% handling of both SMV and MMV cases. The simplest approach would be
% if S could always be reshaped to 4d, with dimensions consisting of
% image rows, image cols, a single dimensional placeholder for number
% of filters, and number of measurements, but in the single
% measurement case the third dimension is collapsed so that the array
% is only 3d.
if size(S,3) > 1,
xsz = [size(S,1) size(S,2) size(D0,3)+1 size(S,3)];
% Insert singleton 3rd dimension (for number of filters) so that
% 4th dimension is number of images in input s volume
S = reshape(S, [size(S,1) size(S,2) 1 size(S,3)]);
if ~isscalar(opt.W) & ndims(opt.W) > 2,
opt.W = reshape(opt.W, [size(opt.W,1) size(opt.W,2) 1 size(opt.W,3)]);
end
else
xsz = [size(S,1) size(S,2) size(D0,3)+1 size(S,4)];
end
Nx = prod(xsz);
Nd = prod(xsz(1:2))*size(D0,3);
cgt = opt.CGTol;
% Impulse filter to extend dictionary
imp = zeros(size(S,1), size(S,2), 1);
imp(1,1,1) = 1.0;
IYW = 1.0 - opt.W;
% Dictionary size may be specified when learning multiscale
% dictionary
if isempty(opt.DictFilterSizes),
dsz = [size(D0,1) size(D0,2)];
else
dsz = opt.DictFilterSizes;
end
% Projection of filter to full image size and its transpose
% (zero-pad and crop respectively)
Pzp = @(x) zpad(x, xsz(1:2));
PzpT = @(x) bcrop(x, dsz);
% Projection of dictionary filters onto constraint set
if opt.ZeroMean,
Pcn = @(x) Pnrm(Pzp(Pzmn(PzpT(x))));
else
Pcn = @(x) Pnrm(Pzp(PzpT(x)));
end
% Compute signal in DFT domain
Sf = fft2(S);
% Set up algorithm parameters and initialise variables
rho = opt.rho;
if isempty(rho), rho = 50*lambda+1; end;
if opt.AutoRho,
asgr = opt.RhoRsdlRatio;
asgm = opt.RhoScaling;
end
sigma = opt.sigma;
if isempty(sigma), sigma = size(S,3); end;
if opt.AutoSigma,
asdr = opt.SigmaRsdlRatio;
asdm = opt.SigmaScaling;
end
optinf = struct('itstat', [], 'opt', opt);
rx = Inf;
sx = Inf;
rd = Inf;
sd = Inf;
eprix = 0;
eduax = 0;
eprid = 0;
eduad = 0;
% Initialise main working variables
X = [];
if isempty(opt.Y0),
Y = zeros(xsz, class(S));
else
Y = opt.Y0;
end
Yprv = Y;
if isempty(opt.U0),
if isempty(opt.Y0),
U = zeros(xsz, class(S));
else
U = (lambda/rho)*sign(Y);
end
else
U = opt.U0;
end
Df = [];
if isempty(opt.G0),
G = Pzp(Pnrm(D0));
else
G = opt.G0;
end
Gprv = G;
if isempty(opt.H0),
if isempty(opt.G0),
H = zeros(size(G), class(S));
else
H = G;
end
else
H = opt.H0;
end
%Gf = fft2(G, size(S,1), size(S,2));
Gf = fft2(cat(3, G, imp));
GSf = bsxfun(@times, conj(Gf), Sf);
% Main loop
k = 1;
while k <= opt.MaxMainIter && (rx > eprix|sx > eduax|rd > eprid|sd >eduad),
% Solve X subproblem. It would be simpler and more efficient (since the
% DFT is already available) to solve for X using the main dictionary
% variable D as the dictionary, but this appears to be unstable. Instead,
% use the projected dictionary variable G
b = GSf + rho*fft2(Y - U);
Xf = solvedbi_sm(Gf, rho, b);
X = ifft2(Xf, 'symmetric');
clear b Xf Gf GSf;
% See pg. 21 of boyd-2010-distributed
if opt.XRelaxParam == 1,
Xr = X;
else
Xr = opt.XRelaxParam*X + (1-opt.XRelaxParam)*Y;
end
% Solve Y subproblem
Y(:,:,1:(end-1),:) = shrink(Xr(:,:,1:(end-1),:) + U(:,:,1:(end-1),:), ...
(lambda/rho)*opt.L1Weight);
Y(:,:,end,:) = bsxfun(@times, IYW, Xr(:,:,end,:) + U(:,:,end,:));
if opt.NonNegCoef,
Y(Y < 0) = 0;
end
if opt.NoBndryCross,
Y((end-size(D,1)+2):end,:,1:(end-1),:) = 0;
Y(:,(end-size(D,2)+2):end,1:(end-1),:) = 0;
end
Yf = fft2(Y);
YGif = Yf(:,:,end,:);
YSf = sum(bsxfun(@times, conj(Yf), Sf - YGif), 4);
YSf0 = YSf(:,:,1:(end-1),:);
YSf1 = YSf(:,:,end,:);
% Update dual variable corresponding to X, Y
U = U + Xr - Y;
clear Xr;
% Compute primal and dual residuals and stopping thresholds for X update
nX = norm(X(:)); nY = norm(Y(:)); nU = norm(U(:));
if opt.StdResiduals,
% See pp. 19-20 of boyd-2010-distributed
rx = norm(vec(X - Y));
sx = norm(vec(rho*(Yprv - Y)));
eprix = sqrt(Nx)*opt.AbsStopTol+max(nX,nY)*opt.RelStopTol;
eduax = sqrt(Nx)*opt.AbsStopTol+rho*nU*opt.RelStopTol;
else
% See wohlberg-2015-adaptive
rx = norm(vec(X - Y))/max(nX,nY);
sx = norm(vec(Yprv - Y))/nU;
eprix = sqrt(Nx)*opt.AbsStopTol/max(nX,nY)+opt.RelStopTol;
eduax = sqrt(Nx)*opt.AbsStopTol/(rho*nU)+opt.RelStopTol;
end
clear X;
% Compute l1 norm of Y
Jl1 = sum(abs(vec(bsxfun(@times, opt.L1Weight, Y(:,:,1:(end-1),:)))));
% Update record of previous step Y
Yprv = Y;
% Solve D subproblem. Similarly, it would be simpler and more efficient to
% solve for D using the main coefficient variable X as the coefficients,
% but it appears to be more stable to use the shrunk coefficient variable Y
b = YSf0 + sigma*fft2(G - H);
if strcmp(opt.LinSolve, 'SM'),
Df = solvemdbi_ism(Yf(:,:,1:(end-1),:), sigma, b);
else
[Df, cgst] = solvemdbi_cg(Yf(:,:,1:(end-1),:), sigma, b, ...
cgt, opt.MaxCGIter, Df(:));
end
clear b YSf;
%D = cat(3, ifft2(Df, 'symmetric'), imp);
D = ifft2(Df, 'symmetric');
if strcmp(opt.LinSolve, 'SM'), clear Df; end
% See pg. 21 of boyd-2010-distributed
if opt.DRelaxParam == 1,
Dr = D;
else
Dr = opt.DRelaxParam*D + (1-opt.DRelaxParam)*G;
end
% Solve G subproblem
G = Pcn(Dr + H);
Gf = fft2(cat(3, G, imp));
GSf = bsxfun(@times, conj(Gf), Sf);
% Update dual variable corresponding to D, G
H = H + Dr - G;
clear Dr;
% Compute primal and dual residuals and stopping thresholds for D update
nD = norm(D(:)); nG = norm(G(:)); nH = norm(H(:));
if opt.StdResiduals,
% See pp. 19-20 of boyd-2010-distributed
rd = norm(vec(D - G));
sd = norm(vec(sigma*(Gprv - G)));
eprid = sqrt(Nd)*opt.AbsStopTol+max(nD,nG)*opt.RelStopTol;
eduad = sqrt(Nd)*opt.AbsStopTol+sigma*nH*opt.RelStopTol;
else
% See wohlberg-2015-adaptive
rd = norm(vec(D - G))/max(nD,nG);
sd = norm(vec(Gprv - G))/nH;
eprid = sqrt(Nd)*opt.AbsStopTol/max(nD,nG)+opt.RelStopTol;
eduad = sqrt(Nd)*opt.AbsStopTol/(sigma*nH)+opt.RelStopTol;
end
% Apply CG auto tolerance policy if enabled
if opt.CGTolAuto && (rd/opt.CGTolFactor) < cgt,
cgt = rd/opt.CGTolFactor;
end
% Compute measure of D constraint violation
Jcn = norm(vec(Pcn(D) - D));
clear D;
% Update record of previous step G
Gprv = G;
% Compute data fidelity term in Fourier domain (note normalisation)
Jdf = sum(vec(abs(sum(bsxfun(@times,Gf,Yf),3)-Sf).^2))/(2*xsz(1)*xsz(2));
Jfn = Jdf + lambda*Jl1;
clear Yf;
% Record and display iteration details
tk = toc(tstart);
optinf.itstat = [optinf.itstat;...
[k Jfn Jdf Jl1 rx sx rd sd eprix eduax eprid eduad rho sigma tk]];
if opt.Verbose,
dvc = [k, Jfn, Jdf, Jl1, Jcn, rx, sx, rd, sd];
if opt.AutoRho,
dvc = [dvc rho];
end
if opt.AutoSigma,
dvc = [dvc sigma];
end
disp(sprintf(sfms, dvc));
end
% See wohlberg-2015-adaptive and pp. 20-21 of boyd-2010-distributed
if opt.AutoRho,
if k ~= 1 && mod(k, opt.AutoRhoPeriod) == 0,
if opt.AutoRhoScaling,
rhomlt = sqrt(rx/sx);
if rhomlt < 1, rhomlt = 1/rhomlt; end
if rhomlt > opt.RhoScaling, rhomlt = opt.RhoScaling; end
else
rhomlt = opt.RhoScaling;
end
rsf = 1;
if rx > opt.RhoRsdlRatio*sx, rsf = rhomlt; end
if sx > opt.RhoRsdlRatio*rx, rsf = 1/rhomlt; end
rho = rsf*rho;
U = U/rsf;
end
end
if opt.AutoSigma,
if k ~= 1 && mod(k, opt.AutoSigmaPeriod) == 0,
if opt.AutoSigmaScaling,
sigmlt = sqrt(rd/sd);
if sigmlt < 1, sigmlt = 1/sigmlt; end
if sigmlt > opt.SigmaScaling, sigmlt = opt.SigmaScaling; end
else
sigmlt = opt.SigmaScaling;
end
ssf = 1;
if rd > opt.SigmaRsdlRatio*sd, ssf = sigmlt; end
if sd > opt.SigmaRsdlRatio*rd, ssf = 1/sigmlt; end
sigma = ssf*sigma;
H = H/ssf;
end
end
k = k + 1;
end
% Record run time and working variables
optinf.runtime = toc(tstart);
optinf.Y = Y;
optinf.U = U;
optinf.G = G;
optinf.H = H;
optinf.lambda = lambda;
optinf.rho = rho;
optinf.sigma = sigma;
optinf.cgt = cgt;
if exist('cgst'), optinf.cgst = cgst; end
if opt.Verbose && opt.MaxMainIter > 0,
disp(char('-' * ones(1,nsep)));
end
D = PzpT(G);
Y = Y(:,:,1:(end-1),:);
return
function u = vec(v)
u = v(:);
return
function u = shrink(v, lambda)
if isscalar(lambda),
u = sign(v).*max(0, abs(v) - lambda);
else
u = sign(v).*max(0, bsxfun(@minus, abs(v), lambda));
end
return
function u = zpad(v, sz)
u = zeros(sz(1), sz(2), size(v,3), size(v,4), class(v));
u(1:size(v,1), 1:size(v,2),:,:) = v;
return
function u = bcrop(v, sz)
if numel(sz) <= 2,
if numel(sz) == 1
cs = [sz sz];
else
cs = sz;
end
u = v(1:cs(1), 1:cs(2), :);
else
cs = max(sz,[],2);
u = zeros(cs(1), cs(2), size(v,3), class(v));
for k = 1:size(v,3),
u(1:sz(1,k), 1:sz(2,k), k) = v(1:sz(1,k), 1:sz(2,k), k);
end
end
return
function opt = defaultopts(opt)
if ~isfield(opt,'Verbose'),
opt.Verbose = 0;
end
if ~isfield(opt,'MaxMainIter'),
opt.MaxMainIter = 1000;
end
if ~isfield(opt,'AbsStopTol'),
opt.AbsStopTol = 1e-6;
end
if ~isfield(opt,'RelStopTol'),
opt.RelStopTol = 1e-4;
end
if ~isfield(opt,'L1Weight'),
opt.L1Weight = 1;
end
if ~isfield(opt,'Y0'),
opt.Y0 = [];
end
if ~isfield(opt,'U0'),
opt.U0 = [];
end
if ~isfield(opt,'G0'),
opt.G0 = [];
end
if ~isfield(opt,'H0'),
opt.H0 = [];
end
if ~isfield(opt,'rho'),
opt.rho = [];
end
if ~isfield(opt,'AutoRho'),
opt.AutoRho = 0;
end
if ~isfield(opt,'AutoRhoPeriod'),
opt.AutoRhoPeriod = 10;
end
if ~isfield(opt,'RhoRsdlRatio'),
opt.RhoRsdlRatio = 10;
end
if ~isfield(opt,'RhoScaling'),
opt.RhoScaling = 2;
end
if ~isfield(opt,'AutoRhoScaling'),
opt.AutoRhoScaling = 0;
end
if ~isfield(opt,'sigma'),
opt.sigma = [];
end
if ~isfield(opt,'AutoSigma'),
opt.AutoSigma = 0;
end
if ~isfield(opt,'AutoSigmaPeriod'),
opt.AutoSigmaPeriod = 10;
end
if ~isfield(opt,'SigmaRsdlRatio'),
opt.SigmaRsdlRatio = 10;
end
if ~isfield(opt,'SigmaScaling'),
opt.SigmaScaling = 2;
end
if ~isfield(opt,'AutoSigmaScaling'),
opt.AutoSigmaScaling = 0;
end
if ~isfield(opt,'StdResiduals'),
opt.StdResiduals = 0;
end
if ~isfield(opt,'XRelaxParam'),
opt.XRelaxParam = 1;
end
if ~isfield(opt,'DRelaxParam'),
opt.DRelaxParam = 1;
end
if ~isfield(opt,'LinSolve'),
opt.LinSolve = 'SM';
end
if ~isfield(opt,'MaxCGIter'),
opt.MaxCGIter = 1000;
end
if ~isfield(opt,'CGTol'),
opt.CGTol = 1e-3;
end
if ~isfield(opt,'CGTolAuto'),
opt.CGTolAuto = 0;
end
if ~isfield(opt,'CGTolAutoFactor'),
opt.CGTolFactor = 50;
end
if ~isfield(opt,'NoBndryCross'),
opt.NoBndryCross = 0;
end
if ~isfield(opt,'DictFilterSizes'),
opt.DictFilterSizes = [];
end
if ~isfield(opt,'NonNegCoef'),
opt.NonNegCoef = 0;
end
if ~isfield(opt,'ZeroMean'),
opt.ZeroMean = 0;
end
if ~isfield(opt,'W'),
opt.W = 1.0;
end
return
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
ccmod.m
|
.m
|
convolutional_sparse_coding-master/DictLearn/ccmod.m
| 10,515 |
utf_8
|
5b4a7f8d3e714708070d3067dcb900e0
|
function [D, optinf] = ccmod(X, S, dsz, opt)
% ccmod -- Convolutional Constrained Method of Optimal Directions (MOD)
%
% argmin_{d_m} (1/2) \sum_k ||\sum_m x_k,m * d_m - s_k||_2^2
% such that ||d_m||_2 = 1
%
% The solution is computed using the ADMM approach (see
% boyd-2010-distributed for details).
%
% Usage:
% [D, optinf] = ccmod(X, S, dsz, opt)
%
% Input:
% X Coefficient maps (3D array)
% S Input images
% dsz Dictionary size
% opt Algorithm parameters structure
%
% Output:
% D Dictionary filter set (3D array)
% optinf Details of optimisation
%
%
% Options structure fields:
% Verbose Flag determining whether iteration status is displayed.
% Fields are iteration number, functional value,
% data fidelity term, l1 regularisation term, and
% primal and dual residuals (see Sec. 3.3 of
% boyd-2010-distributed). The values of rho and sigma
% are also displayed if options request that they are
% automatically adjusted.
% MaxMainIter Maximum main iterations
% AbsStopTol Absolute convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% RelStopTol Relative convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% G0 Initial value for G
% H0 Initial value for H
% sigma ADMM penalty parameter
% AutoSigma Flag determining whether sigma is automatically updated
% (see Sec. 3.4.1 of boyd-2010-distributed)
% AutoSigmaPeriod Iteration period on which sigma is updated
% SigmaRsdlRatio Primal/dual residual ratio in sigma update test
% SigmaScaling Multiplier applied to sigma when updated
% AutoSigmaScaling Flag determining whether SigmaScaling value is
% adaptively determined (see wohlberg-2015-adaptive). If
% enabled, SigmaScaling specifies a maximum allowed
% multiplier instead of a fixed multiplier.
% StdResiduals Flag determining whether standard residual definitions
% (see Sec 3.3 of boyd-2010-distributed) are used instead
% of normalised residuals (see wohlberg-2015-adaptive)
% RelaxParam Relaxation parameter (see Sec. 3.4.3 of
% boyd-2010-distributed)
% LinSolve Linear solver for main problem: 'SM' or 'CG'
% MaxCGIter Maximum CG iterations when using CG solver
% CGTol CG tolerance when using CG solver
% CGTolAuto Flag determining use of automatic CG tolerance
% CGTolFactor Factor by which primal residual is divided to obtain CG
% tolerance, when automatic tolerance is active
% ZeroMean Force learned dictionary entries to be zero-mean
% AuxVarObj Flag determining whether objective function is computed
% using the auxiliary (split) variable
%
%
% Author: Brendt Wohlberg <[email protected]> Modified: 2015-07-30
%
% This file is part of the SPORCO library. Details of the copyright
% and user license can be found in the 'Copyright' and 'License' files
% distributed with the library.
if nargin < 4,
opt = [];
end
checkopt(opt, defaultopts([]));
opt = defaultopts(opt);
% Set up status display for verbose operation
hstr = 'Itn Obj Cnst r s ';
sfms = '%4d %9.2e %9.2e %9.2e %9.2e';
nsep = 44;
if opt.AutoSigma,
hstr = [hstr ' sigma '];
sfms = [sfms ' %9.2e'];
nsep = nsep + 10;
end
if opt.Verbose && opt.MaxMainIter > 0,
disp(hstr);
disp(char('-' * ones(1,nsep)));
end
% Collapsing of trailing singleton dimensions greatly complicates
% handling of both SMV and MMV cases. The simplest approach would be
% if S could always be reshaped to 4d, with dimensions consisting of
% image rows, image cols, a single dimensional placeholder for number
% of filters, and number of measurements, but in the single
% measurement case the third dimension is collapsed so that the array
% is only 3d.
if size(S,3) > 1,
xsz = size(X);
hrm = [1 1 1 size(S,3)];
% Insert singleton 3rd dimension (for number of filters) so that
% 4th dimension is number of images in input s volume
S = reshape(S, [size(S,1) size(S,2) 1 size(S,3)]);
else
xsz = [size(X) 1];
hrm = 1;
end
xrm = [1 1 size(X,3)];
% Set dsz to correct form
if numel(dsz) == 3, dsz = dsz(1:2); end
% Mean removal and normalisation projections
Pzmn = @(x) bsxfun(@minus, x, mean(mean(x,1),2));
Pnrm = @(x) bsxfun(@rdivide, x, sqrt(sum(sum(x.^2, 1), 2)));
% Projection of filter to full image size and its transpose
% (zero-pad and crop respectively)
Pzp = @(x) zpad(x, xsz(1:2));
PzpT = @(x) bcrop(x, dsz);
% Projection of dictionary filters onto constraint set
if opt.ZeroMean,
Pcn = @(x) Pnrm(Pzp(Pzmn(PzpT(x))));
else
Pcn = @(x) Pnrm(Pzp(PzpT(x)));
end
% Start timer
tstart = tic;
% Compute coefficients in DFT domain
Xf = fft2(X, size(S,1), size(S,2));
% Compute signal in DFT domain
Sf = fft2(S);
% S convolved with all coefficients in DFT domain
XSf = sum(bsxfun(@times, conj(Xf), Sf), 4);
% Set up algorithm parameters and initialise variables
sigma = opt.sigma;
if isempty(sigma), sigma = size(S,3); end;
Nd = prod(xsz(1:3));
cgt = opt.CGTol;
optinf = struct('itstat', [], 'opt', opt);
r = Inf;
s = Inf;
epri = 0;
edua = 0;
% Initialise main working variables
D = []; Df = [];
if isempty(opt.G0),
G = zeros([xsz(1) xsz(2) xsz(3)]);
else
G = opt.G0;
end
Gprv = G;
if isempty(opt.H0),
if isempty(opt.G0),
H = zeros([xsz(1) xsz(2) xsz(3)]);
else
H = G;
end
else
H = opt.H0;
end
% Main loop
k = 1;
while k <= opt.MaxMainIter && (r > epri | s > edua),
% Solve subproblems and update dual variable
if strcmp(opt.LinSolve, 'SM'),
Df = solvemdbi_ism(Xf, sigma, XSf + sigma*fft2(G - H));
else
[Df, cgst] = solvemdbi_cg(Xf, sigma, XSf + sigma*fft2(G - H), ...
cgt, opt.MaxCGIter, Df(:));
end
D = ifft2(Df, 'symmetric');
% See pg. 21 of boyd-2010-distributed
if opt.RelaxParam == 1,
Dr = D;
else
Dr = opt.RelaxParam*D + (1-opt.RelaxParam)*G;
end
G = Pcn(Dr + H);
H = H + Dr - G;
% Compute data fidelity term in Fourier domain (note normalisation)
if opt.AuxVarObj,
Gf = fft2(G); % This represents unnecessary computational cost
Job = sum(vec(abs(sum(bsxfun(@times,Gf,Xf),3)-Sf).^2))/(2*xsz(1)*xsz(2));
Jcn = 0;
else
Job = sum(vec(abs(sum(bsxfun(@times,Df,Xf),3)-Sf).^2))/(2*xsz(1)*xsz(2));
Jcn = norm(vec(Pcn(D) - D));
end
nD = norm(D(:)); nG = norm(G(:)); nH = norm(H(:));
if opt.StdResiduals,
% See pp. 19-20 of boyd-2010-distributed
r = norm(vec(D - G));
s = norm(vec(sigma*(Gprv - G)));
epri = sqrt(Nd)*opt.AbsStopTol+max(nD,nG)*opt.RelStopTol;
edua = sqrt(Nd)*opt.AbsStopTol+sigma*nH*opt.RelStopTol;
else
% See wohlberg-2015-adaptive
r = norm(vec(D - G))/max(nD,nG);
s = norm(vec(Gprv - G))/nH;
epri = sqrt(Nd)*opt.AbsStopTol/max(nD,nG)+opt.RelStopTol;
edua = sqrt(Nd)*opt.AbsStopTol/(sigma*nH)+opt.RelStopTol;
end
if opt.CGTolAuto && (r/opt.CGTolFactor) < cgt,
cgt = r/opt.CGTolFactor;
end
% Record and display iteration details
tk = toc(tstart);
optinf.itstat = [optinf.itstat; [k Job Jcn r s epri edua sigma tk]];
if opt.Verbose,
if opt.AutoSigma,
disp(sprintf(sfms, k, Job, Jcn, r, s, sigma));
else
disp(sprintf(sfms, k, Job, Jcn, r, s));
end
end
% See wohlberg-2015-adaptive and pp. 20-21 of boyd-2010-distributed
if opt.AutoSigma,
if k ~= 1 && mod(k, opt.AutoSigmaPeriod) == 0,
if opt.AutoSigmaScaling,
sigmlt = sqrt(r/s);
if sigmlt < 1, sigmlt = 1/sigmlt; end
if sigmlt > opt.SigmaScaling, sigmlt = opt.SigmaScaling; end
else
sigmlt = opt.SigmaScaling;
end
ssf = 1;
if r > opt.SigmaRsdlRatio*s, ssf = sigmlt; end
if s > opt.SigmaRsdlRatio*r, ssf = 1/sigmlt; end
sigma = ssf*sigma;
H = H/ssf;
end
end
Gprv = G;
k = k + 1;
end
% Record run time and working variables
optinf.runtime = toc(tstart);
optinf.D = D;
optinf.G = G;
optinf.H = H;
optinf.sigma = sigma;
optinf.cgt = cgt;
if exist('cgst'), optinf.cgst = cgst; end
D = PzpT(G);
if opt.Verbose && opt.MaxMainIter > 0,
disp(char('-' * ones(1,nsep)));
end
return
function u = vec(v)
u = v(:);
return
function u = zpad(v, sz)
u = zeros(sz(1), sz(2), size(v,3), size(v,4), class(v));
u(1:size(v,1), 1:size(v,2),:,:) = v;
return
function u = bcrop(v, sz)
if numel(sz) <= 2,
if numel(sz) == 1
cs = [sz sz];
else
cs = sz;
end
u = v(1:cs(1), 1:cs(2), :);
else
if size(sz,1) < size(sz,2), sz = sz'; end
cs = max(sz);
u = zeros(cs(1), cs(2), size(v,3));
for k = 1:size(v,3),
u(1:sz(k,1), 1:sz(k,2), k) = v(1:sz(k,1), 1:sz(k,2), k);
end
end
return
function opt = defaultopts(opt)
if ~isfield(opt,'Verbose'),
opt.Verbose = 0;
end
if ~isfield(opt,'MaxMainIter'),
opt.MaxMainIter = 200;
end
if ~isfield(opt,'AbsStopTol'),
opt.AbsStopTol = 1e-6;
end
if ~isfield(opt,'RelStopTol'),
opt.RelStopTol = 1e-4;
end
if ~isfield(opt,'G0'),
opt.G0 = [];
end
if ~isfield(opt,'H0'),
opt.H0 = [];
end
if ~isfield(opt,'sigma'),
opt.sigma = [];
end
if ~isfield(opt,'AutoSigma'),
opt.AutoSigma = 0;
end
if ~isfield(opt,'AutoSigmaPeriod'),
opt.AutoSigmaPeriod = 10;
end
if ~isfield(opt,'SigmaRsdlRatio'),
opt.SigmaRsdlRatio = 10;
end
if ~isfield(opt,'SigmaScaling'),
opt.SigmaScaling = 2;
end
if ~isfield(opt,'AutoSigmaScaling'),
opt.AutoSigmaScaling = 0;
end
if ~isfield(opt,'StdResiduals'),
opt.StdResiduals = 0;
end
if ~isfield(opt,'RelaxParam'),
opt.RelaxParam = 1;
end
if ~isfield(opt,'LinSolve'),
opt.LinSolve = 'SM';
end
if ~isfield(opt,'MaxCGIter'),
opt.MaxCGIter = 1000;
end
if ~isfield(opt,'CGTol'),
opt.CGTol = 1e-3;
end
if ~isfield(opt,'CGTolAuto'),
opt.CGTolAuto = 0;
end
if ~isfield(opt,'CGTolAutoFactor'),
opt.CGTolFactor = 50;
end
if ~isfield(opt,'ZeroMean'),
opt.ZeroMean = 0;
end
if ~isfield(opt,'AuxVarObj'),
opt.AuxVarObj = 0;
end
return
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
cbpdndl_gpu.m
|
.m
|
convolutional_sparse_coding-master/DictLearn/cbpdndl_gpu.m
| 17,223 |
utf_8
|
f503b15857b3a6c14895f23722dd20bf
|
function [D, Y, optinf] = cbpdndl_gpu(D0, S, lambda, opt)
% cbpdndl_gpu -- Convolutional BPDN Dictionary Learning (GPU version)
%
% argmin_{x_m,d_m} (1/2) \sum_k ||\sum_m d_m * x_k,m - s_k||_2^2 +
% lambda \sum_k \sum_m ||x_k,m||_1
%
% The solution is computed using Augmented Lagrangian methods
% (see boyd-2010-distributed) with efficient solution of the
% main linear systems (see wohlberg-2016-efficient).
%
% Usage:
% [D, X, optinf] = cbpdndl_gpu(D0, S, lambda, opt)
%
% Input:
% D0 Initial dictionary
% S Input images
% lambda Regularization parameter
% opt Options/algorithm parameters structure (see below)
%
% Output:
% D Dictionary filter set (3D array)
% X Coefficient maps (3D array)
% optinf Details of optimisation
%
%
% Options structure fields:
% Verbose Flag determining whether iteration status is displayed.
% Fields are iteration number, functional value,
% data fidelity term, l1 regularisation term, and
% primal and dual residuals (see Sec. 3.3 of
% boyd-2010-distributed). The values of rho and sigma
% are also displayed if options request that they are
% automatically adjusted.
% MaxMainIter Maximum main iterations
% AbsStopTol Absolute convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% RelStopTol Relative convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% L1Weight Weight array for L1 norm
% Y0 Initial value for Y
% U0 Initial value for U
% G0 Initial value for G (overrides D0 if specified)
% H0 Initial value for H
% rho Augmented Lagrangian penalty parameter
% AutoRho Flag determining whether rho is automatically updated
% (see Sec. 3.4.1 of boyd-2010-distributed)
% AutoRhoPeriod Iteration period on which rho is updated
% RhoRsdlRatio Primal/dual residual ratio in rho update test
% RhoScaling Multiplier applied to rho when updated
% AutoRhoScaling Flag determining whether RhoScaling value is
% adaptively determined (see wohlberg-2015-adaptive). If
% enabled, RhoScaling specifies a maximum allowed
% multiplier instead of a fixed multiplier
% sigma Augmented Lagrangian penalty parameter
% AutoSigma Flag determining whether sigma is automatically
% updated (see Sec. 3.4.1 of boyd-2010-distributed)
% AutoSigmaPeriod Iteration period on which sigma is updated
% SigmaRsdlRatio Primal/dual residual ratio in sigma update test
% SigmaScaling Multiplier applied to sigma when updated
% AutoSigmaScaling Flag determining whether SigmaScaling value is
% adaptively determined (see wohlberg-2015-adaptive). If
% enabled, SigmaScaling specifies a maximum allowed
% multiplier instead of a fixed multiplier.
% StdResiduals Flag determining whether standard residual definitions
% (see Sec 3.3 of boyd-2010-distributed) are used instead
% of normalised residuals (see wohlberg-2015-adaptive)
% XRelaxParam Relaxation parameter (see Sec. 3.4.3 of
% boyd-2010-distributed) for X update
% DRelaxParam Relaxation parameter (see Sec. 3.4.3 of
% boyd-2010-distributed) for D update
% LinSolve Linear solver for main problem: 'SM' or 'CG'
% MaxCGIter Maximum CG iterations when using CG solver
% CGTol CG tolerance when using CG solver
% CGTolAuto Flag determining use of automatic CG tolerance
% CGTolFactor Factor by which primal residual is divided to obtain CG
% tolerance, when automatic tolerance is active
% NoBndryCross Flag indicating whether all solution coefficients
% corresponding to filters crossing the image boundary
% should be forced to zero.
% DictFilterSizes Array of size 2 x M where each column specifies the
% filter size (rows x columns) of the corresponding
% dictionary filter
% ZeroMean Force learned dictionary entries to be zero-mean
%
%
% Authors: Brendt Wohlberg <[email protected]>
% Ping-Keng Jao <[email protected]>
% Modified: 2015-12-18
%
% This file is part of the SPORCO library. Details of the copyright
% and user license can be found in the 'License' file distributed with
% the library.
gS = gpuArray(S);
gD = gpuArray(D0);
glambda = gpuArray(lambda);
if nargin < 4,
opt = [];
end
checkopt(opt, defaultopts([]));
opt = defaultopts(opt);
% Set up status display for verbose operation
hstr = ['Itn Fnc DFid l1 Cnstr '...
'r(X) s(X) r(D) s(D) '];
sfms = '%4d %9.2e %9.2e %9.2e %9.2e %9.2e %9.2e %9.2e %9.2e';
nsep = 84;
if opt.AutoRho,
hstr = [hstr ' rho '];
sfms = [sfms ' %9.2e'];
nsep = nsep + 10;
end
if opt.AutoSigma,
hstr = [hstr ' sigma '];
sfms = [sfms ' %9.2e'];
nsep = nsep + 10;
end
if opt.Verbose && opt.MaxMainIter > 0,
disp(hstr);
disp(char('-' * ones(1,nsep)));
end
% Collapsing of trailing singleton dimensions greatly complicates
% handling of both SMV and MMV cases. The simplest approach would be
% if S could always be reshaped to 4d, with dimensions consisting of
% image rows, image cols, a single dimensional placeholder for number
% of filters, and number of measurements, but in the single
% measurement case the third dimension is collapsed so that the array
% is only 3d.
if size(S,3) > 1,
xsz = [size(S,1) size(S,2) size(D0,3) size(S,3)];
% Insert singleton 3rd dimension (for number of filters) so that
% 4th dimension is number of images in input s volume
gS = gpuArray(reshape(gS, [size(S,1) size(S,2) 1 size(S,3)]));
else
xsz = [size(S,1) size(S,2) size(D0,3) 1];
end
gNx = gpuArray(prod(xsz));
gNd = gpuArray(prod(xsz(1:2))*size(D0,3));
gcgt = gpuArray(opt.CGTol);
% Dictionary size may be specified when learning multiscale
% dictionary
if isempty(opt.DictFilterSizes),
dsz = [size(D0,1) size(D0,2)];
else
dsz = opt.DictFilterSizes;
end
% Mean removal and normalisation projections
Pzmn = @(x) bsxfun(@minus, x, mean(mean(x,1),2));
Pnrm = @(x) bsxfun(@rdivide, x, sqrt(sum(sum(x.^2, 1), 2)));
% Projection of filter to full image size and its transpose
% (zero-pad and crop respectively)
Pzp = @(x) zpad(x, xsz(1:2));
PzpT = @(x) bcrop(x, dsz);
% Projection of dictionary filters onto constraint set
if opt.ZeroMean,
Pcn = @(x) Pnrm(Pzp(Pzmn(PzpT(x))));
else
Pcn = @(x) Pnrm(Pzp(PzpT(x)));
end
% Start timer
tstart = tic;
% Project initial dictionary onto constraint set
% D = Pnrm(D0);
gD = Pnrm(gD);
% Compute signal in DFT domain
gSf = fft2(gS);
% Set up algorithm parameters and initialise variables
grho = gpuArray(opt.rho);
if isempty(grho), grho = 50*glambda+1; end;
if opt.AutoRho,
asgr = opt.RhoRsdlRatio;
asgm = opt.RhoScaling;
end
gsigma = gpuArray(opt.sigma);
if isempty(gsigma), gsigma = gpuArray(size(S,3)); end;
if opt.AutoSigma,
asdr = opt.SigmaRsdlRatio;
asdm = opt.SigmaScaling;
end
optinf = struct('itstat', [], 'opt', opt);
grx = gpuArray(Inf);
gsx = gpuArray(Inf);
grd = gpuArray(Inf);
gsd = gpuArray(Inf);
geprix = gpuArray(0);
geduax = gpuArray(0);
geprid = gpuArray(0);
geduad = gpuArray(0);
% Initialise main working variables
% X = [];
if isempty(opt.Y0),
gY = gpuArray.zeros(xsz, class(S));
else
gY = gpuArray(opt.Y0);
end
gYprv = gY;
if isempty(opt.U0),
if isempty(opt.Y0),
gU = gpuArray.zeros(xsz, class(S));
else
gU = (glambda/grho)*sign(gY);
end
else
gU = gpuArray(opt.U0);
end
% Df = [];
if isempty(opt.G0),
gG = Pzp(gD);
else
gG = gpuArray(opt.G0);
end
gGprv = gG;
if isempty(opt.H0),
if isempty(opt.G0),
gH = gpuArray.zeros(size(gG), class(S));
else
gH = gG;
end
else
gH = gpuArray(opt.H0);
end
gGf = fft2(gG, size(S,1), size(S,2));
gGSf = bsxfun(@times, conj(gGf), gSf);
% Main loop
k = 1;
while k <= opt.MaxMainIter & (grx > geprix | gsx > geduax | ...
grd > geprid | gsd >geduad),
% Solve X subproblem. It would be simpler and more efficient (since the
% DFT is already available) to solve for X using the main dictionary
% variable D as the dictionary, but this appears to be unstable. Instead,
% use the projected dictionary variable G
gXf = solvedbi_sm(gGf, grho, gGSf + grho*fft2(gY - gU));
gX = ifft2(gXf, 'symmetric');
clear gXf gGf gGSf;
% See pg. 21 of boyd-2010-distributed
if opt.XRelaxParam == 1,
gXr = gX;
else
gXr = opt.XRelaxParam*gX + (1-opt.XRelaxParam)*gY;
end
% Solve Y subproblem
gY = shrink(gXr + gU, (glambda/grho)*opt.L1Weight);
if opt.NoBndryCross,
gY((end-size(gD,1)+2):end,:,:,:) = 0;
gY(:,(end-size(gD,1)+2):end,:,:) = 0;
end
gYf = fft2(gY);
gYSf = sum(bsxfun(@times, conj(gYf), gSf), 4);
% Update dual variable corresponding to X, Y
gU = gU + gXr - gY;
clear gXr;
% Compute primal and dual residuals and stopping thresholds for X update
gnX = norm(gX(:)); gnY = norm(gY(:)); gnU = norm(gU(:));
if opt.StdResiduals,
% See pp. 19-20 of boyd-2010-distributed
grx = norm(vec(gX - gY));
gsx = norm(vec(grho*(gYprv - gY)));
geprix = sqrt(gNx)*opt.AbsStopTol+max(gnX,gnY)*opt.RelStopTol;
geduax = sqrt(gNx)*opt.AbsStopTol+grho*gnU*opt.RelStopTol;
else
% See wohlberg-2015-adaptive
grx = norm(vec(gX - gY))/max(gnX,gnY);
gsx = norm(vec(gYprv - gY))/gnU;
geprix = sqrt(gNx)*opt.AbsStopTol/max(gnX,gnY)+opt.RelStopTol;
geduax = sqrt(gNx)*opt.AbsStopTol/(grho*gnU)+opt.RelStopTol;
end
clear gX;
% Compute l1 norm of Y
gJl1 = sum(abs(vec(opt.L1Weight .* gY)));
% Update record of previous step Y
gYprv = gY;
% Solve D subproblem. Similarly, it would be simpler and more efficient to
% solve for D using the main coefficient variable X as the coefficients,
% but it appears to be more stable to use the shrunk coefficient variable Y
if strcmp(opt.LinSolve, 'SM'),
gDf = solvemdbi_ism_gpu(gYf, gsigma, gYSf + gsigma*fft2(gG - gH));
else
[gDf, gcgst] = solvemdbi_cg(gYf, gsigma, gYSf + gsigma*fft2(gG - gH), ...
gcgt, opt.MaxCGIter, gDf(:));
end
clear YSf;
gD = ifft2(gDf, 'symmetric');
if strcmp(opt.LinSolve, 'SM'), clear gDf; end
% See pg. 21 of boyd-2010-distributed
if opt.DRelaxParam == 1,
gDr = gD;
else
gDr = opt.DRelaxParam*gD + (1-opt.DRelaxParam)*gG;
end
% Solve G subproblem
gG = Pcn(gDr + gH);
gGf = fft2(gG);
gGSf = bsxfun(@times, conj(gGf), gSf);
% Update dual variable corresponding to D, G
gH = gH + gDr - gG;
clear gDr;
% Compute primal and dual residuals and stopping thresholds for D update
gnD = norm(gD(:)); gnG = norm(gG(:)); gnH = norm(gH(:));
if opt.StdResiduals,
% See pp. 19-20 of boyd-2010-distributed
grd = norm(vec(gD - gG));
gsd = norm(vec(sigma*(gGprv - gG)));
geprid = sqrt(gNd)*opt.AbsStopTol+max(gnD,gnG)*opt.RelStopTol;
geduad = sqrt(gNd)*opt.AbsStopTol+gsigma*gnH*opt.RelStopTol;
else
% See wohlberg-2015-adaptive
grd = norm(vec(gD - gG))/max(gnD,gnG);
gsd = norm(vec(gGprv - gG))/gnH;
geprid = sqrt(gNd)*opt.AbsStopTol/max(gnD,gnG)+opt.RelStopTol;
geduad = sqrt(gNd)*opt.AbsStopTol/(gsigma*gnH)+opt.RelStopTol;
end
% Apply CG auto tolerance policy if enabled
if opt.CGTolAuto && (grd/opt.CGTolFactor) < gcgt,
gcgt = grd/opt.CGTolFactor;
end
% Compute measure of D constraint violation
gJcn = norm(vec(Pcn(gD) - gD));
clear gD;
% Update record of previous step G
gGprv = gG;
% Compute data fidelity term in Fourier domain (note normalisation)
gJdf = sum(vec(abs(sum(bsxfun(@times,gGf,gYf),3)-gSf).^2))/(2*xsz(1)*xsz(2));
clear gYf;
gJfn = gJdf + glambda*gJl1;
% Record and display iteration details
tk = toc(tstart);
optinf.itstat = [optinf.itstat;...
[k gather(gJfn) gather(gJdf) gather(gJl1) gather(grx) gather(gsx)...
gather(grd) gather(gsd) gather(geprix) gather(geduax) gather(geprid)...
gather(geduad) gather(grho) gather(gsigma) tk]];
if opt.Verbose,
dvc = [k, gather(gJfn), gather(gJdf), gather(gJl1) gather(gJcn), ...
gather(grx), gather(gsx), gather(grd), gather(gsd)];
if opt.AutoRho,
dvc = [dvc gather(grho)];
end
if opt.AutoSigma,
dvc = [dvc gather(gsigma)];
end
disp(sprintf(sfms, dvc));
end
% See wohlberg-2015-adaptive and pp. 20-21 of boyd-2010-distributed
if opt.AutoRho,
if k ~= 1 && mod(k, opt.AutoRhoPeriod) == 0,
if opt.AutoRhoScaling,
grhomlt = sqrt(grx/gsx);
if grhomlt < 1, grhomlt = 1/grhomlt; end
if grhomlt > opt.RhoScaling, grhomlt = gpuArray(opt.RhoScaling); end
else
grhomlt = gpuArray(opt.RhoScaling);
end
grsf = 1;
if grx > opt.RhoRsdlRatio*gsx, grsf = grhomlt; end
if gsx > opt.RhoRsdlRatio*grx, grsf = 1/grhomlt; end
grho = grsf*grho;
gU = gU/grsf;
end
end
if opt.AutoSigma,
if k ~= 1 && mod(k, opt.AutoSigmaPeriod) == 0,
if opt.AutoSigmaScaling,
gsigmlt = sqrt(grd/gsd);
if gsigmlt < 1, gsigmlt = 1/gsigmlt; end
if gsigmlt > opt.SigmaScaling, gsigmlt = gpuArray(opt.SigmaScaling); end
else
gsigmlt = gpuArray(opt.SigmaScaling);
end
gssf = gpuArray(1);
if grd > opt.SigmaRsdlRatio*gsd, gssf = gsigmlt; end
if gsd > opt.SigmaRsdlRatio*grd, gssf = 1/gsigmlt; end
gsigma = gssf*gsigma;
gH = gH/gssf;
end
end
k = k + 1;
end
gD = PzpT(gG);
% Record run time and working variables
optinf.runtime = toc(tstart);
optinf.Y = gather(gY);
optinf.U = gather(gU);
optinf.G = gather(gG);
optinf.H = gather(gH);
optinf.lambda = gather(glambda);
optinf.rho = gather(grho);
optinf.sigma = gather(gsigma);
optinf.cgt = gather(gcgt);
if exist('gcgst'), optinf.cgst = gather(gcgst); end
D = gather(gD);
Y = optinf.Y;
if opt.Verbose && opt.MaxMainIter > 0,
disp(char('-' * ones(1,nsep)));
end
return
function u = vec(v)
u = v(:);
return
function u = shrink(v, lambda)
u = sign(v).*max(0, abs(v) - lambda);
return
function u = zpad(v, sz)
% u = zeros(sz(1), sz(2), size(v,3), size(v,4), class(v));
u = gpuArray.zeros(sz(1), sz(2), size(v,3), size(v,4));
u(1:size(v,1), 1:size(v,2),:,:) = v;
return
function u = bcrop(v, sz)
if numel(sz) <= 2,
if numel(sz) == 1
cs = [sz sz];
else
cs = sz;
end
u = v(1:cs(1), 1:cs(2), :);
else
if size(sz,1) < size(sz,2), sz = sz'; end
cs = max(sz);
% u = zeros(cs(1), cs(2), size(v,3), class(v));
u = gpuArray.zeros(cs(1), cs(2), size(v,3));
for k = 1:size(v,3),
u(1:sz(k,1), 1:sz(k,2), k) = v(1:sz(k,1), 1:sz(k,2), k);
end
end
return
function opt = defaultopts(opt)
if ~isfield(opt,'Verbose'),
opt.Verbose = 0;
end
if ~isfield(opt,'MaxMainIter'),
opt.MaxMainIter = 1000;
end
if ~isfield(opt,'AbsStopTol'),
opt.AbsStopTol = 1e-6;
end
if ~isfield(opt,'RelStopTol'),
opt.RelStopTol = 1e-4;
end
if ~isfield(opt,'L1Weight'),
opt.L1Weight = 1;
end
if ~isfield(opt,'Y0'),
opt.Y0 = [];
end
if ~isfield(opt,'U0'),
opt.U0 = [];
end
if ~isfield(opt,'G0'),
opt.G0 = [];
end
if ~isfield(opt,'H0'),
opt.H0 = [];
end
if ~isfield(opt,'rho'),
opt.rho = [];
end
if ~isfield(opt,'AutoRho'),
opt.AutoRho = 0;
end
if ~isfield(opt,'AutoRhoPeriod'),
opt.AutoRhoPeriod = 10;
end
if ~isfield(opt,'RhoRsdlRatio'),
opt.RhoRsdlRatio = 10;
end
if ~isfield(opt,'RhoScaling'),
opt.RhoScaling = 2;
end
if ~isfield(opt,'AutoRhoScaling'),
opt.AutoRhoScaling = 0;
end
if ~isfield(opt,'sigma'),
opt.sigma = [];
end
if ~isfield(opt,'AutoSigma'),
opt.AutoSigma = 0;
end
if ~isfield(opt,'AutoSigmaPeriod'),
opt.AutoSigmaPeriod = 10;
end
if ~isfield(opt,'SigmaRsdlRatio'),
opt.SigmaRsdlRatio = 10;
end
if ~isfield(opt,'SigmaScaling'),
opt.SigmaScaling = 2;
end
if ~isfield(opt,'AutoSigmaScaling'),
opt.AutoSigmaScaling = 0;
end
if ~isfield(opt,'StdResiduals'),
opt.StdResiduals = 0;
end
if ~isfield(opt,'XRelaxParam'),
opt.XRelaxParam = 1;
end
if ~isfield(opt,'DRelaxParam'),
opt.DRelaxParam = 1;
end
if ~isfield(opt,'LinSolve'),
opt.LinSolve = 'SM';
end
if ~isfield(opt,'MaxCGIter'),
opt.MaxCGIter = 1000;
end
if ~isfield(opt,'CGTol'),
opt.CGTol = 1e-3;
end
if ~isfield(opt,'CGTolAuto'),
opt.CGTolAuto = 0;
end
if ~isfield(opt,'CGTolAutoFactor'),
opt.CGTolFactor = 50;
end
if ~isfield(opt,'NoBndryCross'),
opt.NoBndryCross = 0;
end
if ~isfield(opt,'DictFilterSizes'),
opt.DictFilterSizes = [];
end
if ~isfield(opt,'ZeroMean'),
opt.ZeroMean = 0;
end
return
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
ccmod_gpu.m
|
.m
|
convolutional_sparse_coding-master/DictLearn/ccmod_gpu.m
| 11,211 |
utf_8
|
017b0a0411e32bb7ab1bde89c394348c
|
function [D, optinf] = ccmod_gpu(X, S, dsz, opt)
% ccmod_gpu -- Convolutional Constrained Method of Optimal Directions
% (MOD) (GPU version)
%
% argmin_{d_m} (1/2) \sum_k ||\sum_m x_k,m * d_m - s_k||_2^2
% such that ||d_m||_2 = 1
%
% The solution of the Convolutional Constrained MOD problem
% (see wohlberg-2016-efficient) is computed using the ADMM
% approach (see boyd-2010-distributed).
%
% Usage:
% [D, optinf] = ccmod_gpu(X, S, dsz, opt)
%
% Input:
% X Coefficient maps (3D array)
% S Input images
% dsz Dictionary size
% opt Algorithm parameters structure
%
% Output:
% D Dictionary filter set (3D array)
% optinf Details of optimisation
%
%
% Options structure fields:
% Verbose Flag determining whether iteration status is displayed.
% Fields are iteration number, functional value,
% data fidelity term, l1 regularisation term, and
% primal and dual residuals (see Sec. 3.3 of
% boyd-2010-distributed). The values of rho and sigma
% are also displayed if options request that they are
% automatically adjusted.
% MaxMainIter Maximum main iterations
% AbsStopTol Absolute convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% RelStopTol Relative convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% G0 Initial value for G
% H0 Initial value for H
% sigma ADMM penalty parameter
% AutoSigma Flag determining whether sigma is automatically updated
% (see Sec. 3.4.1 of boyd-2010-distributed)
% AutoSigmaPeriod Iteration period on which sigma is updated
% SigmaRsdlRatio Primal/dual residual ratio in sigma update test
% SigmaScaling Multiplier applied to sigma when updated
% AutoSigmaScaling Flag determining whether SigmaScaling value is
% adaptively determined (see wohlberg-2015-adaptive). If
% enabled, SigmaScaling specifies a maximum allowed
% multiplier instead of a fixed multiplier.
% StdResiduals Flag determining whether standard residual definitions
% (see Sec 3.3 of boyd-2010-distributed) are used instead
% of normalised residuals (see wohlberg-2015-adaptive)
% RelaxParam Relaxation parameter (see Sec. 3.4.3 of
% boyd-2010-distributed)
% LinSolve Linear solver for main problem: 'SM' or 'CG'
% MaxCGIter Maximum CG iterations when using CG solver
% CGTol CG tolerance when using CG solver
% CGTolAuto Flag determining use of automatic CG tolerance
% CGTolFactor Factor by which primal residual is divided to obtain CG
% tolerance, when automatic tolerance is active
% ZeroMean Force learned dictionary entries to be zero-mean
% AuxVarObj Flag determining whether objective function is computed
% using the auxiliary (split) variable
%
%
% Authors: Brendt Wohlberg <[email protected]>
% Ping-Keng Jao <[email protected]>
% Modified: 2015-12-18
%
% This file is part of the SPORCO library. Details of the copyright
% and user license can be found in the 'License' file distributed with
% the library.
gS = gpuArray(S);
gX = gpuArray(X);
if nargin < 4,
opt = [];
end
checkopt(opt, defaultopts([]));
opt = defaultopts(opt);
% Set up status display for verbose operation
hstr = 'Itn Obj Cnst r s ';
sfms = '%4d %9.2e %9.2e %9.2e %9.2e';
nsep = 44;
if opt.AutoSigma,
hstr = [hstr ' sigma '];
sfms = [sfms ' %9.2e'];
nsep = nsep + 10;
end
if opt.Verbose && opt.MaxMainIter > 0,
disp(hstr);
disp(char('-' * ones(1,nsep)));
end
% Collapsing of trailing singleton dimensions greatly complicates
% handling of both SMV and MMV cases. The simplest approach would be
% if S could always be reshaped to 4d, with dimensions consisting of
% image rows, image cols, a single dimensional placeholder for number
% of filters, and number of measurements, but in the single
% measurement case the third dimension is collapsed so that the array
% is only 3d.
if size(S,3) > 1,
xsz = size(X);
% Insert singleton 3rd dimension (for number of filters) so that
% 4th dimension is number of images in input s volume
gS = reshape(gS, [size(S,1) size(S,2) 1 size(S,3)]);
else
xsz = [size(X) 1];
end
% Set dsz to correct form
if numel(dsz) == 3, dsz = dsz(1:2); end
% Mean removal and normalisation projections
Pzmn = @(x) bsxfun(@minus, x, mean(mean(x,1),2));
Pnrm = @(x) bsxfun(@rdivide, x, sqrt(sum(sum(x.^2, 1), 2)));
% Projection of filter to full image size and its transpose
% (zero-pad and crop respectively)
Pzp = @(x) zpad(x, xsz(1:2));
PzpT = @(x) bcrop(x, dsz);
% Projection of dictionary filters onto constraint set
if opt.ZeroMean,
Pcn = @(x) Pnrm(Pzp(Pzmn(PzpT(x))));
else
Pcn = @(x) Pnrm(Pzp(PzpT(x)));
end
% Start timer
tstart = tic;
% Compute coefficients in DFT domain
gXf = fft2(gX, size(gS,1), size(gS,2));
% Compute signal in DFT domain
gSf = fft2(gS);
% S convolved with all coefficients in DFT domain
gXSf = sum(bsxfun(@times, conj(gXf), gSf), 4);
% Set up algorithm parameters and initialise variables
gsigma = gpuArray(opt.sigma);
if isempty(gsigma), gsigma = size(gS,3); end;
gNd = gpuArray(prod(xsz(1:3)));
gcgt = gpuArray(opt.CGTol);
optinf = struct('itstat', [], 'opt', opt);
gr = gpuArray(Inf);
gs = gpuArray(Inf);
gepri = gpuArray(0);
gedua = gpuArray(0);
% Initialise main working variables
D = []; Df = [];
if isempty(opt.G0),
gG = gpuArray.zeros([xsz(1) xsz(2) xsz(3)]);
else
gG = gpuArray(opt.G0);
end
gGprv = gG;
if isempty(opt.H0),
if isempty(opt.G0),
gH = gpuArray.zeros([xsz(1) xsz(2) xsz(3)]);
else
gH = gG;
end
else
gH = gpuArray(opt.H0);
end
% Main loop
k = 1;
while k <= opt.MaxMainIter & (gr > gepri | gs > gedua),
% Solve subproblems and update dual variable
if strcmp(opt.LinSolve, 'SM'),
gDf = solvemdbi_ism_gpu(gXf, gsigma, gXSf + gsigma*fft2(gG - gH));
else
[gDf, gcgst] = solvemdbi_cg(gXf, gsigma, gXSf + gsigma*fft2(gG - gH), ...
gcgt, opt.MaxCGIter, gDf(:));
end
gD = ifft2(gDf, 'symmetric');
% See pg. 21 of boyd-2010-distributed
if opt.RelaxParam == 1,
gDr = gD;
else
gDr = opt.RelaxParam*gD + (1-opt.RelaxParam)*gG;
end
gG = Pcn(gDr + gH);
gH = gH + gDr - gG;
% Compute data fidelity term in Fourier domain (note normalisation)
if opt.AuxVarObj,
gGf = fft2(gG); % This represents unnecessary computational cost
gJob = sum(vec(abs(sum(bsxfun(@times,gGf,gXf),3)-gSf).^2)) / ...
(2*xsz(1)*xsz(2));
gJcn = 0;
else
gJob = sum(vec(abs(sum(bsxfun(@times,gDf,gXf),3)-gSf).^2)) / ...
(2*xsz(1)*xsz(2));
gJcn = norm(vec(Pcn(gD) - gD));
end
gnD = norm(gD(:)); gnG = norm(gG(:)); gnH = norm(gH(:));
if opt.StdResiduals,
% See pp. 19-20 of boyd-2010-distributed
gr = norm(vec(gD - gG));
gs = norm(vec(gsigma*(gGprv - gG)));
gepri = sqrt(gNd)*opt.AbsStopTol+max(gnD,gnG)*opt.RelStopTol;
gedua = sqrt(gNd)*opt.AbsStopTol+gsigma*gnH*opt.RelStopTol;
else
% See wohlberg-2015-adaptive
gr = norm(vec(gD - gG))/max(gnD,gnG);
gs = norm(vec(gGprv - gG))/gnH;
gepri = sqrt(gNd)*opt.AbsStopTol/max(gnD,gnG)+opt.RelStopTol;
gedua = sqrt(gNd)*opt.AbsStopTol/(gsigma*gnH)+opt.RelStopTol;
end
if opt.CGTolAuto && (gr/opt.CGTolFactor) < gcgt,
gcgt = gr/opt.CGTolFactor;
end
% Record and display iteration details
tk = toc(tstart);
optinf.itstat = [optinf.itstat; [k gather(gJob) gather(gJcn) gather(gr) ...
gather(gs) gather(gepri) gather(gedua) gather(gsigma) tk]];
if opt.Verbose,
if opt.AutoSigma,
disp(sprintf(sfms, k, gather(gJob), gather(gJcn), gather(gr), ...
gather(gs), gather(gsigma)));
else
disp(sprintf(sfms, k, gather(gJob), gather(gJcn), gather(gr), ...
gather(gs)));
end
end
% See wohlberg-2015-adaptive and pp. 20-21 of boyd-2010-distributed
if opt.AutoSigma,
if k ~= 1 && mod(k, opt.AutoSigmaPeriod) == 0,
if opt.AutoSigmaScaling,
gsigmlt = sqrt(gr/gs);
if gsigmlt < 1, gsigmlt = 1/gsigmlt; end
if gsigmlt > opt.SigmaScaling, gsigmlt = gpuArray(opt.SigmaScaling); end
else
gsigmlt = gpuArray(opt.SigmaScaling);
end
gssf = 1;
if gr > opt.SigmaRsdlRatio*gs, gssf = gsigmlt; end
if gs > opt.SigmaRsdlRatio*gr, gssf = 1/gsigmlt; end
gsigma = gssf*gsigma;
gH = gH/gssf;
end
end
gGprv = gG;
k = k + 1;
end
% Record run time and working variables
optinf.runtime = toc(tstart);
optinf.D = gather(gD);
optinf.G = gather(gG);
optinf.H = gather(gH);
optinf.sigma = gather(gsigma);
optinf.cgt = gather(gcgt);
if exist('gcgst'), optinf.cgst = gather(gcgst); end
D = gather(PzpT(gG));
if opt.Verbose && opt.MaxMainIter > 0,
disp(char('-' * ones(1,nsep)));
end
return
function u = vec(v)
u = v(:);
return
function u = zpad(v, sz)
u = gpuArray.zeros(sz(1), sz(2), size(v,3), size(v,4));
u(1:size(v,1), 1:size(v,2),:,:) = v;
return
function u = bcrop(v, sz)
if numel(sz) <= 2,
if numel(sz) == 1
cs = [sz sz];
else
cs = sz;
end
u = v(1:cs(1), 1:cs(2), :);
else
if size(sz,1) < size(sz,2), sz = sz'; end
cs = max(sz);
u = gpuArray.zeros(cs(1), cs(2), size(v,3));
for k = 1:size(v,3),
u(1:sz(k,1), 1:sz(k,2), k) = v(1:sz(k,1), 1:sz(k,2), k);
end
end
return
function opt = defaultopts(opt)
if ~isfield(opt,'Verbose'),
opt.Verbose = 0;
end
if ~isfield(opt,'MaxMainIter'),
opt.MaxMainIter = 200;
end
if ~isfield(opt,'AbsStopTol'),
opt.AbsStopTol = 1e-6;
end
if ~isfield(opt,'RelStopTol'),
opt.RelStopTol = 1e-4;
end
if ~isfield(opt,'G0'),
opt.G0 = [];
end
if ~isfield(opt,'H0'),
opt.H0 = [];
end
if ~isfield(opt,'sigma'),
opt.sigma = [];
end
if ~isfield(opt,'AutoSigma'),
opt.AutoSigma = 0;
end
if ~isfield(opt,'AutoSigmaPeriod'),
opt.AutoSigmaPeriod = 10;
end
if ~isfield(opt,'SigmaRsdlRatio'),
opt.SigmaRsdlRatio = 10;
end
if ~isfield(opt,'SigmaScaling'),
opt.SigmaScaling = 2;
end
if ~isfield(opt,'AutoSigmaScaling'),
opt.AutoSigmaScaling = 0;
end
if ~isfield(opt,'StdResiduals'),
opt.StdResiduals = 0;
end
if ~isfield(opt,'RelaxParam'),
opt.RelaxParam = 1;
end
if ~isfield(opt,'LinSolve'),
opt.LinSolve = 'SM';
end
if ~isfield(opt,'MaxCGIter'),
opt.MaxCGIter = 1000;
end
if ~isfield(opt,'CGTol'),
opt.CGTol = 1e-3;
end
if ~isfield(opt,'CGTolAuto'),
opt.CGTolAuto = 0;
end
if ~isfield(opt,'CGTolAutoFactor'),
opt.CGTolFactor = 50;
end
if ~isfield(opt,'ZeroMean'),
opt.ZeroMean = 0;
end
if ~isfield(opt,'AuxVarObj'),
opt.AuxVarObj = 0;
end
return
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
cmod.m
|
.m
|
convolutional_sparse_coding-master/DictLearn/cmod.m
| 8,290 |
utf_8
|
24954ffeb844d1dccd2b8cbea196190f
|
function [G, optinf] = cmod(X, S, opt)
% cmod -- Constrained Method of Optimal Directions (MOD)
%
% argmin_D (1/2)||D X - S||_2^2 such that ||d_k||_2 = 1
% where d_k are columns of D
%
% The solution is computed using the ADMM approach (see
% boyd-2010-distributed for details).
%
% Usage:
% [G, optinf] = cmod(X, S, opt)
%
% Input:
% X Coefficients
% S Input images
% opt Algorithm parameters structure
%
% Output:
% G Dictionary
% optinf Details of optimisation
%
%
% Options structure fields:
% Verbose Flag determining whether iteration status is displayed.
% Fields are iteration number, functional value,
% data fidelity term, and
% primal and dual residuals (see Sec. 3.3 of
% boyd-2010-distributed). The value of sigma
% is also displayed if options request that they are
% automatically adjusted.
% MaxMainIter Maximum main iterations
% AbsStopTol Absolute convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% RelStopTol Relative convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% G0 Initial value for G
% H0 Initial value for H
% sigma ADMM penalty parameter
% AutoSigma Flag determining whether sigma is automatically updated
% (see Sec. 3.4.1 of boyd-2010-distributed)
% AutoSigmaPeriod Iteration period on which sigma is updated
% SigmaRsdlRatio Primal/dual residual ratio in sigma update test
% SigmaScaling Multiplier applied to sigma when updated
% AutoSigmaScaling Flag determining whether SigmaScaling value is
% adaptively determined (see wohlberg-2015-adaptive). If
% enabled, SigmaScaling specifies a maximum allowed
% multiplier instead of a fixed multiplier.
% SigmaRsdlTarget Residual ratio targeted by auto sigma update policy.
% StdResiduals Flag determining whether standard residual definitions
% (see Sec 3.3 of boyd-2010-distributed) are used instead
% of normalised residuals (see wohlberg-2015-adaptive)
% RelaxParam Relaxation parameter (see Sec. 3.4.3 of
% boyd-2010-distributed)
% ZeroMean Force learned dictionary entries to be zero-mean
% AuxVarObj Flag determining whether objective function is computed
% using the auxiliary (split) variable
%
%
% Author: Brendt Wohlberg <[email protected]> Modified: 2015-07-10
%
% This file is part of the SPORCO library. Details of the copyright
% and user license can be found in the 'Copyright' and 'License' files
% distributed with the library.
if nargin < 3,
opt = [];
end
checkopt(opt, defaultopts([]));
opt = defaultopts(opt);
% Set up status display for verbose operation
hstr = 'Itn Obj Cnst r s ';
sfms = '%4d %9.2e %9.2e %9.2e %9.2e';
nsep = 44;
if opt.AutoSigma,
hstr = [hstr ' sigma'];
sfms = [sfms ' %9.2e'];
nsep = nsep + 10;
end
if opt.Verbose && opt.MaxMainIter > 0,
disp(hstr);
disp(char('-' * ones(1,nsep)));
end
% Mean removal and normalisation projections
Pzmn = @(x) bsxfun(@minus, x, mean(x,1));
Pnrm = @(x) normalise(x);
% Projection of dictionary filters onto constraint set
if opt.ZeroMean,
Pcn = @(x) Pnrm(Pzmn(x));
else
Pcn = @(x) Pnrm(x);
end
% Start timer
tstart = tic;
% Set up algorithm parameters and initialise variables
sigma = opt.sigma;
if isempty(sigma), sigma = size(S,2)/200; end;
Nc = size(S,1);
Nm = size(X,1);
Nd = Nc*Nm;
SX = S*X';
[luL, luU] = factorise(X, sigma);
optinf = struct('itstat', [], 'opt', opt);
r = Inf;
s = Inf;
epri = 0;
edua = 0;
% Initialise main working variables
D = [];
if isempty(opt.G0),
G = zeros(Nc,Nm);
else
G = opt.G0;
end
Gprv = G;
if isempty(opt.H0),
if isempty(opt.G0),
H = zeros(Nc,Nm);
else
H = G;
end
else
H = opt.H0;
end
% Main loop
k = 1;
while k <= opt.MaxMainIter && (r > epri | s > edua),
D = linsolve(X, sigma, luL, luU, SX + sigma*(G - H));
%rrs( D*(X*X' + sigma*eye(size(X,1))), SX + sigma*(G - H))
% See pg. 21 of boyd-2010-distributed
if opt.RelaxParam == 1,
Dr = D;
else
Dr = opt.RelaxParam*D + (1-opt.RelaxParam)*G;
end
G = Pcn(Dr + H);
H = H + Dr - G;
% Objective function and convergence measures
if opt.AuxVarObj
Job = sum(vec(abs(G*X - S).^2))/2;
Jcn = 0;
else
Job = sum(vec(abs(D*X - S).^2))/2;
Jcn = norm(vec(Pcn(D) - D));
end
nD = norm(D(:)); nG = norm(G(:)); nH = norm(H(:));
if opt.StdResiduals,
% See pp. 19-20 of boyd-2010-distributed
r = norm(vec(D - G));
s = norm(vec(sigma*(Gprv - G)));
epri = sqrt(Nd)*opt.AbsStopTol+max(nD,nG)*opt.RelStopTol;
edua = sqrt(Nd)*opt.AbsStopTol+sigma*nH*opt.RelStopTol;
else
% See wohlberg-2015-adaptive
r = norm(vec(D - G))/max(nD,nG);
s = norm(vec(Gprv - G))/nH;
epri = sqrt(Nd)*opt.AbsStopTol/max(nD,nG)+opt.RelStopTol;
edua = sqrt(Nd)*opt.AbsStopTol/(sigma*nH)+opt.RelStopTol;
end
% Record and display iteration details
tk = toc(tstart);
optinf.itstat = [optinf.itstat; [k Job Jcn r s epri edua sigma tk]];
if opt.Verbose,
if opt.AutoSigma,
disp(sprintf(sfms, k, Job, Jcn, r, s, sigma));
else
disp(sprintf(sfms, k, Job, Jcn, r, s));
end
end
% See wohlberg-2015-adaptive and pp. 20-21 of boyd-2010-distributed
if opt.AutoSigma,
if k ~= 1 && mod(k, opt.AutoSigmaPeriod) == 0,
if opt.AutoSigmaScaling,
sigmlt = sqrt(r/(s*opt.SigmaRsdlTarget));
if sigmlt < 1, sigmlt = 1/sigmlt; end
if sigmlt > opt.SigmaScaling, sigmlt = opt.SigmaScaling; end
else
sigmlt = opt.SigmaScaling;
end
ssf = 1;
if r > opt.SigmaRsdlTarget*opt.SigmaRsdlRatio*s, ssf = sigmlt; end
if s > (opt.SigmaRsdlRatio/opt.SigmaRsdlTarget)*r, ssf = 1/sigmlt; end
sigma = ssf*sigma;
H = H/ssf;
if ssf ~= 1,
[luL, luU] = factorise(X, sigma);
end
end
end
Gprv = G;
k = k + 1;
end
% Record run time and working variables
optinf.runtime = toc(tstart);
optinf.D = D;
optinf.G = G;
optinf.H = H;
optinf.sigma = sigma;
if opt.Verbose && opt.MaxMainIter > 0,
disp(char('-' * ones(1,nsep)));
end
return
function u = vec(v)
u = v(:);
return
function u = normalise(v)
vn = sqrt(sum(v.^2, 1));
vn(vn == 0) = 1;
u = bsxfun(@rdivide, v, vn);
return
function [L,U] = factorise(A, c)
[N,M] = size(A);
% If N < M it is cheaper to factorise A*A' + cI and then use the
% matrix inversion lemma to compute the inverse of A'*A + cI
if N >= M,
[L,U] = lu(A'*A + c*eye(M,M));
else
[L,U] = lu(A*A' + c*eye(N,N));
end
return
function x = linsolve(A, c, L, U, b)
[N,M] = size(A);
if N >= M,
x = (b - (((b*A) / U) / L)*A')/c;
else
x = (b / U) / L;
end
return
function opt = defaultopts(opt)
if ~isfield(opt,'Verbose'),
opt.Verbose = 0;
end
if ~isfield(opt,'MaxMainIter'),
opt.MaxMainIter = 200;
end
if ~isfield(opt,'AbsStopTol'),
opt.AbsStopTol = 1e-6;
end
if ~isfield(opt,'RelStopTol'),
opt.RelStopTol = 1e-4;
end
if ~isfield(opt,'G0'),
opt.G0 = [];
end
if ~isfield(opt,'H0'),
opt.H0 = [];
end
if ~isfield(opt,'sigma'),
opt.sigma = [];
end
if ~isfield(opt,'AutoSigma'),
opt.AutoSigma = 0;
end
if ~isfield(opt,'AutoSigmaPeriod'),
opt.AutoSigmaPeriod = 10;
end
if ~isfield(opt,'SigmaRsdlRatio'),
opt.SigmaRsdlRatio = 10;
end
if ~isfield(opt,'SigmaScaling'),
opt.SigmaScaling = 2;
end
if ~isfield(opt,'AutoSigmaScaling'),
opt.AutoSigmaScaling = 0;
end
if ~isfield(opt,'SigmaRsdlTarget'),
opt.SigmaRsdlTarget = 1;
end
if ~isfield(opt,'StdResiduals'),
opt.StdResiduals = 0;
end
if ~isfield(opt,'RelaxParam'),
opt.RelaxParam = 1;
end
if ~isfield(opt,'ZeroMean'),
opt.ZeroMean = 0;
end
if ~isfield(opt,'AuxVarObj'),
opt.AuxVarObj = 0;
end
return
|
github
|
wanghan0501/convolutional_sparse_coding-master
|
cbpdndlmd.m
|
.m
|
convolutional_sparse_coding-master/DictLearn/cbpdndlmd.m
| 18,514 |
utf_8
|
db3b0d7d52f06931c0a6b9f3b65d57af
|
function [D, Y, optinf] = cbpdndlmd(D0, S, lambda, opt)
% cbpdndlmd -- Convolutional BPDN Dictionary Learning (Mask Decoupling)
%
% argmin_{x_m,d_m} (1/2) \sum_k ||W \sum_m d_m * x_k,m - s_k||_2^2 +
% lambda \sum_k \sum_m ||x_k,m||_1
%
% The solution is computed using Augmented Lagrangian methods
% (see boyd-2010-distributed) with efficient solution of the
% main linear systems (see wohlberg-2016-efficient and
% wohlberg-2016-boundary).
%
% Usage:
% [D, Y, optinf] = cbpdndlmd(D0, S, lambda, opt)
%
% Input:
% D0 Initial dictionary
% S Input images
% lambda Regularization parameter
% opt Options/algorithm parameters structure (see below)
%
% Output:
% D Dictionary filter set (3D array)
% X Coefficient maps (4D array)
% optinf Details of optimisation
%
%
% Options structure fields:
% Verbose Flag determining whether iteration status is displayed.
% Fields are iteration number, functional value,
% data fidelity term, l1 regularisation term, and
% primal and dual residuals (see Sec. 3.3 of
% boyd-2010-distributed). The values of rho and sigma
% are also displayed if options request that they are
% automatically adjusted.
% MaxMainIter Maximum main iterations
% AbsStopTol Absolute convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% RelStopTol Relative convergence tolerance (see Sec. 3.3.1 of
% boyd-2010-distributed)
% L1Weight Weight array for L1 norm
% Y0 Initial value for Y
% U0 Initial value for U
% G0 Initial value for G (overrides D0 if specified)
% H0 Initial value for H
% rho Augmented Lagrangian penalty parameter
% AutoRho Flag determining whether rho is automatically updated
% (see Sec. 3.4.1 of boyd-2010-distributed)
% AutoRhoPeriod Iteration period on which rho is updated
% RhoRsdlRatio Primal/dual residual ratio in rho update test
% RhoScaling Multiplier applied to rho when updated
% AutoRhoScaling Flag determining whether RhoScaling value is
% adaptively determined (see wohlberg-2015-adaptive). If
% enabled, RhoScaling specifies a maximum allowed
% multiplier instead of a fixed multiplier
% sigma Augmented Lagrangian penalty parameter
% AutoSigma Flag determining whether sigma is automatically
% updated (see Sec. 3.4.1 of boyd-2010-distributed)
% AutoSigmaPeriod Iteration period on which sigma is updated
% SigmaRsdlRatio Primal/dual residual ratio in sigma update test
% SigmaScaling Multiplier applied to sigma when updated
% AutoSigmaScaling Flag determining whether SigmaScaling value is
% adaptively determined (see wohlberg-2015-adaptive). If
% enabled, SigmaScaling specifies a maximum allowed
% multiplier instead of a fixed multiplier.
% StdResiduals Flag determining whether standard residual definitions
% (see Sec 3.3 of boyd-2010-distributed) are used instead
% of normalised residuals (see wohlberg-2015-adaptive)
% XRelaxParam Relaxation parameter (see Sec. 3.4.3 of
% boyd-2010-distributed) for X update
% DRelaxParam Relaxation parameter (see Sec. 3.4.3 of
% boyd-2010-distributed) for D update
% LinSolve Linear solver for main problem: 'SM' or 'CG'
% MaxCGIter Maximum CG iterations when using CG solver
% CGTol CG tolerance when using CG solver
% CGTolAuto Flag determining use of automatic CG tolerance
% CGTolFactor Factor by which primal residual is divided to obtain CG
% tolerance, when automatic tolerance is active
% NoBndryCross Flag indicating whether all solution coefficients
% corresponding to filters crossing the image boundary
% should be forced to zero.
% DictFilterSizes Array of size 2 x M where each column specifies the
% filter size (rows x columns) of the corresponding
% dictionary filter
% NonNegCoef Flag indicating whether solution should be forced to
% be non-negative
% ZeroMean Force learned dictionary entries to be zero-mean
% W Synthesis spatial weighting matrix
%
%
% Author: Brendt Wohlberg <[email protected]> Modified: 2017-04-29
%
% This file is part of the SPORCO library. Details of the copyright
% and user license can be found in the 'License' file distributed with
% the library.
if nargin < 4,
opt = [];
end
checkopt(opt, defaultopts([]));
opt = defaultopts(opt);
% Set up status display for verbose operation
hstr = ['Itn Fnc DFid l1 Cnstr '...
'r(X) s(X) r(D) s(D) '];
sfms = '%4d %9.2e %9.2e %9.2e %9.2e %9.2e %9.2e %9.2e %9.2e';
nsep = 84;
if opt.AutoRho,
hstr = [hstr ' rho '];
sfms = [sfms ' %9.2e'];
nsep = nsep + 10;
end
if opt.AutoSigma,
hstr = [hstr ' sigma '];
sfms = [sfms ' %9.2e'];
nsep = nsep + 10;
end
if opt.Verbose && opt.MaxMainIter > 0,
disp(hstr);
disp(char('-' * ones(1,nsep)));
end
% Start timer
tstart = tic;
% Collapsing of trailing singleton dimensions greatly complicates
% handling of both SMV and MMV cases. The simplest approach would be
% if S could always be reshaped to 4d, with dimensions consisting of
% image rows, image cols, a single dimensional placeholder for number
% of filters, and number of measurements, but in the single
% measurement case the third dimension is collapsed so that the array
% is only 3d.
if size(S,3) > 1,
xsz = [size(S,1) size(S,2) size(D0,3) size(S,3)];
% Insert singleton 3rd dimension (for number of filters) so that
% 4th dimension is number of images in input s volume
S = reshape(S, [size(S,1) size(S,2) 1 size(S,3)]);
if ~isscalar(opt.W) & ndims(opt.W) > 2,
opt.W = reshape(opt.W, [size(opt.W,1) size(opt.W,2) 1 size(opt.W,3)]);
end
else
xsz = [size(S,1) size(S,2) size(D0,3) 1];
end
K = size(S,4);
Nx = prod(xsz);
Ny = prod(xsz + [0 0 1 0]);
Nd = prod(xsz(1:2))*size(D0,3);
Ng = prod([xsz(1) xsz(2) xsz(3)+K]);
cgt = opt.CGTol;
W = opt.W;
% Dictionary size may be specified when learning multiscale
% dictionary
if isempty(opt.DictFilterSizes),
dsz = [size(D0,1) size(D0,2)];
else
dsz = opt.DictFilterSizes;
end
% Mean removal and normalisation projections
Pzmn = @(x) bsxfun(@minus, x, mean(mean(x,1),2));
% Projection of filter to full image size and its transpose
% (zero-pad and crop respectively)
Pzp = @(x) zpad(x, xsz(1:2));
PzpT = @(x) bcrop(x, dsz);
% Projection of dictionary filters onto constraint set
if opt.ZeroMean,
Pcn = @(x) Pnrm(Pzp(Pzmn(PzpT(x))));
else
Pcn = @(x) Pnrm(Pzp(PzpT(x)));
end
% Project initial dictionary onto constraint set
D = Pnrm(D0);
% Compute signal in DFT domain
Sf = fft2(S);
% Set up algorithm parameters and initialise variables
rho = opt.rho;
if isempty(rho), rho = 50*lambda+1; end;
if opt.AutoRho,
asgr = opt.RhoRsdlRatio;
asgm = opt.RhoScaling;
end
sigma = opt.sigma;
if isempty(sigma), sigma = size(S,3); end;
if opt.AutoSigma,
asdr = opt.SigmaRsdlRatio;
asdm = opt.SigmaScaling;
end
optinf = struct('itstat', [], 'opt', opt);
rx = Inf;
sx = Inf;
rd = Inf;
sd = Inf;
eprix = 0;
eduax = 0;
eprid = 0;
eduad = 0;
% Initialise main working variables
X = [];
if isempty(opt.Y0),
Y = zeros(xsz + [0 0 1 0], class(S));
Y(:,:,end,:) = S;
else
Y = opt.Y0;
end
Yf = fft2(Y);
Yprv = Y;
if isempty(opt.U0),
if isempty(opt.Y0),
U = zeros(xsz + [0 0 1 0], class(S));
else
U(:,:,1:(end-1),:) = (lambda/rho)*sign(Y(:,:,1:(end-1),:));
U(:,:,end,:) = bsxfun(@times, W, (bsxfun(@times, W, ...
Y(:,:,end,:)) - S))/rho;
end
else
U = opt.U0;
end
Df = [];
if isempty(opt.G0),
G = zeros(xsz(1:end-1) + [0 0 K], class(S));
G(:,:,1:end-K) = Pzp(D);
G(:,:,end-K+1:end) = squeeze(S);
else
G = opt.G0;
end
Gprv = G;
if isempty(opt.H0),
if isempty(opt.G0),
H = zeros(xsz(1:end-1) + [0 0 K], class(S));
else
H(:,:,1:(end-K)) = G(:,:,1:(end-K));
H(:,:,end-K+1:end) = bsxfun(@times, W, (bsxfun(@times, W, ...
G(:,:,end-K+1:end)) - S))/rho;
end
else
H = opt.H0;
end
Gf = fft2(G(:,:,1:(end-K),:), size(S,1), size(S,2));
% Main loop
k = 1;
while k <= opt.MaxMainIter && (rx > eprix|sx > eduax|rd > eprid|sd >eduad),
% Solve X subproblem. It would be simpler and more efficient (since the
% DFT is already available) to solve for X using the main dictionary
% variable D as the dictionary, but this appears to be unstable. Instead,
% use the projected dictionary variable G
YUf = fft2(Y - U);
YU0f = YUf(:,:,1:(end-1),:);
YU1f = YUf(:,:,end,:);
GHop = @(x) bsxfun(@times, conj(Gf), x);
Xf = solvedbi_sm(Gf, 1.0, GHop(YU1f) + YU0f);
X = ifft2(Xf, 'symmetric');
GX = ifft2(sum(bsxfun(@times, Gf, Xf), 3), 'symmetric');
clear Xf;
% See pg. 21 of boyd-2010-distributed
AX = cat(3, X, GX);
if opt.XRelaxParam ~= 1.0,
AX = opt.XRelaxParam*AX + (1-opt.XRelaxParam)*Y;
end
% Solve Y subproblem
Y(:,:,1:(end-1),:) = shrink(AX(:,:,1:(end-1),:) + U(:,:,1:(end-1),:), ...
(lambda/rho)*opt.L1Weight);
if opt.NonNegCoef,
Y(Y < 0) = 0;
end
if opt.NoBndryCross,
Y((end-max(dsz(1,:))+2):end,:,1:(end-1),:) = 0;
Y(:,(end-max(dsz(2,:))+2):end,1:(end-1),:) = 0;
end
Y(:,:,end,:) = bsxfun(@rdivide, (bsxfun(@times, W, S) + ...
rho*(GX + U(:,:,end,:))), ((W.^2) + rho));
Yf = fft2(Y(:,:,1:(end-1),:));
% Update dual variable corresponding to X, Y
U = U + AX - Y;
% Compute primal and dual residuals and stopping thresholds for X update
U0 = U(:,:,1:(end-1),:);
U1 = U(:,:,end,:);
ATU0 = U0;
ATU1 = ifft2(GHop(fft2(U1)), 'symmetric');
nAX = norm(AX(:)); nY = norm(Y(:)); nU0 = norm(U0(:)); nU1 = norm(U1(:));
if opt.StdResiduals,
% See pp. 19-20 of boyd-2010-distributed
rx = norm(vec(AX - Y));
sx = rho*norm(vec(ATU0 + ATU1));
eprix = sqrt(Ny)*opt.AbsStopTol+max(nAX,nY)*opt.RelStopTol;
eduax = sqrt(Nx)*opt.AbsStopTol+rho*max(nU0,nU1)*opt.RelStopTol;
else
% See wohlberg-2015-adaptive
rx = norm(vec(AX - Y))/max(nAX,nY);
sx = norm(vec(ATU0 + ATU1))/max(nU0,nU1);
eprix = sqrt(Ny)*opt.AbsStopTol/max(nAX,nY)+opt.RelStopTol;
eduax = sqrt(Nx)*opt.AbsStopTol/(rho*max(nU0,nU1))+opt.RelStopTol;
end
clear X, AX;
% Compute l1 norm of Y
Jl1 = sum(abs(vec(bsxfun(@times, opt.L1Weight, Y(:,:,1:(end-1),:)))));
% Update record of previous step Y
Yprv = Y;
% Solve D subproblem. Similarly, it would be simpler and more efficient to
% solve for D using the main coefficient variable X as the coefficients,
% but it appears to be more stable to use the shrunk coefficient variable Y
GHf = fft2(G - H);
GH0f = GHf(:,:,1:(end-K));
GH1f = reshape(GHf(:,:,end-K+1:end), [xsz(1), xsz(2), 1, K]);
YHop = @(x) sum(bsxfun(@times, conj(Yf), x), 4);
if strcmp(opt.LinSolve, 'SM'),
Df = solvemdbi_ism(Yf, 1.0, YHop(GH1f) + GH0f);
else
[Df, cgst] = solvemdbi_cg(Yf, sigma, ...
YHop(GH1f) + GH0f, cgt, opt.MaxCGIter, Df(:));
end
%clear YSf;
D = ifft2(Df, 'symmetric');
YD = ifft2(sum(bsxfun(@times, Yf, Df), 3), 'symmetric');
if strcmp(opt.LinSolve, 'SM'), clear Df; end
% See pg. 21 of boyd-2010-distributed
AD = cat(3, D, squeeze(YD));
if opt.DRelaxParam ~= 1.0,
AD = opt.DRelaxParam*AD + (1-opt.DRelaxParam)*G;
end
% Solve G subproblem
G(:,:,1:(end-K)) = Pcn(AD(:,:,1:(end-K)) + H(:,:,1:(end-K)));
G(:,:,end-K+1:end) = bsxfun(@rdivide, (squeeze(bsxfun(@times, W, S)) + ...
rho*(squeeze(YD) + H(:,:,end-K+1:end))), ...
((squeeze(W).^2) + rho));
Gf = fft2(G(:,:,1:(end-K)), size(S,1), size(S,2));
% Update dual variable corresponding to D, G
H = H + AD - G;
% Compute primal and dual residuals and stopping thresholds for D update
H0 = H(:,:,1:(end-K));
H1 = reshape(H(:,:,end-K+1:end), [xsz(1), xsz(2), 1, K]);
ATH0 = H0;
ATH1 = ifft2(YHop(fft2(H1)), 'symmetric');
nAD = norm(AD(:)); nG = norm(G(:)); nH0 = norm(H0(:)); nH1 = norm(H1(:));
if opt.StdResiduals,
% See pp. 19-20 of boyd-2010-distributed
rd = norm(vec(AD - G));
sd = norm(vec(sigma*(ATH0 + ATH1)));
eprid = sqrt(Ng)*opt.AbsStopTol+max(nAD,nG)*opt.RelStopTol;
eduad = sqrt(Nd)*opt.AbsStopTol+sigma*max(nH0,nH1)*opt.RelStopTol;
else
% See wohlberg-2015-adaptive
rd = norm(vec(AD - G))/max(nAD,nG);
sd = norm(vec(ATH0 + ATH1))/max(nH0,nH1);
eprid = sqrt(Ng)*opt.AbsStopTol/max(nAD,nG)+opt.RelStopTol;
eduad = sqrt(Nd)*opt.AbsStopTol/(sigma*max(nH0,nH1))+opt.RelStopTol;
end
% Apply CG auto tolerance policy if enabled
if opt.CGTolAuto && (rd/opt.CGTolFactor) < cgt,
cgt = rd/opt.CGTolFactor;
end
% Compute measure of D constraint violation
Jcn = norm(vec(Pcn(D) - D));
clear D, AD;
% Update record of previous step G
Gprv = G;
% Compute data fidelity term in Fourier domain (note normalisation)
Jdf = sum(vec(abs(bsxfun(@times, opt.W, GX) - S).^2))/2;
Jfn = Jdf + lambda*Jl1;
% Record and display iteration details
tk = toc(tstart);
optinf.itstat = [optinf.itstat;...
[k Jfn Jdf Jl1 rx sx rd sd eprix eduax eprid eduad rho sigma tk]];
if opt.Verbose,
dvc = [k, Jfn, Jdf, Jl1, Jcn, rx, sx, rd, sd];
if opt.AutoRho,
dvc = [dvc rho];
end
if opt.AutoSigma,
dvc = [dvc sigma];
end
disp(sprintf(sfms, dvc));
end
% See wohlberg-2015-adaptive and pp. 20-21 of boyd-2010-distributed
if opt.AutoRho,
if k ~= 1 && mod(k, opt.AutoRhoPeriod) == 0,
if opt.AutoRhoScaling,
rhomlt = sqrt(rx/sx);
if rhomlt < 1, rhomlt = 1/rhomlt; end
if rhomlt > opt.RhoScaling, rhomlt = opt.RhoScaling; end
else
rhomlt = opt.RhoScaling;
end
rsf = 1;
if rx > opt.RhoRsdlRatio*sx, rsf = rhomlt; end
if sx > opt.RhoRsdlRatio*rx, rsf = 1/rhomlt; end
rho = rsf*rho;
U = U/rsf;
end
end
if opt.AutoSigma,
if k ~= 1 && mod(k, opt.AutoSigmaPeriod) == 0,
if opt.AutoSigmaScaling,
sigmlt = sqrt(rd/sd);
if sigmlt < 1, sigmlt = 1/sigmlt; end
if sigmlt > opt.SigmaScaling, sigmlt = opt.SigmaScaling; end
else
sigmlt = opt.SigmaScaling;
end
ssf = 1;
if rd > opt.SigmaRsdlRatio*sd, ssf = sigmlt; end
if sd > opt.SigmaRsdlRatio*rd, ssf = 1/sigmlt; end
sigma = ssf*sigma;
H = H/ssf;
end
end
k = k + 1;
end
D = PzpT(G(:,:,1:(end-K)));
Y = Y(:,:,1:(end-1),:);
% Record run time and working variables
optinf.runtime = toc(tstart);
optinf.Y = Y;
optinf.U = U;
optinf.G = G;
optinf.H = H;
optinf.lambda = lambda;
optinf.rho = rho;
optinf.sigma = sigma;
optinf.cgt = cgt;
if exist('cgst'), optinf.cgst = cgst; end
if opt.Verbose && opt.MaxMainIter > 0,
disp(char('-' * ones(1,nsep)));
end
return
function u = vec(v)
u = v(:);
return
function u = shrink(v, lambda)
if isscalar(lambda),
u = sign(v).*max(0, abs(v) - lambda);
else
u = sign(v).*max(0, bsxfun(@minus, abs(v), lambda));
end
return
function u = Pnrm(v)
vn = sqrt(sum(sum(v.^2, 1), 2));
vnm = ones(size(vn));
vnm(vn == 0) = 0;
vm = bsxfun(@times, v, vnm);
vn(vn == 0) = 1;
u = bsxfun(@rdivide, vm, vn);
return
function u = zpad(v, sz)
u = zeros(sz(1), sz(2), size(v,3), size(v,4), class(v));
u(1:size(v,1), 1:size(v,2),:,:) = v;
return
function u = bcrop(v, sz)
if numel(sz) <= 2,
if numel(sz) == 1
cs = [sz sz];
else
cs = sz;
end
u = v(1:cs(1), 1:cs(2), :);
else
cs = max(sz,[],2);
u = zeros(cs(1), cs(2), size(v,3), class(v));
for k = 1:size(v,3),
u(1:sz(1,k), 1:sz(2,k), k) = v(1:sz(1,k), 1:sz(2,k), k);
end
end
return
function opt = defaultopts(opt)
if ~isfield(opt,'Verbose'),
opt.Verbose = 0;
end
if ~isfield(opt,'MaxMainIter'),
opt.MaxMainIter = 1000;
end
if ~isfield(opt,'AbsStopTol'),
opt.AbsStopTol = 1e-6;
end
if ~isfield(opt,'RelStopTol'),
opt.RelStopTol = 1e-4;
end
if ~isfield(opt,'L1Weight'),
opt.L1Weight = 1;
end
if ~isfield(opt,'Y0'),
opt.Y0 = [];
end
if ~isfield(opt,'U0'),
opt.U0 = [];
end
if ~isfield(opt,'G0'),
opt.G0 = [];
end
if ~isfield(opt,'H0'),
opt.H0 = [];
end
if ~isfield(opt,'rho'),
opt.rho = [];
end
if ~isfield(opt,'AutoRho'),
opt.AutoRho = 0;
end
if ~isfield(opt,'AutoRhoPeriod'),
opt.AutoRhoPeriod = 10;
end
if ~isfield(opt,'RhoRsdlRatio'),
opt.RhoRsdlRatio = 10;
end
if ~isfield(opt,'RhoScaling'),
opt.RhoScaling = 2;
end
if ~isfield(opt,'AutoRhoScaling'),
opt.AutoRhoScaling = 0;
end
if ~isfield(opt,'sigma'),
opt.sigma = [];
end
if ~isfield(opt,'AutoSigma'),
opt.AutoSigma = 0;
end
if ~isfield(opt,'AutoSigmaPeriod'),
opt.AutoSigmaPeriod = 10;
end
if ~isfield(opt,'SigmaRsdlRatio'),
opt.SigmaRsdlRatio = 10;
end
if ~isfield(opt,'SigmaScaling'),
opt.SigmaScaling = 2;
end
if ~isfield(opt,'AutoSigmaScaling'),
opt.AutoSigmaScaling = 0;
end
if ~isfield(opt,'StdResiduals'),
opt.StdResiduals = 0;
end
if ~isfield(opt,'XRelaxParam'),
opt.XRelaxParam = 1;
end
if ~isfield(opt,'DRelaxParam'),
opt.DRelaxParam = 1;
end
if ~isfield(opt,'LinSolve'),
opt.LinSolve = 'SM';
end
if ~isfield(opt,'MaxCGIter'),
opt.MaxCGIter = 1000;
end
if ~isfield(opt,'CGTol'),
opt.CGTol = 1e-3;
end
if ~isfield(opt,'CGTolAuto'),
opt.CGTolAuto = 0;
end
if ~isfield(opt,'CGTolAutoFactor'),
opt.CGTolFactor = 50;
end
if ~isfield(opt,'NoBndryCross'),
opt.NoBndryCross = 0;
end
if ~isfield(opt,'DictFilterSizes'),
opt.DictFilterSizes = [];
end
if ~isfield(opt,'NonNegCoef'),
opt.NonNegCoef = 0;
end
if ~isfield(opt,'ZeroMean'),
opt.ZeroMean = 0;
end
if ~isfield(opt,'W'),
opt.W = 1.0;
end
return
|
github
|
changken1/IDH_Prediction-master
|
readDICOMdir.m
|
.m
|
IDH_Prediction-master/MatlabScripts/readDICOMdir.m
| 6,680 |
utf_8
|
f26b5bc8fcfd0af05c2feb487282707e
|
function [sData] = readDICOMdir(dicomPath,waitB)
% -------------------------------------------------------------------------
% function [sData] = readDICOMdir(dicomPath,waitB)
% -------------------------------------------------------------------------
% DESCRIPTION:
% This function reads the DICOM content of a single directory. It then
% organizes the data it in a cell of structures called 'sData', and
% computes the region of interest (ROI) defined by a given RTstruct (if
% present in the directory).
% -------------------------------------------------------------------------
% INPUTS:
% - dicomPath: Full path where the DICOM files to read are located.
% - waitB: Logical boolean. If true, a waiting bar will be displayed.
% -------------------------------------------------------------------------
% OUTPUTS:
% - sData: Cell of structures organizing the content of the volume data,
% DICOM headers, DICOM RTstruct* (used to compute the ROI) and
% DICOM REGstruct* (used to register a MRI volume to a PET volume)
% * If present in the directory
% --> sData{1}: Explanation of cell content
% --> sData{2}: Imaging data and ROI defintion (if applicable)
% --> sData{3}: DICOM headers of imaging data
% --> sData{4}: DICOM RTstruct (if applicable)
% --> sData{5}: DICOM REGstruct (if applicable)
% -------------------------------------------------------------------------
% AUTHOR(S):
% - Martin Vallieres <[email protected]>
% - Sebastien Laberge <[email protected]>
% -------------------------------------------------------------------------
% HISTORY:
% - Creation: May 2015
%--------------------------------------------------------------------------
% STATEMENT:
% This file is part of <https://github.com/mvallieres/radiomics/>,
% a package providing MATLAB programming tools for radiomics analysis.
% --> Copyright (C) 2015 Martin Vallieres, Sebastien Laberge
%
% This package 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 package 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 package. If not, see <http://www.gnu.org/licenses/>.
% -------------------------------------------------------------------------
% INITIALIZATION
if waitB
waitbarHandle = waitbar(0,'Loading DICOM files...','WindowStyle','modal');
end
elements = dir(dicomPath);
nElements = length(elements);
volume = cell(1,1,nElements);
dicomHeaders = [];
RTstruct = [];
REG = [];
% READING DIRECTORY CONTENT
sliceNumber = 0;
for elementNumber = 1:nElements
elementName = elements(elementNumber).name;
if ~strcmp(elementName,'.') && ~strcmp(elementName,'..') % Good enough for Linux, add conditions for MAC and Windows.
elementFullFile = fullfile(dicomPath,elementName);
if isdicom(elementFullFile)
tmp = dicominfo(elementFullFile);
if strcmp(tmp.Modality,'RTSTRUCT')
RTstruct = tmp;
elseif strcmp(tmp.Modality,'REG')
REG = tmp;
elseif strcmp(tmp.Modality,'MR') || strcmp(tmp.Modality,'PT') || strcmp(tmp.Modality,'CT')
sliceNumber = sliceNumber + 1;
volume{sliceNumber} = double(dicomread(elementFullFile));
dicomHeaders = appendStruct(dicomHeaders,tmp);
end
end
end
if waitB
waitbar(elementNumber/nElements,waitbarHandle);
end
end
nSlices = sliceNumber; % Total number of slices
volume = volume(1:nSlices); % Suppress empty cells in images
% DETERMINE THE SCAN ORIENTATION
dist = [abs(dicomHeaders(2).ImagePositionPatient(1) - dicomHeaders(1).ImagePositionPatient(1)), ...
abs(dicomHeaders(2).ImagePositionPatient(2) - dicomHeaders(1).ImagePositionPatient(2)), ...
abs(dicomHeaders(2).ImagePositionPatient(3) - dicomHeaders(1).ImagePositionPatient(3))];
[~,index] = max(dist);
if index == 1
orientation = 'Sagittal';
elseif index == 2
orientation = 'Coronal';
else
orientation = 'Axial';
end
% SORT THE IMAGES AND DICOM HEADERS
slicePositions = zeros(1,nSlices);
for sliceNumber = 1:nSlices
slicePositions(sliceNumber) = dicomHeaders(sliceNumber).ImagePositionPatient(index);
end
[~,indices] = sort(slicePositions);
volume = cell2mat(volume(indices));
dicomHeaders = dicomHeaders(indices);
% FILL sData
sData = cell(1,5);
type = dicomHeaders(1).Modality;
if strcmp(type,'PT') || strcmp(type,'CT')
if strcmp(type,'PT')
type = 'PET';
end
for i=1:size(volume,3)
volume(:,:,i)=volume(:,:,i)*dicomHeaders(i).RescaleSlope + dicomHeaders(i).RescaleIntercept;
end
end
type = [type,'scan'];
sData{1} = struct('Cell_1','Explanation of cell content', ...
'Cell_2','Imaging data and ROI defintion (if applicable)', ...
'Cell_3','DICOM headers of imaging data', ...
'Cell_4','DICOM RTstruct (if applicable)', ...
'Cell_5','DICOM REGstruct (if applicable)');
sData{2}.scan.volume = volume;
sData{2}.scan.orientation = orientation;
try sData{2}.scan.pixelW = dicomHeaders(1).PixelSpacing(1); catch sData{2}.scan.pixelW = []; end % Pixel Width
try sData{2}.scan.sliceT = dicomHeaders(1).SliceThickness; catch sData{2}.scan.sliceT = []; end % Slice Thickness
s1 = round(0.5*nSlices); s2 = round(0.5*nSlices) + 1; % Slices selected to calculate slice spacing
sData{2}.scan.sliceS = sqrt(sum((dicomHeaders(s1).ImagePositionPatient - dicomHeaders(s2).ImagePositionPatient).^2)); % Slice Spacing
sData{2}.type = type;
sData{3} = dicomHeaders;
sData{4} = RTstruct;
sData{5} = REG;
% COMPUTE TUMOR DELINEATION USING RTstruct
if ~isempty(sData{4})
[sData] = computeROI(sData);
end
if waitB
close(waitbarHandle)
end
end
% UTILITY FUNCTION
function [structureArray] = appendStruct(structureArray,newStructure)
if isempty(structureArray)
structureArray = newStructure;
return
end
structLength = length(structureArray);
fields = fieldnames(structureArray(1));
nFields = length(fields);
for i = 1:nFields
try
structureArray(structLength + 1).(fields{i}) = newStructure.(fields{i});
catch
structureArray(structLength + 1).(fields{i}) = 'FIELD NOT PRESENT';
end
end
end
|
github
|
changken1/IDH_Prediction-master
|
load_nii_ext.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/load_nii_ext.m
| 5,337 |
utf_8
|
fa0e831b0a596c3208b21bddc1c6d812
|
% Load NIFTI header extension after its header is loaded using load_nii_hdr.
%
% Usage: ext = load_nii_ext(filename)
%
% filename - NIFTI file name.
%
% Returned values:
%
% ext - Structure of NIFTI header extension, which includes num_ext,
% and all the extended header sections in the header extension.
% Each extended header section will have its esize, ecode, and
% edata, where edata can be plain text, xml, or any raw data
% that was saved in the extended header section.
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function ext = load_nii_ext(filename)
if ~exist('filename','var'),
error('Usage: ext = load_nii_ext(filename)');
end
v = version;
% Check file extension. If .gz, unpack it into temp folder
%
if length(filename) > 2 & strcmp(filename(end-2:end), '.gz')
if ~strcmp(filename(end-6:end), '.img.gz') & ...
~strcmp(filename(end-6:end), '.hdr.gz') & ...
~strcmp(filename(end-6:end), '.nii.gz')
error('Please check filename.');
end
if str2num(v(1:3)) < 7.1 | ~usejava('jvm')
error('Please use MATLAB 7.1 (with java) and above, or run gunzip outside MATLAB.');
elseif strcmp(filename(end-6:end), '.img.gz')
filename1 = filename;
filename2 = filename;
filename2(end-6:end) = '';
filename2 = [filename2, '.hdr.gz'];
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename1 = gunzip(filename1, tmpDir);
filename2 = gunzip(filename2, tmpDir);
filename = char(filename1); % convert from cell to string
elseif strcmp(filename(end-6:end), '.hdr.gz')
filename1 = filename;
filename2 = filename;
filename2(end-6:end) = '';
filename2 = [filename2, '.img.gz'];
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename1 = gunzip(filename1, tmpDir);
filename2 = gunzip(filename2, tmpDir);
filename = char(filename1); % convert from cell to string
elseif strcmp(filename(end-6:end), '.nii.gz')
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename = gunzip(filename, tmpDir);
filename = char(filename); % convert from cell to string
end
end
machine = 'ieee-le';
new_ext = 0;
if findstr('.nii',filename) & strcmp(filename(end-3:end), '.nii')
new_ext = 1;
filename(end-3:end)='';
end
if findstr('.hdr',filename) & strcmp(filename(end-3:end), '.hdr')
filename(end-3:end)='';
end
if findstr('.img',filename) & strcmp(filename(end-3:end), '.img')
filename(end-3:end)='';
end
if new_ext
fn = sprintf('%s.nii',filename);
if ~exist(fn)
msg = sprintf('Cannot find file "%s.nii".', filename);
error(msg);
end
else
fn = sprintf('%s.hdr',filename);
if ~exist(fn)
msg = sprintf('Cannot find file "%s.hdr".', filename);
error(msg);
end
end
fid = fopen(fn,'r',machine);
vox_offset = 0;
if fid < 0,
msg = sprintf('Cannot open file %s.',fn);
error(msg);
else
fseek(fid,0,'bof');
if fread(fid,1,'int32') == 348
if new_ext
fseek(fid,108,'bof');
vox_offset = fread(fid,1,'float32');
end
ext = read_extension(fid, vox_offset);
fclose(fid);
else
fclose(fid);
% first try reading the opposite endian to 'machine'
%
switch machine,
case 'ieee-le', machine = 'ieee-be';
case 'ieee-be', machine = 'ieee-le';
end
fid = fopen(fn,'r',machine);
if fid < 0,
msg = sprintf('Cannot open file %s.',fn);
error(msg);
else
fseek(fid,0,'bof');
if fread(fid,1,'int32') ~= 348
% Now throw an error
%
msg = sprintf('File "%s" is corrupted.',fn);
error(msg);
end
if new_ext
fseek(fid,108,'bof');
vox_offset = fread(fid,1,'float32');
end
ext = read_extension(fid, vox_offset);
fclose(fid);
end
end
end
% Clean up after gunzip
%
if exist('gzFileName', 'var')
rmdir(tmpDir,'s');
end
return % load_nii_ext
%---------------------------------------------------------------------
function ext = read_extension(fid, vox_offset)
ext = [];
if vox_offset
end_of_ext = vox_offset;
else
fseek(fid, 0, 'eof');
end_of_ext = ftell(fid);
end
if end_of_ext > 352
fseek(fid, 348, 'bof');
ext.extension = fread(fid,4)';
end
if isempty(ext) | ext.extension(1) == 0
ext = [];
return;
end
i = 1;
while(ftell(fid) < end_of_ext)
ext.section(i).esize = fread(fid,1,'int32');
ext.section(i).ecode = fread(fid,1,'int32');
ext.section(i).edata = char(fread(fid,ext.section(i).esize-8)');
i = i + 1;
end
ext.num_ext = length(ext.section);
return % read_extension
|
github
|
changken1/IDH_Prediction-master
|
rri_orient.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/rri_orient.m
| 2,251 |
utf_8
|
4253fb96b9189a8a4bad49661d9ecac3
|
% Convert image of different orientations to standard Analyze orientation
%
% Usage: nii = rri_orient(nii);
% Jimmy Shen ([email protected]), 26-APR-04
%___________________________________________________________________
function [nii, orient, pattern] = rri_orient(nii, varargin)
if nargin > 1
pattern = varargin{1};
else
pattern = [];
end
if(nargin > 2)
orient = varargin{2};
if(length(find(orient>6)) || length(find(orient<1))) %value checking
orient=[1 2 3]; %set to default if bogus values set
end
else
orient = [1 2 3];
end
dim = double(nii.hdr.dime.dim([2:4]));
if ~isempty(pattern) & ~isequal(length(pattern), prod(dim))
return;
end
% get orient of the current image
%
if isequal(orient, [1 2 3])
orient = rri_orient_ui;
pause(.1);
end
% no need for conversion
%
if isequal(orient, [1 2 3])
return;
end
if isempty(pattern)
pattern = 1:prod(dim);
end
pattern = reshape(pattern, dim);
img = nii.img;
% calculate after flip orient
%
rot_orient = mod(orient + 2, 3) + 1;
% do flip:
%
flip_orient = orient - rot_orient;
for i = 1:3
if flip_orient(i)
pattern = flipdim(pattern, i);
img = flipdim(img, i);
end
end
% get index of orient (do inverse)
%
[tmp rot_orient] = sort(rot_orient);
% do rotation:
%
pattern = permute(pattern, rot_orient);
img = permute(img, [rot_orient 4 5 6]);
% rotate resolution, or 'dim'
%
new_dim = nii.hdr.dime.dim([2:4]);
new_dim = new_dim(rot_orient);
nii.hdr.dime.dim([2:4]) = new_dim;
% rotate voxel_size, or 'pixdim'
%
tmp = nii.hdr.dime.pixdim([2:4]);
tmp = tmp(rot_orient);
nii.hdr.dime.pixdim([2:4]) = tmp;
% re-calculate originator
%
tmp = nii.hdr.hist.originator([1:3]);
tmp = tmp(rot_orient);
flip_orient = flip_orient(rot_orient);
for i = 1:3
if flip_orient(i) & ~isequal(double(tmp(i)), 0)
tmp(i) = int16(double(new_dim(i)) - double(tmp(i)) + 1);
end
end
nii.hdr.hist.originator([1:3]) = tmp;
nii.img = img;
pattern = pattern(:);
return; % rri_orient
|
github
|
changken1/IDH_Prediction-master
|
save_untouch0_nii_hdr.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/save_untouch0_nii_hdr.m
| 8,594 |
utf_8
|
7e8b1b327e1924837820f75780d52d01
|
% internal function
% - Jimmy Shen ([email protected])
function save_nii_hdr(hdr, fid)
if ~isequal(hdr.hk.sizeof_hdr,348),
error('hdr.hk.sizeof_hdr must be 348.');
end
write_header(hdr, fid);
return; % save_nii_hdr
%---------------------------------------------------------------------
function write_header(hdr, fid)
% Original header structures
% struct dsr /* dsr = hdr */
% {
% struct header_key hk; /* 0 + 40 */
% struct image_dimension dime; /* 40 + 108 */
% struct data_history hist; /* 148 + 200 */
% }; /* total= 348 bytes*/
header_key(fid, hdr.hk);
image_dimension(fid, hdr.dime);
data_history(fid, hdr.hist);
% check the file size is 348 bytes
%
fbytes = ftell(fid);
if ~isequal(fbytes,348),
msg = sprintf('Header size is not 348 bytes.');
warning(msg);
end
return; % write_header
%---------------------------------------------------------------------
function header_key(fid, hk)
fseek(fid,0,'bof');
% Original header structures
% struct header_key /* header key */
% { /* off + size */
% int sizeof_hdr /* 0 + 4 */
% char data_type[10]; /* 4 + 10 */
% char db_name[18]; /* 14 + 18 */
% int extents; /* 32 + 4 */
% short int session_error; /* 36 + 2 */
% char regular; /* 38 + 1 */
% char hkey_un0; /* 39 + 1 */
% }; /* total=40 bytes */
fwrite(fid, hk.sizeof_hdr(1), 'int32'); % must be 348.
% data_type = sprintf('%-10s',hk.data_type); % ensure it is 10 chars from left
% fwrite(fid, data_type(1:10), 'uchar');
pad = zeros(1, 10-length(hk.data_type));
hk.data_type = [hk.data_type char(pad)];
fwrite(fid, hk.data_type(1:10), 'uchar');
% db_name = sprintf('%-18s', hk.db_name); % ensure it is 18 chars from left
% fwrite(fid, db_name(1:18), 'uchar');
pad = zeros(1, 18-length(hk.db_name));
hk.db_name = [hk.db_name char(pad)];
fwrite(fid, hk.db_name(1:18), 'uchar');
fwrite(fid, hk.extents(1), 'int32');
fwrite(fid, hk.session_error(1), 'int16');
fwrite(fid, hk.regular(1), 'uchar');
fwrite(fid, hk.hkey_un0(1), 'uchar');
return; % header_key
%---------------------------------------------------------------------
function image_dimension(fid, dime)
%struct image_dimension
% { /* off + size */
% short int dim[8]; /* 0 + 16 */
% char vox_units[4]; /* 16 + 4 */
% char cal_units[8]; /* 20 + 8 */
% short int unused1; /* 28 + 2 */
% short int datatype; /* 30 + 2 */
% short int bitpix; /* 32 + 2 */
% short int dim_un0; /* 34 + 2 */
% float pixdim[8]; /* 36 + 32 */
% /*
% pixdim[] specifies the voxel dimensions:
% pixdim[1] - voxel width
% pixdim[2] - voxel height
% pixdim[3] - interslice distance
% ..etc
% */
% float vox_offset; /* 68 + 4 */
% float roi_scale; /* 72 + 4 */
% float funused1; /* 76 + 4 */
% float funused2; /* 80 + 4 */
% float cal_max; /* 84 + 4 */
% float cal_min; /* 88 + 4 */
% int compressed; /* 92 + 4 */
% int verified; /* 96 + 4 */
% int glmax; /* 100 + 4 */
% int glmin; /* 104 + 4 */
% }; /* total=108 bytes */
fwrite(fid, dime.dim(1:8), 'int16');
pad = zeros(1, 4-length(dime.vox_units));
dime.vox_units = [dime.vox_units char(pad)];
fwrite(fid, dime.vox_units(1:4), 'uchar');
pad = zeros(1, 8-length(dime.cal_units));
dime.cal_units = [dime.cal_units char(pad)];
fwrite(fid, dime.cal_units(1:8), 'uchar');
fwrite(fid, dime.unused1(1), 'int16');
fwrite(fid, dime.datatype(1), 'int16');
fwrite(fid, dime.bitpix(1), 'int16');
fwrite(fid, dime.dim_un0(1), 'int16');
fwrite(fid, dime.pixdim(1:8), 'float32');
fwrite(fid, dime.vox_offset(1), 'float32');
fwrite(fid, dime.roi_scale(1), 'float32');
fwrite(fid, dime.funused1(1), 'float32');
fwrite(fid, dime.funused2(1), 'float32');
fwrite(fid, dime.cal_max(1), 'float32');
fwrite(fid, dime.cal_min(1), 'float32');
fwrite(fid, dime.compressed(1), 'int32');
fwrite(fid, dime.verified(1), 'int32');
fwrite(fid, dime.glmax(1), 'int32');
fwrite(fid, dime.glmin(1), 'int32');
return; % image_dimension
%---------------------------------------------------------------------
function data_history(fid, hist)
% Original header structures - ANALYZE 7.5
%struct data_history
% { /* off + size */
% char descrip[80]; /* 0 + 80 */
% char aux_file[24]; /* 80 + 24 */
% char orient; /* 104 + 1 */
% char originator[10]; /* 105 + 10 */
% char generated[10]; /* 115 + 10 */
% char scannum[10]; /* 125 + 10 */
% char patient_id[10]; /* 135 + 10 */
% char exp_date[10]; /* 145 + 10 */
% char exp_time[10]; /* 155 + 10 */
% char hist_un0[3]; /* 165 + 3 */
% int views /* 168 + 4 */
% int vols_added; /* 172 + 4 */
% int start_field; /* 176 + 4 */
% int field_skip; /* 180 + 4 */
% int omax; /* 184 + 4 */
% int omin; /* 188 + 4 */
% int smax; /* 192 + 4 */
% int smin; /* 196 + 4 */
% }; /* total=200 bytes */
% descrip = sprintf('%-80s', hist.descrip); % 80 chars from left
% fwrite(fid, descrip(1:80), 'uchar');
pad = zeros(1, 80-length(hist.descrip));
hist.descrip = [hist.descrip char(pad)];
fwrite(fid, hist.descrip(1:80), 'uchar');
% aux_file = sprintf('%-24s', hist.aux_file); % 24 chars from left
% fwrite(fid, aux_file(1:24), 'uchar');
pad = zeros(1, 24-length(hist.aux_file));
hist.aux_file = [hist.aux_file char(pad)];
fwrite(fid, hist.aux_file(1:24), 'uchar');
fwrite(fid, hist.orient(1), 'uchar');
fwrite(fid, hist.originator(1:5), 'int16');
pad = zeros(1, 10-length(hist.generated));
hist.generated = [hist.generated char(pad)];
fwrite(fid, hist.generated(1:10), 'uchar');
pad = zeros(1, 10-length(hist.scannum));
hist.scannum = [hist.scannum char(pad)];
fwrite(fid, hist.scannum(1:10), 'uchar');
pad = zeros(1, 10-length(hist.patient_id));
hist.patient_id = [hist.patient_id char(pad)];
fwrite(fid, hist.patient_id(1:10), 'uchar');
pad = zeros(1, 10-length(hist.exp_date));
hist.exp_date = [hist.exp_date char(pad)];
fwrite(fid, hist.exp_date(1:10), 'uchar');
pad = zeros(1, 10-length(hist.exp_time));
hist.exp_time = [hist.exp_time char(pad)];
fwrite(fid, hist.exp_time(1:10), 'uchar');
pad = zeros(1, 3-length(hist.hist_un0));
hist.hist_un0 = [hist.hist_un0 char(pad)];
fwrite(fid, hist.hist_un0(1:3), 'uchar');
fwrite(fid, hist.views(1), 'int32');
fwrite(fid, hist.vols_added(1), 'int32');
fwrite(fid, hist.start_field(1),'int32');
fwrite(fid, hist.field_skip(1), 'int32');
fwrite(fid, hist.omax(1), 'int32');
fwrite(fid, hist.omin(1), 'int32');
fwrite(fid, hist.smax(1), 'int32');
fwrite(fid, hist.smin(1), 'int32');
return; % data_history
|
github
|
changken1/IDH_Prediction-master
|
rri_zoom_menu.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/rri_zoom_menu.m
| 737 |
utf_8
|
d8151523470b0fba970eb1d98ba56030
|
% Imbed a zoom menu to any figure.
%
% Usage: rri_zoom_menu(fig);
%
% - Jimmy Shen ([email protected])
%
%--------------------------------------------------------------------
function menu_hdl = rri_zoom_menu(fig)
if isnumeric(fig)
menu_hdl = uimenu('Parent',fig, ...
'Label','Zoom on', ...
'Userdata', 1, ...
'Callback','rri_zoom_menu(''zoom'');');
return;
end
zoom_on_state = get(gcbo,'Userdata');
if (zoom_on_state == 1)
zoom on;
set(gcbo,'Userdata',0,'Label','Zoom off');
set(gcbf,'pointer','crosshair');
else
zoom off;
set(gcbo,'Userdata',1,'Label','Zoom on');
set(gcbf,'pointer','arrow');
end
return % rri_zoom_menu
|
github
|
changken1/IDH_Prediction-master
|
rri_select_file.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/rri_select_file.m
| 16,599 |
utf_8
|
e349954ca803370f62ceeabdbab5912e
|
function [selected_file, selected_path] = rri_select_file(varargin)
%
% USAGE: [selected_file, selected_path] = ...
% rri_select_file(dir_name, fig_title)
%
% Allow user to select a file from a list of Matlab competible
% file format
%
% Example:
%
% [selected_file, selected_path] = ...
% rri_select_file('/usr','Select Data File');
%
% See Also RRI_GETFILES
% -- Created June 2001 by Wilkin Chau, Rotman Research Institute
%
% use rri_select_file to open & save Matlab recognized format
% -- Modified Dec 2002 by Jimmy Shen, Rotman Research Institute
%
if nargin == 0 | ischar(varargin{1}) % create rri_select_file figure
dir_name = '';
fig_title = 'Select a File';
if nargin > 0
dir_name = varargin{1};
end
if nargin > 1
fig_title = varargin{2};
end
Init(fig_title,dir_name);
uiwait; % wait for user finish
selected_path = getappdata(gcf,'SelectedDirectory');
selected_file = getappdata(gcf,'SelectedFile');
cd (getappdata(gcf,'StartDirectory'));
close(gcf);
return;
end;
% clear the message line,
%
h = findobj(gcf,'Tag','MessageLine');
set(h,'String','');
action = varargin{1}{1};
% change 'File format':
% update 'Files' & 'File selection' based on file pattern
%
if strcmp(action,'EditFilter'),
EditFilter;
% run delete_fig when figure is closing
%
elseif strcmp(action,'delete_fig'),
delete_fig;
% select 'Directories':
% go into the selected dir
% update 'Files' & 'File selection' based on file pattern
%
elseif strcmp(action,'select_dir'),
select_dir;
% select 'Files':
% update 'File selection'
%
elseif strcmp(action,'select_file'),
select_file;
% change 'File selection':
% if it is a file, select that,
% if it is more than a file (*), select those,
% if it is a directory, select based on file pattern
%
elseif strcmp(action,'EditSelection'),
EditSelection;
% clicked 'Select'
%
elseif strcmp(action,'DONE_BUTTON_PRESSED'),
h = findobj(gcf,'Tag','SelectionEdit');
[filepath,filename,fileext] = fileparts(get(h,'String'));
if isempty(filepath) | isempty(filename) | isempty(fileext)
setappdata(gcf,'SelectedDirectory',[]);
setappdata(gcf,'SelectedFile',[]);
else
if ~strcmp(filepath(end),filesep) % not end with filesep
filepath = [filepath filesep]; % add a filesep to filepath
end
setappdata(gcf,'SelectedDirectory',filepath);
setappdata(gcf,'SelectedFile',[filename fileext]);
end
if getappdata(gcf,'ready') % ready to exit
uiresume;
end
% clicked 'cancel'
%
elseif strcmp(action,'CANCEL_BUTTON_PRESSED'),
setappdata(gcf,'SelectedDirectory',[]);
setappdata(gcf,'SelectedFile',[]);
set(findobj(gcf,'Tag','FileList'),'String','');
uiresume;
end;
return;
% --------------------------------------------------------------------
function Init(fig_title,dir_name),
StartDirectory = pwd;
if isempty(StartDirectory),
StartDirectory = filesep;
end;
filter_disp = {'JPEG image (*.jpg)', ...
'TIFF image, compressed (*.tif)', ...
'EPS Level 1 (*.eps)', ...
'Adobe Illustrator 88 (*.ai)', ...
'Enhanced metafile (*.emf)', ...
'Matlab Figure (*.fig)', ...
'Matlab M-file (*.m)', ...
'Portable bitmap (*.pbm)', ...
'Paintbrush 24-bit (*.pcx)', ...
'Portable Graymap (*.pgm)', ...
'Portable Network Graphics (*.png)', ...
'Portable Pixmap (*.ppm)', ...
};
filter_string = {'*.jpg', ...
'*.tif', ...
'*.eps', ...
'*.ai', ...
'*.emf', ...
'*.fig', ...
'*.m', ...
'*.pbm', ...
'*.pcx', ...
'*.pgm', ...
'*.png', ...
'*.ppm', ...
};
% filter_disp = char(filter_disp);
filter_string = char(filter_string);
margine = 0.05;
line_height = 0.07;
char_height = line_height*0.8;
save_setting_status = 'on';
rri_select_file_pos = [];
try
load('pls_profile');
catch
end
if ~isempty(rri_select_file_pos) & strcmp(save_setting_status,'on')
pos = rri_select_file_pos;
else
w = 0.4;
h = 0.6;
x = (1-w)/2;
y = (1-h)/2;
pos = [x y w h];
end
h0 = figure('parent',0, 'Color',[0.8 0.8 0.8], ...
'Units','normal', ...
'Name',fig_title, ...
'NumberTitle','off', ...
'MenuBar','none', ...
'Position', pos, ...
'deleteFcn','rri_select_file({''delete_fig''});', ...
'WindowStyle', 'modal', ...
'Tag','GetFilesFigure', ...
'ToolBar','none');
x = margine;
y = 1 - 1*line_height - margine;
w = 1-2*x;
h = char_height;
pos = [x y w h];
h1 = uicontrol('Parent',h0, ... % Filter Label
'Style','text', ...
'Units','normal', ...
'BackgroundColor',[0.8 0.8 0.8], ...
'fontunit','normal', ...
'FontSize',0.5, ...
'HorizontalAlignment','left', ...
'Position', pos, ...
'String','Choose one of the file format:', ...
'Tag','FilterLabel');
y = 1 - 2*line_height - margine + line_height*0.2;
w = 1-2*x;
pos = [x y w h];
h_filter = uicontrol('Parent',h0, ... % Filter list
'Style','popupmenu', ...
'Units','normal', ...
'BackgroundColor',[1 1 1], ...
'fontunit','normal', ...
'FontSize',0.5, ...
'HorizontalAlignment','left', ...
'Position', pos, ...
'String', filter_disp, ...
'user', filter_string, ...
'value', 1, ...
'Callback','rri_select_file({''EditFilter''});', ...
'Tag','FilterEdit');
y = 1 - 3*line_height - margine;
w = 0.5 - x - margine/2;
pos = [x y w h];
h1 = uicontrol('Parent',h0, ... % Directory Label
'Style','text', ...
'Units','normal', ...
'BackgroundColor',[0.8 0.8 0.8], ...
'fontunit','normal', ...
'FontSize',0.5, ...
'HorizontalAlignment','left', ...
'ListboxTop',0, ...
'Position', pos, ...
'String','Directories', ...
'Tag','DirectoryLabel');
x = 0.5;
y = 1 - 3*line_height - margine;
w = 0.5 - margine;
pos = [x y w h];
h1 = uicontrol('Parent',h0, ... % File Label
'Style','text', ...
'Units','normal', ...
'BackgroundColor',[0.8 0.8 0.8], ...
'fontunit','normal', ...
'FontSize',0.5, ...
'HorizontalAlignment','left', ...
'ListboxTop',0, ...
'Position', pos, ...
'String','Files', ...
'Tag','FileLabel');
x = margine;
y = 4*line_height + margine;
w = 0.5 - x - margine/2;
h = 1 - 7*line_height - 2*margine;
pos = [x y w h];
h_dir = uicontrol('Parent',h0, ... % Directory Listbox
'Style','listbox', ...
'Units','normal', ...
'fontunit','normal', ...
'FontSize',0.08, ...
'HorizontalAlignment','left', ...
'Interruptible', 'off', ...
'ListboxTop',1, ...
'Position', pos, ...
'String', '', ...
'Callback','rri_select_file({''select_dir''});', ...
'Tag','DirectoryList');
x = 0.5;
y = 4*line_height + margine;
w = 0.5 - margine;
h = 1 - 7*line_height - 2*margine;
pos = [x y w h];
h_file = uicontrol('Parent',h0, ... % File Listbox
'Style','listbox', ...
'Units','normal', ...
'fontunit','normal', ...
'FontSize',0.08, ...
'HorizontalAlignment','left', ...
'ListboxTop',1, ...
'Position', pos, ...
'String', '', ...
'Callback','rri_select_file({''select_file''});', ...
'Tag','FileList');
x = margine;
y = 3*line_height + margine - line_height*0.2;
w = 1-2*x;
h = char_height;
pos = [x y w h];
h1 = uicontrol('Parent',h0, ... % Selection Label
'Style','text', ...
'Units','normal', ...
'BackgroundColor',[0.8 0.8 0.8], ...
'fontunit','normal', ...
'FontSize',0.5, ...
'HorizontalAlignment','left', ...
'Position', pos, ...
'String','File you selected:', ...
'Tag','SelectionLabel');
y = 2*line_height + margine;
w = 1-2*x;
pos = [x y w h];
h_select = uicontrol('Parent',h0, ... % Selection Edit
'Style','edit', ...
'Units','normal', ...
'BackgroundColor',[1 1 1], ...
'fontunit','normal', ...
'FontSize',0.5, ...
'HorizontalAlignment','left', ...
'Position', pos, ...
'String', '', ...
'Callback','rri_select_file({''EditSelection''});', ...
'Tag','SelectionEdit');
x = 2*margine;
y = line_height/2 + margine;
w = 0.2;
h = line_height;
pos = [x y w h];
h_done = uicontrol('Parent',h0, ... % DONE
'Units','normal', ...
'fontunit','normal', ...
'FontSize',0.5, ...
'ListboxTop',0, ...
'Position', pos, ...
'HorizontalAlignment','center', ...
'String','Save', ... % 'Select', ...
'Callback','rri_select_file({''DONE_BUTTON_PRESSED''});', ...
'Tag','DONEButton');
x = 1 - x - w;
pos = [x y w h];
h_cancel = uicontrol('Parent',h0, ... % CANCEL
'Units','normal', ...
'fontunit','normal', ...
'FontSize',0.5, ...
'ListboxTop',0, ...
'Position', pos, ...
'HorizontalAlignment','center', ...
'String','Cancel', ...
'Callback','rri_select_file({''CANCEL_BUTTON_PRESSED''});', ...
'Tag','CANCELButton');
if isempty(dir_name)
dir_name = StartDirectory;
end
set(h_select,'string',dir_name);
filter_select = get(h_filter,'value');
filter_pattern = filter_string(filter_select,:);
setappdata(gcf,'FilterPattern',deblank(filter_pattern));
setappdata(gcf,'filter_string',filter_string);
setappdata(gcf,'h_filter', h_filter);
setappdata(gcf,'h_dir', h_dir);
setappdata(gcf,'h_file', h_file);
setappdata(gcf,'h_select', h_select);
setappdata(gcf,'h_done', h_done);
setappdata(gcf,'h_cancel', h_cancel);
setappdata(gcf,'StartDirectory',StartDirectory);
EditSelection;
h_file = getappdata(gcf,'h_file');
if isempty(get(h_file,'string'))
setappdata(gcf,'ready',0);
else
setappdata(gcf,'ready',1);
end
return; % Init
% called by all the actions, to update 'Directories' or 'Files'
% based on filter_pattern. Select first file in filelist.
%
% --------------------------------------------------------------------
function update_dirlist;
filter_path = getappdata(gcf,'curr_dir');
filter_pattern = getappdata(gcf,'FilterPattern');
if exist(filter_pattern) == 2 % user input specific filename
is_single_file = 1; % need manually take path out later
else
is_single_file = 0;
end
% take the file path out from filter_pattern
%
[fpath fname fext] = fileparts(filter_pattern);
filter_pattern = [fname fext];
dir_struct = dir(filter_path);
if isempty(dir_struct)
msg = 'ERROR: Directory not found!';
uiwait(msgbox(msg,'File Selection Error','modal'));
return;
end;
old_pointer = get(gcf,'Pointer');
set(gcf,'Pointer','watch');
dir_list = dir_struct(find([dir_struct.isdir] == 1));
[sorted_dir_names,sorted_dir_index] = sortrows({dir_list.name}');
dir_struct = dir([filter_path filesep filter_pattern]);
if isempty(dir_struct)
sorted_file_names = [];
else
file_list = dir_struct(find([dir_struct.isdir] == 0));
if is_single_file % take out path
tmp = file_list.name;
[fpath fname fext] = fileparts(tmp);
file_list.name = [fname fext];
end
[sorted_file_names,sorted_file_index] = sortrows({file_list.name}');
end;
disp_dir_names = []; % if need full path, use this
% instead of sorted_dir_names
for i=1:length(sorted_dir_names)
tmp = [filter_path filesep sorted_dir_names{i}];
disp_dir_names = [disp_dir_names {tmp}];
end
h = findobj(gcf,'Tag','DirectoryList');
set(h,'String',sorted_dir_names,'Value',1);
h = findobj(gcf,'Tag','FileList');
set(h,'String',sorted_file_names,'value',1);
h_select = getappdata(gcf,'h_select');
if strcmp(filter_path(end),filesep) % filepath end with filesep
filter_path = filter_path(1:end-1); % take filesep out
end
if isempty(sorted_file_names)
set(h_select,'string',[filter_path filesep]);
else
set(h_select,'string',[filter_path filesep sorted_file_names{1}]);
end
set(gcf,'Pointer',old_pointer);
return; % update_dirlist
% change 'File format':
% update 'Files' & 'File selection' based on file pattern
%
% --------------------------------------------------------------------
function EditFilter()
filter_select = get(gcbo,'value');
filter_string = getappdata(gcf,'filter_string');
filter_pattern = filter_string(filter_select,:);
filter_path = getappdata(gcf,'curr_dir');
% update filter_pattern
setappdata(gcf,'FilterPattern',deblank(filter_pattern));
if isempty(filter_path),
filter_path = filesep;
end;
update_dirlist;
h_file = getappdata(gcf,'h_file');
if isempty(get(h_file,'string'))
setappdata(gcf,'ready',0);
else
setappdata(gcf,'ready',1);
end
return; % EditFilter
% select 'Directories':
% go into the selected dir
% update 'Files' & 'File selection' based on file pattern
%
% --------------------------------------------------------------------
function select_dir()
listed_dir = get(gcbo,'String');
selected_dir_idx = get(gcbo,'Value');
selected_dir = listed_dir{selected_dir_idx};
curr_dir = getappdata(gcf,'curr_dir');
% update the selection box
%
try
cd ([curr_dir filesep selected_dir]);
catch
msg = 'ERROR: Cannot access directory';
uiwait(msgbox(msg,'File Selection Error','modal'));
return;
end;
if isempty(pwd)
curr_dir = filesep;
else
curr_dir = pwd;
end;
setappdata(gcf,'curr_dir',curr_dir);
update_dirlist;
h_file = getappdata(gcf,'h_file');
if isempty(get(h_file,'string'))
setappdata(gcf,'ready',0);
else
setappdata(gcf,'ready',1);
end
return; % select_dir
% select 'Files':
% update 'File selection'
%
% --------------------------------------------------------------------
function select_file()
setappdata(gcf,'ready',1);
listed_file = get(gcbo,'String');
selected_file_idx = get(gcbo,'Value');
selected_file = listed_file{selected_file_idx};
curr_dir = getappdata(gcf,'curr_dir');
if strcmp(curr_dir(end),filesep) % filepath end with filesep
curr_dir = curr_dir(1:end-1); % take filesep out
end
h_select = getappdata(gcf,'h_select');
set(h_select,'string',[curr_dir filesep selected_file]);
return; % select_file
% change 'File selection':
% if it is a file, select that,
% if it is more than a file (*), select those,
% if it is a directory, select based on file pattern
%
% --------------------------------------------------------------------
function EditSelection()
filter_string = getappdata(gcf,'filter_string');
h_select = getappdata(gcf,'h_select');
selected_file = get(h_select,'string');
if exist(selected_file) == 7 % if user enter a dir
setappdata(gcf,'ready',0);
setappdata(gcf,'curr_dir',selected_file); % get new dir
update_dirlist;
else
setappdata(gcf,'ready',1);
[fpath fname fext]= fileparts(selected_file);
if exist(fpath) ~=7 % fpath is not a dir
setappdata(gcf,'ready',0);
msg = 'ERROR: Cannot access directory';
uiwait(msgbox(msg,'File Selection Error','modal'));
end
% if the file format user entered is not supported by matlab
if isempty(strmatch(['*',fext],filter_string,'exact'))
setappdata(gcf,'ready',0);
msg = 'ERROR: File format is not supported by Matlab.';
uiwait(msgbox(msg,'File Selection Error','modal'));
end
end
return; % EditSelection
% --------------------------------------------------------------------
function delete_fig()
try
load('pls_profile');
pls_profile = which('pls_profile.mat');
rri_select_file_pos = get(gcbf,'position');
save(pls_profile, '-append', 'rri_select_file_pos');
catch
end
return;
|
github
|
changken1/IDH_Prediction-master
|
clip_nii.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/clip_nii.m
| 3,306 |
utf_8
|
a70bdbed5a0813312d4c83f94b99a710
|
% CLIP_NII: Clip the NIfTI volume from any of the 6 sides
%
% Usage: nii = clip_nii(nii, [option])
%
% Inputs:
%
% nii - NIfTI volume.
%
% option - struct instructing how many voxel to be cut from which side.
%
% option.cut_from_L = ( number of voxel )
% option.cut_from_R = ( number of voxel )
% option.cut_from_P = ( number of voxel )
% option.cut_from_A = ( number of voxel )
% option.cut_from_I = ( number of voxel )
% option.cut_from_S = ( number of voxel )
%
% Options description in detail:
% ==============================
%
% cut_from_L: Number of voxels from Left side will be clipped.
%
% cut_from_R: Number of voxels from Right side will be clipped.
%
% cut_from_P: Number of voxels from Posterior side will be clipped.
%
% cut_from_A: Number of voxels from Anterior side will be clipped.
%
% cut_from_I: Number of voxels from Inferior side will be clipped.
%
% cut_from_S: Number of voxels from Superior side will be clipped.
%
% NIfTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function nii = clip_nii(nii, opt)
dims = abs(nii.hdr.dime.dim(2:4));
origin = abs(nii.hdr.hist.originator(1:3));
if isempty(origin) | all(origin == 0) % according to SPM
origin = round((dims+1)/2);
end
cut_from_L = 0;
cut_from_R = 0;
cut_from_P = 0;
cut_from_A = 0;
cut_from_I = 0;
cut_from_S = 0;
if nargin > 1 & ~isempty(opt)
if ~isstruct(opt)
error('option argument should be a struct');
end
if isfield(opt,'cut_from_L')
cut_from_L = round(opt.cut_from_L);
if cut_from_L >= origin(1) | cut_from_L < 0
error('cut_from_L cannot be negative or cut beyond originator');
end
end
if isfield(opt,'cut_from_P')
cut_from_P = round(opt.cut_from_P);
if cut_from_P >= origin(2) | cut_from_P < 0
error('cut_from_P cannot be negative or cut beyond originator');
end
end
if isfield(opt,'cut_from_I')
cut_from_I = round(opt.cut_from_I);
if cut_from_I >= origin(3) | cut_from_I < 0
error('cut_from_I cannot be negative or cut beyond originator');
end
end
if isfield(opt,'cut_from_R')
cut_from_R = round(opt.cut_from_R);
if cut_from_R > dims(1)-origin(1) | cut_from_R < 0
error('cut_from_R cannot be negative or cut beyond originator');
end
end
if isfield(opt,'cut_from_A')
cut_from_A = round(opt.cut_from_A);
if cut_from_A > dims(2)-origin(2) | cut_from_A < 0
error('cut_from_A cannot be negative or cut beyond originator');
end
end
if isfield(opt,'cut_from_S')
cut_from_S = round(opt.cut_from_S);
if cut_from_S > dims(3)-origin(3) | cut_from_S < 0
error('cut_from_S cannot be negative or cut beyond originator');
end
end
end
nii = make_nii(nii.img( (cut_from_L+1) : (dims(1)-cut_from_R), ...
(cut_from_P+1) : (dims(2)-cut_from_A), ...
(cut_from_I+1) : (dims(3)-cut_from_S), ...
:,:,:,:,:), nii.hdr.dime.pixdim(2:4), ...
[origin(1)-cut_from_L origin(2)-cut_from_P origin(3)-cut_from_I], ...
nii.hdr.dime.datatype, nii.hdr.hist.descrip);
return;
|
github
|
changken1/IDH_Prediction-master
|
affine.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/affine.m
| 16,110 |
utf_8
|
768d2303e551a9584685bdb01abf6f8b
|
% Using 2D or 3D affine matrix to rotate, translate, scale, reflect and
% shear a 2D image or 3D volume. 2D image is represented by a 2D matrix,
% 3D volume is represented by a 3D matrix, and data type can be real
% integer or floating-point.
%
% You may notice that MATLAB has a function called 'imtransform.m' for
% 2D spatial transformation. However, keep in mind that 'imtransform.m'
% assumes y for the 1st dimension, and x for the 2nd dimension. They are
% equivalent otherwise.
%
% In addition, if you adjust the 'new_elem_size' parameter, this 'affine.m'
% is equivalent to 'interp2.m' for 2D image, and equivalent to 'interp3.m'
% for 3D volume.
%
% Usage: [new_img new_M] = ...
% affine(old_img, old_M, [new_elem_size], [verbose], [bg], [method]);
%
% old_img - original 2D image or 3D volume. We assume x for the 1st
% dimension, y for the 2nd dimension, and z for the 3rd
% dimension.
%
% old_M - a 3x3 2D affine matrix for 2D image, or a 4x4 3D affine
% matrix for 3D volume. We assume x for the 1st dimension,
% y for the 2nd dimension, and z for the 3rd dimension.
%
% new_elem_size (optional) - size of voxel along x y z direction for
% a transformed 3D volume, or size of pixel along x y for
% a transformed 2D image. We assume x for the 1st dimension
% y for the 2nd dimension, and z for the 3rd dimension.
% 'new_elem_size' is 1 if it is default or empty.
%
% You can increase its value to decrease the resampling rate,
% and make the 2D image or 3D volume more coarse. It works
% just like 'interp3'.
%
% verbose (optional) - 1, 0
% 1: show transforming progress in percentage
% 2: progress will not be displayed
% 'verbose' is 1 if it is default or empty.
%
% bg (optional) - background voxel intensity in any extra corner that
% is caused by the interpolation. 0 in most cases. If it is
% default or empty, 'bg' will be the average of two corner
% voxel intensities in original data.
%
% method (optional) - 1, 2, or 3
% 1: for Trilinear interpolation
% 2: for Nearest Neighbor interpolation
% 3: for Fischer's Bresenham interpolation
% 'method' is 1 if it is default or empty.
%
% new_img - transformed 2D image or 3D volume
%
% new_M - transformed affine matrix
%
% Example 1 (3D rotation):
% load mri.mat; old_img = double(squeeze(D));
% old_M = [0.88 0.5 3 -90; -0.5 0.88 3 -126; 0 0 2 -72; 0 0 0 1];
% new_img = affine(old_img, old_M, 2);
% [x y z] = meshgrid(1:128,1:128,1:27);
% sz = size(new_img);
% [x1 y1 z1] = meshgrid(1:sz(2),1:sz(1),1:sz(3));
% figure; slice(x, y, z, old_img, 64, 64, 13.5);
% shading flat; colormap(map); view(-66, 66);
% figure; slice(x1, y1, z1, new_img, sz(1)/2, sz(2)/2, sz(3)/2);
% shading flat; colormap(map); view(-66, 66);
%
% Example 2 (2D interpolation):
% load mri.mat; old_img=D(:,:,1,13)';
% old_M = [1 0 0; 0 1 0; 0 0 1];
% new_img = affine(old_img, old_M, [.2 .4]);
% figure; image(old_img); colormap(map);
% figure; image(new_img); colormap(map);
%
% This program is inspired by:
% SPM5 Software from Wellcome Trust Centre for Neuroimaging
% http://www.fil.ion.ucl.ac.uk/spm/software
% Fischer, J., A. del Rio (2004). A Fast Method for Applying Rigid
% Transformations to Volume Data, WSCG2004 Conference.
% http://wscg.zcu.cz/wscg2004/Papers_2004_Short/M19.pdf
%
% - Jimmy Shen ([email protected])
%
function [new_img, new_M] = affine(old_img, old_M, new_elem_size, verbose, bg, method)
if ~exist('old_img','var') | ~exist('old_M','var')
error('Usage: [new_img new_M] = affine(old_img, old_M, [new_elem_size], [verbose], [bg], [method]);');
end
if ndims(old_img) == 3
if ~isequal(size(old_M),[4 4])
error('old_M should be a 4x4 affine matrix for 3D volume.');
end
elseif ndims(old_img) == 2
if ~isequal(size(old_M),[3 3])
error('old_M should be a 3x3 affine matrix for 2D image.');
end
else
error('old_img should be either 2D image or 3D volume.');
end
if ~exist('new_elem_size','var') | isempty(new_elem_size)
new_elem_size = [1 1 1];
elseif length(new_elem_size) < 2
new_elem_size = new_elem_size(1)*ones(1,3);
elseif length(new_elem_size) < 3
new_elem_size = [new_elem_size(:); 1]';
end
if ~exist('method','var') | isempty(method)
method = 1;
elseif ~exist('bresenham_line3d.m','file') & method == 3
error([char(10) char(10) 'Please download 3D Bresenham''s line generation program from:' char(10) char(10) 'http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=21057' char(10) char(10) 'to test Fischer''s Bresenham interpolation method.' char(10) char(10)]);
end
% Make compatible to MATLAB earlier than version 7 (R14), which
% can only perform arithmetic on double data type
%
old_img = double(old_img);
old_dim = size(old_img);
if ~exist('bg','var') | isempty(bg)
bg = mean([old_img(1) old_img(end)]);
end
if ~exist('verbose','var') | isempty(verbose)
verbose = 1;
end
if ndims(old_img) == 2
old_dim(3) = 1;
old_M = old_M(:, [1 2 3 3]);
old_M = old_M([1 2 3 3], :);
old_M(3,:) = [0 0 1 0];
old_M(:,3) = [0 0 1 0]';
end
% Vertices of img in voxel
%
XYZvox = [ 1 1 1
1 1 old_dim(3)
1 old_dim(2) 1
1 old_dim(2) old_dim(3)
old_dim(1) 1 1
old_dim(1) 1 old_dim(3)
old_dim(1) old_dim(2) 1
old_dim(1) old_dim(2) old_dim(3) ]';
old_R = old_M(1:3,1:3);
old_T = old_M(1:3,4);
% Vertices of img in millimeter
%
XYZmm = old_R*(XYZvox-1) + repmat(old_T, [1, 8]);
% Make scale of new_M according to new_elem_size
%
new_M = diag([new_elem_size 1]);
% Make translation so minimum vertex is moved to [1,1,1]
%
new_M(1:3,4) = round( min(XYZmm,[],2) );
% New dimensions will be the maximum vertices in XYZ direction (dim_vox)
% i.e. compute dim_vox via dim_mm = R*(dim_vox-1)+T
% where, dim_mm = round(max(XYZmm,[],2));
%
new_dim = ceil(new_M(1:3,1:3) \ ( round(max(XYZmm,[],2))-new_M(1:3,4) )+1)';
% Initialize new_img with new_dim
%
new_img = zeros(new_dim(1:3));
% Mask out any changes from Z axis of transformed volume, since we
% will traverse it voxel by voxel below. We will only apply unit
% increment of mask_Z(3,4) to simulate the cursor movement
%
% i.e. we will use mask_Z * new_XYZvox to replace new_XYZvox
%
mask_Z = diag(ones(1,4));
mask_Z(3,3) = 0;
% It will be easier to do the interpolation if we invert the process
% by not traversing the original volume. Instead, we traverse the
% transformed volume, and backproject each voxel in the transformed
% volume back into the original volume. If the backprojected voxel
% in original volume is within its boundary, the intensity of that
% voxel can be used by the cursor location in the transformed volume.
%
% First, we traverse along Z axis of transformed volume voxel by voxel
%
for z = 1:new_dim(3)
if verbose & ~mod(z,10)
fprintf('%.2f percent is done.\n', 100*z/new_dim(3));
end
% We need to find out the mapping from voxel in the transformed
% volume (new_XYZvox) to voxel in the original volume (old_XYZvox)
%
% The following equation works, because they all equal to XYZmm:
% new_R*(new_XYZvox-1) + new_T == old_R*(old_XYZvox-1) + old_T
%
% We can use modified new_M1 & old_M1 to substitute new_M & old_M
% new_M1 * new_XYZvox == old_M1 * old_XYZvox
%
% where: M1 = M; M1(:,4) = M(:,4) - sum(M(:,1:3),2);
% and: M(:,4) == [T; 1] == sum(M1,2)
%
% Therefore: old_XYZvox = old_M1 \ new_M1 * new_XYZvox;
%
% Since we are traverse Z axis, and new_XYZvox is replaced
% by mask_Z * new_XYZvox, the above formula can be rewritten
% as: old_XYZvox = old_M1 \ new_M1 * mask_Z * new_XYZvox;
%
% i.e. we find the mapping from new_XYZvox to old_XYZvox:
% M = old_M1 \ new_M1 * mask_Z;
%
% First, compute modified old_M1 & new_M1
%
old_M1 = old_M; old_M1(:,4) = old_M(:,4) - sum(old_M(:,1:3),2);
new_M1 = new_M; new_M1(:,4) = new_M(:,4) - sum(new_M(:,1:3),2);
% Then, apply unit increment of mask_Z(3,4) to simulate the
% cursor movement
%
mask_Z(3,4) = z;
% Here is the mapping from new_XYZvox to old_XYZvox
%
M = old_M1 \ new_M1 * mask_Z;
switch method
case 1
new_img(:,:,z) = trilinear(old_img, new_dim, old_dim, M, bg);
case 2
new_img(:,:,z) = nearest_neighbor(old_img, new_dim, old_dim, M, bg);
case 3
new_img(:,:,z) = bresenham(old_img, new_dim, old_dim, M, bg);
end
end; % for z
if ndims(old_img) == 2
new_M(3,:) = [];
new_M(:,3) = [];
end
return; % affine
%--------------------------------------------------------------------
function img_slice = trilinear(img, dim1, dim2, M, bg)
img_slice = zeros(dim1(1:2));
TINY = 5e-2; % tolerance
% Dimension of transformed 3D volume
%
xdim1 = dim1(1);
ydim1 = dim1(2);
% Dimension of original 3D volume
%
xdim2 = dim2(1);
ydim2 = dim2(2);
zdim2 = dim2(3);
% initialize new_Y accumulation
%
Y2X = 0;
Y2Y = 0;
Y2Z = 0;
for y = 1:ydim1
% increment of new_Y accumulation
%
Y2X = Y2X + M(1,2); % new_Y to old_X
Y2Y = Y2Y + M(2,2); % new_Y to old_Y
Y2Z = Y2Z + M(3,2); % new_Y to old_Z
% backproject new_Y accumulation and translation to old_XYZ
%
old_X = Y2X + M(1,4);
old_Y = Y2Y + M(2,4);
old_Z = Y2Z + M(3,4);
for x = 1:xdim1
% accumulate the increment of new_X, and apply it
% to the backprojected old_XYZ
%
old_X = M(1,1) + old_X ;
old_Y = M(2,1) + old_Y ;
old_Z = M(3,1) + old_Z ;
% within boundary of original image
%
if ( old_X > 1-TINY & old_X < xdim2+TINY & ...
old_Y > 1-TINY & old_Y < ydim2+TINY & ...
old_Z > 1-TINY & old_Z < zdim2+TINY )
% Calculate distance of old_XYZ to its neighbors for
% weighted intensity average
%
dx = old_X - floor(old_X);
dy = old_Y - floor(old_Y);
dz = old_Z - floor(old_Z);
x000 = floor(old_X);
x100 = x000 + 1;
if floor(old_X) < 1
x000 = 1;
x100 = x000;
elseif floor(old_X) > xdim2-1
x000 = xdim2;
x100 = x000;
end
x010 = x000;
x001 = x000;
x011 = x000;
x110 = x100;
x101 = x100;
x111 = x100;
y000 = floor(old_Y);
y010 = y000 + 1;
if floor(old_Y) < 1
y000 = 1;
y100 = y000;
elseif floor(old_Y) > ydim2-1
y000 = ydim2;
y010 = y000;
end
y100 = y000;
y001 = y000;
y101 = y000;
y110 = y010;
y011 = y010;
y111 = y010;
z000 = floor(old_Z);
z001 = z000 + 1;
if floor(old_Z) < 1
z000 = 1;
z001 = z000;
elseif floor(old_Z) > zdim2-1
z000 = zdim2;
z001 = z000;
end
z100 = z000;
z010 = z000;
z110 = z000;
z101 = z001;
z011 = z001;
z111 = z001;
x010 = x000;
x001 = x000;
x011 = x000;
x110 = x100;
x101 = x100;
x111 = x100;
v000 = double(img(x000, y000, z000));
v010 = double(img(x010, y010, z010));
v001 = double(img(x001, y001, z001));
v011 = double(img(x011, y011, z011));
v100 = double(img(x100, y100, z100));
v110 = double(img(x110, y110, z110));
v101 = double(img(x101, y101, z101));
v111 = double(img(x111, y111, z111));
img_slice(x,y) = v000*(1-dx)*(1-dy)*(1-dz) + ...
v010*(1-dx)*dy*(1-dz) + ...
v001*(1-dx)*(1-dy)*dz + ...
v011*(1-dx)*dy*dz + ...
v100*dx*(1-dy)*(1-dz) + ...
v110*dx*dy*(1-dz) + ...
v101*dx*(1-dy)*dz + ...
v111*dx*dy*dz;
else
img_slice(x,y) = bg;
end % if boundary
end % for x
end % for y
return; % trilinear
%--------------------------------------------------------------------
function img_slice = nearest_neighbor(img, dim1, dim2, M, bg)
img_slice = zeros(dim1(1:2));
% Dimension of transformed 3D volume
%
xdim1 = dim1(1);
ydim1 = dim1(2);
% Dimension of original 3D volume
%
xdim2 = dim2(1);
ydim2 = dim2(2);
zdim2 = dim2(3);
% initialize new_Y accumulation
%
Y2X = 0;
Y2Y = 0;
Y2Z = 0;
for y = 1:ydim1
% increment of new_Y accumulation
%
Y2X = Y2X + M(1,2); % new_Y to old_X
Y2Y = Y2Y + M(2,2); % new_Y to old_Y
Y2Z = Y2Z + M(3,2); % new_Y to old_Z
% backproject new_Y accumulation and translation to old_XYZ
%
old_X = Y2X + M(1,4);
old_Y = Y2Y + M(2,4);
old_Z = Y2Z + M(3,4);
for x = 1:xdim1
% accumulate the increment of new_X and apply it
% to the backprojected old_XYZ
%
old_X = M(1,1) + old_X ;
old_Y = M(2,1) + old_Y ;
old_Z = M(3,1) + old_Z ;
xi = round(old_X);
yi = round(old_Y);
zi = round(old_Z);
% within boundary of original image
%
if ( xi >= 1 & xi <= xdim2 & ...
yi >= 1 & yi <= ydim2 & ...
zi >= 1 & zi <= zdim2 )
img_slice(x,y) = img(xi,yi,zi);
else
img_slice(x,y) = bg;
end % if boundary
end % for x
end % for y
return; % nearest_neighbor
%--------------------------------------------------------------------
function img_slice = bresenham(img, dim1, dim2, M, bg)
img_slice = zeros(dim1(1:2));
% Dimension of transformed 3D volume
%
xdim1 = dim1(1);
ydim1 = dim1(2);
% Dimension of original 3D volume
%
xdim2 = dim2(1);
ydim2 = dim2(2);
zdim2 = dim2(3);
for y = 1:ydim1
start_old_XYZ = round(M*[0 y 0 1]');
end_old_XYZ = round(M*[xdim1 y 0 1]');
[X Y Z] = bresenham_line3d(start_old_XYZ, end_old_XYZ);
% line error correction
%
% del = end_old_XYZ - start_old_XYZ;
% del_dom = max(del);
% idx_dom = find(del==del_dom);
% idx_dom = idx_dom(1);
% idx_other = [1 2 3];
% idx_other(idx_dom) = [];
%del_x1 = del(idx_other(1));
% del_x2 = del(idx_other(2));
% line_slope = sqrt((del_x1/del_dom)^2 + (del_x2/del_dom)^2 + 1);
% line_error = line_slope - 1;
% line error correction removed because it is too slow
for x = 1:xdim1
% rescale ratio
%
i = round(x * length(X) / xdim1);
if i < 1
i = 1;
elseif i > length(X)
i = length(X);
end
xi = X(i);
yi = Y(i);
zi = Z(i);
% within boundary of the old XYZ space
%
if ( xi >= 1 & xi <= xdim2 & ...
yi >= 1 & yi <= ydim2 & ...
zi >= 1 & zi <= zdim2 )
img_slice(x,y) = img(xi,yi,zi);
% if line_error > 1
% x = x + 1;
% if x <= xdim1
% img_slice(x,y) = img(xi,yi,zi);
% line_error = line_slope - 1;
% end
% end % if line_error
% line error correction removed because it is too slow
else
img_slice(x,y) = bg;
end % if boundary
end % for x
end % for y
return; % bresenham
|
github
|
changken1/IDH_Prediction-master
|
load_untouch_nii_img.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/load_untouch_nii_img.m
| 14,756 |
utf_8
|
688b2a42f8071c6402a037c7ca923689
|
% internal function
% - Jimmy Shen ([email protected])
function [img,hdr] = load_untouch_nii_img(hdr,filetype,fileprefix,machine,img_idx,dim5_idx,dim6_idx,dim7_idx,old_RGB,slice_idx)
if ~exist('hdr','var') | ~exist('filetype','var') | ~exist('fileprefix','var') | ~exist('machine','var')
error('Usage: [img,hdr] = load_nii_img(hdr,filetype,fileprefix,machine,[img_idx],[dim5_idx],[dim6_idx],[dim7_idx],[old_RGB],[slice_idx]);');
end
if ~exist('img_idx','var') | isempty(img_idx) | hdr.dime.dim(5)<1
img_idx = [];
end
if ~exist('dim5_idx','var') | isempty(dim5_idx) | hdr.dime.dim(6)<1
dim5_idx = [];
end
if ~exist('dim6_idx','var') | isempty(dim6_idx) | hdr.dime.dim(7)<1
dim6_idx = [];
end
if ~exist('dim7_idx','var') | isempty(dim7_idx) | hdr.dime.dim(8)<1
dim7_idx = [];
end
if ~exist('old_RGB','var') | isempty(old_RGB)
old_RGB = 0;
end
if ~exist('slice_idx','var') | isempty(slice_idx) | hdr.dime.dim(4)<1
slice_idx = [];
end
% check img_idx
%
if ~isempty(img_idx) & ~isnumeric(img_idx)
error('"img_idx" should be a numerical array.');
end
if length(unique(img_idx)) ~= length(img_idx)
error('Duplicate image index in "img_idx"');
end
if ~isempty(img_idx) & (min(img_idx) < 1 | max(img_idx) > hdr.dime.dim(5))
max_range = hdr.dime.dim(5);
if max_range == 1
error(['"img_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"img_idx" should be an integer within the range of [' range '].']);
end
end
% check dim5_idx
%
if ~isempty(dim5_idx) & ~isnumeric(dim5_idx)
error('"dim5_idx" should be a numerical array.');
end
if length(unique(dim5_idx)) ~= length(dim5_idx)
error('Duplicate index in "dim5_idx"');
end
if ~isempty(dim5_idx) & (min(dim5_idx) < 1 | max(dim5_idx) > hdr.dime.dim(6))
max_range = hdr.dime.dim(6);
if max_range == 1
error(['"dim5_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"dim5_idx" should be an integer within the range of [' range '].']);
end
end
% check dim6_idx
%
if ~isempty(dim6_idx) & ~isnumeric(dim6_idx)
error('"dim6_idx" should be a numerical array.');
end
if length(unique(dim6_idx)) ~= length(dim6_idx)
error('Duplicate index in "dim6_idx"');
end
if ~isempty(dim6_idx) & (min(dim6_idx) < 1 | max(dim6_idx) > hdr.dime.dim(7))
max_range = hdr.dime.dim(7);
if max_range == 1
error(['"dim6_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"dim6_idx" should be an integer within the range of [' range '].']);
end
end
% check dim7_idx
%
if ~isempty(dim7_idx) & ~isnumeric(dim7_idx)
error('"dim7_idx" should be a numerical array.');
end
if length(unique(dim7_idx)) ~= length(dim7_idx)
error('Duplicate index in "dim7_idx"');
end
if ~isempty(dim7_idx) & (min(dim7_idx) < 1 | max(dim7_idx) > hdr.dime.dim(8))
max_range = hdr.dime.dim(8);
if max_range == 1
error(['"dim7_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"dim7_idx" should be an integer within the range of [' range '].']);
end
end
% check slice_idx
%
if ~isempty(slice_idx) & ~isnumeric(slice_idx)
error('"slice_idx" should be a numerical array.');
end
if length(unique(slice_idx)) ~= length(slice_idx)
error('Duplicate index in "slice_idx"');
end
if ~isempty(slice_idx) & (min(slice_idx) < 1 | max(slice_idx) > hdr.dime.dim(4))
max_range = hdr.dime.dim(4);
if max_range == 1
error(['"slice_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"slice_idx" should be an integer within the range of [' range '].']);
end
end
[img,hdr] = read_image(hdr,filetype,fileprefix,machine,img_idx,dim5_idx,dim6_idx,dim7_idx,old_RGB,slice_idx);
return % load_nii_img
%---------------------------------------------------------------------
function [img,hdr] = read_image(hdr,filetype,fileprefix,machine,img_idx,dim5_idx,dim6_idx,dim7_idx,old_RGB,slice_idx)
switch filetype
case {0, 1}
fn = [fileprefix '.img'];
case 2
fn = [fileprefix '.nii'];
end
fid = fopen(fn,'r',machine);
if fid < 0,
msg = sprintf('Cannot open file %s.',fn);
error(msg);
end
% Set bitpix according to datatype
%
% /*Acceptable values for datatype are*/
%
% 0 None (Unknown bit per voxel) % DT_NONE, DT_UNKNOWN
% 1 Binary (ubit1, bitpix=1) % DT_BINARY
% 2 Unsigned char (uchar or uint8, bitpix=8) % DT_UINT8, NIFTI_TYPE_UINT8
% 4 Signed short (int16, bitpix=16) % DT_INT16, NIFTI_TYPE_INT16
% 8 Signed integer (int32, bitpix=32) % DT_INT32, NIFTI_TYPE_INT32
% 16 Floating point (single or float32, bitpix=32) % DT_FLOAT32, NIFTI_TYPE_FLOAT32
% 32 Complex, 2 float32 (Use float32, bitpix=64) % DT_COMPLEX64, NIFTI_TYPE_COMPLEX64
% 64 Double precision (double or float64, bitpix=64) % DT_FLOAT64, NIFTI_TYPE_FLOAT64
% 128 uint8 RGB (Use uint8, bitpix=24) % DT_RGB24, NIFTI_TYPE_RGB24
% 256 Signed char (schar or int8, bitpix=8) % DT_INT8, NIFTI_TYPE_INT8
% 511 Single RGB (Use float32, bitpix=96) % DT_RGB96, NIFTI_TYPE_RGB96
% 512 Unsigned short (uint16, bitpix=16) % DT_UNINT16, NIFTI_TYPE_UNINT16
% 768 Unsigned integer (uint32, bitpix=32) % DT_UNINT32, NIFTI_TYPE_UNINT32
% 1024 Signed long long (int64, bitpix=64) % DT_INT64, NIFTI_TYPE_INT64
% 1280 Unsigned long long (uint64, bitpix=64) % DT_UINT64, NIFTI_TYPE_UINT64
% 1536 Long double, float128 (Unsupported, bitpix=128) % DT_FLOAT128, NIFTI_TYPE_FLOAT128
% 1792 Complex128, 2 float64 (Use float64, bitpix=128) % DT_COMPLEX128, NIFTI_TYPE_COMPLEX128
% 2048 Complex256, 2 float128 (Unsupported, bitpix=256) % DT_COMPLEX128, NIFTI_TYPE_COMPLEX128
%
switch hdr.dime.datatype
case 1,
hdr.dime.bitpix = 1; precision = 'ubit1';
case 2,
hdr.dime.bitpix = 8; precision = 'uint8';
case 4,
hdr.dime.bitpix = 16; precision = 'int16';
case 8,
hdr.dime.bitpix = 32; precision = 'int32';
case 16,
hdr.dime.bitpix = 32; precision = 'float32';
case 32,
hdr.dime.bitpix = 64; precision = 'float32';
case 64,
hdr.dime.bitpix = 64; precision = 'float64';
case 128,
hdr.dime.bitpix = 24; precision = 'uint8';
case 256
hdr.dime.bitpix = 8; precision = 'int8';
case 511
hdr.dime.bitpix = 96; precision = 'float32';
case 512
hdr.dime.bitpix = 16; precision = 'uint16';
case 768
hdr.dime.bitpix = 32; precision = 'uint32';
case 1024
hdr.dime.bitpix = 64; precision = 'int64';
case 1280
hdr.dime.bitpix = 64; precision = 'uint64';
case 1792,
hdr.dime.bitpix = 128; precision = 'float64';
otherwise
error('This datatype is not supported');
end
tmp = hdr.dime.dim(2:end);
tmp(find(tmp < 1)) = 1;
hdr.dime.dim(2:end) = tmp;
% move pointer to the start of image block
%
switch filetype
case {0, 1}
fseek(fid, 0, 'bof');
case 2
fseek(fid, hdr.dime.vox_offset, 'bof');
end
% Load whole image block for old Analyze format or binary image;
% otherwise, load images that are specified in img_idx, dim5_idx,
% dim6_idx, and dim7_idx
%
% For binary image, we have to read all because pos can not be
% seeked in bit and can not be calculated the way below.
%
if hdr.dime.datatype == 1 | isequal(hdr.dime.dim(4:8),ones(1,5)) | ...
(isempty(img_idx) & isempty(dim5_idx) & isempty(dim6_idx) & isempty(dim7_idx) & isempty(slice_idx))
% For each frame, precision of value will be read
% in img_siz times, where img_siz is only the
% dimension size of an image, not the byte storage
% size of an image.
%
img_siz = prod(hdr.dime.dim(2:8));
% For complex float32 or complex float64, voxel values
% include [real, imag]
%
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792
img_siz = img_siz * 2;
end
%MPH: For RGB24, voxel values include 3 separate color planes
%
if hdr.dime.datatype == 128 | hdr.dime.datatype == 511
img_siz = img_siz * 3;
end
img = fread(fid, img_siz, sprintf('*%s',precision));
d1 = hdr.dime.dim(2);
d2 = hdr.dime.dim(3);
d3 = hdr.dime.dim(4);
d4 = hdr.dime.dim(5);
d5 = hdr.dime.dim(6);
d6 = hdr.dime.dim(7);
d7 = hdr.dime.dim(8);
if isempty(slice_idx)
slice_idx = 1:d3;
end
if isempty(img_idx)
img_idx = 1:d4;
end
if isempty(dim5_idx)
dim5_idx = 1:d5;
end
if isempty(dim6_idx)
dim6_idx = 1:d6;
end
if isempty(dim7_idx)
dim7_idx = 1:d7;
end
else
d1 = hdr.dime.dim(2);
d2 = hdr.dime.dim(3);
d3 = hdr.dime.dim(4);
d4 = hdr.dime.dim(5);
d5 = hdr.dime.dim(6);
d6 = hdr.dime.dim(7);
d7 = hdr.dime.dim(8);
if isempty(slice_idx)
slice_idx = 1:d3;
end
if isempty(img_idx)
img_idx = 1:d4;
end
if isempty(dim5_idx)
dim5_idx = 1:d5;
end
if isempty(dim6_idx)
dim6_idx = 1:d6;
end
if isempty(dim7_idx)
dim7_idx = 1:d7;
end
%ROMAN: begin
roman = 1;
if(roman)
% compute size of one slice
%
img_siz = prod(hdr.dime.dim(2:3));
% For complex float32 or complex float64, voxel values
% include [real, imag]
%
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792
img_siz = img_siz * 2;
end
%MPH: For RGB24, voxel values include 3 separate color planes
%
if hdr.dime.datatype == 128 | hdr.dime.datatype == 511
img_siz = img_siz * 3;
end
% preallocate img
img = zeros(img_siz, length(slice_idx)*length(img_idx)*length(dim5_idx)*length(dim6_idx)*length(dim7_idx) );
currentIndex = 1;
else
img = [];
end; %if(roman)
% ROMAN: end
for i7=1:length(dim7_idx)
for i6=1:length(dim6_idx)
for i5=1:length(dim5_idx)
for t=1:length(img_idx)
for s=1:length(slice_idx)
% Position is seeked in bytes. To convert dimension size
% to byte storage size, hdr.dime.bitpix/8 will be
% applied.
%
pos = sub2ind([d1 d2 d3 d4 d5 d6 d7], 1, 1, slice_idx(s), ...
img_idx(t), dim5_idx(i5),dim6_idx(i6),dim7_idx(i7)) -1;
pos = pos * hdr.dime.bitpix/8;
% ROMAN: begin
if(roman)
% do nothing
else
img_siz = prod(hdr.dime.dim(2:3));
% For complex float32 or complex float64, voxel values
% include [real, imag]
%
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792
img_siz = img_siz * 2;
end
%MPH: For RGB24, voxel values include 3 separate color planes
%
if hdr.dime.datatype == 128 | hdr.dime.datatype == 511
img_siz = img_siz * 3;
end
end; % if (roman)
% ROMAN: end
if filetype == 2
fseek(fid, pos + hdr.dime.vox_offset, 'bof');
else
fseek(fid, pos, 'bof');
end
% For each frame, fread will read precision of value
% in img_siz times
%
% ROMAN: begin
if(roman)
img(:,currentIndex) = fread(fid, img_siz, sprintf('*%s',precision));
currentIndex = currentIndex +1;
else
img = [img fread(fid, img_siz, sprintf('*%s',precision))];
end; %if(roman)
% ROMAN: end
end
end
end
end
end
end
% For complex float32 or complex float64, voxel values
% include [real, imag]
%
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792
img = reshape(img, [2, length(img)/2]);
img = complex(img(1,:)', img(2,:)');
end
fclose(fid);
% Update the global min and max values
%
hdr.dime.glmax = double(max(img(:)));
hdr.dime.glmin = double(min(img(:)));
% old_RGB treat RGB slice by slice, now it is treated voxel by voxel
%
if old_RGB & hdr.dime.datatype == 128 & hdr.dime.bitpix == 24
% remove squeeze
img = (reshape(img, [hdr.dime.dim(2:3) 3 length(slice_idx) length(img_idx) length(dim5_idx) length(dim6_idx) length(dim7_idx)]));
img = permute(img, [1 2 4 3 5 6 7 8]);
elseif hdr.dime.datatype == 128 & hdr.dime.bitpix == 24
% remove squeeze
img = (reshape(img, [3 hdr.dime.dim(2:3) length(slice_idx) length(img_idx) length(dim5_idx) length(dim6_idx) length(dim7_idx)]));
img = permute(img, [2 3 4 1 5 6 7 8]);
elseif hdr.dime.datatype == 511 & hdr.dime.bitpix == 96
img = double(img(:));
img = single((img - min(img))/(max(img) - min(img)));
% remove squeeze
img = (reshape(img, [3 hdr.dime.dim(2:3) length(slice_idx) length(img_idx) length(dim5_idx) length(dim6_idx) length(dim7_idx)]));
img = permute(img, [2 3 4 1 5 6 7 8]);
else
% remove squeeze
img = (reshape(img, [hdr.dime.dim(2:3) length(slice_idx) length(img_idx) length(dim5_idx) length(dim6_idx) length(dim7_idx)]));
end
if ~isempty(slice_idx)
hdr.dime.dim(4) = length(slice_idx);
end
if ~isempty(img_idx)
hdr.dime.dim(5) = length(img_idx);
end
if ~isempty(dim5_idx)
hdr.dime.dim(6) = length(dim5_idx);
end
if ~isempty(dim6_idx)
hdr.dime.dim(7) = length(dim6_idx);
end
if ~isempty(dim7_idx)
hdr.dime.dim(8) = length(dim7_idx);
end
return % read_image
|
github
|
changken1/IDH_Prediction-master
|
load_untouch_nii.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/load_untouch_nii.m
| 6,182 |
utf_8
|
93108a725d2e357d773c8aa0acf71328
|
% Load NIFTI or ANALYZE dataset, but not applying any appropriate affine
% geometric transform or voxel intensity scaling.
%
% Although according to NIFTI website, all those header information are
% supposed to be applied to the loaded NIFTI image, there are some
% situations that people do want to leave the original NIFTI header and
% data untouched. They will probably just use MATLAB to do certain image
% processing regardless of image orientation, and to save data back with
% the same NIfTI header.
%
% Since this program is only served for those situations, please use it
% together with "save_untouch_nii.m", and do not use "save_nii.m" or
% "view_nii.m" for the data that is loaded by "load_untouch_nii.m". For
% normal situation, you should use "load_nii.m" instead.
%
% Usage: nii = load_untouch_nii(filename, [img_idx], [dim5_idx], [dim6_idx], ...
% [dim7_idx], [old_RGB], [slice_idx])
%
% filename - NIFTI or ANALYZE file name.
%
% img_idx (optional) - a numerical array of image volume indices.
% Only the specified volumes will be loaded. All available image
% volumes will be loaded, if it is default or empty.
%
% The number of images scans can be obtained from get_nii_frame.m,
% or simply: hdr.dime.dim(5).
%
% dim5_idx (optional) - a numerical array of 5th dimension indices.
% Only the specified range will be loaded. All available range
% will be loaded, if it is default or empty.
%
% dim6_idx (optional) - a numerical array of 6th dimension indices.
% Only the specified range will be loaded. All available range
% will be loaded, if it is default or empty.
%
% dim7_idx (optional) - a numerical array of 7th dimension indices.
% Only the specified range will be loaded. All available range
% will be loaded, if it is default or empty.
%
% old_RGB (optional) - a scale number to tell difference of new RGB24
% from old RGB24. New RGB24 uses RGB triple sequentially for each
% voxel, like [R1 G1 B1 R2 G2 B2 ...]. Analyze 6.0 from AnalyzeDirect
% uses old RGB24, in a way like [R1 R2 ... G1 G2 ... B1 B2 ...] for
% each slices. If the image that you view is garbled, try to set
% old_RGB variable to 1 and try again, because it could be in
% old RGB24. It will be set to 0, if it is default or empty.
%
% slice_idx (optional) - a numerical array of image slice indices.
% Only the specified slices will be loaded. All available image
% slices will be loaded, if it is default or empty.
%
% Returned values:
%
% nii structure:
%
% hdr - struct with NIFTI header fields.
%
% filetype - Analyze format .hdr/.img (0);
% NIFTI .hdr/.img (1);
% NIFTI .nii (2)
%
% fileprefix - NIFTI filename without extension.
%
% machine - machine string variable.
%
% img - 3D (or 4D) matrix of NIFTI data.
%
% - Jimmy Shen ([email protected])
%
function nii = load_untouch_nii(filename, img_idx, dim5_idx, dim6_idx, dim7_idx, ...
old_RGB, slice_idx)
if ~exist('filename','var')
error('Usage: nii = load_untouch_nii(filename, [img_idx], [dim5_idx], [dim6_idx], [dim7_idx], [old_RGB], [slice_idx])');
end
if ~exist('img_idx','var') | isempty(img_idx)
img_idx = [];
end
if ~exist('dim5_idx','var') | isempty(dim5_idx)
dim5_idx = [];
end
if ~exist('dim6_idx','var') | isempty(dim6_idx)
dim6_idx = [];
end
if ~exist('dim7_idx','var') | isempty(dim7_idx)
dim7_idx = [];
end
if ~exist('old_RGB','var') | isempty(old_RGB)
old_RGB = 0;
end
if ~exist('slice_idx','var') | isempty(slice_idx)
slice_idx = [];
end
v = version;
% Check file extension. If .gz, unpack it into temp folder
%
if length(filename) > 2 & strcmp(filename(end-2:end), '.gz')
if ~strcmp(filename(end-6:end), '.img.gz') & ...
~strcmp(filename(end-6:end), '.hdr.gz') & ...
~strcmp(filename(end-6:end), '.nii.gz')
error('Please check filename.');
end
if str2num(v(1:3)) < 7.1 | ~usejava('jvm')
error('Please use MATLAB 7.1 (with java) and above, or run gunzip outside MATLAB.');
elseif strcmp(filename(end-6:end), '.img.gz')
filename1 = filename;
filename2 = filename;
filename2(end-6:end) = '';
filename2 = [filename2, '.hdr.gz'];
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename1 = gunzip(filename1, tmpDir);
filename2 = gunzip(filename2, tmpDir);
filename = char(filename1); % convert from cell to string
elseif strcmp(filename(end-6:end), '.hdr.gz')
filename1 = filename;
filename2 = filename;
filename2(end-6:end) = '';
filename2 = [filename2, '.img.gz'];
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename1 = gunzip(filename1, tmpDir);
filename2 = gunzip(filename2, tmpDir);
filename = char(filename1); % convert from cell to string
elseif strcmp(filename(end-6:end), '.nii.gz')
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename = gunzip(filename, tmpDir);
filename = char(filename); % convert from cell to string
end
end
% Read the dataset header
%
[nii.hdr,nii.filetype,nii.fileprefix,nii.machine] = load_nii_hdr(filename);
if nii.filetype == 0
nii.hdr = load_untouch0_nii_hdr(nii.fileprefix,nii.machine);
nii.ext = [];
else
nii.hdr = load_untouch_nii_hdr(nii.fileprefix,nii.machine,nii.filetype);
% Read the header extension
%
nii.ext = load_nii_ext(filename);
end
% Read the dataset body
%
[nii.img,nii.hdr] = load_untouch_nii_img(nii.hdr,nii.filetype,nii.fileprefix, ...
nii.machine,img_idx,dim5_idx,dim6_idx,dim7_idx,old_RGB,slice_idx);
% Perform some of sform/qform transform
%
% nii = xform_nii(nii, tolerance, preferredForm);
nii.untouch = 1;
% Clean up after gunzip
%
if exist('gzFileName', 'var')
% fix fileprefix so it doesn't point to temp location
%
nii.fileprefix = gzFileName(1:end-7);
rmdir(tmpDir,'s');
end
return % load_untouch_nii
|
github
|
changken1/IDH_Prediction-master
|
collapse_nii_scan.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/collapse_nii_scan.m
| 6,778 |
utf_8
|
64b1cb0f7cd9e095d3c11ca66453df69
|
% Collapse multiple single-scan NIFTI files into a multiple-scan NIFTI file
%
% Usage: collapse_nii_scan(scan_file_pattern, [collapsed_fileprefix], [scan_file_folder])
%
% Here, scan_file_pattern should look like: 'myscan_0*.img'
% If collapsed_fileprefix is omit, 'multi_scan' will be used
% If scan_file_folder is omit, current file folder will be used
%
% The order of volumes in the collapsed file will be the order of
% corresponding filenames for those selected scan files.
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function collapse_nii_scan(scan_pattern, fileprefix, scan_path)
if ~exist('fileprefix','var')
fileprefix = 'multi_scan';
else
[tmp fileprefix] = fileparts(fileprefix);
end
if ~exist('scan_path','var'), scan_path = pwd; end
pnfn = fullfile(scan_path, scan_pattern);
file_lst = dir(pnfn);
flist = {file_lst.name};
flist = flist(:);
filename = flist{1};
v = version;
% Check file extension. If .gz, unpack it into temp folder
%
if length(filename) > 2 & strcmp(filename(end-2:end), '.gz')
if ~strcmp(filename(end-6:end), '.img.gz') & ...
~strcmp(filename(end-6:end), '.hdr.gz') & ...
~strcmp(filename(end-6:end), '.nii.gz')
error('Please check filename.');
end
if str2num(v(1:3)) < 7.1 | ~usejava('jvm')
error('Please use MATLAB 7.1 (with java) and above, or run gunzip outside MATLAB.');
else
gzFile = 1;
end
else
if ~strcmp(filename(end-3:end), '.img') & ...
~strcmp(filename(end-3:end), '.hdr') & ...
~strcmp(filename(end-3:end), '.nii')
error('Please check filename.');
end
end
nii = load_untouch_nii(fullfile(scan_path,filename));
nii.hdr.dime.dim(5) = length(flist);
if nii.hdr.dime.dim(1) < 4
nii.hdr.dime.dim(1) = 4;
end
hdr = nii.hdr;
filetype = nii.filetype;
if isfield(nii,'ext') & ~isempty(nii.ext)
ext = nii.ext;
[ext, esize_total] = verify_nii_ext(ext);
else
ext = [];
end
switch double(hdr.dime.datatype),
case 1,
hdr.dime.bitpix = int16(1 ); precision = 'ubit1';
case 2,
hdr.dime.bitpix = int16(8 ); precision = 'uint8';
case 4,
hdr.dime.bitpix = int16(16); precision = 'int16';
case 8,
hdr.dime.bitpix = int16(32); precision = 'int32';
case 16,
hdr.dime.bitpix = int16(32); precision = 'float32';
case 32,
hdr.dime.bitpix = int16(64); precision = 'float32';
case 64,
hdr.dime.bitpix = int16(64); precision = 'float64';
case 128,
hdr.dime.bitpix = int16(24); precision = 'uint8';
case 256
hdr.dime.bitpix = int16(8 ); precision = 'int8';
case 512
hdr.dime.bitpix = int16(16); precision = 'uint16';
case 768
hdr.dime.bitpix = int16(32); precision = 'uint32';
case 1024
hdr.dime.bitpix = int16(64); precision = 'int64';
case 1280
hdr.dime.bitpix = int16(64); precision = 'uint64';
case 1792,
hdr.dime.bitpix = int16(128); precision = 'float64';
otherwise
error('This datatype is not supported');
end
if filetype == 2
fid = fopen(sprintf('%s.nii',fileprefix),'w');
if fid < 0,
msg = sprintf('Cannot open file %s.nii.',fileprefix);
error(msg);
end
hdr.dime.vox_offset = 352;
if ~isempty(ext)
hdr.dime.vox_offset = hdr.dime.vox_offset + esize_total;
end
hdr.hist.magic = 'n+1';
save_untouch_nii_hdr(hdr, fid);
if ~isempty(ext)
save_nii_ext(ext, fid);
end
elseif filetype == 1
fid = fopen(sprintf('%s.hdr',fileprefix),'w');
if fid < 0,
msg = sprintf('Cannot open file %s.hdr.',fileprefix);
error(msg);
end
hdr.dime.vox_offset = 0;
hdr.hist.magic = 'ni1';
save_untouch_nii_hdr(hdr, fid);
if ~isempty(ext)
save_nii_ext(ext, fid);
end
fclose(fid);
fid = fopen(sprintf('%s.img',fileprefix),'w');
else
fid = fopen(sprintf('%s.hdr',fileprefix),'w');
if fid < 0,
msg = sprintf('Cannot open file %s.hdr.',fileprefix);
error(msg);
end
save_untouch0_nii_hdr(hdr, fid);
fclose(fid);
fid = fopen(sprintf('%s.img',fileprefix),'w');
end
if filetype == 2 & isempty(ext)
skip_bytes = double(hdr.dime.vox_offset) - 348;
else
skip_bytes = 0;
end
if skip_bytes
fwrite(fid, zeros(1,skip_bytes), 'uint8');
end
glmax = -inf;
glmin = inf;
for i = 1:length(flist)
nii = load_untouch_nii(fullfile(scan_path,flist{i}));
if double(hdr.dime.datatype) == 128
% RGB planes are expected to be in the 4th dimension of nii.img
%
if(size(nii.img,4)~=3)
error(['The NII structure does not appear to have 3 RGB color planes in the 4th dimension']);
end
nii.img = permute(nii.img, [4 1 2 3 5 6 7 8]);
end
% For complex float32 or complex float64, voxel values
% include [real, imag]
%
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792
real_img = real(nii.img(:))';
nii.img = imag(nii.img(:))';
nii.img = [real_img; nii.img];
end
if nii.hdr.dime.glmax > glmax
glmax = nii.hdr.dime.glmax;
end
if nii.hdr.dime.glmin < glmin
glmin = nii.hdr.dime.glmin;
end
fwrite(fid, nii.img, precision);
end
hdr.dime.glmax = round(glmax);
hdr.dime.glmin = round(glmin);
if filetype == 2
fseek(fid, 140, 'bof');
fwrite(fid, hdr.dime.glmax, 'int32');
fwrite(fid, hdr.dime.glmin, 'int32');
elseif filetype == 1
fid2 = fopen(sprintf('%s.hdr',fileprefix),'w');
if fid2 < 0,
msg = sprintf('Cannot open file %s.hdr.',fileprefix);
error(msg);
end
save_untouch_nii_hdr(hdr, fid2);
if ~isempty(ext)
save_nii_ext(ext, fid2);
end
fclose(fid2);
else
fid2 = fopen(sprintf('%s.hdr',fileprefix),'w');
if fid2 < 0,
msg = sprintf('Cannot open file %s.hdr.',fileprefix);
error(msg);
end
save_untouch0_nii_hdr(hdr, fid2);
fclose(fid2);
end
fclose(fid);
% gzip output file if requested
%
if exist('gzFile', 'var')
if filetype == 1
gzip([fileprefix, '.img']);
delete([fileprefix, '.img']);
gzip([fileprefix, '.hdr']);
delete([fileprefix, '.hdr']);
elseif filetype == 2
gzip([fileprefix, '.nii']);
delete([fileprefix, '.nii']);
end;
end;
return; % collapse_nii_scan
|
github
|
changken1/IDH_Prediction-master
|
rri_orient_ui.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/rri_orient_ui.m
| 5,384 |
utf_8
|
e1196b81940d9f93fbdb43c33799e587
|
% Return orientation of the current image:
% orient is orientation 1x3 matrix, in that:
% Three elements represent: [x y z]
% Element value: 1 - Left to Right; 2 - Posterior to Anterior;
% 3 - Inferior to Superior; 4 - Right to Left;
% 5 - Anterior to Posterior; 6 - Superior to Inferior;
% e.g.:
% Standard RAS Orientation: [1 2 3]
% Standard RHOS Orientation: [2 4 3]
% Jimmy Shen ([email protected]), 26-APR-04
%
function orient = rri_orient_ui(varargin)
if nargin == 0
init;
orient_ui_fig = gcf;
uiwait; % wait for user finish
orient = getappdata(gcf, 'orient');
if isempty(orient)
orient = [1 2 3];
end
if ishandle(orient_ui_fig)
close(gcf);
end
return;
end
action = varargin{1};
if strcmp(action, 'done')
click_done;
elseif strcmp(action, 'cancel')
uiresume;
end
return; % rri_orient_ui
%----------------------------------------------------------------------
function init
save_setting_status = 'on';
rri_orient_pos = [];
try
load('pls_profile');
catch
end
try
load('rri_pos_profile');
catch
end
if ~isempty(rri_orient_pos) & strcmp(save_setting_status,'on')
pos = rri_orient_pos;
else
w = 0.35;
h = 0.4;
x = (1-w)/2;
y = (1-h)/2;
pos = [x y w h];
end
handles.figure = figure('Color',[0.8 0.8 0.8], ...
'Units','normal', ...
'Name', 'Convert to standard RAS orientation', ...
'NumberTitle','off', ...
'MenuBar','none', ...
'Position',pos, ...
'WindowStyle', 'normal', ...
'ToolBar','none');
h0 = handles.figure;
Font.FontUnits = 'point';
Font.FontSize = 12;
margin = .1;
line_num = 6;
line_ht = (1 - margin*2) / line_num;
x = margin;
y = 1 - margin - line_ht;
w = 1 - margin * 2;
h = line_ht * .7;
pos = [x y w h];
handles.Ttit = uicontrol('parent', h0, ...
'style','text', ...
'unit', 'normal', ...
Font, ...
'Position',pos, ...
'HorizontalAlignment','left',...
'background', [0.8 0.8 0.8], ...
'string', 'Please input orientation of the current image:');
y = y - line_ht;
w = .2;
pos = [x y w h];
handles.Tx_orient = uicontrol('parent', h0, ...
'style','text', ...
'unit', 'normal', ...
Font, ...
'Position',pos, ...
'HorizontalAlignment','left',...
'background', [0.8 0.8 0.8], ...
'string', 'X Axes:');
y = y - line_ht;
pos = [x y w h];
handles.Ty_orient = uicontrol('parent', h0, ...
'style','text', ...
'unit', 'normal', ...
Font, ...
'Position',pos, ...
'HorizontalAlignment','left',...
'background', [0.8 0.8 0.8], ...
'string', 'Y Axes:');
y = y - line_ht;
pos = [x y w h];
handles.Tz_orient = uicontrol('parent', h0, ...
'style','text', ...
'unit', 'normal', ...
Font, ...
'Position',pos, ...
'HorizontalAlignment','left',...
'background', [0.8 0.8 0.8], ...
'string', 'Z Axes:');
choice = { 'From Left to Right', 'From Posterior to Anterior', ...
'From Inferior to Superior', 'From Right to Left', ...
'From Anterior to Posterior', 'From Superior to Inferior' };
y = 1 - margin - line_ht;
y = y - line_ht;
w = 1 - margin - x - w;
x = 1 - margin - w;
pos = [x y w h];
handles.x_orient = uicontrol('parent', h0, ...
'style','popupmenu', ...
'unit', 'normal', ...
Font, ...
'Position',pos, ...
'HorizontalAlignment','left',...
'string', choice, ...
'value', 1, ...
'background', [1 1 1]);
y = y - line_ht;
pos = [x y w h];
handles.y_orient = uicontrol('parent', h0, ...
'style','popupmenu', ...
'unit', 'normal', ...
Font, ...
'Position',pos, ...
'HorizontalAlignment','left',...
'string', choice, ...
'value', 2, ...
'background', [1 1 1]);
y = y - line_ht;
pos = [x y w h];
handles.z_orient = uicontrol('parent', h0, ...
'style','popupmenu', ...
'unit', 'normal', ...
Font, ...
'Position',pos, ...
'HorizontalAlignment','left',...
'string', choice, ...
'value', 3, ...
'background', [1 1 1]);
x = margin;
y = y - line_ht * 1.5;
w = .3;
pos = [x y w h];
handles.done = uicontrol('parent', h0, ...
'unit', 'normal', ...
Font, ...
'Position',pos, ...
'HorizontalAlignment','center',...
'callback', 'rri_orient_ui(''done'');', ...
'string', 'Done');
x = 1 - margin - w;
pos = [x y w h];
handles.cancel = uicontrol('parent', h0, ...
'unit', 'normal', ...
Font, ...
'Position',pos, ...
'HorizontalAlignment','center',...
'callback', 'rri_orient_ui(''cancel'');', ...
'string', 'Cancel');
setappdata(h0, 'handles', handles);
setappdata(h0, 'orient', [1 2 3]);
return; % init
%----------------------------------------------------------------------
function click_done
handles = getappdata(gcf, 'handles');
x_orient = get(handles.x_orient, 'value');
y_orient = get(handles.y_orient, 'value');
z_orient = get(handles.z_orient, 'value');
orient = [x_orient y_orient z_orient];
test_orient = [orient, orient + 3];
test_orient = mod(test_orient, 3);
if length(unique(test_orient)) ~= 3
msgbox('Please don''t choose same or opposite direction','Error','modal');
return;
end
setappdata(gcf, 'orient', [x_orient y_orient z_orient]);
uiresume;
return; % click_done
|
github
|
changken1/IDH_Prediction-master
|
load_untouch0_nii_hdr.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/load_untouch0_nii_hdr.m
| 8,093 |
utf_8
|
3de9ff6a1da47b56ae680e7660eaa041
|
% internal function
% - Jimmy Shen ([email protected])
function hdr = load_nii_hdr(fileprefix, machine)
fn = sprintf('%s.hdr',fileprefix);
fid = fopen(fn,'r',machine);
if fid < 0,
msg = sprintf('Cannot open file %s.',fn);
error(msg);
else
fseek(fid,0,'bof');
hdr = read_header(fid);
fclose(fid);
end
return % load_nii_hdr
%---------------------------------------------------------------------
function [ dsr ] = read_header(fid)
% Original header structures
% struct dsr
% {
% struct header_key hk; /* 0 + 40 */
% struct image_dimension dime; /* 40 + 108 */
% struct data_history hist; /* 148 + 200 */
% }; /* total= 348 bytes*/
dsr.hk = header_key(fid);
dsr.dime = image_dimension(fid);
dsr.hist = data_history(fid);
return % read_header
%---------------------------------------------------------------------
function [ hk ] = header_key(fid)
fseek(fid,0,'bof');
% Original header structures
% struct header_key /* header key */
% { /* off + size */
% int sizeof_hdr /* 0 + 4 */
% char data_type[10]; /* 4 + 10 */
% char db_name[18]; /* 14 + 18 */
% int extents; /* 32 + 4 */
% short int session_error; /* 36 + 2 */
% char regular; /* 38 + 1 */
% char hkey_un0; /* 39 + 1 */
% }; /* total=40 bytes */
%
% int sizeof_header Should be 348.
% char regular Must be 'r' to indicate that all images and
% volumes are the same size.
v6 = version;
if str2num(v6(1))<6
directchar = '*char';
else
directchar = 'uchar=>char';
end
hk.sizeof_hdr = fread(fid, 1,'int32')'; % should be 348!
hk.data_type = deblank(fread(fid,10,directchar)');
hk.db_name = deblank(fread(fid,18,directchar)');
hk.extents = fread(fid, 1,'int32')';
hk.session_error = fread(fid, 1,'int16')';
hk.regular = fread(fid, 1,directchar)';
hk.hkey_un0 = fread(fid, 1,directchar)';
return % header_key
%---------------------------------------------------------------------
function [ dime ] = image_dimension(fid)
%struct image_dimension
% { /* off + size */
% short int dim[8]; /* 0 + 16 */
% /*
% dim[0] Number of dimensions in database; usually 4.
% dim[1] Image X dimension; number of *pixels* in an image row.
% dim[2] Image Y dimension; number of *pixel rows* in slice.
% dim[3] Volume Z dimension; number of *slices* in a volume.
% dim[4] Time points; number of volumes in database
% */
% char vox_units[4]; /* 16 + 4 */
% char cal_units[8]; /* 20 + 8 */
% short int unused1; /* 28 + 2 */
% short int datatype; /* 30 + 2 */
% short int bitpix; /* 32 + 2 */
% short int dim_un0; /* 34 + 2 */
% float pixdim[8]; /* 36 + 32 */
% /*
% pixdim[] specifies the voxel dimensions:
% pixdim[1] - voxel width, mm
% pixdim[2] - voxel height, mm
% pixdim[3] - slice thickness, mm
% pixdim[4] - volume timing, in msec
% ..etc
% */
% float vox_offset; /* 68 + 4 */
% float roi_scale; /* 72 + 4 */
% float funused1; /* 76 + 4 */
% float funused2; /* 80 + 4 */
% float cal_max; /* 84 + 4 */
% float cal_min; /* 88 + 4 */
% int compressed; /* 92 + 4 */
% int verified; /* 96 + 4 */
% int glmax; /* 100 + 4 */
% int glmin; /* 104 + 4 */
% }; /* total=108 bytes */
v6 = version;
if str2num(v6(1))<6
directchar = '*char';
else
directchar = 'uchar=>char';
end
dime.dim = fread(fid,8,'int16')';
dime.vox_units = deblank(fread(fid,4,directchar)');
dime.cal_units = deblank(fread(fid,8,directchar)');
dime.unused1 = fread(fid,1,'int16')';
dime.datatype = fread(fid,1,'int16')';
dime.bitpix = fread(fid,1,'int16')';
dime.dim_un0 = fread(fid,1,'int16')';
dime.pixdim = fread(fid,8,'float32')';
dime.vox_offset = fread(fid,1,'float32')';
dime.roi_scale = fread(fid,1,'float32')';
dime.funused1 = fread(fid,1,'float32')';
dime.funused2 = fread(fid,1,'float32')';
dime.cal_max = fread(fid,1,'float32')';
dime.cal_min = fread(fid,1,'float32')';
dime.compressed = fread(fid,1,'int32')';
dime.verified = fread(fid,1,'int32')';
dime.glmax = fread(fid,1,'int32')';
dime.glmin = fread(fid,1,'int32')';
return % image_dimension
%---------------------------------------------------------------------
function [ hist ] = data_history(fid)
%struct data_history
% { /* off + size */
% char descrip[80]; /* 0 + 80 */
% char aux_file[24]; /* 80 + 24 */
% char orient; /* 104 + 1 */
% char originator[10]; /* 105 + 10 */
% char generated[10]; /* 115 + 10 */
% char scannum[10]; /* 125 + 10 */
% char patient_id[10]; /* 135 + 10 */
% char exp_date[10]; /* 145 + 10 */
% char exp_time[10]; /* 155 + 10 */
% char hist_un0[3]; /* 165 + 3 */
% int views /* 168 + 4 */
% int vols_added; /* 172 + 4 */
% int start_field; /* 176 + 4 */
% int field_skip; /* 180 + 4 */
% int omax; /* 184 + 4 */
% int omin; /* 188 + 4 */
% int smax; /* 192 + 4 */
% int smin; /* 196 + 4 */
% }; /* total=200 bytes */
v6 = version;
if str2num(v6(1))<6
directchar = '*char';
else
directchar = 'uchar=>char';
end
hist.descrip = deblank(fread(fid,80,directchar)');
hist.aux_file = deblank(fread(fid,24,directchar)');
hist.orient = fread(fid, 1,'char')';
hist.originator = fread(fid, 5,'int16')';
hist.generated = deblank(fread(fid,10,directchar)');
hist.scannum = deblank(fread(fid,10,directchar)');
hist.patient_id = deblank(fread(fid,10,directchar)');
hist.exp_date = deblank(fread(fid,10,directchar)');
hist.exp_time = deblank(fread(fid,10,directchar)');
hist.hist_un0 = deblank(fread(fid, 3,directchar)');
hist.views = fread(fid, 1,'int32')';
hist.vols_added = fread(fid, 1,'int32')';
hist.start_field = fread(fid, 1,'int32')';
hist.field_skip = fread(fid, 1,'int32')';
hist.omax = fread(fid, 1,'int32')';
hist.omin = fread(fid, 1,'int32')';
hist.smax = fread(fid, 1,'int32')';
hist.smin = fread(fid, 1,'int32')';
return % data_history
|
github
|
changken1/IDH_Prediction-master
|
load_nii.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/load_nii.m
| 6,808 |
utf_8
|
d098a5dbea3cd4ad76cea624ffbef9db
|
% Load NIFTI or ANALYZE dataset. Support both *.nii and *.hdr/*.img
% file extension. If file extension is not provided, *.hdr/*.img will
% be used as default.
%
% A subset of NIFTI transform is included. For non-orthogonal rotation,
% shearing etc., please use 'reslice_nii.m' to reslice the NIFTI file.
% It will not cause negative effect, as long as you remember not to do
% slice time correction after reslicing the NIFTI file. Output variable
% nii will be in RAS orientation, i.e. X axis from Left to Right,
% Y axis from Posterior to Anterior, and Z axis from Inferior to
% Superior.
%
% Usage: nii = load_nii(filename, [img_idx], [dim5_idx], [dim6_idx], ...
% [dim7_idx], [old_RGB], [tolerance], [preferredForm])
%
% filename - NIFTI or ANALYZE file name.
%
% img_idx (optional) - a numerical array of 4th dimension indices,
% which is the indices of image scan volume. The number of images
% scan volumes can be obtained from get_nii_frame.m, or simply
% hdr.dime.dim(5). Only the specified volumes will be loaded.
% All available image volumes will be loaded, if it is default or
% empty.
%
% dim5_idx (optional) - a numerical array of 5th dimension indices.
% Only the specified range will be loaded. All available range
% will be loaded, if it is default or empty.
%
% dim6_idx (optional) - a numerical array of 6th dimension indices.
% Only the specified range will be loaded. All available range
% will be loaded, if it is default or empty.
%
% dim7_idx (optional) - a numerical array of 7th dimension indices.
% Only the specified range will be loaded. All available range
% will be loaded, if it is default or empty.
%
% old_RGB (optional) - a scale number to tell difference of new RGB24
% from old RGB24. New RGB24 uses RGB triple sequentially for each
% voxel, like [R1 G1 B1 R2 G2 B2 ...]. Analyze 6.0 from AnalyzeDirect
% uses old RGB24, in a way like [R1 R2 ... G1 G2 ... B1 B2 ...] for
% each slices. If the image that you view is garbled, try to set
% old_RGB variable to 1 and try again, because it could be in
% old RGB24. It will be set to 0, if it is default or empty.
%
% tolerance (optional) - distortion allowed in the loaded image for any
% non-orthogonal rotation or shearing of NIfTI affine matrix. If
% you set 'tolerance' to 0, it means that you do not allow any
% distortion. If you set 'tolerance' to 1, it means that you do
% not care any distortion. The image will fail to be loaded if it
% can not be tolerated. The tolerance will be set to 0.1 (10%), if
% it is default or empty.
%
% preferredForm (optional) - selects which transformation from voxels
% to RAS coordinates; values are s,q,S,Q. Lower case s,q indicate
% "prefer sform or qform, but use others if preferred not present".
% Upper case indicate the program is forced to use the specificied
% tranform or fail loading. 'preferredForm' will be 's', if it is
% default or empty. - Jeff Gunter
%
% Returned values:
%
% nii structure:
%
% hdr - struct with NIFTI header fields.
%
% filetype - Analyze format .hdr/.img (0);
% NIFTI .hdr/.img (1);
% NIFTI .nii (2)
%
% fileprefix - NIFTI filename without extension.
%
% machine - machine string variable.
%
% img - 3D (or 4D) matrix of NIFTI data.
%
% original - the original header before any affine transform.
%
% Part of this file is copied and modified from:
% http://www.mathworks.com/matlabcentral/fileexchange/1878-mri-analyze-tools
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function nii = load_nii(filename, img_idx, dim5_idx, dim6_idx, dim7_idx, ...
old_RGB, tolerance, preferredForm)
if ~exist('filename','var')
error('Usage: nii = load_nii(filename, [img_idx], [dim5_idx], [dim6_idx], [dim7_idx], [old_RGB], [tolerance], [preferredForm])');
end
if ~exist('img_idx','var') | isempty(img_idx)
img_idx = [];
end
if ~exist('dim5_idx','var') | isempty(dim5_idx)
dim5_idx = [];
end
if ~exist('dim6_idx','var') | isempty(dim6_idx)
dim6_idx = [];
end
if ~exist('dim7_idx','var') | isempty(dim7_idx)
dim7_idx = [];
end
if ~exist('old_RGB','var') | isempty(old_RGB)
old_RGB = 0;
end
if ~exist('tolerance','var') | isempty(tolerance)
tolerance = 0.1; % 10 percent
end
if ~exist('preferredForm','var') | isempty(preferredForm)
preferredForm= 's'; % Jeff
end
v = version;
% Check file extension. If .gz, unpack it into temp folder
%
if length(filename) > 2 & strcmp(filename(end-2:end), '.gz')
if ~strcmp(filename(end-6:end), '.img.gz') & ...
~strcmp(filename(end-6:end), '.hdr.gz') & ...
~strcmp(filename(end-6:end), '.nii.gz')
error('Please check filename.');
end
if str2num(v(1:3)) < 7.1 | ~usejava('jvm')
error('Please use MATLAB 7.1 (with java) and above, or run gunzip outside MATLAB.');
elseif strcmp(filename(end-6:end), '.img.gz')
filename1 = filename;
filename2 = filename;
filename2(end-6:end) = '';
filename2 = [filename2, '.hdr.gz'];
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename1 = gunzip(filename1, tmpDir);
filename2 = gunzip(filename2, tmpDir);
filename = char(filename1); % convert from cell to string
elseif strcmp(filename(end-6:end), '.hdr.gz')
filename1 = filename;
filename2 = filename;
filename2(end-6:end) = '';
filename2 = [filename2, '.img.gz'];
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename1 = gunzip(filename1, tmpDir);
filename2 = gunzip(filename2, tmpDir);
filename = char(filename1); % convert from cell to string
elseif strcmp(filename(end-6:end), '.nii.gz')
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename = gunzip(filename, tmpDir);
filename = char(filename); % convert from cell to string
end
end
% Read the dataset header
%
[nii.hdr,nii.filetype,nii.fileprefix,nii.machine] = load_nii_hdr(filename);
% Read the header extension
%
% nii.ext = load_nii_ext(filename);
% Read the dataset body
%
[nii.img,nii.hdr] = load_nii_img(nii.hdr,nii.filetype,nii.fileprefix, ...
nii.machine,img_idx,dim5_idx,dim6_idx,dim7_idx,old_RGB);
% Perform some of sform/qform transform
%
nii = xform_nii(nii, tolerance, preferredForm);
% Clean up after gunzip
%
if exist('gzFileName', 'var')
% fix fileprefix so it doesn't point to temp location
%
nii.fileprefix = gzFileName(1:end-7);
rmdir(tmpDir,'s');
end
return % load_nii
|
github
|
changken1/IDH_Prediction-master
|
unxform_nii.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/unxform_nii.m
| 1,181 |
utf_8
|
a77d113be34b09d588b2eb326a3c65c8
|
% Undo the flipping and rotations performed by xform_nii; spit back only
% the raw img data block. Initial cut will only deal with 3D volumes
% strongly assume we have called xform_nii to write down the steps used
% in xform_nii.
%
% Usage: a = load_nii('original_name');
% manipulate a.img to make array b;
%
% if you use unxform_nii to un-tranform the image (img) data
% block, then nii.original.hdr is the corresponding header.
%
% nii.original.img = unxform_nii(a, b);
% save_nii(nii.original,'newname');
%
% Where, 'newname' is created with data in the same space as the
% original_name data
%
% - Jeff Gunter, 26-JUN-06
%
function outblock = unxform_nii(nii, inblock)
if isempty(nii.hdr.hist.rot_orient)
outblock=inblock;
else
[dummy unrotate_orient] = sort(nii.hdr.hist.rot_orient);
outblock = permute(inblock, unrotate_orient);
end
if ~isempty(nii.hdr.hist.flip_orient)
flip_orient = nii.hdr.hist.flip_orient(unrotate_orient);
for i = 1:3
if flip_orient(i)
outblock = flipdim(outblock, i);
end
end
end;
return;
|
github
|
changken1/IDH_Prediction-master
|
load_untouch_nii_hdr.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/load_untouch_nii_hdr.m
| 8,522 |
utf_8
|
2d4bc8c8ffb83b37daf1e8dd87c108e6
|
% internal function
% - Jimmy Shen ([email protected])
function hdr = load_nii_hdr(fileprefix, machine, filetype)
if filetype == 2
fn = sprintf('%s.nii',fileprefix);
if ~exist(fn)
msg = sprintf('Cannot find file "%s.nii".', fileprefix);
error(msg);
end
else
fn = sprintf('%s.hdr',fileprefix);
if ~exist(fn)
msg = sprintf('Cannot find file "%s.hdr".', fileprefix);
error(msg);
end
end
fid = fopen(fn,'r',machine);
if fid < 0,
msg = sprintf('Cannot open file %s.',fn);
error(msg);
else
fseek(fid,0,'bof');
hdr = read_header(fid);
fclose(fid);
end
return % load_nii_hdr
%---------------------------------------------------------------------
function [ dsr ] = read_header(fid)
% Original header structures
% struct dsr
% {
% struct header_key hk; /* 0 + 40 */
% struct image_dimension dime; /* 40 + 108 */
% struct data_history hist; /* 148 + 200 */
% }; /* total= 348 bytes*/
dsr.hk = header_key(fid);
dsr.dime = image_dimension(fid);
dsr.hist = data_history(fid);
% For Analyze data format
%
if ~strcmp(dsr.hist.magic, 'n+1') & ~strcmp(dsr.hist.magic, 'ni1')
dsr.hist.qform_code = 0;
dsr.hist.sform_code = 0;
end
return % read_header
%---------------------------------------------------------------------
function [ hk ] = header_key(fid)
fseek(fid,0,'bof');
% Original header structures
% struct header_key /* header key */
% { /* off + size */
% int sizeof_hdr /* 0 + 4 */
% char data_type[10]; /* 4 + 10 */
% char db_name[18]; /* 14 + 18 */
% int extents; /* 32 + 4 */
% short int session_error; /* 36 + 2 */
% char regular; /* 38 + 1 */
% char dim_info; % char hkey_un0; /* 39 + 1 */
% }; /* total=40 bytes */
%
% int sizeof_header Should be 348.
% char regular Must be 'r' to indicate that all images and
% volumes are the same size.
v6 = version;
if str2num(v6(1))<6
directchar = '*char';
else
directchar = 'uchar=>char';
end
hk.sizeof_hdr = fread(fid, 1,'int32')'; % should be 348!
hk.data_type = deblank(fread(fid,10,directchar)');
hk.db_name = deblank(fread(fid,18,directchar)');
hk.extents = fread(fid, 1,'int32')';
hk.session_error = fread(fid, 1,'int16')';
hk.regular = fread(fid, 1,directchar)';
hk.dim_info = fread(fid, 1,'uchar')';
return % header_key
%---------------------------------------------------------------------
function [ dime ] = image_dimension(fid)
% Original header structures
% struct image_dimension
% { /* off + size */
% short int dim[8]; /* 0 + 16 */
% /*
% dim[0] Number of dimensions in database; usually 4.
% dim[1] Image X dimension; number of *pixels* in an image row.
% dim[2] Image Y dimension; number of *pixel rows* in slice.
% dim[3] Volume Z dimension; number of *slices* in a volume.
% dim[4] Time points; number of volumes in database
% */
% float intent_p1; % char vox_units[4]; /* 16 + 4 */
% float intent_p2; % char cal_units[8]; /* 20 + 4 */
% float intent_p3; % char cal_units[8]; /* 24 + 4 */
% short int intent_code; % short int unused1; /* 28 + 2 */
% short int datatype; /* 30 + 2 */
% short int bitpix; /* 32 + 2 */
% short int slice_start; % short int dim_un0; /* 34 + 2 */
% float pixdim[8]; /* 36 + 32 */
% /*
% pixdim[] specifies the voxel dimensions:
% pixdim[1] - voxel width, mm
% pixdim[2] - voxel height, mm
% pixdim[3] - slice thickness, mm
% pixdim[4] - volume timing, in msec
% ..etc
% */
% float vox_offset; /* 68 + 4 */
% float scl_slope; % float roi_scale; /* 72 + 4 */
% float scl_inter; % float funused1; /* 76 + 4 */
% short slice_end; % float funused2; /* 80 + 2 */
% char slice_code; % float funused2; /* 82 + 1 */
% char xyzt_units; % float funused2; /* 83 + 1 */
% float cal_max; /* 84 + 4 */
% float cal_min; /* 88 + 4 */
% float slice_duration; % int compressed; /* 92 + 4 */
% float toffset; % int verified; /* 96 + 4 */
% int glmax; /* 100 + 4 */
% int glmin; /* 104 + 4 */
% }; /* total=108 bytes */
dime.dim = fread(fid,8,'int16')';
dime.intent_p1 = fread(fid,1,'float32')';
dime.intent_p2 = fread(fid,1,'float32')';
dime.intent_p3 = fread(fid,1,'float32')';
dime.intent_code = fread(fid,1,'int16')';
dime.datatype = fread(fid,1,'int16')';
dime.bitpix = fread(fid,1,'int16')';
dime.slice_start = fread(fid,1,'int16')';
dime.pixdim = fread(fid,8,'float32')';
dime.vox_offset = fread(fid,1,'float32')';
dime.scl_slope = fread(fid,1,'float32')';
dime.scl_inter = fread(fid,1,'float32')';
dime.slice_end = fread(fid,1,'int16')';
dime.slice_code = fread(fid,1,'uchar')';
dime.xyzt_units = fread(fid,1,'uchar')';
dime.cal_max = fread(fid,1,'float32')';
dime.cal_min = fread(fid,1,'float32')';
dime.slice_duration = fread(fid,1,'float32')';
dime.toffset = fread(fid,1,'float32')';
dime.glmax = fread(fid,1,'int32')';
dime.glmin = fread(fid,1,'int32')';
return % image_dimension
%---------------------------------------------------------------------
function [ hist ] = data_history(fid)
% Original header structures
% struct data_history
% { /* off + size */
% char descrip[80]; /* 0 + 80 */
% char aux_file[24]; /* 80 + 24 */
% short int qform_code; /* 104 + 2 */
% short int sform_code; /* 106 + 2 */
% float quatern_b; /* 108 + 4 */
% float quatern_c; /* 112 + 4 */
% float quatern_d; /* 116 + 4 */
% float qoffset_x; /* 120 + 4 */
% float qoffset_y; /* 124 + 4 */
% float qoffset_z; /* 128 + 4 */
% float srow_x[4]; /* 132 + 16 */
% float srow_y[4]; /* 148 + 16 */
% float srow_z[4]; /* 164 + 16 */
% char intent_name[16]; /* 180 + 16 */
% char magic[4]; % int smin; /* 196 + 4 */
% }; /* total=200 bytes */
v6 = version;
if str2num(v6(1))<6
directchar = '*char';
else
directchar = 'uchar=>char';
end
hist.descrip = deblank(fread(fid,80,directchar)');
hist.aux_file = deblank(fread(fid,24,directchar)');
hist.qform_code = fread(fid,1,'int16')';
hist.sform_code = fread(fid,1,'int16')';
hist.quatern_b = fread(fid,1,'float32')';
hist.quatern_c = fread(fid,1,'float32')';
hist.quatern_d = fread(fid,1,'float32')';
hist.qoffset_x = fread(fid,1,'float32')';
hist.qoffset_y = fread(fid,1,'float32')';
hist.qoffset_z = fread(fid,1,'float32')';
hist.srow_x = fread(fid,4,'float32')';
hist.srow_y = fread(fid,4,'float32')';
hist.srow_z = fread(fid,4,'float32')';
hist.intent_name = deblank(fread(fid,16,directchar)');
hist.magic = deblank(fread(fid,4,directchar)');
return % data_history
|
github
|
changken1/IDH_Prediction-master
|
save_nii_ext.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/save_nii_ext.m
| 977 |
utf_8
|
b60a98ab7537a883dc3ffef3175f19ae
|
% Save NIFTI header extension.
%
% Usage: save_nii_ext(ext, fid)
%
% ext - struct with NIFTI header extension fields.
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function save_nii_ext(ext, fid)
if ~exist('ext','var') | ~exist('fid','var')
error('Usage: save_nii_ext(ext, fid)');
end
if ~isfield(ext,'extension') | ~isfield(ext,'section') | ~isfield(ext,'num_ext')
error('Wrong header extension');
end
write_ext(ext, fid);
return; % save_nii_ext
%---------------------------------------------------------------------
function write_ext(ext, fid)
fwrite(fid, ext.extension, 'uchar');
for i=1:ext.num_ext
fwrite(fid, ext.section(i).esize, 'int32');
fwrite(fid, ext.section(i).ecode, 'int32');
fwrite(fid, ext.section(i).edata, 'uchar');
end
return; % write_ext
|
github
|
changken1/IDH_Prediction-master
|
view_nii_menu.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/view_nii_menu.m
| 14,415 |
utf_8
|
32dd591fa1070721f0255f47f6e02510
|
% Imbed Zoom, Interp, and Info menu to view_nii window.
%
% Usage: view_nii_menu(fig);
%
% - Jimmy Shen ([email protected])
%
%--------------------------------------------------------------------
function menu_hdl = view_nii_menu(fig, varargin)
if isnumeric(fig)
menu_hdl = init(fig);
return;
end
menu_hdl = [];
switch fig
case 'interp'
if nargin > 1
fig = varargin{1};
else
fig = gcbf;
end
nii_menu = getappdata(fig, 'nii_menu');
interp_on_state = get(nii_menu.Minterp,'Userdata');
if (interp_on_state == 1)
opt.useinterp = 1;
view_nii(fig,opt);
set(nii_menu.Minterp,'Userdata',0,'Label','Interp off');
reset_zoom(fig);
else
opt.useinterp = 0;
view_nii(fig,opt);
set(nii_menu.Minterp,'Userdata',1,'Label','Interp on');
reset_zoom(fig);
end
case 'reset_zoom'
if nargin > 1
fig = varargin{1};
else
fig = gcbf;
end
reset_zoom(fig);
case 'orient'
orient;
case 'editvox'
editvox;
case 'img_info'
img_info;
case 'img_hist'
img_hist;
case 'save_disp'
save_disp;
end
return % view_nii_menu
%--------------------------------------------------------------------
function menu_hdl = init(fig)
% search for edit, view menu
%
nii_menu.Mfile = [];
nii_menu.Medit = [];
nii_menu.Mview = [];
menuitems = findobj(fig, 'type', 'uimenu');
for i=1:length(menuitems)
filelabel = get(menuitems(i),'label');
if strcmpi(strrep(filelabel, '&', ''), 'file')
nii_menu.Mfile = menuitems(i);
end
editlabel = get(menuitems(i),'label');
if strcmpi(strrep(editlabel, '&', ''), 'edit')
nii_menu.Medit = menuitems(i);
end
viewlabel = get(menuitems(i),'label');
if strcmpi(strrep(viewlabel, '&', ''), 'view')
nii_menu.Mview = menuitems(i);
end
end
set(fig, 'menubar', 'none');
if isempty(nii_menu.Mfile)
nii_menu.Mfile = uimenu('Parent',fig, ...
'Label','File');
nii_menu.Mfile_save = uimenu('Parent',nii_menu.Mfile, ...
'Label','Save displayed image as ...', ...
'Callback','view_nii_menu(''save_disp'');');
else
nii_menu.Mfile_save = uimenu('Parent',nii_menu.Mfile, ...
'Label','Save displayed image as ...', ...
'separator','on', ...
'Callback','view_nii_menu(''save_disp'');');
end
if isempty(nii_menu.Medit)
nii_menu.Medit = uimenu('Parent',fig, ...
'Label','Edit');
nii_menu.Medit_orient = uimenu('Parent',nii_menu.Medit, ...
'Label','Convert to RAS orientation', ...
'Callback','view_nii_menu(''orient'');');
nii_menu.Medit_editvox = uimenu('Parent',nii_menu.Medit, ...
'Label','Edit voxel value at crosshair', ...
'Callback','view_nii_menu(''editvox'');');
else
nii_menu.Medit_orient = uimenu('Parent',nii_menu.Medit, ...
'Label','Convert to RAS orientation', ...
'separator','on', ...
'Callback','view_nii_menu(''orient'');');
nii_menu.Medit_editvox = uimenu('Parent',nii_menu.Medit, ...
'Label','Edit voxel value at crosshair', ...
'Callback','view_nii_menu(''editvox'');');
end
if isempty(nii_menu.Mview)
nii_menu.Mview = uimenu('Parent',fig, ...
'Label','View');
nii_menu.Mview_info = uimenu('Parent',nii_menu.Mview, ...
'Label','Image Information', ...
'Callback','view_nii_menu(''img_info'');');
nii_menu.Mview_info = uimenu('Parent',nii_menu.Mview, ...
'Label','Volume Histogram', ...
'Callback','view_nii_menu(''img_hist'');');
else
nii_menu.Mview_info = uimenu('Parent',nii_menu.Mview, ...
'Label','Image Information', ...
'separator','on', ...
'Callback','view_nii_menu(''img_info'');');
nii_menu.Mview_info = uimenu('Parent',nii_menu.Mview, ...
'Label','Volume Histogram', ...
'Callback','view_nii_menu(''img_hist'');');
end
nii_menu.Mzoom = rri_zoom_menu(fig);
nii_menu.Minterp = uimenu('Parent',fig, ...
'Label','Interp on', ...
'Userdata', 1, ...
'Callback','view_nii_menu(''interp'');');
setappdata(fig,'nii_menu',nii_menu);
menu_hdl = nii_menu.Minterp;
return % init
%----------------------------------------------------------------
function reset_zoom(fig)
old_handle_vis = get(fig, 'HandleVisibility');
set(fig, 'HandleVisibility', 'on');
nii_view = getappdata(fig, 'nii_view');
nii_menu = getappdata(fig, 'nii_menu');
set(nii_menu.Mzoom,'Userdata',1,'Label','Zoom on');
set(fig,'pointer','arrow');
zoom off;
axes(nii_view.handles.axial_axes);
setappdata(get(gca,'zlabel'), 'ZOOMAxesData', ...
[get(gca, 'xlim') get(gca, 'ylim')])
% zoom reset;
% zoom getlimits;
zoom out;
axes(nii_view.handles.coronal_axes);
setappdata(get(gca,'zlabel'), 'ZOOMAxesData', ...
[get(gca, 'xlim') get(gca, 'ylim')])
% zoom reset;
% zoom getlimits;
zoom out;
axes(nii_view.handles.sagittal_axes);
setappdata(get(gca,'zlabel'), 'ZOOMAxesData', ...
[get(gca, 'xlim') get(gca, 'ylim')])
% zoom reset;
% zoom getlimits;
zoom out;
set(fig, 'HandleVisibility', old_handle_vis);
return; % reset_zoom
%----------------------------------------------------------------
function img_info
nii_view = getappdata(gcbf, 'nii_view');
hdr = nii_view.nii.hdr;
max_value = num2str(double(max(nii_view.nii.img(:))));
min_value = num2str(double(min(nii_view.nii.img(:))));
dim = sprintf('%d %d %d', double(hdr.dime.dim(2:4)));
vox = sprintf('%.3f %.3f %.3f', double(hdr.dime.pixdim(2:4)));
if double(hdr.dime.datatype) == 1
type = '1-bit binary';
elseif double(hdr.dime.datatype) == 2
type = '8-bit unsigned integer';
elseif double(hdr.dime.datatype) == 4
type = '16-bit signed integer';
elseif double(hdr.dime.datatype) == 8
type = '32-bit signed integer';
elseif double(hdr.dime.datatype) == 16
type = '32-bit single float';
elseif double(hdr.dime.datatype) == 64
type = '64-bit double precision';
elseif double(hdr.dime.datatype) == 128
type = '24-bit RGB true color';
elseif double(hdr.dime.datatype) == 256
type = '8-bit signed integer';
elseif double(hdr.dime.datatype) == 511
type = '96-bit RGB true color';
elseif double(hdr.dime.datatype) == 512
type = '16-bit unsigned integer';
elseif double(hdr.dime.datatype) == 768
type = '32-bit unsigned integer';
elseif double(hdr.dime.datatype) == 1024
type = '64-bit signed integer';
elseif double(hdr.dime.datatype) == 1280
type = '64-bit unsigned integer';
end
msg = {};
msg = [msg {''}];
msg = [msg {['Dimension: [', dim, ']']}];
msg = [msg {''}];
msg = [msg {['Voxel Size: [', vox, ']']}];
msg = [msg {''}];
msg = [msg {['Data Type: [', type, ']']}];
msg = [msg {''}];
msg = [msg {['Max Value: [', max_value, ']']}];
msg = [msg {''}];
msg = [msg {['Min Value: [', min_value, ']']}];
msg = [msg {''}];
if isfield(nii_view.nii, 'fileprefix')
if isfield(nii_view.nii, 'filetype') & nii_view.nii.filetype == 2
msg = [msg {['File Name: [', nii_view.nii.fileprefix, '.nii]']}];
msg = [msg {''}];
elseif isfield(nii_view.nii, 'filetype')
msg = [msg {['File Name: [', nii_view.nii.fileprefix, '.img]']}];
msg = [msg {''}];
else
msg = [msg {['File Prefix: [', nii_view.nii.fileprefix, ']']}];
msg = [msg {''}];
end
end
h = msgbox(msg, 'Image Information', 'modal');
set(h,'color',[1 1 1]);
return; % img_info
%----------------------------------------------------------------
function orient
fig = gcbf;
nii_view = getappdata(fig, 'nii_view');
nii = nii_view.nii;
if ~isempty(nii_view.bgimg)
msg = 'You can not modify an overlay image';
h = msgbox(msg, 'Error', 'modal');
return;
end
old_pointer = get(fig,'Pointer');
set(fig,'Pointer','watch');
[nii orient] = rri_orient(nii);
if isequal(orient, [1 2 3]) % do nothing
set(fig,'Pointer',old_pointer);
return;
end
oldopt = view_nii(fig);
opt.command = 'updatenii';
opt.usecolorbar = oldopt.usecolorbar;
opt.usepanel = oldopt.usepanel;
opt.usecrosshair = oldopt.usecrosshair;
opt.usestretch = oldopt.usestretch;
opt.useimagesc = oldopt.useimagesc;
opt.useinterp = oldopt.useinterp;
opt.setarea = oldopt.area;
opt.setunit = oldopt.unit;
opt.setviewpoint = oldopt.viewpoint;
opt.setscanid = oldopt.scanid;
opt.setcbarminmax = oldopt.cbarminmax;
opt.setcolorindex = oldopt.colorindex;
opt.setcolormap = oldopt.colormap;
opt.setcolorlevel = oldopt.colorlevel;
if isfield(oldopt,'highcolor')
opt.sethighcolor = oldopt.highcolor;
end
view_nii(fig, nii, opt);
set(fig,'Pointer',old_pointer);
reset_zoom(fig);
return; % orient
%----------------------------------------------------------------
function editvox
fig = gcbf;
nii_view = getappdata(fig, 'nii_view');
if ~isempty(nii_view.bgimg)
msg = 'You can not modify an overlay image';
h = msgbox(msg, 'Error', 'modal');
return;
end
nii = nii_view.nii;
oldopt = view_nii(fig);
sag = nii_view.imgXYZ.vox(1);
cor = nii_view.imgXYZ.vox(2);
axi = nii_view.imgXYZ.vox(3);
if nii_view.nii.hdr.dime.datatype == 128
imgvalue = [double(nii.img(sag,cor,axi,1,nii_view.scanid)) double(nii.img(sag,cor,axi,2,nii_view.scanid)) double(nii.img(sag,cor,axi,3,nii_view.scanid))];
init_val = sprintf('%7.4g %7.4g %7.4g',imgvalue);
elseif nii_view.nii.hdr.dime.datatype == 511
R = double(nii.img(sag,cor,axi,1,nii_view.scanid)) * (nii_view.nii.hdr.dime.glmax - ...
nii_view.nii.hdr.dime.glmin) + nii_view.nii.hdr.dime.glmin;
G = double(nii.img(sag,cor,axi,2,nii_view.scanid)) * (nii_view.nii.hdr.dime.glmax - ...
nii_view.nii.hdr.dime.glmin) + nii_view.nii.hdr.dime.glmin;
B = double(nii.img(sag,cor,axi,3,nii_view.scanid)) * (nii_view.nii.hdr.dime.glmax - ...
nii_view.nii.hdr.dime.glmin) + nii_view.nii.hdr.dime.glmin;
imgvalue = [R G B];
init_val = sprintf('%7.4g %7.4g %7.4g',imgvalue);
else
imgvalue = double(nii.img(sag,cor,axi,nii_view.scanid));
init_val = sprintf('%.6g',imgvalue);
end
old_pointer = get(fig,'Pointer');
set(fig,'Pointer','watch');
repeat = 1;
while repeat
if nii_view.nii.hdr.dime.datatype == 128 | nii_view.nii.hdr.dime.datatype == 511
init_val = inputdlg({'Replace the current voxel values with 3 new numbers:'}, ...
'Edit voxel value at crosshair', 1, {num2str(init_val)});
else
init_val = inputdlg({'Replace the current voxel value with 1 new number:'}, ...
'Edit voxel value at crosshair', 1, {num2str(init_val)});
end
if isempty(init_val)
set(fig,'Pointer',old_pointer);
return
end
imgvalue = str2num(init_val{1});
if ( (nii_view.nii.hdr.dime.datatype == 128 | nii_view.nii.hdr.dime.datatype == 511) ...
& length(imgvalue) ~= 3 ) | ...
( (nii_view.nii.hdr.dime.datatype ~= 128 & nii_view.nii.hdr.dime.datatype ~= 511) ...
& length(imgvalue) ~= 1 )
% do nothing
else
repeat = 0;
end
end
if nii_view.nii.hdr.dime.datatype == 128
nii.img(sag,cor,axi,1,nii_view.scanid) = imgvalue(1);
nii.img(sag,cor,axi,2,nii_view.scanid) = imgvalue(2);
nii.img(sag,cor,axi,3,nii_view.scanid) = imgvalue(3);
elseif nii_view.nii.hdr.dime.datatype == 511
nii.img(sag,cor,axi,1,nii_view.scanid) = (imgvalue(1) - nii_view.nii.hdr.dime.glmin) ...
/ (nii_view.nii.hdr.dime.glmax - nii_view.nii.hdr.dime.glmin);
nii.img(sag,cor,axi,2,nii_view.scanid) = (imgvalue(2) - nii_view.nii.hdr.dime.glmin) ...
/ (nii_view.nii.hdr.dime.glmax - nii_view.nii.hdr.dime.glmin);
nii.img(sag,cor,axi,3,nii_view.scanid) = (imgvalue(3) - nii_view.nii.hdr.dime.glmin) ...
/ (nii_view.nii.hdr.dime.glmax - nii_view.nii.hdr.dime.glmin);
else
nii.img(sag,cor,axi,nii_view.scanid) = imgvalue;
end
opt.command = 'updatenii';
opt.usecolorbar = oldopt.usecolorbar;
opt.usepanel = oldopt.usepanel;
opt.usecrosshair = oldopt.usecrosshair;
opt.usestretch = oldopt.usestretch;
opt.useimagesc = oldopt.useimagesc;
opt.useinterp = oldopt.useinterp;
opt.setarea = oldopt.area;
opt.setunit = oldopt.unit;
opt.setviewpoint = oldopt.viewpoint;
opt.setscanid = oldopt.scanid;
opt.setcbarminmax = oldopt.cbarminmax;
opt.setcolorindex = oldopt.colorindex;
opt.setcolormap = oldopt.colormap;
opt.setcolorlevel = oldopt.colorlevel;
if isfield(oldopt,'highcolor')
opt.sethighcolor = oldopt.highcolor;
end
view_nii(fig, nii, opt);
set(fig,'Pointer',old_pointer);
reset_zoom(fig);
return; % editvox
%----------------------------------------------------------------
function save_disp
[filename pathname] = uiputfile('*.*', 'Save displayed image as (*.nii or *.img)');
if isequal(filename,0) | isequal(pathname,0)
return;
else
out_imgfile = fullfile(pathname, filename); % original image file
end
old_pointer = get(gcbf,'Pointer');
set(gcbf,'Pointer','watch');
nii_view = getappdata(gcbf, 'nii_view');
nii = nii_view.nii;
try
save_nii(nii, out_imgfile);
catch
msg = 'File can not be saved.';
msgbox(msg, 'File write error', 'modal');
end
set(gcbf,'Pointer',old_pointer);
return; % save_disp
%----------------------------------------------------------------
function img_hist
nii_view = getappdata(gcbf, 'nii_view');
N = hist(double(nii_view.nii.img(:)),256);
x = linspace(double(min(nii_view.nii.img(:))), double(max(nii_view.nii.img(:))), 256);
figure;bar(x,N);
set(gcf, 'number', 'off', 'name', 'Volume Histogram');
set(gcf, 'windowstyle', 'modal'); % no zoom ...
xspan = max(x) - min(x) + 1;
yspan = max(N) + 1;
set(gca, 'xlim', [min(x)-xspan/20, max(x)+xspan/20]);
set(gca, 'ylim', [-yspan/20, max(N)+yspan/20]);
return; % img_hist
|
github
|
changken1/IDH_Prediction-master
|
save_untouch_header_only.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/save_untouch_header_only.m
| 2,132 |
utf_8
|
5f0515ef6a35f171bc8371d0f3fd365d
|
% This function is only used to save Analyze or NIfTI header that is
% ended with .hdr and loaded by load_untouch_header_only.m. If you
% have NIfTI file that is ended with .nii and you want to change its
% header only, you can use load_untouch_nii / save_untouch_nii pair.
%
% Usage: save_untouch_header_only(hdr, new_header_file_name)
%
% hdr - struct with NIfTI / Analyze header fields, which is obtained from:
% hdr = load_untouch_header_only(original_header_file_name)
%
% new_header_file_name - NIfTI / Analyze header name ended with .hdr.
% You can either copy original.img(.gz) to new.img(.gz) manually,
% or simply input original.hdr(.gz) in save_untouch_header_only.m
% to overwrite the original header.
%
% - Jimmy Shen ([email protected])
%
function save_untouch_header_only(hdr, filename)
if ~exist('hdr','var') | isempty(hdr) | ~exist('filename','var') | isempty(filename)
error('Usage: save_untouch_header_only(hdr, filename)');
end
v = version;
% Check file extension. If .gz, unpack it into temp folder
%
if length(filename) > 2 & strcmp(filename(end-2:end), '.gz')
if ~strcmp(filename(end-6:end), '.hdr.gz')
error('Please check filename.');
end
if str2num(v(1:3)) < 7.1 | ~usejava('jvm')
error('Please use MATLAB 7.1 (with java) and above, or run gunzip outside MATLAB.');
else
gzFile = 1;
filename = filename(1:end-3);
end
end
[p,f] = fileparts(filename);
fileprefix = fullfile(p, f);
write_hdr(hdr, fileprefix);
% gzip output file if requested
%
if exist('gzFile', 'var')
gzip([fileprefix, '.hdr']);
delete([fileprefix, '.hdr']);
end;
return % save_untouch_header_only
%-----------------------------------------------------------------------------------
function write_hdr(hdr, fileprefix)
fid = fopen(sprintf('%s.hdr',fileprefix),'w');
if isfield(hdr.hist,'magic')
save_untouch_nii_hdr(hdr, fid);
else
save_untouch0_nii_hdr(hdr, fid);
end
fclose(fid);
return % write_hdr
|
github
|
changken1/IDH_Prediction-master
|
pad_nii.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/pad_nii.m
| 3,712 |
utf_8
|
0b9de8feba6840e2d8ea1ab1752747c7
|
% PAD_NII: Pad the NIfTI volume from any of the 6 sides
%
% Usage: nii = pad_nii(nii, [option])
%
% Inputs:
%
% nii - NIfTI volume.
%
% option - struct instructing how many voxel to be padded from which side.
%
% option.pad_from_L = ( number of voxel )
% option.pad_from_R = ( number of voxel )
% option.pad_from_P = ( number of voxel )
% option.pad_from_A = ( number of voxel )
% option.pad_from_I = ( number of voxel )
% option.pad_from_S = ( number of voxel )
% option.bg = [0]
%
% Options description in detail:
% ==============================
%
% pad_from_L: Number of voxels from Left side will be padded.
%
% pad_from_R: Number of voxels from Right side will be padded.
%
% pad_from_P: Number of voxels from Posterior side will be padded.
%
% pad_from_A: Number of voxels from Anterior side will be padded.
%
% pad_from_I: Number of voxels from Inferior side will be padded.
%
% pad_from_S: Number of voxels from Superior side will be padded.
%
% bg: Background intensity, which is 0 by default.
%
% NIfTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function nii = pad_nii(nii, opt)
dims = abs(nii.hdr.dime.dim(2:4));
origin = abs(nii.hdr.hist.originator(1:3));
if isempty(origin) | all(origin == 0) % according to SPM
origin = round((dims+1)/2);
end
pad_from_L = 0;
pad_from_R = 0;
pad_from_P = 0;
pad_from_A = 0;
pad_from_I = 0;
pad_from_S = 0;
bg = 0;
if nargin > 1 & ~isempty(opt)
if ~isstruct(opt)
error('option argument should be a struct');
end
if isfield(opt,'pad_from_L')
pad_from_L = round(opt.pad_from_L);
if pad_from_L >= origin(1) | pad_from_L < 0
error('pad_from_L cannot be negative');
end
end
if isfield(opt,'pad_from_P')
pad_from_P = round(opt.pad_from_P);
if pad_from_P >= origin(2) | pad_from_P < 0
error('pad_from_P cannot be negative');
end
end
if isfield(opt,'pad_from_I')
pad_from_I = round(opt.pad_from_I);
if pad_from_I >= origin(3) | pad_from_I < 0
error('pad_from_I cannot be negative');
end
end
if isfield(opt,'pad_from_R')
pad_from_R = round(opt.pad_from_R);
if pad_from_R > dims(1)-origin(1) | pad_from_R < 0
error('pad_from_R cannot be negative');
end
end
if isfield(opt,'pad_from_A')
pad_from_A = round(opt.pad_from_A);
if pad_from_A > dims(2)-origin(2) | pad_from_A < 0
error('pad_from_A cannot be negative');
end
end
if isfield(opt,'pad_from_S')
pad_from_S = round(opt.pad_from_S);
if pad_from_S > dims(3)-origin(3) | pad_from_S < 0
error('pad_from_S cannot be negative');
end
end
if isfield(opt,'bg')
bg = opt.bg;
end
end
blk = bg * ones( pad_from_L, dims(2), dims(3) );
nii.img = cat(1, blk, nii.img);
blk = bg * ones( pad_from_R, dims(2), dims(3) );
nii.img = cat(1, nii.img, blk);
dims = size(nii.img);
blk = bg * ones( dims(1), pad_from_P, dims(3) );
nii.img = cat(2, blk, nii.img);
blk = bg * ones( dims(1), pad_from_A, dims(3) );
nii.img = cat(2, nii.img, blk);
dims = size(nii.img);
blk = bg * ones( dims(1), dims(2), pad_from_I );
nii.img = cat(3, blk, nii.img);
blk = bg * ones( dims(1), dims(2), pad_from_S );
nii.img = cat(3, nii.img, blk);
nii = make_nii(nii.img, nii.hdr.dime.pixdim(2:4), ...
[origin(1)+pad_from_L origin(2)+pad_from_P origin(3)+pad_from_I], ...
nii.hdr.dime.datatype, nii.hdr.hist.descrip);
return;
|
github
|
changken1/IDH_Prediction-master
|
load_nii_hdr.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/load_nii_hdr.m
| 10,031 |
utf_8
|
e95839e314863f7ee463cc2626dd447c
|
% internal function
% - Jimmy Shen ([email protected])
function [hdr, filetype, fileprefix, machine] = load_nii_hdr(fileprefix)
if ~exist('fileprefix','var'),
error('Usage: [hdr, filetype, fileprefix, machine] = load_nii_hdr(filename)');
end
machine = 'ieee-le';
new_ext = 0;
if findstr('.nii',fileprefix) & strcmp(fileprefix(end-3:end), '.nii')
new_ext = 1;
fileprefix(end-3:end)='';
end
if findstr('.hdr',fileprefix) & strcmp(fileprefix(end-3:end), '.hdr')
fileprefix(end-3:end)='';
end
if findstr('.img',fileprefix) & strcmp(fileprefix(end-3:end), '.img')
fileprefix(end-3:end)='';
end
if new_ext
fn = sprintf('%s.nii',fileprefix);
if ~exist(fn)
msg = sprintf('Cannot find file "%s.nii".', fileprefix);
error(msg);
end
else
fn = sprintf('%s.hdr',fileprefix);
if ~exist(fn)
msg = sprintf('Cannot find file "%s.hdr".', fileprefix);
error(msg);
end
end
fid = fopen(fn,'r',machine);
if fid < 0,
msg = sprintf('Cannot open file %s.',fn);
error(msg);
else
fseek(fid,0,'bof');
if fread(fid,1,'int32') == 348
hdr = read_header(fid);
fclose(fid);
else
fclose(fid);
% first try reading the opposite endian to 'machine'
%
switch machine,
case 'ieee-le', machine = 'ieee-be';
case 'ieee-be', machine = 'ieee-le';
end
fid = fopen(fn,'r',machine);
if fid < 0,
msg = sprintf('Cannot open file %s.',fn);
error(msg);
else
fseek(fid,0,'bof');
if fread(fid,1,'int32') ~= 348
% Now throw an error
%
msg = sprintf('File "%s" is corrupted.',fn);
error(msg);
end
hdr = read_header(fid);
fclose(fid);
end
end
end
if strcmp(hdr.hist.magic, 'n+1')
filetype = 2;
elseif strcmp(hdr.hist.magic, 'ni1')
filetype = 1;
else
filetype = 0;
end
return % load_nii_hdr
%---------------------------------------------------------------------
function [ dsr ] = read_header(fid)
% Original header structures
% struct dsr
% {
% struct header_key hk; /* 0 + 40 */
% struct image_dimension dime; /* 40 + 108 */
% struct data_history hist; /* 148 + 200 */
% }; /* total= 348 bytes*/
dsr.hk = header_key(fid);
dsr.dime = image_dimension(fid);
dsr.hist = data_history(fid);
% For Analyze data format
%
if ~strcmp(dsr.hist.magic, 'n+1') & ~strcmp(dsr.hist.magic, 'ni1')
dsr.hist.qform_code = 0;
dsr.hist.sform_code = 0;
end
return % read_header
%---------------------------------------------------------------------
function [ hk ] = header_key(fid)
fseek(fid,0,'bof');
% Original header structures
% struct header_key /* header key */
% { /* off + size */
% int sizeof_hdr /* 0 + 4 */
% char data_type[10]; /* 4 + 10 */
% char db_name[18]; /* 14 + 18 */
% int extents; /* 32 + 4 */
% short int session_error; /* 36 + 2 */
% char regular; /* 38 + 1 */
% char dim_info; % char hkey_un0; /* 39 + 1 */
% }; /* total=40 bytes */
%
% int sizeof_header Should be 348.
% char regular Must be 'r' to indicate that all images and
% volumes are the same size.
v6 = version;
if str2num(v6(1))<6
directchar = '*char';
else
directchar = 'uchar=>char';
end
hk.sizeof_hdr = fread(fid, 1,'int32')'; % should be 348!
hk.data_type = deblank(fread(fid,10,directchar)');
hk.db_name = deblank(fread(fid,18,directchar)');
hk.extents = fread(fid, 1,'int32')';
hk.session_error = fread(fid, 1,'int16')';
hk.regular = fread(fid, 1,directchar)';
hk.dim_info = fread(fid, 1,'uchar')';
return % header_key
%---------------------------------------------------------------------
function [ dime ] = image_dimension(fid)
% Original header structures
% struct image_dimension
% { /* off + size */
% short int dim[8]; /* 0 + 16 */
% /*
% dim[0] Number of dimensions in database; usually 4.
% dim[1] Image X dimension; number of *pixels* in an image row.
% dim[2] Image Y dimension; number of *pixel rows* in slice.
% dim[3] Volume Z dimension; number of *slices* in a volume.
% dim[4] Time points; number of volumes in database
% */
% float intent_p1; % char vox_units[4]; /* 16 + 4 */
% float intent_p2; % char cal_units[8]; /* 20 + 4 */
% float intent_p3; % char cal_units[8]; /* 24 + 4 */
% short int intent_code; % short int unused1; /* 28 + 2 */
% short int datatype; /* 30 + 2 */
% short int bitpix; /* 32 + 2 */
% short int slice_start; % short int dim_un0; /* 34 + 2 */
% float pixdim[8]; /* 36 + 32 */
% /*
% pixdim[] specifies the voxel dimensions:
% pixdim[1] - voxel width, mm
% pixdim[2] - voxel height, mm
% pixdim[3] - slice thickness, mm
% pixdim[4] - volume timing, in msec
% ..etc
% */
% float vox_offset; /* 68 + 4 */
% float scl_slope; % float roi_scale; /* 72 + 4 */
% float scl_inter; % float funused1; /* 76 + 4 */
% short slice_end; % float funused2; /* 80 + 2 */
% char slice_code; % float funused2; /* 82 + 1 */
% char xyzt_units; % float funused2; /* 83 + 1 */
% float cal_max; /* 84 + 4 */
% float cal_min; /* 88 + 4 */
% float slice_duration; % int compressed; /* 92 + 4 */
% float toffset; % int verified; /* 96 + 4 */
% int glmax; /* 100 + 4 */
% int glmin; /* 104 + 4 */
% }; /* total=108 bytes */
dime.dim = fread(fid,8,'int16')';
dime.intent_p1 = fread(fid,1,'float32')';
dime.intent_p2 = fread(fid,1,'float32')';
dime.intent_p3 = fread(fid,1,'float32')';
dime.intent_code = fread(fid,1,'int16')';
dime.datatype = fread(fid,1,'int16')';
dime.bitpix = fread(fid,1,'int16')';
dime.slice_start = fread(fid,1,'int16')';
dime.pixdim = fread(fid,8,'float32')';
dime.vox_offset = fread(fid,1,'float32')';
dime.scl_slope = fread(fid,1,'float32')';
dime.scl_inter = fread(fid,1,'float32')';
dime.slice_end = fread(fid,1,'int16')';
dime.slice_code = fread(fid,1,'uchar')';
dime.xyzt_units = fread(fid,1,'uchar')';
dime.cal_max = fread(fid,1,'float32')';
dime.cal_min = fread(fid,1,'float32')';
dime.slice_duration = fread(fid,1,'float32')';
dime.toffset = fread(fid,1,'float32')';
dime.glmax = fread(fid,1,'int32')';
dime.glmin = fread(fid,1,'int32')';
return % image_dimension
%---------------------------------------------------------------------
function [ hist ] = data_history(fid)
% Original header structures
% struct data_history
% { /* off + size */
% char descrip[80]; /* 0 + 80 */
% char aux_file[24]; /* 80 + 24 */
% short int qform_code; /* 104 + 2 */
% short int sform_code; /* 106 + 2 */
% float quatern_b; /* 108 + 4 */
% float quatern_c; /* 112 + 4 */
% float quatern_d; /* 116 + 4 */
% float qoffset_x; /* 120 + 4 */
% float qoffset_y; /* 124 + 4 */
% float qoffset_z; /* 128 + 4 */
% float srow_x[4]; /* 132 + 16 */
% float srow_y[4]; /* 148 + 16 */
% float srow_z[4]; /* 164 + 16 */
% char intent_name[16]; /* 180 + 16 */
% char magic[4]; % int smin; /* 196 + 4 */
% }; /* total=200 bytes */
v6 = version;
if str2num(v6(1))<6
directchar = '*char';
else
directchar = 'uchar=>char';
end
hist.descrip = deblank(fread(fid,80,directchar)');
hist.aux_file = deblank(fread(fid,24,directchar)');
hist.qform_code = fread(fid,1,'int16')';
hist.sform_code = fread(fid,1,'int16')';
hist.quatern_b = fread(fid,1,'float32')';
hist.quatern_c = fread(fid,1,'float32')';
hist.quatern_d = fread(fid,1,'float32')';
hist.qoffset_x = fread(fid,1,'float32')';
hist.qoffset_y = fread(fid,1,'float32')';
hist.qoffset_z = fread(fid,1,'float32')';
hist.srow_x = fread(fid,4,'float32')';
hist.srow_y = fread(fid,4,'float32')';
hist.srow_z = fread(fid,4,'float32')';
hist.intent_name = deblank(fread(fid,16,directchar)');
hist.magic = deblank(fread(fid,4,directchar)');
fseek(fid,253,'bof');
hist.originator = fread(fid, 5,'int16')';
return % data_history
|
github
|
changken1/IDH_Prediction-master
|
save_untouch_slice.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/save_untouch_slice.m
| 19,683 |
utf_8
|
364468e5dbd3790c1aadf9a768534f1f
|
% Save back to the original image with a portion of slices that was
% loaded by "load_untouch_nii". You can process those slices matrix
% in any way, as long as their dimension is not altered.
%
% Usage: save_untouch_slice(slice, filename, ...
% slice_idx, [img_idx], [dim5_idx], [dim6_idx], [dim7_idx])
%
% slice - a portion of slices that was loaded by "load_untouch_nii".
% This should be a numeric matrix (i.e. only the .img field in the
% loaded structure)
%
% filename - NIfTI or ANALYZE file name.
%
% slice_idx (depending on slice size) - a numerical array of image
% slice indices, which should be the same as that you entered
% in "load_untouch_nii" command.
%
% img_idx (depending on slice size) - a numerical array of image
% volume indices, which should be the same as that you entered
% in "load_untouch_nii" command.
%
% dim5_idx (depending on slice size) - a numerical array of 5th
% dimension indices, which should be the same as that you entered
% in "load_untouch_nii" command.
%
% dim6_idx (depending on slice size) - a numerical array of 6th
% dimension indices, which should be the same as that you entered
% in "load_untouch_nii" command.
%
% dim7_idx (depending on slice size) - a numerical array of 7th
% dimension indices, which should be the same as that you entered
% in "load_untouch_nii" command.
%
% Example:
% nii = load_nii('avg152T1_LR_nifti.nii');
% save_nii(nii, 'test.nii');
% view_nii(nii);
% nii = load_untouch_nii('test.nii','','','','','',[40 51:53]);
% nii.img = ones(91,109,4)*122;
% save_untouch_slice(nii.img, 'test.nii', [40 51:52]);
% nii = load_nii('test.nii');
% view_nii(nii);
%
% - Jimmy Shen ([email protected])
%
function save_untouch_slice(slice, filename, slice_idx, img_idx, dim5_idx, dim6_idx, dim7_idx)
if ~exist('slice','var') | ~isnumeric(slice)
msg = [char(10) '"slice" argument should be a portion of slices that was loaded' char(10)];
msg = [msg 'by "load_untouch_nii.m". This should be a numeric matrix (i.e.' char(10)];
msg = [msg 'only the .img field in the loaded structure).'];
error(msg);
end
if ~exist('filename','var') | ~exist(filename,'file')
error('In order to save back, original NIfTI or ANALYZE file must exist.');
end
if ~exist('slice_idx','var') | isempty(slice_idx) | ~isequal(size(slice,3),length(slice_idx))
msg = [char(10) '"slice_idx" is a numerical array of image slice indices, which' char(10)];
msg = [msg 'should be the same as that you entered in "load_untouch_nii.m"' char(10)];
msg = [msg 'command.'];
error(msg);
end
if ~exist('img_idx','var') | isempty(img_idx)
img_idx = [];
if ~isequal(size(slice,4),1)
msg = [char(10) '"img_idx" is a numerical array of image volume indices, which' char(10)];
msg = [msg 'should be the same as that you entered in "load_untouch_nii.m"' char(10)];
msg = [msg 'command.'];
error(msg);
end
elseif ~isequal(size(slice,4),length(img_idx))
msg = [char(10) '"img_idx" is a numerical array of image volume indices, which' char(10)];
msg = [msg 'should be the same as that you entered in "load_untouch_nii.m"' char(10)];
msg = [msg 'command.'];
error(msg);
end
if ~exist('dim5_idx','var') | isempty(dim5_idx)
dim5_idx = [];
if ~isequal(size(slice,5),1)
msg = [char(10) '"dim5_idx" is a numerical array of 5th dimension indices, which' char(10)];
msg = [msg 'should be the same as that you entered in "load_untouch_nii.m"' char(10)];
msg = [msg 'command.'];
error(msg);
end
elseif ~isequal(size(slice,5),length(img_idx))
msg = [char(10) '"img_idx" is a numerical array of 5th dimension indices, which' char(10)];
msg = [msg 'should be the same as that you entered in "load_untouch_nii.m"' char(10)];
msg = [msg 'command.'];
error(msg);
end
if ~exist('dim6_idx','var') | isempty(dim6_idx)
dim6_idx = [];
if ~isequal(size(slice,6),1)
msg = [char(10) '"dim6_idx" is a numerical array of 6th dimension indices, which' char(10)];
msg = [msg 'should be the same as that you entered in "load_untouch_nii.m"' char(10)];
msg = [msg 'command.'];
error(msg);
end
elseif ~isequal(size(slice,6),length(img_idx))
msg = [char(10) '"img_idx" is a numerical array of 6th dimension indices, which' char(10)];
msg = [msg 'should be the same as that you entered in "load_untouch_nii.m"' char(10)];
msg = [msg 'command.'];
error(msg);
end
if ~exist('dim7_idx','var') | isempty(dim7_idx)
dim7_idx = [];
if ~isequal(size(slice,7),1)
msg = [char(10) '"dim7_idx" is a numerical array of 7th dimension indices, which' char(10)];
msg = [msg 'should be the same as that you entered in "load_untouch_nii.m"' char(10)];
msg = [msg 'command.'];
error(msg);
end
elseif ~isequal(size(slice,7),length(img_idx))
msg = [char(10) '"img_idx" is a numerical array of 7th dimension indices, which' char(10)];
msg = [msg 'should be the same as that you entered in "load_untouch_nii.m"' char(10)];
msg = [msg 'command.'];
error(msg);
end
v = version;
% Check file extension. If .gz, unpack it into temp folder
%
if length(filename) > 2 & strcmp(filename(end-2:end), '.gz')
if ~strcmp(filename(end-6:end), '.img.gz') & ...
~strcmp(filename(end-6:end), '.hdr.gz') & ...
~strcmp(filename(end-6:end), '.nii.gz')
error('Please check filename.');
end
if str2num(v(1:3)) < 7.1 | ~usejava('jvm')
error('Please use MATLAB 7.1 (with java) and above, or run gunzip outside MATLAB.');
elseif strcmp(filename(end-6:end), '.img.gz')
filename1 = filename;
filename2 = filename;
filename2(end-6:end) = '';
filename2 = [filename2, '.hdr.gz'];
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename1 = gunzip(filename1, tmpDir);
filename2 = gunzip(filename2, tmpDir);
filename = char(filename1); % convert from cell to string
elseif strcmp(filename(end-6:end), '.hdr.gz')
filename1 = filename;
filename2 = filename;
filename2(end-6:end) = '';
filename2 = [filename2, '.img.gz'];
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename1 = gunzip(filename1, tmpDir);
filename2 = gunzip(filename2, tmpDir);
filename = char(filename1); % convert from cell to string
elseif strcmp(filename(end-6:end), '.nii.gz')
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename = gunzip(filename, tmpDir);
filename = char(filename); % convert from cell to string
end
end
% Read the dataset header
%
[nii.hdr,nii.filetype,nii.fileprefix,nii.machine] = load_nii_hdr(filename);
if nii.filetype == 0
nii.hdr = load_untouch0_nii_hdr(nii.fileprefix,nii.machine);
else
nii.hdr = load_untouch_nii_hdr(nii.fileprefix,nii.machine,nii.filetype);
end
% Clean up after gunzip
%
if exist('gzFileName', 'var')
% fix fileprefix so it doesn't point to temp location
%
nii.fileprefix = gzFileName(1:end-7);
% rmdir(tmpDir,'s');
end
[p,f] = fileparts(filename);
fileprefix = fullfile(p, f);
% fileprefix = nii.fileprefix;
filetype = nii.filetype;
if ~isequal( nii.hdr.dime.dim(2:3), [size(slice,1),size(slice,2)] )
msg = [char(10) 'The first two dimensions of slice matrix should be the same as' char(10)];
msg = [msg 'the first two dimensions of image loaded by "load_untouch_nii".'];
error(msg);
end
% Save the dataset body
%
save_untouch_slice_img(slice, nii.hdr, filetype, fileprefix, ...
nii.machine, slice_idx,img_idx,dim5_idx,dim6_idx,dim7_idx);
% gzip output file if requested
%
if exist('gzFileName', 'var')
[p,f] = fileparts(gzFileName);
if filetype == 1
gzip([fileprefix, '.img']);
delete([fileprefix, '.img']);
movefile([fileprefix, '.img.gz']);
gzip([fileprefix, '.hdr']);
delete([fileprefix, '.hdr']);
movefile([fileprefix, '.hdr.gz']);
elseif filetype == 2
gzip([fileprefix, '.nii']);
delete([fileprefix, '.nii']);
movefile([fileprefix, '.nii.gz']);
end;
rmdir(tmpDir,'s');
end;
return % save_untouch_slice
%--------------------------------------------------------------------------
function save_untouch_slice_img(slice,hdr,filetype,fileprefix,machine,slice_idx,img_idx,dim5_idx,dim6_idx,dim7_idx)
if ~exist('hdr','var') | ~exist('filetype','var') | ~exist('fileprefix','var') | ~exist('machine','var')
error('Usage: save_untouch_slice_img(slice,hdr,filetype,fileprefix,machine,slice_idx,[img_idx],[dim5_idx],[dim6_idx],[dim7_idx]);');
end
if ~exist('slice_idx','var') | isempty(slice_idx) | hdr.dime.dim(4)<1
slice_idx = [];
end
if ~exist('img_idx','var') | isempty(img_idx) | hdr.dime.dim(5)<1
img_idx = [];
end
if ~exist('dim5_idx','var') | isempty(dim5_idx) | hdr.dime.dim(6)<1
dim5_idx = [];
end
if ~exist('dim6_idx','var') | isempty(dim6_idx) | hdr.dime.dim(7)<1
dim6_idx = [];
end
if ~exist('dim7_idx','var') | isempty(dim7_idx) | hdr.dime.dim(8)<1
dim7_idx = [];
end
% check img_idx
%
if ~isempty(img_idx) & ~isnumeric(img_idx)
error('"img_idx" should be a numerical array.');
end
if length(unique(img_idx)) ~= length(img_idx)
error('Duplicate image index in "img_idx"');
end
if ~isempty(img_idx) & (min(img_idx) < 1 | max(img_idx) > hdr.dime.dim(5))
max_range = hdr.dime.dim(5);
if max_range == 1
error(['"img_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"img_idx" should be an integer within the range of [' range '].']);
end
end
% check dim5_idx
%
if ~isempty(dim5_idx) & ~isnumeric(dim5_idx)
error('"dim5_idx" should be a numerical array.');
end
if length(unique(dim5_idx)) ~= length(dim5_idx)
error('Duplicate index in "dim5_idx"');
end
if ~isempty(dim5_idx) & (min(dim5_idx) < 1 | max(dim5_idx) > hdr.dime.dim(6))
max_range = hdr.dime.dim(6);
if max_range == 1
error(['"dim5_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"dim5_idx" should be an integer within the range of [' range '].']);
end
end
% check dim6_idx
%
if ~isempty(dim6_idx) & ~isnumeric(dim6_idx)
error('"dim6_idx" should be a numerical array.');
end
if length(unique(dim6_idx)) ~= length(dim6_idx)
error('Duplicate index in "dim6_idx"');
end
if ~isempty(dim6_idx) & (min(dim6_idx) < 1 | max(dim6_idx) > hdr.dime.dim(7))
max_range = hdr.dime.dim(7);
if max_range == 1
error(['"dim6_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"dim6_idx" should be an integer within the range of [' range '].']);
end
end
% check dim7_idx
%
if ~isempty(dim7_idx) & ~isnumeric(dim7_idx)
error('"dim7_idx" should be a numerical array.');
end
if length(unique(dim7_idx)) ~= length(dim7_idx)
error('Duplicate index in "dim7_idx"');
end
if ~isempty(dim7_idx) & (min(dim7_idx) < 1 | max(dim7_idx) > hdr.dime.dim(8))
max_range = hdr.dime.dim(8);
if max_range == 1
error(['"dim7_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"dim7_idx" should be an integer within the range of [' range '].']);
end
end
% check slice_idx
%
if ~isempty(slice_idx) & ~isnumeric(slice_idx)
error('"slice_idx" should be a numerical array.');
end
if length(unique(slice_idx)) ~= length(slice_idx)
error('Duplicate index in "slice_idx"');
end
if ~isempty(slice_idx) & (min(slice_idx) < 1 | max(slice_idx) > hdr.dime.dim(4))
max_range = hdr.dime.dim(4);
if max_range == 1
error(['"slice_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"slice_idx" should be an integer within the range of [' range '].']);
end
end
write_image(slice,hdr,filetype,fileprefix,machine,slice_idx,img_idx,dim5_idx,dim6_idx,dim7_idx);
return % save_untouch_slice_img
%---------------------------------------------------------------------
function write_image(slice,hdr,filetype,fileprefix,machine,slice_idx,img_idx,dim5_idx,dim6_idx,dim7_idx)
if filetype == 2
fid = fopen(sprintf('%s.nii',fileprefix),'r+');
if fid < 0,
msg = sprintf('Cannot open file %s.nii.',fileprefix);
error(msg);
end
else
fid = fopen(sprintf('%s.img',fileprefix),'r+');
if fid < 0,
msg = sprintf('Cannot open file %s.img.',fileprefix);
error(msg);
end
end
% Set bitpix according to datatype
%
% /*Acceptable values for datatype are*/
%
% 0 None (Unknown bit per voxel) % DT_NONE, DT_UNKNOWN
% 1 Binary (ubit1, bitpix=1) % DT_BINARY
% 2 Unsigned char (uchar or uint8, bitpix=8) % DT_UINT8, NIFTI_TYPE_UINT8
% 4 Signed short (int16, bitpix=16) % DT_INT16, NIFTI_TYPE_INT16
% 8 Signed integer (int32, bitpix=32) % DT_INT32, NIFTI_TYPE_INT32
% 16 Floating point (single or float32, bitpix=32) % DT_FLOAT32, NIFTI_TYPE_FLOAT32
% 32 Complex, 2 float32 (Use float32, bitpix=64) % DT_COMPLEX64, NIFTI_TYPE_COMPLEX64
% 64 Double precision (double or float64, bitpix=64) % DT_FLOAT64, NIFTI_TYPE_FLOAT64
% 128 uint8 RGB (Use uint8, bitpix=24) % DT_RGB24, NIFTI_TYPE_RGB24
% 256 Signed char (schar or int8, bitpix=8) % DT_INT8, NIFTI_TYPE_INT8
% 511 Single RGB (Use float32, bitpix=96) % DT_RGB96, NIFTI_TYPE_RGB96
% 512 Unsigned short (uint16, bitpix=16) % DT_UNINT16, NIFTI_TYPE_UNINT16
% 768 Unsigned integer (uint32, bitpix=32) % DT_UNINT32, NIFTI_TYPE_UNINT32
% 1024 Signed long long (int64, bitpix=64) % DT_INT64, NIFTI_TYPE_INT64
% 1280 Unsigned long long (uint64, bitpix=64) % DT_UINT64, NIFTI_TYPE_UINT64
% 1536 Long double, float128 (Unsupported, bitpix=128) % DT_FLOAT128, NIFTI_TYPE_FLOAT128
% 1792 Complex128, 2 float64 (Use float64, bitpix=128) % DT_COMPLEX128, NIFTI_TYPE_COMPLEX128
% 2048 Complex256, 2 float128 (Unsupported, bitpix=256) % DT_COMPLEX128, NIFTI_TYPE_COMPLEX128
%
switch hdr.dime.datatype
case 2,
hdr.dime.bitpix = 8; precision = 'uint8';
case 4,
hdr.dime.bitpix = 16; precision = 'int16';
case 8,
hdr.dime.bitpix = 32; precision = 'int32';
case 16,
hdr.dime.bitpix = 32; precision = 'float32';
case 64,
hdr.dime.bitpix = 64; precision = 'float64';
case 128,
hdr.dime.bitpix = 24; precision = 'uint8';
case 256
hdr.dime.bitpix = 8; precision = 'int8';
case 511
hdr.dime.bitpix = 96; precision = 'float32';
case 512
hdr.dime.bitpix = 16; precision = 'uint16';
case 768
hdr.dime.bitpix = 32; precision = 'uint32';
case 1024
hdr.dime.bitpix = 64; precision = 'int64';
case 1280
hdr.dime.bitpix = 64; precision = 'uint64';
otherwise
error('This datatype is not supported');
end
hdr.dime.dim(find(hdr.dime.dim < 1)) = 1;
% move pointer to the start of image block
%
switch filetype
case {0, 1}
fseek(fid, 0, 'bof');
case 2
fseek(fid, hdr.dime.vox_offset, 'bof');
end
if hdr.dime.datatype == 1 | isequal(hdr.dime.dim(4:8),ones(1,5)) | ...
(isempty(img_idx) & isempty(dim5_idx) & isempty(dim6_idx) & isempty(dim7_idx) & isempty(slice_idx))
msg = [char(10) char(10) ' "save_untouch_slice" is used to save back to the original image a' char(10)];
msg = [msg ' portion of slices that were loaded by "load_untouch_nii". You can' char(10)];
msg = [msg ' process those slices matrix in any way, as long as their dimension' char(10)];
msg = [msg ' is not changed.'];
error(msg);
else
d1 = hdr.dime.dim(2);
d2 = hdr.dime.dim(3);
d3 = hdr.dime.dim(4);
d4 = hdr.dime.dim(5);
d5 = hdr.dime.dim(6);
d6 = hdr.dime.dim(7);
d7 = hdr.dime.dim(8);
if isempty(slice_idx)
slice_idx = 1:d3;
end
if isempty(img_idx)
img_idx = 1:d4;
end
if isempty(dim5_idx)
dim5_idx = 1:d5;
end
if isempty(dim6_idx)
dim6_idx = 1:d6;
end
if isempty(dim7_idx)
dim7_idx = 1:d7;
end
%ROMAN: begin
roman = 1;
if(roman)
% compute size of one slice
%
img_siz = prod(hdr.dime.dim(2:3));
% For complex float32 or complex float64, voxel values
% include [real, imag]
%
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792
img_siz = img_siz * 2;
end
%MPH: For RGB24, voxel values include 3 separate color planes
%
if hdr.dime.datatype == 128 | hdr.dime.datatype == 511
img_siz = img_siz * 3;
end
end; %if(roman)
% ROMAN: end
for i7=1:length(dim7_idx)
for i6=1:length(dim6_idx)
for i5=1:length(dim5_idx)
for t=1:length(img_idx)
for s=1:length(slice_idx)
% Position is seeked in bytes. To convert dimension size
% to byte storage size, hdr.dime.bitpix/8 will be
% applied.
%
pos = sub2ind([d1 d2 d3 d4 d5 d6 d7], 1, 1, slice_idx(s), ...
img_idx(t), dim5_idx(i5),dim6_idx(i6),dim7_idx(i7)) -1;
pos = pos * hdr.dime.bitpix/8;
% ROMAN: begin
if(roman)
% do nothing
else
img_siz = prod(hdr.dime.dim(2:3));
% For complex float32 or complex float64, voxel values
% include [real, imag]
%
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792
img_siz = img_siz * 2;
end
%MPH: For RGB24, voxel values include 3 separate color planes
%
if hdr.dime.datatype == 128 | hdr.dime.datatype == 511
img_siz = img_siz * 3;
end
end; % if (roman)
% ROMAN: end
if filetype == 2
fseek(fid, pos + hdr.dime.vox_offset, 'bof');
else
fseek(fid, pos, 'bof');
end
% For each frame, fwrite will write precision of value
% in img_siz times
%
fwrite(fid, slice(:,:,s,t,i5,i6,i7), sprintf('*%s',precision));
end
end
end
end
end
end
fclose(fid);
return % write_image
|
github
|
changken1/IDH_Prediction-master
|
load_nii_img.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/load_nii_img.m
| 12,328 |
utf_8
|
b1b9dd2838a8f217b10fefdc8a931d5e
|
% internal function
% - Jimmy Shen ([email protected])
function [img,hdr] = load_nii_img(hdr,filetype,fileprefix,machine,img_idx,dim5_idx,dim6_idx,dim7_idx,old_RGB)
if ~exist('hdr','var') | ~exist('filetype','var') | ~exist('fileprefix','var') | ~exist('machine','var')
error('Usage: [img,hdr] = load_nii_img(hdr,filetype,fileprefix,machine,[img_idx],[dim5_idx],[dim6_idx],[dim7_idx],[old_RGB]);');
end
if ~exist('img_idx','var') | isempty(img_idx) | hdr.dime.dim(5)<1
img_idx = [];
end
if ~exist('dim5_idx','var') | isempty(dim5_idx) | hdr.dime.dim(6)<1
dim5_idx = [];
end
if ~exist('dim6_idx','var') | isempty(dim6_idx) | hdr.dime.dim(7)<1
dim6_idx = [];
end
if ~exist('dim7_idx','var') | isempty(dim7_idx) | hdr.dime.dim(8)<1
dim7_idx = [];
end
if ~exist('old_RGB','var') | isempty(old_RGB)
old_RGB = 0;
end
% check img_idx
%
if ~isempty(img_idx) & ~isnumeric(img_idx)
error('"img_idx" should be a numerical array.');
end
if length(unique(img_idx)) ~= length(img_idx)
error('Duplicate image index in "img_idx"');
end
if ~isempty(img_idx) & (min(img_idx) < 1 | max(img_idx) > hdr.dime.dim(5))
max_range = hdr.dime.dim(5);
if max_range == 1
error(['"img_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"img_idx" should be an integer within the range of [' range '].']);
end
end
% check dim5_idx
%
if ~isempty(dim5_idx) & ~isnumeric(dim5_idx)
error('"dim5_idx" should be a numerical array.');
end
if length(unique(dim5_idx)) ~= length(dim5_idx)
error('Duplicate index in "dim5_idx"');
end
if ~isempty(dim5_idx) & (min(dim5_idx) < 1 | max(dim5_idx) > hdr.dime.dim(6))
max_range = hdr.dime.dim(6);
if max_range == 1
error(['"dim5_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"dim5_idx" should be an integer within the range of [' range '].']);
end
end
% check dim6_idx
%
if ~isempty(dim6_idx) & ~isnumeric(dim6_idx)
error('"dim6_idx" should be a numerical array.');
end
if length(unique(dim6_idx)) ~= length(dim6_idx)
error('Duplicate index in "dim6_idx"');
end
if ~isempty(dim6_idx) & (min(dim6_idx) < 1 | max(dim6_idx) > hdr.dime.dim(7))
max_range = hdr.dime.dim(7);
if max_range == 1
error(['"dim6_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"dim6_idx" should be an integer within the range of [' range '].']);
end
end
% check dim7_idx
%
if ~isempty(dim7_idx) & ~isnumeric(dim7_idx)
error('"dim7_idx" should be a numerical array.');
end
if length(unique(dim7_idx)) ~= length(dim7_idx)
error('Duplicate index in "dim7_idx"');
end
if ~isempty(dim7_idx) & (min(dim7_idx) < 1 | max(dim7_idx) > hdr.dime.dim(8))
max_range = hdr.dime.dim(8);
if max_range == 1
error(['"dim7_idx" should be 1.']);
else
range = ['1 ' num2str(max_range)];
error(['"dim7_idx" should be an integer within the range of [' range '].']);
end
end
[img,hdr] = read_image(hdr,filetype,fileprefix,machine,img_idx,dim5_idx,dim6_idx,dim7_idx,old_RGB);
return % load_nii_img
%---------------------------------------------------------------------
function [img,hdr] = read_image(hdr,filetype,fileprefix,machine,img_idx,dim5_idx,dim6_idx,dim7_idx,old_RGB)
switch filetype
case {0, 1}
fn = [fileprefix '.img'];
case 2
fn = [fileprefix '.nii'];
end
fid = fopen(fn,'r',machine);
if fid < 0,
msg = sprintf('Cannot open file %s.',fn);
error(msg);
end
% Set bitpix according to datatype
%
% /*Acceptable values for datatype are*/
%
% 0 None (Unknown bit per voxel) % DT_NONE, DT_UNKNOWN
% 1 Binary (ubit1, bitpix=1) % DT_BINARY
% 2 Unsigned char (uchar or uint8, bitpix=8) % DT_UINT8, NIFTI_TYPE_UINT8
% 4 Signed short (int16, bitpix=16) % DT_INT16, NIFTI_TYPE_INT16
% 8 Signed integer (int32, bitpix=32) % DT_INT32, NIFTI_TYPE_INT32
% 16 Floating point (single or float32, bitpix=32) % DT_FLOAT32, NIFTI_TYPE_FLOAT32
% 32 Complex, 2 float32 (Use float32, bitpix=64) % DT_COMPLEX64, NIFTI_TYPE_COMPLEX64
% 64 Double precision (double or float64, bitpix=64) % DT_FLOAT64, NIFTI_TYPE_FLOAT64
% 128 uint8 RGB (Use uint8, bitpix=24) % DT_RGB24, NIFTI_TYPE_RGB24
% 256 Signed char (schar or int8, bitpix=8) % DT_INT8, NIFTI_TYPE_INT8
% 511 Single RGB (Use float32, bitpix=96) % DT_RGB96, NIFTI_TYPE_RGB96
% 512 Unsigned short (uint16, bitpix=16) % DT_UNINT16, NIFTI_TYPE_UNINT16
% 768 Unsigned integer (uint32, bitpix=32) % DT_UNINT32, NIFTI_TYPE_UNINT32
% 1024 Signed long long (int64, bitpix=64) % DT_INT64, NIFTI_TYPE_INT64
% 1280 Unsigned long long (uint64, bitpix=64) % DT_UINT64, NIFTI_TYPE_UINT64
% 1536 Long double, float128 (Unsupported, bitpix=128) % DT_FLOAT128, NIFTI_TYPE_FLOAT128
% 1792 Complex128, 2 float64 (Use float64, bitpix=128) % DT_COMPLEX128, NIFTI_TYPE_COMPLEX128
% 2048 Complex256, 2 float128 (Unsupported, bitpix=256) % DT_COMPLEX128, NIFTI_TYPE_COMPLEX128
%
switch hdr.dime.datatype
case 1,
hdr.dime.bitpix = 1; precision = 'ubit1';
case 2,
hdr.dime.bitpix = 8; precision = 'uint8';
case 4,
hdr.dime.bitpix = 16; precision = 'int16';
case 8,
hdr.dime.bitpix = 32; precision = 'int32';
case 16,
hdr.dime.bitpix = 32; precision = 'float32';
case 32,
hdr.dime.bitpix = 64; precision = 'float32';
case 64,
hdr.dime.bitpix = 64; precision = 'float64';
case 128,
hdr.dime.bitpix = 24; precision = 'uint8';
case 256
hdr.dime.bitpix = 8; precision = 'int8';
case 511
hdr.dime.bitpix = 96; precision = 'float32';
case 512
hdr.dime.bitpix = 16; precision = 'uint16';
case 768
hdr.dime.bitpix = 32; precision = 'uint32';
case 1024
hdr.dime.bitpix = 64; precision = 'int64';
case 1280
hdr.dime.bitpix = 64; precision = 'uint64';
case 1792,
hdr.dime.bitpix = 128; precision = 'float64';
otherwise
error('This datatype is not supported');
end
hdr.dime.dim(find(hdr.dime.dim < 1)) = 1;
% move pointer to the start of image block
%
switch filetype
case {0, 1}
fseek(fid, 0, 'bof');
case 2
fseek(fid, hdr.dime.vox_offset, 'bof');
end
% Load whole image block for old Analyze format or binary image;
% otherwise, load images that are specified in img_idx, dim5_idx,
% dim6_idx, and dim7_idx
%
% For binary image, we have to read all because pos can not be
% seeked in bit and can not be calculated the way below.
%
if hdr.dime.datatype == 1 | isequal(hdr.dime.dim(5:8),ones(1,4)) | ...
(isempty(img_idx) & isempty(dim5_idx) & isempty(dim6_idx) & isempty(dim7_idx))
% For each frame, precision of value will be read
% in img_siz times, where img_siz is only the
% dimension size of an image, not the byte storage
% size of an image.
%
img_siz = prod(hdr.dime.dim(2:8));
% For complex float32 or complex float64, voxel values
% include [real, imag]
%
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792
img_siz = img_siz * 2;
end
%MPH: For RGB24, voxel values include 3 separate color planes
%
if hdr.dime.datatype == 128 | hdr.dime.datatype == 511
img_siz = img_siz * 3;
end
img = fread(fid, img_siz, sprintf('*%s',precision));
d1 = hdr.dime.dim(2);
d2 = hdr.dime.dim(3);
d3 = hdr.dime.dim(4);
d4 = hdr.dime.dim(5);
d5 = hdr.dime.dim(6);
d6 = hdr.dime.dim(7);
d7 = hdr.dime.dim(8);
if isempty(img_idx)
img_idx = 1:d4;
end
if isempty(dim5_idx)
dim5_idx = 1:d5;
end
if isempty(dim6_idx)
dim6_idx = 1:d6;
end
if isempty(dim7_idx)
dim7_idx = 1:d7;
end
else
d1 = hdr.dime.dim(2);
d2 = hdr.dime.dim(3);
d3 = hdr.dime.dim(4);
d4 = hdr.dime.dim(5);
d5 = hdr.dime.dim(6);
d6 = hdr.dime.dim(7);
d7 = hdr.dime.dim(8);
if isempty(img_idx)
img_idx = 1:d4;
end
if isempty(dim5_idx)
dim5_idx = 1:d5;
end
if isempty(dim6_idx)
dim6_idx = 1:d6;
end
if isempty(dim7_idx)
dim7_idx = 1:d7;
end
% compute size of one image
%
img_siz = prod(hdr.dime.dim(2:4));
% For complex float32 or complex float64, voxel values
% include [real, imag]
%
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792
img_siz = img_siz * 2;
end
%MPH: For RGB24, voxel values include 3 separate color planes
%
if hdr.dime.datatype == 128 | hdr.dime.datatype == 511
img_siz = img_siz * 3;
end
% preallocate img
img = zeros(img_siz, length(img_idx)*length(dim5_idx)*length(dim6_idx)*length(dim7_idx) );
currentIndex = 1;
for i7=1:length(dim7_idx)
for i6=1:length(dim6_idx)
for i5=1:length(dim5_idx)
for t=1:length(img_idx)
% Position is seeked in bytes. To convert dimension size
% to byte storage size, hdr.dime.bitpix/8 will be
% applied.
%
pos = sub2ind([d1 d2 d3 d4 d5 d6 d7], 1, 1, 1, ...
img_idx(t), dim5_idx(i5),dim6_idx(i6),dim7_idx(i7)) -1;
pos = pos * hdr.dime.bitpix/8;
if filetype == 2
fseek(fid, pos + hdr.dime.vox_offset, 'bof');
else
fseek(fid, pos, 'bof');
end
% For each frame, fread will read precision of value
% in img_siz times
%
img(:,currentIndex) = fread(fid, img_siz, sprintf('*%s',precision));
currentIndex = currentIndex +1;
end
end
end
end
end
% For complex float32 or complex float64, voxel values
% include [real, imag]
%
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792
img = reshape(img, [2, length(img)/2]);
img = complex(img(1,:)', img(2,:)');
end
fclose(fid);
% Update the global min and max values
%
hdr.dime.glmax = double(max(img(:)));
hdr.dime.glmin = double(min(img(:)));
% old_RGB treat RGB slice by slice, now it is treated voxel by voxel
%
if old_RGB & hdr.dime.datatype == 128 & hdr.dime.bitpix == 24
% remove squeeze
img = (reshape(img, [hdr.dime.dim(2:3) 3 hdr.dime.dim(4) length(img_idx) length(dim5_idx) length(dim6_idx) length(dim7_idx)]));
img = permute(img, [1 2 4 3 5 6 7 8]);
elseif hdr.dime.datatype == 128 & hdr.dime.bitpix == 24
% remove squeeze
img = (reshape(img, [3 hdr.dime.dim(2:4) length(img_idx) length(dim5_idx) length(dim6_idx) length(dim7_idx)]));
img = permute(img, [2 3 4 1 5 6 7 8]);
elseif hdr.dime.datatype == 511 & hdr.dime.bitpix == 96
img = double(img(:));
img = single((img - min(img))/(max(img) - min(img)));
% remove squeeze
img = (reshape(img, [3 hdr.dime.dim(2:4) length(img_idx) length(dim5_idx) length(dim6_idx) length(dim7_idx)]));
img = permute(img, [2 3 4 1 5 6 7 8]);
else
% remove squeeze
img = (reshape(img, [hdr.dime.dim(2:4) length(img_idx) length(dim5_idx) length(dim6_idx) length(dim7_idx)]));
end
if ~isempty(img_idx)
hdr.dime.dim(5) = length(img_idx);
end
if ~isempty(dim5_idx)
hdr.dime.dim(6) = length(dim5_idx);
end
if ~isempty(dim6_idx)
hdr.dime.dim(7) = length(dim6_idx);
end
if ~isempty(dim7_idx)
hdr.dime.dim(8) = length(dim7_idx);
end
return % read_image
|
github
|
changken1/IDH_Prediction-master
|
bresenham_line3d.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/bresenham_line3d.m
| 4,493 |
utf_8
|
c19f06df423676afeb59762ac55c0c2f
|
% Generate X Y Z coordinates of a 3D Bresenham's line between
% two given points.
%
% A very useful application of this algorithm can be found in the
% implementation of Fischer's Bresenham interpolation method in my
% another program that can rotate three dimensional image volume
% with an affine matrix:
% http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=21080
%
% Usage: [X Y Z] = bresenham_line3d(P1, P2, [precision]);
%
% P1 - vector for Point1, where P1 = [x1 y1 z1]
%
% P2 - vector for Point2, where P2 = [x2 y2 z2]
%
% precision (optional) - Although according to Bresenham's line
% algorithm, point coordinates x1 y1 z1 and x2 y2 z2 should
% be integer numbers, this program extends its limit to all
% real numbers. If any of them are floating numbers, you
% should specify how many digits of decimal that you would
% like to preserve. Be aware that the length of output X Y
% Z coordinates will increase in 10 times for each decimal
% digit that you want to preserve. By default, the precision
% is 0, which means that they will be rounded to the nearest
% integer.
%
% X - a set of x coordinates on Bresenham's line
%
% Y - a set of y coordinates on Bresenham's line
%
% Z - a set of z coordinates on Bresenham's line
%
% Therefore, all points in XYZ set (i.e. P(i) = [X(i) Y(i) Z(i)])
% will constitute the Bresenham's line between P1 and P1.
%
% Example:
% P1 = [12 37 6]; P2 = [46 3 35];
% [X Y Z] = bresenham_line3d(P1, P2);
% figure; plot3(X,Y,Z,'s','markerface','b');
%
% This program is ported to MATLAB from:
%
% B.Pendleton. line3d - 3D Bresenham's (a 3D line drawing algorithm)
% ftp://ftp.isc.org/pub/usenet/comp.sources.unix/volume26/line3d, 1992
%
% Which is also referenced by:
%
% Fischer, J., A. del Rio (2004). A Fast Method for Applying Rigid
% Transformations to Volume Data, WSCG2004 Conference.
% http://wscg.zcu.cz/wscg2004/Papers_2004_Short/M19.pdf
%
% - Jimmy Shen ([email protected])
%
function [X,Y,Z] = bresenham_line3d(P1, P2, precision)
if ~exist('precision','var') | isempty(precision) | round(precision) == 0
precision = 0;
P1 = round(P1);
P2 = round(P2);
else
precision = round(precision);
P1 = round(P1*(10^precision));
P2 = round(P2*(10^precision));
end
d = max(abs(P2-P1)+1);
X = zeros(1, d);
Y = zeros(1, d);
Z = zeros(1, d);
x1 = P1(1);
y1 = P1(2);
z1 = P1(3);
x2 = P2(1);
y2 = P2(2);
z2 = P2(3);
dx = x2 - x1;
dy = y2 - y1;
dz = z2 - z1;
ax = abs(dx)*2;
ay = abs(dy)*2;
az = abs(dz)*2;
sx = sign(dx);
sy = sign(dy);
sz = sign(dz);
x = x1;
y = y1;
z = z1;
idx = 1;
if(ax>=max(ay,az)) % x dominant
yd = ay - ax/2;
zd = az - ax/2;
while(1)
X(idx) = x;
Y(idx) = y;
Z(idx) = z;
idx = idx + 1;
if(x == x2) % end
break;
end
if(yd >= 0) % move along y
y = y + sy;
yd = yd - ax;
end
if(zd >= 0) % move along z
z = z + sz;
zd = zd - ax;
end
x = x + sx; % move along x
yd = yd + ay;
zd = zd + az;
end
elseif(ay>=max(ax,az)) % y dominant
xd = ax - ay/2;
zd = az - ay/2;
while(1)
X(idx) = x;
Y(idx) = y;
Z(idx) = z;
idx = idx + 1;
if(y == y2) % end
break;
end
if(xd >= 0) % move along x
x = x + sx;
xd = xd - ay;
end
if(zd >= 0) % move along z
z = z + sz;
zd = zd - ay;
end
y = y + sy; % move along y
xd = xd + ax;
zd = zd + az;
end
elseif(az>=max(ax,ay)) % z dominant
xd = ax - az/2;
yd = ay - az/2;
while(1)
X(idx) = x;
Y(idx) = y;
Z(idx) = z;
idx = idx + 1;
if(z == z2) % end
break;
end
if(xd >= 0) % move along x
x = x + sx;
xd = xd - az;
end
if(yd >= 0) % move along y
y = y + sy;
yd = yd - az;
end
z = z + sz; % move along z
xd = xd + ax;
yd = yd + ay;
end
end
if precision ~= 0
X = X/(10^precision);
Y = Y/(10^precision);
Z = Z/(10^precision);
end
return; % bresenham_line3d
|
github
|
changken1/IDH_Prediction-master
|
make_nii.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/make_nii.m
| 6,849 |
utf_8
|
3c7c8b81655c111a9ce4b82086bde4f5
|
% Make NIfTI structure specified by an N-D matrix. Usually, N is 3 for
% 3D matrix [x y z], or 4 for 4D matrix with time series [x y z t].
% Optional parameters can also be included, such as: voxel_size,
% origin, datatype, and description.
%
% Once the NIfTI structure is made, it can be saved into NIfTI file
% using "save_nii" command (for more detail, type: help save_nii).
%
% Usage: nii = make_nii(img, [voxel_size], [origin], [datatype], [description])
%
% Where:
%
% img: Usually, img is a 3D matrix [x y z], or a 4D
% matrix with time series [x y z t]. However,
% NIfTI allows a maximum of 7D matrix. When the
% image is in RGB format, make sure that the size
% of 4th dimension is always 3 (i.e. [R G B]). In
% that case, make sure that you must specify RGB
% datatype, which is either 128 or 511.
%
% voxel_size (optional): Voxel size in millimeter for each
% dimension. Default is [1 1 1].
%
% origin (optional): The AC origin. Default is [0 0 0].
%
% datatype (optional): Storage data type:
% 2 - uint8, 4 - int16, 8 - int32, 16 - float32,
% 32 - complex64, 64 - float64, 128 - RGB24,
% 256 - int8, 511 - RGB96, 512 - uint16,
% 768 - uint32, 1792 - complex128
% Default will use the data type of 'img' matrix
% For RGB image, you must specify it to either 128
% or 511.
%
% description (optional): Description of data. Default is ''.
%
% e.g.:
% origin = [33 44 13]; datatype = 64;
% nii = make_nii(img, [], origin, datatype); % default voxel_size
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function nii = make_nii(varargin)
nii.img = varargin{1};
dims = size(nii.img);
dims = [length(dims) dims ones(1,8)];
dims = dims(1:8);
voxel_size = [0 ones(1,7)];
origin = zeros(1,5);
descrip = '';
switch class(nii.img)
case 'uint8'
datatype = 2;
case 'int16'
datatype = 4;
case 'int32'
datatype = 8;
case 'single'
if isreal(nii.img)
datatype = 16;
else
datatype = 32;
end
case 'double'
if isreal(nii.img)
datatype = 64;
else
datatype = 1792;
end
case 'int8'
datatype = 256;
case 'uint16'
datatype = 512;
case 'uint32'
datatype = 768;
otherwise
error('Datatype is not supported by make_nii.');
end
if nargin > 1 & ~isempty(varargin{2})
voxel_size(2:4) = double(varargin{2});
end
if nargin > 2 & ~isempty(varargin{3})
origin(1:3) = double(varargin{3});
end
if nargin > 3 & ~isempty(varargin{4})
datatype = double(varargin{4});
if datatype == 128 | datatype == 511
dims(5) = [];
dims(1) = dims(1) - 1;
dims = [dims 1];
end
end
if nargin > 4 & ~isempty(varargin{5})
descrip = varargin{5};
end
if ndims(nii.img) > 7
error('NIfTI only allows a maximum of 7 Dimension matrix.');
end
maxval = round(double(max(nii.img(:))));
minval = round(double(min(nii.img(:))));
nii.hdr = make_header(dims, voxel_size, origin, datatype, ...
descrip, maxval, minval);
switch nii.hdr.dime.datatype
case 2
nii.img = uint8(nii.img);
case 4
nii.img = int16(nii.img);
case 8
nii.img = int32(nii.img);
case 16
nii.img = single(nii.img);
case 32
nii.img = single(nii.img);
case 64
nii.img = double(nii.img);
case 128
nii.img = uint8(nii.img);
case 256
nii.img = int8(nii.img);
case 511
img = double(nii.img(:));
img = single((img - min(img))/(max(img) - min(img)));
nii.img = reshape(img, size(nii.img));
nii.hdr.dime.glmax = double(max(img));
nii.hdr.dime.glmin = double(min(img));
case 512
nii.img = uint16(nii.img);
case 768
nii.img = uint32(nii.img);
case 1792
nii.img = double(nii.img);
otherwise
error('Datatype is not supported by make_nii.');
end
return; % make_nii
%---------------------------------------------------------------------
function hdr = make_header(dims, voxel_size, origin, datatype, ...
descrip, maxval, minval)
hdr.hk = header_key;
hdr.dime = image_dimension(dims, voxel_size, datatype, maxval, minval);
hdr.hist = data_history(origin, descrip);
return; % make_header
%---------------------------------------------------------------------
function hk = header_key
hk.sizeof_hdr = 348; % must be 348!
hk.data_type = '';
hk.db_name = '';
hk.extents = 0;
hk.session_error = 0;
hk.regular = 'r';
hk.dim_info = 0;
return; % header_key
%---------------------------------------------------------------------
function dime = image_dimension(dims, voxel_size, datatype, maxval, minval)
dime.dim = dims;
dime.intent_p1 = 0;
dime.intent_p2 = 0;
dime.intent_p3 = 0;
dime.intent_code = 0;
dime.datatype = datatype;
switch dime.datatype
case 2,
dime.bitpix = 8; precision = 'uint8';
case 4,
dime.bitpix = 16; precision = 'int16';
case 8,
dime.bitpix = 32; precision = 'int32';
case 16,
dime.bitpix = 32; precision = 'float32';
case 32,
dime.bitpix = 64; precision = 'float32';
case 64,
dime.bitpix = 64; precision = 'float64';
case 128
dime.bitpix = 24; precision = 'uint8';
case 256
dime.bitpix = 8; precision = 'int8';
case 511
dime.bitpix = 96; precision = 'float32';
case 512
dime.bitpix = 16; precision = 'uint16';
case 768
dime.bitpix = 32; precision = 'uint32';
case 1792,
dime.bitpix = 128; precision = 'float64';
otherwise
error('Datatype is not supported by make_nii.');
end
dime.slice_start = 0;
dime.pixdim = voxel_size;
dime.vox_offset = 0;
dime.scl_slope = 0;
dime.scl_inter = 0;
dime.slice_end = 0;
dime.slice_code = 0;
dime.xyzt_units = 0;
dime.cal_max = 0;
dime.cal_min = 0;
dime.slice_duration = 0;
dime.toffset = 0;
dime.glmax = maxval;
dime.glmin = minval;
return; % image_dimension
%---------------------------------------------------------------------
function hist = data_history(origin, descrip)
hist.descrip = descrip;
hist.aux_file = 'none';
hist.qform_code = 0;
hist.sform_code = 0;
hist.quatern_b = 0;
hist.quatern_c = 0;
hist.quatern_d = 0;
hist.qoffset_x = 0;
hist.qoffset_y = 0;
hist.qoffset_z = 0;
hist.srow_x = zeros(1,4);
hist.srow_y = zeros(1,4);
hist.srow_z = zeros(1,4);
hist.intent_name = '';
hist.magic = '';
hist.originator = origin;
return; % data_history
|
github
|
changken1/IDH_Prediction-master
|
verify_nii_ext.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/verify_nii_ext.m
| 1,676 |
utf_8
|
db3d32ecba688905185f5ed01b409fd1
|
% Verify NIFTI header extension to make sure that each extension section
% must be an integer multiple of 16 byte long that includes the first 8
% bytes of esize and ecode. If the length of extension section is not the
% above mentioned case, edata should be padded with all 0.
%
% Usage: [ext, esize_total] = verify_nii_ext(ext)
%
% ext - Structure of NIFTI header extension, which includes num_ext,
% and all the extended header sections in the header extension.
% Each extended header section will have its esize, ecode, and
% edata, where edata can be plain text, xml, or any raw data
% that was saved in the extended header section.
%
% esize_total - Sum of all esize variable in all header sections.
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function [ext, esize_total] = verify_nii_ext(ext)
if ~isfield(ext, 'section')
error('Incorrect NIFTI header extension structure.');
elseif ~isfield(ext, 'num_ext')
ext.num_ext = length(ext.section);
elseif ~isfield(ext, 'extension')
ext.extension = [1 0 0 0];
end
esize_total = 0;
for i=1:ext.num_ext
if ~isfield(ext.section(i), 'ecode') | ~isfield(ext.section(i), 'edata')
error('Incorrect NIFTI header extension structure.');
end
ext.section(i).esize = ceil((length(ext.section(i).edata)+8)/16)*16;
ext.section(i).edata = ...
[ext.section(i).edata ...
zeros(1,ext.section(i).esize-length(ext.section(i).edata)-8)];
esize_total = esize_total + ext.section(i).esize;
end
return % verify_nii_ext
|
github
|
changken1/IDH_Prediction-master
|
get_nii_frame.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/get_nii_frame.m
| 4,333 |
utf_8
|
8b0cba9d07733a6f82753b0c40b51107
|
% Return time frame of a NIFTI dataset. Support both *.nii and
% *.hdr/*.img file extension. If file extension is not provided,
% *.hdr/*.img will be used as default.
%
% It is a lightweighted "load_nii_hdr", and is equivalent to
% hdr.dime.dim(5)
%
% Usage: [ total_scan ] = get_nii_frame(filename)
%
% filename - NIFTI file name.
%
% Returned values:
%
% total_scan - total number of image scans for the time frame
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function [ total_scan ] = get_nii_frame(filename)
if ~exist('filename','var'),
error('Usage: [ total_scan ] = get_nii_frame(filename)');
end
v = version;
% Check file extension. If .gz, unpack it into temp folder
%
if length(filename) > 2 & strcmp(filename(end-2:end), '.gz')
if ~strcmp(filename(end-6:end), '.img.gz') & ...
~strcmp(filename(end-6:end), '.hdr.gz') & ...
~strcmp(filename(end-6:end), '.nii.gz')
error('Please check filename.');
end
if str2num(v(1:3)) < 7.1 | ~usejava('jvm')
error('Please use MATLAB 7.1 (with java) and above, or run gunzip outside MATLAB.');
elseif strcmp(filename(end-6:end), '.img.gz')
filename1 = filename;
filename2 = filename;
filename2(end-6:end) = '';
filename2 = [filename2, '.hdr.gz'];
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename1 = gunzip(filename1, tmpDir);
filename2 = gunzip(filename2, tmpDir);
filename = char(filename1); % convert from cell to string
elseif strcmp(filename(end-6:end), '.hdr.gz')
filename1 = filename;
filename2 = filename;
filename2(end-6:end) = '';
filename2 = [filename2, '.img.gz'];
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename1 = gunzip(filename1, tmpDir);
filename2 = gunzip(filename2, tmpDir);
filename = char(filename1); % convert from cell to string
elseif strcmp(filename(end-6:end), '.nii.gz')
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename = gunzip(filename, tmpDir);
filename = char(filename); % convert from cell to string
end
end
fileprefix = filename;
machine = 'ieee-le';
new_ext = 0;
if findstr('.nii',fileprefix) & strcmp(fileprefix(end-3:end), '.nii')
new_ext = 1;
fileprefix(end-3:end)='';
end
if findstr('.hdr',fileprefix) & strcmp(fileprefix(end-3:end), '.hdr')
fileprefix(end-3:end)='';
end
if findstr('.img',fileprefix) & strcmp(fileprefix(end-3:end), '.img')
fileprefix(end-3:end)='';
end
if new_ext
fn = sprintf('%s.nii',fileprefix);
if ~exist(fn)
msg = sprintf('Cannot find file "%s.nii".', fileprefix);
error(msg);
end
else
fn = sprintf('%s.hdr',fileprefix);
if ~exist(fn)
msg = sprintf('Cannot find file "%s.hdr".', fileprefix);
error(msg);
end
end
fid = fopen(fn,'r',machine);
if fid < 0,
msg = sprintf('Cannot open file %s.',fn);
error(msg);
else
hdr = read_header(fid);
fclose(fid);
end
if hdr.sizeof_hdr ~= 348
% first try reading the opposite endian to 'machine'
switch machine,
case 'ieee-le', machine = 'ieee-be';
case 'ieee-be', machine = 'ieee-le';
end
fid = fopen(fn,'r',machine);
if fid < 0,
msg = sprintf('Cannot open file %s.',fn);
error(msg);
else
hdr = read_header(fid);
fclose(fid);
end
end
if hdr.sizeof_hdr ~= 348
% Now throw an error
msg = sprintf('File "%s" is corrupted.',fn);
error(msg);
end
total_scan = hdr.dim(5);
% Clean up after gunzip
%
if exist('gzFileName', 'var')
rmdir(tmpDir,'s');
end
return; % get_nii_frame
%---------------------------------------------------------------------
function [ dsr ] = read_header(fid)
fseek(fid,0,'bof');
dsr.sizeof_hdr = fread(fid,1,'int32')'; % should be 348!
fseek(fid,40,'bof');
dsr.dim = fread(fid,8,'int16')';
return; % read_header
|
github
|
changken1/IDH_Prediction-master
|
flip_lr.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/flip_lr.m
| 3,484 |
utf_8
|
a0b2d0189d90339a841863efeb60681a
|
% When you load any ANALYZE or NIfTI file with 'load_nii.m', and view
% it with 'view_nii.m', you may find that the image is L-R flipped.
% This is because of the confusion of radiological and neurological
% convention in the medical image before NIfTI format is adopted. You
% can find more details from:
%
% http://www.rotman-baycrest.on.ca/~jimmy/UseANALYZE.htm
%
% Sometime, people even want to convert RAS (standard orientation) back
% to LAS orientation to satisfy the legend programs or processes. This
% program is only written for those purpose. So PLEASE BE VERY CAUTIOUS
% WHEN USING THIS 'FLIP_LR.M' PROGRAM.
%
% With 'flip_lr.m', you can convert any ANALYZE or NIfTI (no matter
% 3D or 4D) file to a flipped NIfTI file. This is implemented simply
% by flipping the affine matrix in the NIfTI header. Since the L-R
% orientation is determined there, so the image will be flipped.
%
% Usage: flip_lr(original_fn, flipped_fn, [old_RGB],[tolerance],[preferredForm])
%
% original_fn - filename of the original ANALYZE or NIfTI (3D or 4D) file
%
% flipped_fn - filename of the L-R flipped NIfTI file
%
% old_RGB (optional) - a scale number to tell difference of new RGB24
% from old RGB24. New RGB24 uses RGB triple sequentially for each
% voxel, like [R1 G1 B1 R2 G2 B2 ...]. Analyze 6.0 from AnalyzeDirect
% uses old RGB24, in a way like [R1 R2 ... G1 G2 ... B1 B2 ...] for
% each slices. If the image that you view is garbled, try to set
% old_RGB variable to 1 and try again, because it could be in
% old RGB24. It will be set to 0, if it is default or empty.
%
% tolerance (optional) - distortion allowed for non-orthogonal rotation
% or shearing in NIfTI affine matrix. It will be set to 0.1 (10%),
% if it is default or empty.
%
% preferredForm (optional) - selects which transformation from voxels
% to RAS coordinates; values are s,q,S,Q. Lower case s,q indicate
% "prefer sform or qform, but use others if preferred not present".
% Upper case indicate the program is forced to use the specificied
% tranform or fail loading. 'preferredForm' will be 's', if it is
% default or empty. - Jeff Gunter
%
% Example: flip_lr('avg152T1_LR_nifti.nii', 'flipped_lr.nii');
% flip_lr('avg152T1_RL_nifti.nii', 'flipped_rl.nii');
%
% You will find that 'avg152T1_LR_nifti.nii' and 'avg152T1_RL_nifti.nii'
% are the same, and 'flipped_lr.nii' and 'flipped_rl.nii' are also the
% the same, but they are L-R flipped from 'avg152T1_*'.
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function flip_lr(original_fn, flipped_fn, old_RGB, tolerance, preferredForm)
if ~exist('original_fn','var') | ~exist('flipped_fn','var')
error('Usage: flip_lr(original_fn, flipped_fn, [old_RGB],[tolerance])');
end
if ~exist('old_RGB','var') | isempty(old_RGB)
old_RGB = 0;
end
if ~exist('tolerance','var') | isempty(tolerance)
tolerance = 0.1;
end
if ~exist('preferredForm','var') | isempty(preferredForm)
preferredForm= 's'; % Jeff
end
nii = load_nii(original_fn, [], [], [], [], old_RGB, tolerance, preferredForm);
M = diag(nii.hdr.dime.pixdim(2:5));
M(1:3,4) = -M(1:3,1:3)*(nii.hdr.hist.originator(1:3)-1)';
M(1,:) = -1*M(1,:);
nii.hdr.hist.sform_code = 1;
nii.hdr.hist.srow_x = M(1,:);
nii.hdr.hist.srow_y = M(2,:);
nii.hdr.hist.srow_z = M(3,:);
save_nii(nii, flipped_fn);
return; % flip_lr
|
github
|
changken1/IDH_Prediction-master
|
save_nii.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/save_nii.m
| 9,404 |
utf_8
|
88aa93174482539fe993ac335fb01541
|
% Save NIFTI dataset. Support both *.nii and *.hdr/*.img file extension.
% If file extension is not provided, *.hdr/*.img will be used as default.
%
% Usage: save_nii(nii, filename, [old_RGB])
%
% nii.hdr - struct with NIFTI header fields (from load_nii.m or make_nii.m)
%
% nii.img - 3D (or 4D) matrix of NIFTI data.
%
% filename - NIFTI file name.
%
% old_RGB - an optional boolean variable to handle special RGB data
% sequence [R1 R2 ... G1 G2 ... B1 B2 ...] that is used only by
% AnalyzeDirect (Analyze Software). Since both NIfTI and Analyze
% file format use RGB triple [R1 G1 B1 R2 G2 B2 ...] sequentially
% for each voxel, this variable is set to FALSE by default. If you
% would like the saved image only to be opened by AnalyzeDirect
% Software, set old_RGB to TRUE (or 1). It will be set to 0, if it
% is default or empty.
%
% Tip: to change the data type, set nii.hdr.dime.datatype,
% and nii.hdr.dime.bitpix to:
%
% 0 None (Unknown bit per voxel) % DT_NONE, DT_UNKNOWN
% 1 Binary (ubit1, bitpix=1) % DT_BINARY
% 2 Unsigned char (uchar or uint8, bitpix=8) % DT_UINT8, NIFTI_TYPE_UINT8
% 4 Signed short (int16, bitpix=16) % DT_INT16, NIFTI_TYPE_INT16
% 8 Signed integer (int32, bitpix=32) % DT_INT32, NIFTI_TYPE_INT32
% 16 Floating point (single or float32, bitpix=32) % DT_FLOAT32, NIFTI_TYPE_FLOAT32
% 32 Complex, 2 float32 (Use float32, bitpix=64) % DT_COMPLEX64, NIFTI_TYPE_COMPLEX64
% 64 Double precision (double or float64, bitpix=64) % DT_FLOAT64, NIFTI_TYPE_FLOAT64
% 128 uint RGB (Use uint8, bitpix=24) % DT_RGB24, NIFTI_TYPE_RGB24
% 256 Signed char (schar or int8, bitpix=8) % DT_INT8, NIFTI_TYPE_INT8
% 511 Single RGB (Use float32, bitpix=96) % DT_RGB96, NIFTI_TYPE_RGB96
% 512 Unsigned short (uint16, bitpix=16) % DT_UNINT16, NIFTI_TYPE_UNINT16
% 768 Unsigned integer (uint32, bitpix=32) % DT_UNINT32, NIFTI_TYPE_UNINT32
% 1024 Signed long long (int64, bitpix=64) % DT_INT64, NIFTI_TYPE_INT64
% 1280 Unsigned long long (uint64, bitpix=64) % DT_UINT64, NIFTI_TYPE_UINT64
% 1536 Long double, float128 (Unsupported, bitpix=128) % DT_FLOAT128, NIFTI_TYPE_FLOAT128
% 1792 Complex128, 2 float64 (Use float64, bitpix=128) % DT_COMPLEX128, NIFTI_TYPE_COMPLEX128
% 2048 Complex256, 2 float128 (Unsupported, bitpix=256) % DT_COMPLEX128, NIFTI_TYPE_COMPLEX128
%
% Part of this file is copied and modified from:
% http://www.mathworks.com/matlabcentral/fileexchange/1878-mri-analyze-tools
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
% - "old_RGB" related codes in "save_nii.m" are added by Mike Harms (2006.06.28)
%
function save_nii(nii, fileprefix, old_RGB)
if ~exist('nii','var') | isempty(nii) | ~isfield(nii,'hdr') | ...
~isfield(nii,'img') | ~exist('fileprefix','var') | isempty(fileprefix)
error('Usage: save_nii(nii, filename, [old_RGB])');
end
if isfield(nii,'untouch') & nii.untouch == 1
error('Usage: please use ''save_untouch_nii.m'' for the untouched structure.');
end
if ~exist('old_RGB','var') | isempty(old_RGB)
old_RGB = 0;
end
v = version;
% Check file extension. If .gz, unpack it into temp folder
%
if length(fileprefix) > 2 & strcmp(fileprefix(end-2:end), '.gz')
if ~strcmp(fileprefix(end-6:end), '.img.gz') & ...
~strcmp(fileprefix(end-6:end), '.hdr.gz') & ...
~strcmp(fileprefix(end-6:end), '.nii.gz')
error('Please check filename.');
end
if str2num(v(1:3)) < 7.1 | ~usejava('jvm')
error('Please use MATLAB 7.1 (with java) and above, or run gunzip outside MATLAB.');
else
gzFile = 1;
fileprefix = fileprefix(1:end-3);
end
end
filetype = 1;
% Note: fileprefix is actually the filename you want to save
%
if findstr('.nii',fileprefix) & strcmp(fileprefix(end-3:end), '.nii')
filetype = 2;
fileprefix(end-3:end)='';
end
if findstr('.hdr',fileprefix) & strcmp(fileprefix(end-3:end), '.hdr')
fileprefix(end-3:end)='';
end
if findstr('.img',fileprefix) & strcmp(fileprefix(end-3:end), '.img')
fileprefix(end-3:end)='';
end
write_nii(nii, filetype, fileprefix, old_RGB);
% gzip output file if requested
%
if exist('gzFile', 'var')
if filetype == 1
gzip([fileprefix, '.img']);
delete([fileprefix, '.img']);
gzip([fileprefix, '.hdr']);
delete([fileprefix, '.hdr']);
elseif filetype == 2
gzip([fileprefix, '.nii']);
delete([fileprefix, '.nii']);
end;
end;
if filetype == 1
% So earlier versions of SPM can also open it with correct originator
%
M=[[diag(nii.hdr.dime.pixdim(2:4)) -[nii.hdr.hist.originator(1:3).*nii.hdr.dime.pixdim(2:4)]'];[0 0 0 1]];
save([fileprefix '.mat'], 'M');
end
return % save_nii
%-----------------------------------------------------------------------------------
function write_nii(nii, filetype, fileprefix, old_RGB)
hdr = nii.hdr;
if isfield(nii,'ext') & ~isempty(nii.ext)
ext = nii.ext;
[ext, esize_total] = verify_nii_ext(ext);
else
ext = [];
end
switch double(hdr.dime.datatype),
case 1,
hdr.dime.bitpix = int16(1 ); precision = 'ubit1';
case 2,
hdr.dime.bitpix = int16(8 ); precision = 'uint8';
case 4,
hdr.dime.bitpix = int16(16); precision = 'int16';
case 8,
hdr.dime.bitpix = int16(32); precision = 'int32';
case 16,
hdr.dime.bitpix = int16(32); precision = 'float32';
case 32,
hdr.dime.bitpix = int16(64); precision = 'float32';
case 64,
hdr.dime.bitpix = int16(64); precision = 'float64';
case 128,
hdr.dime.bitpix = int16(24); precision = 'uint8';
case 256
hdr.dime.bitpix = int16(8 ); precision = 'int8';
case 511,
hdr.dime.bitpix = int16(96); precision = 'float32';
case 512
hdr.dime.bitpix = int16(16); precision = 'uint16';
case 768
hdr.dime.bitpix = int16(32); precision = 'uint32';
case 1024
hdr.dime.bitpix = int16(64); precision = 'int64';
case 1280
hdr.dime.bitpix = int16(64); precision = 'uint64';
case 1792,
hdr.dime.bitpix = int16(128); precision = 'float64';
otherwise
error('This datatype is not supported');
end
hdr.dime.glmax = round(double(max(nii.img(:))));
hdr.dime.glmin = round(double(min(nii.img(:))));
if filetype == 2
fid = fopen(sprintf('%s.nii',fileprefix),'w');
if fid < 0,
msg = sprintf('Cannot open file %s.nii.',fileprefix);
error(msg);
end
hdr.dime.vox_offset = 352;
if ~isempty(ext)
hdr.dime.vox_offset = hdr.dime.vox_offset + esize_total;
end
hdr.hist.magic = 'n+1';
save_nii_hdr(hdr, fid);
if ~isempty(ext)
save_nii_ext(ext, fid);
end
else
fid = fopen(sprintf('%s.hdr',fileprefix),'w');
if fid < 0,
msg = sprintf('Cannot open file %s.hdr.',fileprefix);
error(msg);
end
hdr.dime.vox_offset = 0;
hdr.hist.magic = 'ni1';
save_nii_hdr(hdr, fid);
if ~isempty(ext)
save_nii_ext(ext, fid);
end
fclose(fid);
fid = fopen(sprintf('%s.img',fileprefix),'w');
end
ScanDim = double(hdr.dime.dim(5)); % t
SliceDim = double(hdr.dime.dim(4)); % z
RowDim = double(hdr.dime.dim(3)); % y
PixelDim = double(hdr.dime.dim(2)); % x
SliceSz = double(hdr.dime.pixdim(4));
RowSz = double(hdr.dime.pixdim(3));
PixelSz = double(hdr.dime.pixdim(2));
x = 1:PixelDim;
if filetype == 2 & isempty(ext)
skip_bytes = double(hdr.dime.vox_offset) - 348;
else
skip_bytes = 0;
end
if double(hdr.dime.datatype) == 128
% RGB planes are expected to be in the 4th dimension of nii.img
%
if(size(nii.img,4)~=3)
error(['The NII structure does not appear to have 3 RGB color planes in the 4th dimension']);
end
if old_RGB
nii.img = permute(nii.img, [1 2 4 3 5 6 7 8]);
else
nii.img = permute(nii.img, [4 1 2 3 5 6 7 8]);
end
end
if double(hdr.dime.datatype) == 511
% RGB planes are expected to be in the 4th dimension of nii.img
%
if(size(nii.img,4)~=3)
error(['The NII structure does not appear to have 3 RGB color planes in the 4th dimension']);
end
if old_RGB
nii.img = permute(nii.img, [1 2 4 3 5 6 7 8]);
else
nii.img = permute(nii.img, [4 1 2 3 5 6 7 8]);
end
end
% For complex float32 or complex float64, voxel values
% include [real, imag]
%
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792
real_img = real(nii.img(:))';
nii.img = imag(nii.img(:))';
nii.img = [real_img; nii.img];
end
if skip_bytes
fwrite(fid, zeros(1,skip_bytes), 'uint8');
end
fwrite(fid, nii.img, precision);
% fwrite(fid, nii.img, precision, skip_bytes); % error using skip
fclose(fid);
return; % write_nii
|
github
|
changken1/IDH_Prediction-master
|
rri_file_menu.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/rri_file_menu.m
| 3,974 |
utf_8
|
1ec91620ceb4108dde9a63945380028f
|
% Imbed a file menu to any figure. If file menu exist, it will append
% to the existing file menu. This file menu includes: Copy to clipboard,
% print, save, close etc.
%
% Usage: rri_file_menu(fig);
%
% rri_file_menu(fig,0) means no 'Close' menu.
%
% - Jimmy Shen ([email protected])
%
%--------------------------------------------------------------------
function rri_file_menu(action, varargin)
if isnumeric(action)
fig = action;
action = 'init';
end
% clear the message line,
%
h = findobj(gcf,'Tag','MessageLine');
set(h,'String','');
if ~strcmp(action, 'init')
set(gcbf, 'InvertHardcopy','off');
% set(gcbf, 'PaperPositionMode','auto');
end
switch action
case {'init'}
if nargin > 1
init(fig, 1); % no 'close' menu
else
init(fig, 0);
end
case {'print_fig'}
printdlg(gcbf);
case {'copy_fig'}
copy_fig;
case {'export_fig'}
export_fig;
end
return % rri_file_menu
%------------------------------------------------
%
% Create (or append) File menu
%
function init(fig, no_close)
% search for file menu
%
h_file = [];
menuitems = findobj(fig, 'type', 'uimenu');
for i=1:length(menuitems)
filelabel = get(menuitems(i),'label');
if strcmpi(strrep(filelabel, '&', ''), 'file')
h_file = menuitems(i);
break;
end
end
set(fig, 'menubar', 'none');
if isempty(h_file)
if isempty(menuitems)
h_file = uimenu('parent', fig, 'label', 'File');
else
h_file = uimenu('parent', fig, 'label', 'Copy Figure');
end
h1 = uimenu('parent', h_file, ...
'callback','rri_file_menu(''copy_fig'');', ...
'label','Copy to Clipboard');
else
h1 = uimenu('parent', h_file, ...
'callback','rri_file_menu(''copy_fig'');', ...
'separator','on', ...
'label','Copy to Clipboard');
end
h2 = uimenu(h_file, ...
'callback','pagesetupdlg(gcbf);', ...
'label','Page Setup...');
h2 = uimenu(h_file, ...
'callback','printpreview(gcbf);', ...
'label','Print Preview...');
h2 = uimenu('parent', h_file, ...
'callback','printdlg(gcbf);', ...
'label','Print Figure ...');
h2 = uimenu('parent', h_file, ...
'callback','rri_file_menu(''export_fig'');', ...
'label','Save Figure ...');
arch = computer;
if ~strcmpi(arch(1:2),'PC')
set(h1, 'enable', 'off');
end
if ~no_close
h1 = uimenu('parent', h_file, ...
'callback','close(gcbf);', ...
'separator','on', ...
'label','Close');
end
return; % init
%------------------------------------------------
%
% Copy to clipboard
%
function copy_fig
arch = computer;
if(~strcmpi(arch(1:2),'PC'))
error('copy to clipboard can only be used under MS Windows');
return;
end
print -noui -dbitmap;
return % copy_fig
%------------------------------------------------
%
% Save as an image file
%
function export_fig
curr = pwd;
if isempty(curr)
curr = filesep;
end
[selected_file, selected_path] = rri_select_file(curr,'Save As');
if isempty(selected_file) | isempty(selected_path)
return;
end
filename = [selected_path selected_file];
if(exist(filename,'file')==2) % file exist
dlg_title = 'Confirm File Overwrite';
msg = ['File ',filename,' exist. Are you sure you want to overwrite it?'];
response = questdlg(msg,dlg_title,'Yes','No','Yes');
if(strcmp(response,'No'))
return;
end
end
old_pointer = get(gcbf,'pointer');
set(gcbf,'pointer','watch');
try
saveas(gcbf,filename);
catch
msg = 'ERROR: Cannot save file';
set(findobj(gcf,'Tag','MessageLine'),'String',msg);
end
set(gcbf,'pointer',old_pointer);
return; % export_fig
|
github
|
changken1/IDH_Prediction-master
|
reslice_nii.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/reslice_nii.m
| 9,817 |
utf_8
|
05783cd4f127a22486db67a9cc89ad2a
|
% The basic application of the 'reslice_nii.m' program is to perform
% any 3D affine transform defined by a NIfTI format image.
%
% In addition, the 'reslice_nii.m' program can also be applied to
% generate an isotropic image from either a NIfTI format image or
% an ANALYZE format image.
%
% The resliced NIfTI file will always be in RAS orientation.
%
% This program only supports real integer or floating-point data type.
% For other data type, the program will exit with an error message
% "Transform of this NIFTI data is not supported by the program".
%
% Usage: reslice_nii(old_fn, new_fn, [voxel_size], [verbose], [bg], ...
% [method], [img_idx], [preferredForm]);
%
% old_fn - filename for original NIfTI file
%
% new_fn - filename for resliced NIfTI file
%
% voxel_size (optional) - size of a voxel in millimeter along x y z
% direction for resliced NIfTI file. 'voxel_size' will use
% the minimum voxel_size in original NIfTI header,
% if it is default or empty.
%
% verbose (optional) - 1, 0
% 1: show transforming progress in percentage
% 2: progress will not be displayed
% 'verbose' is 1 if it is default or empty.
%
% bg (optional) - background voxel intensity in any extra corner that
% is caused by 3D interpolation. 0 in most cases. 'bg'
% will be the average of two corner voxel intensities
% in original image volume, if it is default or empty.
%
% method (optional) - 1, 2, or 3
% 1: for Trilinear interpolation
% 2: for Nearest Neighbor interpolation
% 3: for Fischer's Bresenham interpolation
% 'method' is 1 if it is default or empty.
%
% img_idx (optional) - a numerical array of image volume indices. Only
% the specified volumes will be loaded. All available image
% volumes will be loaded, if it is default or empty.
%
% The number of images scans can be obtained from get_nii_frame.m,
% or simply: hdr.dime.dim(5).
%
% preferredForm (optional) - selects which transformation from voxels
% to RAS coordinates; values are s,q,S,Q. Lower case s,q indicate
% "prefer sform or qform, but use others if preferred not present".
% Upper case indicate the program is forced to use the specificied
% tranform or fail loading. 'preferredForm' will be 's', if it is
% default or empty. - Jeff Gunter
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function reslice_nii(old_fn, new_fn, voxel_size, verbose, bg, method, img_idx, preferredForm)
if ~exist('old_fn','var') | ~exist('new_fn','var')
error('Usage: reslice_nii(old_fn, new_fn, [voxel_size], [verbose], [bg], [method], [img_idx])');
end
if ~exist('method','var') | isempty(method)
method = 1;
end
if ~exist('img_idx','var') | isempty(img_idx)
img_idx = [];
end
if ~exist('verbose','var') | isempty(verbose)
verbose = 1;
end
if ~exist('preferredForm','var') | isempty(preferredForm)
preferredForm= 's'; % Jeff
end
nii = load_nii_no_xform(old_fn, img_idx, 0, preferredForm);
if ~ismember(nii.hdr.dime.datatype, [2,4,8,16,64,256,512,768])
error('Transform of this NIFTI data is not supported by the program.');
end
if ~exist('voxel_size','var') | isempty(voxel_size)
voxel_size = abs(min(nii.hdr.dime.pixdim(2:4)))*ones(1,3);
elseif length(voxel_size) < 3
voxel_size = abs(voxel_size(1))*ones(1,3);
end
if ~exist('bg','var') | isempty(bg)
bg = mean([nii.img(1) nii.img(end)]);
end
old_M = nii.hdr.hist.old_affine;
if nii.hdr.dime.dim(5) > 1
for i = 1:nii.hdr.dime.dim(5)
if verbose
fprintf('Reslicing %d of %d volumes.\n', i, nii.hdr.dime.dim(5));
end
[img(:,:,:,i) M] = ...
affine(nii.img(:,:,:,i), old_M, voxel_size, verbose, bg, method);
end
else
[img M] = affine(nii.img, old_M, voxel_size, verbose, bg, method);
end
new_dim = size(img);
nii.img = img;
nii.hdr.dime.dim(2:4) = new_dim(1:3);
nii.hdr.dime.datatype = 16;
nii.hdr.dime.bitpix = 32;
nii.hdr.dime.pixdim(2:4) = voxel_size(:)';
nii.hdr.dime.glmax = max(img(:));
nii.hdr.dime.glmin = min(img(:));
nii.hdr.hist.qform_code = 0;
nii.hdr.hist.sform_code = 1;
nii.hdr.hist.srow_x = M(1,:);
nii.hdr.hist.srow_y = M(2,:);
nii.hdr.hist.srow_z = M(3,:);
nii.hdr.hist.new_affine = M;
save_nii(nii, new_fn);
return; % reslice_nii
%--------------------------------------------------------------------
function [nii] = load_nii_no_xform(filename, img_idx, old_RGB, preferredForm)
if ~exist('filename','var'),
error('Usage: [nii] = load_nii(filename, [img_idx], [old_RGB])');
end
if ~exist('img_idx','var'), img_idx = []; end
if ~exist('old_RGB','var'), old_RGB = 0; end
if ~exist('preferredForm','var'), preferredForm= 's'; end % Jeff
v = version;
% Check file extension. If .gz, unpack it into temp folder
%
if length(filename) > 2 & strcmp(filename(end-2:end), '.gz')
if ~strcmp(filename(end-6:end), '.img.gz') & ...
~strcmp(filename(end-6:end), '.hdr.gz') & ...
~strcmp(filename(end-6:end), '.nii.gz')
error('Please check filename.');
end
if str2num(v(1:3)) < 7.1 | ~usejava('jvm')
error('Please use MATLAB 7.1 (with java) and above, or run gunzip outside MATLAB.');
elseif strcmp(filename(end-6:end), '.img.gz')
filename1 = filename;
filename2 = filename;
filename2(end-6:end) = '';
filename2 = [filename2, '.hdr.gz'];
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename1 = gunzip(filename1, tmpDir);
filename2 = gunzip(filename2, tmpDir);
filename = char(filename1); % convert from cell to string
elseif strcmp(filename(end-6:end), '.hdr.gz')
filename1 = filename;
filename2 = filename;
filename2(end-6:end) = '';
filename2 = [filename2, '.img.gz'];
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename1 = gunzip(filename1, tmpDir);
filename2 = gunzip(filename2, tmpDir);
filename = char(filename1); % convert from cell to string
elseif strcmp(filename(end-6:end), '.nii.gz')
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename = gunzip(filename, tmpDir);
filename = char(filename); % convert from cell to string
end
end
% Read the dataset header
%
[nii.hdr,nii.filetype,nii.fileprefix,nii.machine] = load_nii_hdr(filename);
% Read the header extension
%
% nii.ext = load_nii_ext(filename);
% Read the dataset body
%
[nii.img,nii.hdr] = ...
load_nii_img(nii.hdr,nii.filetype,nii.fileprefix,nii.machine,img_idx,'','','',old_RGB);
% Perform some of sform/qform transform
%
% nii = xform_nii(nii, preferredForm);
% Clean up after gunzip
%
if exist('gzFileName', 'var')
% fix fileprefix so it doesn't point to temp location
%
nii.fileprefix = gzFileName(1:end-7);
rmdir(tmpDir,'s');
end
hdr = nii.hdr;
% NIFTI can have both sform and qform transform. This program
% will check sform_code prior to qform_code by default.
%
% If user specifys "preferredForm", user can then choose the
% priority. - Jeff
%
useForm=[]; % Jeff
if isequal(preferredForm,'S')
if isequal(hdr.hist.sform_code,0)
error('User requires sform, sform not set in header');
else
useForm='s';
end
end % Jeff
if isequal(preferredForm,'Q')
if isequal(hdr.hist.qform_code,0)
error('User requires sform, sform not set in header');
else
useForm='q';
end
end % Jeff
if isequal(preferredForm,'s')
if hdr.hist.sform_code > 0
useForm='s';
elseif hdr.hist.qform_code > 0
useForm='q';
end
end % Jeff
if isequal(preferredForm,'q')
if hdr.hist.qform_code > 0
useForm='q';
elseif hdr.hist.sform_code > 0
useForm='s';
end
end % Jeff
if isequal(useForm,'s')
R = [hdr.hist.srow_x(1:3)
hdr.hist.srow_y(1:3)
hdr.hist.srow_z(1:3)];
T = [hdr.hist.srow_x(4)
hdr.hist.srow_y(4)
hdr.hist.srow_z(4)];
nii.hdr.hist.old_affine = [ [R;[0 0 0]] [T;1] ];
elseif isequal(useForm,'q')
b = hdr.hist.quatern_b;
c = hdr.hist.quatern_c;
d = hdr.hist.quatern_d;
if 1.0-(b*b+c*c+d*d) < 0
if abs(1.0-(b*b+c*c+d*d)) < 1e-5
a = 0;
else
error('Incorrect quaternion values in this NIFTI data.');
end
else
a = sqrt(1.0-(b*b+c*c+d*d));
end
qfac = hdr.dime.pixdim(1);
i = hdr.dime.pixdim(2);
j = hdr.dime.pixdim(3);
k = qfac * hdr.dime.pixdim(4);
R = [a*a+b*b-c*c-d*d 2*b*c-2*a*d 2*b*d+2*a*c
2*b*c+2*a*d a*a+c*c-b*b-d*d 2*c*d-2*a*b
2*b*d-2*a*c 2*c*d+2*a*b a*a+d*d-c*c-b*b];
T = [hdr.hist.qoffset_x
hdr.hist.qoffset_y
hdr.hist.qoffset_z];
nii.hdr.hist.old_affine = [ [R * diag([i j k]);[0 0 0]] [T;1] ];
elseif nii.filetype == 0 & exist([nii.fileprefix '.mat'],'file')
load([nii.fileprefix '.mat']); % old SPM affine matrix
R=M(1:3,1:3);
T=M(1:3,4);
T=R*ones(3,1)+T;
M(1:3,4)=T;
nii.hdr.hist.old_affine = M;
else
M = diag(hdr.dime.pixdim(2:5));
M(1:3,4) = -M(1:3,1:3)*(hdr.hist.originator(1:3)-1)';
M(4,4) = 1;
nii.hdr.hist.old_affine = M;
end
return % load_nii_no_xform
|
github
|
changken1/IDH_Prediction-master
|
save_untouch_nii.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/save_untouch_nii.m
| 6,494 |
utf_8
|
50fa95cbb847654356241a853328f912
|
% Save NIFTI or ANALYZE dataset that is loaded by "load_untouch_nii.m".
% The output image format and file extension will be the same as the
% input one (NIFTI.nii, NIFTI.img or ANALYZE.img). Therefore, any file
% extension that you specified will be ignored.
%
% Usage: save_untouch_nii(nii, filename)
%
% nii - nii structure that is loaded by "load_untouch_nii.m"
%
% filename - NIFTI or ANALYZE file name.
%
% - Jimmy Shen ([email protected])
%
function save_untouch_nii(nii, filename)
if ~exist('nii','var') | isempty(nii) | ~isfield(nii,'hdr') | ...
~isfield(nii,'img') | ~exist('filename','var') | isempty(filename)
error('Usage: save_untouch_nii(nii, filename)');
end
if ~isfield(nii,'untouch') | nii.untouch == 0
error('Usage: please use ''save_nii.m'' for the modified structure.');
end
if isfield(nii.hdr.hist,'magic') & strcmp(nii.hdr.hist.magic(1:3),'ni1')
filetype = 1;
elseif isfield(nii.hdr.hist,'magic') & strcmp(nii.hdr.hist.magic(1:3),'n+1')
filetype = 2;
else
filetype = 0;
end
v = version;
% Check file extension. If .gz, unpack it into temp folder
%
if length(filename) > 2 & strcmp(filename(end-2:end), '.gz')
if ~strcmp(filename(end-6:end), '.img.gz') & ...
~strcmp(filename(end-6:end), '.hdr.gz') & ...
~strcmp(filename(end-6:end), '.nii.gz')
error('Please check filename.');
end
if str2num(v(1:3)) < 7.1 | ~usejava('jvm')
error('Please use MATLAB 7.1 (with java) and above, or run gunzip outside MATLAB.');
else
gzFile = 1;
filename = filename(1:end-3);
end
end
[p,f] = fileparts(filename);
fileprefix = fullfile(p, f);
write_nii(nii, filetype, fileprefix);
% gzip output file if requested
%
if exist('gzFile', 'var')
if filetype == 1
gzip([fileprefix, '.img']);
delete([fileprefix, '.img']);
gzip([fileprefix, '.hdr']);
delete([fileprefix, '.hdr']);
elseif filetype == 2
gzip([fileprefix, '.nii']);
delete([fileprefix, '.nii']);
end;
end;
% % So earlier versions of SPM can also open it with correct originator
% %
% if filetype == 0
% M=[[diag(nii.hdr.dime.pixdim(2:4)) -[nii.hdr.hist.originator(1:3).*nii.hdr.dime.pixdim(2:4)]'];[0 0 0 1]];
% save(fileprefix, 'M');
% elseif filetype == 1
% M=[];
% save(fileprefix, 'M');
%end
return % save_untouch_nii
%-----------------------------------------------------------------------------------
function write_nii(nii, filetype, fileprefix)
hdr = nii.hdr;
if isfield(nii,'ext') & ~isempty(nii.ext)
ext = nii.ext;
[ext, esize_total] = verify_nii_ext(ext);
else
ext = [];
end
switch double(hdr.dime.datatype),
case 1,
hdr.dime.bitpix = int16(1 ); precision = 'ubit1';
case 2,
hdr.dime.bitpix = int16(8 ); precision = 'uint8';
case 4,
hdr.dime.bitpix = int16(16); precision = 'int16';
case 8,
hdr.dime.bitpix = int16(32); precision = 'int32';
case 16,
hdr.dime.bitpix = int16(32); precision = 'float32';
case 32,
hdr.dime.bitpix = int16(64); precision = 'float32';
case 64,
hdr.dime.bitpix = int16(64); precision = 'float64';
case 128,
hdr.dime.bitpix = int16(24); precision = 'uint8';
case 256
hdr.dime.bitpix = int16(8 ); precision = 'int8';
case 512
hdr.dime.bitpix = int16(16); precision = 'uint16';
case 768
hdr.dime.bitpix = int16(32); precision = 'uint32';
case 1024
hdr.dime.bitpix = int16(64); precision = 'int64';
case 1280
hdr.dime.bitpix = int16(64); precision = 'uint64';
case 1792,
hdr.dime.bitpix = int16(128); precision = 'float64';
otherwise
error('This datatype is not supported');
end
% hdr.dime.glmax = round(double(max(nii.img(:))));
% hdr.dime.glmin = round(double(min(nii.img(:))));
if filetype == 2
fid = fopen(sprintf('%s.nii',fileprefix),'w');
if fid < 0,
msg = sprintf('Cannot open file %s.nii.',fileprefix);
error(msg);
end
hdr.dime.vox_offset = 352;
if ~isempty(ext)
hdr.dime.vox_offset = hdr.dime.vox_offset + esize_total;
end
hdr.hist.magic = 'n+1';
save_untouch_nii_hdr(hdr, fid);
if ~isempty(ext)
save_nii_ext(ext, fid);
end
elseif filetype == 1
fid = fopen(sprintf('%s.hdr',fileprefix),'w');
if fid < 0,
msg = sprintf('Cannot open file %s.hdr.',fileprefix);
error(msg);
end
hdr.dime.vox_offset = 0;
hdr.hist.magic = 'ni1';
save_untouch_nii_hdr(hdr, fid);
if ~isempty(ext)
save_nii_ext(ext, fid);
end
fclose(fid);
fid = fopen(sprintf('%s.img',fileprefix),'w');
else
fid = fopen(sprintf('%s.hdr',fileprefix),'w');
if fid < 0,
msg = sprintf('Cannot open file %s.hdr.',fileprefix);
error(msg);
end
save_untouch0_nii_hdr(hdr, fid);
fclose(fid);
fid = fopen(sprintf('%s.img',fileprefix),'w');
end
ScanDim = double(hdr.dime.dim(5)); % t
SliceDim = double(hdr.dime.dim(4)); % z
RowDim = double(hdr.dime.dim(3)); % y
PixelDim = double(hdr.dime.dim(2)); % x
SliceSz = double(hdr.dime.pixdim(4));
RowSz = double(hdr.dime.pixdim(3));
PixelSz = double(hdr.dime.pixdim(2));
x = 1:PixelDim;
if filetype == 2 & isempty(ext)
skip_bytes = double(hdr.dime.vox_offset) - 348;
else
skip_bytes = 0;
end
if double(hdr.dime.datatype) == 128
% RGB planes are expected to be in the 4th dimension of nii.img
%
if(size(nii.img,4)~=3)
error(['The NII structure does not appear to have 3 RGB color planes in the 4th dimension']);
end
nii.img = permute(nii.img, [4 1 2 3 5 6 7 8]);
end
% For complex float32 or complex float64, voxel values
% include [real, imag]
%
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792
real_img = real(nii.img(:))';
nii.img = imag(nii.img(:))';
nii.img = [real_img; nii.img];
end
if skip_bytes
fwrite(fid, zeros(1,skip_bytes), 'uint8');
end
fwrite(fid, nii.img, precision);
% fwrite(fid, nii.img, precision, skip_bytes); % error using skip
fclose(fid);
return; % write_nii
|
github
|
changken1/IDH_Prediction-master
|
view_nii.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/view_nii.m
| 139,608 |
utf_8
|
74f9dea7539a45a7993beb22becf2fa2
|
% VIEW_NII: Create or update a 3-View (Front, Top, Side) of the
% brain data that is specified by nii structure
%
% Usage: status = view_nii([h], nii, [option]) or
% status = view_nii(h, [option])
%
% Where, h is the figure on which the 3-View will be plotted;
% nii is the brain data in NIFTI format;
% option is a struct that configures the view plotted, can be:
%
% option.command = 'init'
% option.command = 'update'
% option.command = 'clearnii'
% option.command = 'updatenii'
% option.command = 'updateimg' (nii is nii.img here)
%
% option.usecolorbar = 0 | [1]
% option.usepanel = 0 | [1]
% option.usecrosshair = 0 | [1]
% option.usestretch = 0 | [1]
% option.useimagesc = 0 | [1]
% option.useinterp = [0] | 1
%
% option.setarea = [x y w h] | [0.05 0.05 0.9 0.9]
% option.setunit = ['vox'] | 'mm'
% option.setviewpoint = [x y z] | [origin]
% option.setscanid = [t] | [1]
% option.setcrosshaircolor = [r g b] | [1 0 0]
% option.setcolorindex = From 1 to 9 (default is 2 or 3)
% option.setcolormap = (Mx3 matrix, 0 <= val <= 1)
% option.setcolorlevel = No more than 256 (default 256)
% option.sethighcolor = []
% option.setcbarminmax = []
% option.setvalue = []
% option.glblocminmax = []
% option.setbuttondown = ''
% option.setcomplex = [0] | 1 | 2
%
% Options description in detail:
% ==============================
%
% 1. command: A char string that can control program.
%
% init: If option.command='init', the program will display
% a 3-View plot on the figure specified by figure h
% or on a new figure. If there is already a 3-View
% plot on the figure, please use option.command =
% 'updatenii' (see detail below); otherwise, the
% new 3-View plot will superimpose on the old one.
% If there is no option provided, the program will
% assume that this is an initial plot. If the figure
% handle is omitted, the program knows that it is
% an initial plot.
%
% update: If there is no command specified, and a figure
% handle of the existing 3-View plot is provided,
% the program will choose option.command='update'
% to update the 3-View plot with some new option
% items.
%
% clearnii: Clear 3-View plot on specific figure
%
% updatenii: If a new nii is going to be loaded on a fig
% that has already 3-View plot on it, use this
% command to clear existing 3-View plot, and then
% display with new nii. So, the new nii will not
% superimpose on the existing one. All options
% for 'init' can be used for 'updatenii'.
%
% updateimg: If a new 3D matrix with the same dimension
% is going to be loaded, option.command='updateimg'
% can be used as a light-weighted 'updatenii, since
% it only updates the 3 slices with new values.
% inputing argument nii should be a 3D matrix
% (nii.img) instead of nii struct. No other option
% should be used together with 'updateimg' to keep
% this command as simple as possible.
%
%
% 2. usecolorbar: If specified and usecolorbar=0, the program
% will not include the colorbar in plot area; otherwise,
% a colorbar will be included in plot area.
%
% 3. usepanel: If specified and usepanel=0, the control panel
% at lower right cornor will be invisible; otherwise,
% it will be visible.
%
% 4. usecrosshair: If specified and usecrosshair=0, the crosshair
% will be invisible; otherwise, it will be visible.
%
% 5. usestretch: If specified and usestretch=0, the 3 slices will
% not be stretched, and will be displayed according to
% the actual voxel size; otherwise, the 3 slices will be
% stretched to the edge.
%
% 6. useimagesc: If specified and useimagesc=0, images data will
% be used directly to match the colormap (like 'image'
% command); otherwise, image data will be scaled to full
% colormap with 'imagesc' command in Matlab.
%
% 7. useinterp: If specified and useinterp=1, the image will be
% displayed using interpolation. Otherwise, it will be
% displayed like mosaic, and each tile stands for a
% pixel. This option does not apply to 'setvalue' option
% is set.
%
%
% 8. setarea: 3-View plot will be displayed on this specific
% region. If it is not specified, program will set the
% plot area to [0.05 0.05 0.9 0.9].
%
% 9. setunit: It can be specified to setunit='voxel' or 'mm'
% and the view will change the axes unit of [X Y Z]
% accordingly.
%
% 10. setviewpoint: If specified, [X Y Z] values will be used
% to set the viewpoint of 3-View plot.
%
% 11. setscanid: If specified, [t] value will be used to display
% the specified image scan in NIFTI data.
%
% 12. setcrosshaircolor: If specified, [r g b] value will be used
% for Crosshair Color. Otherwise, red will be the default.
%
% 13. setcolorindex: If specified, the 3-View will choose the
% following colormap: 2 - Bipolar; 3 - Gray; 4 - Jet;
% 5 - Cool; 6 - Bone; 7 - Hot; 8 - Copper; 9 - Pink;
% If not specified, it will choose 3 - Gray if all data
% values are not less than 0; otherwise, it will choose
% 2 - Bipolar if there is value less than 0. (Contrast
% control can only apply to 3 - Gray colormap.
%
% 14. setcolormap: 3-View plot will use it as a customized colormap.
% It is a 3-column matrix with value between 0 and 1. If
% using MS-Windows version of Matlab, the number of rows
% can not be more than 256, because of Matlab limitation.
% When colormap is used, setcolorlevel option will be
% disabled automatically.
%
% 15. setcolorlevel: If specified (must be no more than 256, and
% cannot be used for customized colormap), row number of
% colormap will be squeezed down to this level; otherwise,
% it will assume that setcolorlevel=256.
%
% 16. sethighcolor: If specified, program will squeeze down the
% colormap, and allocate sethighcolor (an Mx3 matrix)
% to high-end portion of the colormap. The sum of M and
% setcolorlevel should be less than 256. If setcolormap
% option is used, sethighcolor will be inserted on top
% of the setcolormap, and the setcolorlevel option will
% be disabled automatically.
%
% 17. setcbarminmax: if specified, the [min max] will be used to
% set the min and max of the colorbar, which does not
% include any data for highcolor.
%
% 18. setvalue: If specified, setvalue.val (with the same size as
% the source data on solution points) in the source area
% setvalue.idx will be superimposed on the current nii
% image. So, the size of setvalue.val should be equal to
% the size of setvalue.idx. To use this feature, it needs
% single or double nii structure for background image.
%
% 19. glblocminmax: If specified, pgm will use glblocminmax to
% calculate the colormap, instead of minmax of image.
%
% 20. setbuttondown: If specified, pgm will evaluate the command
% after a click or slide action is invoked to the new
% view point.
%
% 21. setcomplex: This option will decide how complex data to be
% displayed: 0 - Real part of complex data; 1 - Imaginary
% part of complex data; 2 - Modulus (magnitude) of complex
% data; If not specified, it will be set to 0 (Real part
% of complex data as default option. This option only apply
% when option.command is set to 'init or 'updatenii'.
%
%
% Additional Options for 'update' command:
% =======================================
%
% option.enablecursormove = [1] | 0
% option.enableviewpoint = 0 | [1]
% option.enableorigin = 0 | [1]
% option.enableunit = 0 | [1]
% option.enablecrosshair = 0 | [1]
% option.enablehistogram = 0 | [1]
% option.enablecolormap = 0 | [1]
% option.enablecontrast = 0 | [1]
% option.enablebrightness = 0 | [1]
% option.enableslider = 0 | [1]
% option.enabledirlabel = 0 | [1]
%
%
% e.g.:
% nii = load_nii('T1'); % T1.img/hdr
% view_nii(nii);
%
% or
%
% h = figure('unit','normal','pos', [0.18 0.08 0.64 0.85]);
% opt.setarea = [0.05 0.05 0.9 0.9];
% view_nii(h, nii, opt);
%
%
% Part of this file is copied and modified from:
% http://www.mathworks.com/matlabcentral/fileexchange/1878-mri-analyze-tools
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function status = view_nii(varargin)
if nargin < 1
error('Please check inputs using ''help view_nii''');
end;
nii = '';
opt = '';
command = '';
usecolorbar = [];
usepanel = [];
usecrosshair = '';
usestretch = [];
useimagesc = [];
useinterp = [];
setarea = [];
setunit = '';
setviewpoint = [];
setscanid = [];
setcrosshaircolor = [];
setcolorindex = '';
setcolormap = 'NA';
setcolorlevel = [];
sethighcolor = 'NA';
setcbarminmax = [];
setvalue = [];
glblocminmax = [];
setbuttondown = '';
setcomplex = 0;
status = [];
if ishandle(varargin{1}) % plot on top of this figure
fig = varargin{1};
if nargin < 2
command = 'update'; % just to get 3-View status
end
if nargin == 2
if ~isstruct(varargin{2})
error('2nd parameter should be either nii struct or option struct');
end
opt = varargin{2};
if isfield(opt,'hdr') & isfield(opt,'img')
nii = opt;
elseif isfield(opt, 'command') & (strcmpi(opt.command,'init') ...
| strcmpi(opt.command,'updatenii') ...
| strcmpi(opt.command,'updateimg') )
error('Option here cannot contain "init", "updatenii", or "updateimg" comand');
end
end
if nargin == 3
nii = varargin{2};
opt = varargin{3};
if ~isstruct(opt)
error('3rd parameter should be option struct');
end
if ~isfield(opt,'command') | ~strcmpi(opt.command,'updateimg')
if ~isstruct(nii) | ~isfield(nii,'hdr') | ~isfield(nii,'img')
error('2nd parameter should be nii struct');
end
if isfield(nii,'untouch') & nii.untouch == 1
error('Usage: please use ''load_nii.m'' to load the structure.');
end
end
end
set(fig, 'menubar', 'none');
elseif ischar(varargin{1}) % call back by event
command = lower(varargin{1});
fig = gcbf;
else % start nii with a new figure
nii = varargin{1};
if ~isstruct(nii) | ~isfield(nii,'hdr') | ~isfield(nii,'img')
error('1st parameter should be either a figure handle or nii struct');
end
if isfield(nii,'untouch') & nii.untouch == 1
error('Usage: please use ''load_nii.m'' to load the structure.');
end
if nargin > 1
opt = varargin{2};
if isfield(opt, 'command') & ~strcmpi(opt.command,'init')
error('Option here must use "init" comand');
end
end
command = 'init';
fig = figure('unit','normal','position',[0.15 0.08 0.70 0.85]);
view_nii_menu(fig);
rri_file_menu(fig);
end
if ~isempty(opt)
if isfield(opt,'command')
command = lower(opt.command);
end
if isempty(command)
command = 'update';
end
if isfield(opt,'usecolorbar')
usecolorbar = opt.usecolorbar;
end
if isfield(opt,'usepanel')
usepanel = opt.usepanel;
end
if isfield(opt,'usecrosshair')
usecrosshair = opt.usecrosshair;
end
if isfield(opt,'usestretch')
usestretch = opt.usestretch;
end
if isfield(opt,'useimagesc')
useimagesc = opt.useimagesc;
end
if isfield(opt,'useinterp')
useinterp = opt.useinterp;
end
if isfield(opt,'setarea')
setarea = opt.setarea;
end
if isfield(opt,'setunit')
setunit = opt.setunit;
end
if isfield(opt,'setviewpoint')
setviewpoint = opt.setviewpoint;
end
if isfield(opt,'setscanid')
setscanid = opt.setscanid;
end
if isfield(opt,'setcrosshaircolor')
setcrosshaircolor = opt.setcrosshaircolor;
if ~isempty(setcrosshaircolor) & (~isnumeric(setcrosshaircolor) | ~isequal(size(setcrosshaircolor),[1 3]) | min(setcrosshaircolor(:))<0 | max(setcrosshaircolor(:))>1)
error('Crosshair Color should be a 1x3 matrix with value between 0 and 1');
end
end
if isfield(opt,'setcolorindex')
setcolorindex = round(opt.setcolorindex);
if ~isnumeric(setcolorindex) | setcolorindex < 1 | setcolorindex > 9
error('Colorindex should be a number between 1 and 9');
end
end
if isfield(opt,'setcolormap')
setcolormap = opt.setcolormap;
if ~isempty(setcolormap) & (~isnumeric(setcolormap) | size(setcolormap,2) ~= 3 | min(setcolormap(:))<0 | max(setcolormap(:))>1)
error('Colormap should be a Mx3 matrix with value between 0 and 1');
end
end
if isfield(opt,'setcolorlevel')
setcolorlevel = round(opt.setcolorlevel);
if ~isnumeric(setcolorlevel) | setcolorlevel > 256 | setcolorlevel < 1
error('Colorlevel should be a number between 1 and 256');
end
end
if isfield(opt,'sethighcolor')
sethighcolor = opt.sethighcolor;
if ~isempty(sethighcolor) & (~isnumeric(sethighcolor) | size(sethighcolor,2) ~= 3 | min(sethighcolor(:))<0 | max(sethighcolor(:))>1)
error('Highcolor should be a Mx3 matrix with value between 0 and 1');
end
end
if isfield(opt,'setcbarminmax')
setcbarminmax = opt.setcbarminmax;
if isempty(setcbarminmax) | ~isnumeric(setcbarminmax) | length(setcbarminmax) ~= 2
error('Colorbar MinMax should contain 2 values: [min max]');
end
end
if isfield(opt,'setvalue')
setvalue = opt.setvalue;
if isempty(setvalue) | ~isstruct(setvalue) | ...
~isfield(opt.setvalue,'idx') | ~isfield(opt.setvalue,'val')
error('setvalue should be a struct contains idx and val');
end
if length(opt.setvalue.idx(:)) ~= length(opt.setvalue.val(:))
error('length of idx and val fields should be the same');
end
if ~strcmpi(class(opt.setvalue.idx),'single')
opt.setvalue.idx = single(opt.setvalue.idx);
end
if ~strcmpi(class(opt.setvalue.val),'single')
opt.setvalue.val = single(opt.setvalue.val);
end
end
if isfield(opt,'glblocminmax')
glblocminmax = opt.glblocminmax;
end
if isfield(opt,'setbuttondown')
setbuttondown = opt.setbuttondown;
end
if isfield(opt,'setcomplex')
setcomplex = opt.setcomplex;
end
end
switch command
case {'init'}
set(fig, 'InvertHardcopy','off');
set(fig, 'PaperPositionMode','auto');
fig = init(nii, fig, setarea, setunit, setviewpoint, setscanid, setbuttondown, ...
setcolorindex, setcolormap, setcolorlevel, sethighcolor, setcbarminmax, ...
usecolorbar, usepanel, usecrosshair, usestretch, useimagesc, useinterp, ...
setvalue, glblocminmax, setcrosshaircolor, setcomplex);
% get status
%
status = get_status(fig);
case {'update'}
nii_view = getappdata(fig,'nii_view');
h = fig;
if isempty(nii_view)
error('The figure should already contain a 3-View plot.');
end
if ~isempty(opt)
% Order of the following update matters.
%
update_shape(h, setarea, usecolorbar, usestretch, useimagesc);
update_useinterp(h, useinterp);
update_useimagesc(h, useimagesc);
update_usepanel(h, usepanel);
update_colorindex(h, setcolorindex);
update_colormap(h, setcolormap);
update_highcolor(h, sethighcolor, setcolorlevel);
update_cbarminmax(h, setcbarminmax);
update_unit(h, setunit);
update_viewpoint(h, setviewpoint);
update_scanid(h, setscanid);
update_buttondown(h, setbuttondown);
update_crosshaircolor(h, setcrosshaircolor);
update_usecrosshair(h, usecrosshair);
% Enable/Disable object
%
update_enable(h, opt);
end
% get status
%
status = get_status(h);
case {'updateimg'}
if ~exist('nii','var')
msg = sprintf('Please input a 3D matrix brain data');
error(msg);
end
% Note: nii is not nii, nii should be a 3D matrix here
%
if ~isnumeric(nii)
msg = sprintf('2nd parameter should be a 3D matrix, not nii struct');
error(msg);
end
nii_view = getappdata(fig,'nii_view');
if isempty(nii_view)
error('The figure should already contain a 3-View plot.');
end
img = nii;
update_img(img, fig, opt);
% get status
%
status = get_status(fig);
case {'updatenii'}
nii_view = getappdata(fig,'nii_view');
if isempty(nii_view)
error('The figure should already contain a 3-View plot.');
end
if ~isstruct(nii) | ~isfield(nii,'hdr') | ~isfield(nii,'img')
error('2nd parameter should be nii struct');
end
if isfield(nii,'untouch') & nii.untouch == 1
error('Usage: please use ''load_nii.m'' to load the structure.');
end
opt.command = 'clearnii';
view_nii(fig, opt);
opt.command = 'init';
view_nii(fig, nii, opt);
% get status
%
status = get_status(fig);
case {'clearnii'}
nii_view = getappdata(fig,'nii_view');
handles = struct2cell(nii_view.handles);
for i=1:length(handles)
if ishandle(handles{i}) % in case already del by parent
delete(handles{i});
end
end
rmappdata(fig,'nii_view');
buttonmotion = get(fig,'windowbuttonmotion');
mymotion = '; view_nii(''move_cursor'');';
buttonmotion = strrep(buttonmotion, mymotion, '');
set(fig, 'windowbuttonmotion', buttonmotion);
case {'axial_image','coronal_image','sagittal_image'}
switch command
case 'axial_image', view = 'axi'; axi = 0; cor = 1; sag = 1;
case 'coronal_image', view = 'cor'; axi = 1; cor = 0; sag = 1;
case 'sagittal_image', view = 'sag'; axi = 1; cor = 1; sag = 0;
end
nii_view = getappdata(fig,'nii_view');
nii_view = get_slice_position(nii_view,view);
if isfield(nii_view, 'disp')
img = nii_view.disp;
else
img = nii_view.nii.img;
end
% CData must be double() for Matlab 6.5 for Windows
%
if axi,
if isfield(nii_view.handles,'axial_bg') & ~isempty(nii_view.handles.axial_bg) & nii_view.useinterp
Saxi = squeeze(nii_view.bgimg(:,:,nii_view.slices.axi));
set(nii_view.handles.axial_bg,'CData',double(Saxi)');
end
if isfield(nii_view.handles,'axial_image'),
if nii_view.nii.hdr.dime.datatype == 128 | nii_view.nii.hdr.dime.datatype == 511
Saxi = squeeze(img(:,:,nii_view.slices.axi,:,nii_view.scanid));
Saxi = permute(Saxi, [2 1 3]);
else
Saxi = squeeze(img(:,:,nii_view.slices.axi,nii_view.scanid));
Saxi = Saxi';
end
set(nii_view.handles.axial_image,'CData',double(Saxi));
end
if isfield(nii_view.handles,'axial_slider'),
set(nii_view.handles.axial_slider,'Value',nii_view.slices.axi);
end;
end
if cor,
if isfield(nii_view.handles,'coronal_bg') & ~isempty(nii_view.handles.coronal_bg) & nii_view.useinterp
Scor = squeeze(nii_view.bgimg(:,nii_view.slices.cor,:));
set(nii_view.handles.coronal_bg,'CData',double(Scor)');
end
if isfield(nii_view.handles,'coronal_image'),
if nii_view.nii.hdr.dime.datatype == 128 | nii_view.nii.hdr.dime.datatype == 511
Scor = squeeze(img(:,nii_view.slices.cor,:,:,nii_view.scanid));
Scor = permute(Scor, [2 1 3]);
else
Scor = squeeze(img(:,nii_view.slices.cor,:,nii_view.scanid));
Scor = Scor';
end
set(nii_view.handles.coronal_image,'CData',double(Scor));
end
if isfield(nii_view.handles,'coronal_slider'),
slider_val = nii_view.dims(2) - nii_view.slices.cor + 1;
set(nii_view.handles.coronal_slider,'Value',slider_val);
end;
end;
if sag,
if isfield(nii_view.handles,'sagittal_bg') & ~isempty(nii_view.handles.sagittal_bg) & nii_view.useinterp
Ssag = squeeze(nii_view.bgimg(nii_view.slices.sag,:,:));
set(nii_view.handles.sagittal_bg,'CData',double(Ssag)');
end
if isfield(nii_view.handles,'sagittal_image'),
if nii_view.nii.hdr.dime.datatype == 128 | nii_view.nii.hdr.dime.datatype == 511
Ssag = squeeze(img(nii_view.slices.sag,:,:,:,nii_view.scanid));
Ssag = permute(Ssag, [2 1 3]);
else
Ssag = squeeze(img(nii_view.slices.sag,:,:,nii_view.scanid));
Ssag = Ssag';
end
set(nii_view.handles.sagittal_image,'CData',double(Ssag));
end
if isfield(nii_view.handles,'sagittal_slider'),
set(nii_view.handles.sagittal_slider,'Value',nii_view.slices.sag);
end;
end;
update_nii_view(nii_view);
if ~isempty(nii_view.buttondown)
eval(nii_view.buttondown);
end
case {'axial_slider','coronal_slider','sagittal_slider'},
switch command
case 'axial_slider', view = 'axi'; axi = 1; cor = 0; sag = 0;
case 'coronal_slider', view = 'cor'; axi = 0; cor = 1; sag = 0;
case 'sagittal_slider', view = 'sag'; axi = 0; cor = 0; sag = 1;
end
nii_view = getappdata(fig,'nii_view');
nii_view = get_slider_position(nii_view);
if isfield(nii_view, 'disp')
img = nii_view.disp;
else
img = nii_view.nii.img;
end
if axi,
if isfield(nii_view.handles,'axial_bg') & ~isempty(nii_view.handles.axial_bg) & nii_view.useinterp
Saxi = squeeze(nii_view.bgimg(:,:,nii_view.slices.axi));
set(nii_view.handles.axial_bg,'CData',double(Saxi)');
end
if isfield(nii_view.handles,'axial_image'),
if nii_view.nii.hdr.dime.datatype == 128 | nii_view.nii.hdr.dime.datatype == 511
Saxi = squeeze(img(:,:,nii_view.slices.axi,:,nii_view.scanid));
Saxi = permute(Saxi, [2 1 3]);
else
Saxi = squeeze(img(:,:,nii_view.slices.axi,nii_view.scanid));
Saxi = Saxi';
end
set(nii_view.handles.axial_image,'CData',double(Saxi));
end
if isfield(nii_view.handles,'axial_slider'),
set(nii_view.handles.axial_slider,'Value',nii_view.slices.axi);
end
end
if cor,
if isfield(nii_view.handles,'coronal_bg') & ~isempty(nii_view.handles.coronal_bg) & nii_view.useinterp
Scor = squeeze(nii_view.bgimg(:,nii_view.slices.cor,:));
set(nii_view.handles.coronal_bg,'CData',double(Scor)');
end
if isfield(nii_view.handles,'coronal_image'),
if nii_view.nii.hdr.dime.datatype == 128 | nii_view.nii.hdr.dime.datatype == 511
Scor = squeeze(img(:,nii_view.slices.cor,:,:,nii_view.scanid));
Scor = permute(Scor, [2 1 3]);
else
Scor = squeeze(img(:,nii_view.slices.cor,:,nii_view.scanid));
Scor = Scor';
end
set(nii_view.handles.coronal_image,'CData',double(Scor));
end
if isfield(nii_view.handles,'coronal_slider'),
slider_val = nii_view.dims(2) - nii_view.slices.cor + 1;
set(nii_view.handles.coronal_slider,'Value',slider_val);
end
end
if sag,
if isfield(nii_view.handles,'sagittal_bg') & ~isempty(nii_view.handles.sagittal_bg) & nii_view.useinterp
Ssag = squeeze(nii_view.bgimg(nii_view.slices.sag,:,:));
set(nii_view.handles.sagittal_bg,'CData',double(Ssag)');
end
if isfield(nii_view.handles,'sagittal_image'),
if nii_view.nii.hdr.dime.datatype == 128 | nii_view.nii.hdr.dime.datatype == 511
Ssag = squeeze(img(nii_view.slices.sag,:,:,:,nii_view.scanid));
Ssag = permute(Ssag, [2 1 3]);
else
Ssag = squeeze(img(nii_view.slices.sag,:,:,nii_view.scanid));
Ssag = Ssag';
end
set(nii_view.handles.sagittal_image,'CData',double(Ssag));
end
if isfield(nii_view.handles,'sagittal_slider'),
set(nii_view.handles.sagittal_slider,'Value',nii_view.slices.sag);
end
end
update_nii_view(nii_view);
if ~isempty(nii_view.buttondown)
eval(nii_view.buttondown);
end
case {'impos_edit'}
nii_view = getappdata(fig,'nii_view');
impos = str2num(get(nii_view.handles.impos,'string'));
if isfield(nii_view, 'disp')
img = nii_view.disp;
else
img = nii_view.nii.img;
end
if isempty(impos) | ~all(size(impos) == [1 3])
msg = 'Please use 3 numbers to represent X,Y and Z';
msgbox(msg,'Error');
return;
end
slices.sag = round(impos(1));
slices.cor = round(impos(2));
slices.axi = round(impos(3));
nii_view = convert2voxel(nii_view,slices);
nii_view = check_slices(nii_view);
impos(1) = nii_view.slices.sag;
impos(2) = nii_view.dims(2) - nii_view.slices.cor + 1;
impos(3) = nii_view.slices.axi;
if isfield(nii_view.handles,'sagittal_slider'),
set(nii_view.handles.sagittal_slider,'Value',impos(1));
end
if isfield(nii_view.handles,'coronal_slider'),
set(nii_view.handles.coronal_slider,'Value',impos(2));
end
if isfield(nii_view.handles,'axial_slider'),
set(nii_view.handles.axial_slider,'Value',impos(3));
end
nii_view = get_slider_position(nii_view);
update_nii_view(nii_view);
if isfield(nii_view.handles,'axial_bg') & ~isempty(nii_view.handles.axial_bg) & nii_view.useinterp
Saxi = squeeze(nii_view.bgimg(:,:,nii_view.slices.axi));
set(nii_view.handles.axial_bg,'CData',double(Saxi)');
end
if isfield(nii_view.handles,'axial_image'),
if nii_view.nii.hdr.dime.datatype == 128 | nii_view.nii.hdr.dime.datatype == 511
Saxi = squeeze(img(:,:,nii_view.slices.axi,:,nii_view.scanid));
Saxi = permute(Saxi, [2 1 3]);
else
Saxi = squeeze(img(:,:,nii_view.slices.axi,nii_view.scanid));
Saxi = Saxi';
end
set(nii_view.handles.axial_image,'CData',double(Saxi));
end
if isfield(nii_view.handles,'axial_slider'),
set(nii_view.handles.axial_slider,'Value',nii_view.slices.axi);
end
if isfield(nii_view.handles,'coronal_bg') & ~isempty(nii_view.handles.coronal_bg) & nii_view.useinterp
Scor = squeeze(nii_view.bgimg(:,nii_view.slices.cor,:));
set(nii_view.handles.coronal_bg,'CData',double(Scor)');
end
if isfield(nii_view.handles,'coronal_image'),
if nii_view.nii.hdr.dime.datatype == 128 | nii_view.nii.hdr.dime.datatype == 511
Scor = squeeze(img(:,nii_view.slices.cor,:,:,nii_view.scanid));
Scor = permute(Scor, [2 1 3]);
else
Scor = squeeze(img(:,nii_view.slices.cor,:,nii_view.scanid));
Scor = Scor';
end
set(nii_view.handles.coronal_image,'CData',double(Scor));
end
if isfield(nii_view.handles,'coronal_slider'),
slider_val = nii_view.dims(2) - nii_view.slices.cor + 1;
set(nii_view.handles.coronal_slider,'Value',slider_val);
end
if isfield(nii_view.handles,'sagittal_bg') & ~isempty(nii_view.handles.sagittal_bg) & nii_view.useinterp
Ssag = squeeze(nii_view.bgimg(nii_view.slices.sag,:,:));
set(nii_view.handles.sagittal_bg,'CData',double(Ssag)');
end
if isfield(nii_view.handles,'sagittal_image'),
if nii_view.nii.hdr.dime.datatype == 128 | nii_view.nii.hdr.dime.datatype == 511
Ssag = squeeze(img(nii_view.slices.sag,:,:,:,nii_view.scanid));
Ssag = permute(Ssag, [2 1 3]);
else
Ssag = squeeze(img(nii_view.slices.sag,:,:,nii_view.scanid));
Ssag = Ssag';
end
set(nii_view.handles.sagittal_image,'CData',double(Ssag));
end
if isfield(nii_view.handles,'sagittal_slider'),
set(nii_view.handles.sagittal_slider,'Value',nii_view.slices.sag);
end
axes(nii_view.handles.axial_axes);
axes(nii_view.handles.coronal_axes);
axes(nii_view.handles.sagittal_axes);
if ~isempty(nii_view.buttondown)
eval(nii_view.buttondown);
end
case 'coordinates',
nii_view = getappdata(fig,'nii_view');
set_image_value(nii_view);
case 'crosshair',
nii_view = getappdata(fig,'nii_view');
if get(nii_view.handles.xhair,'value') == 2 % off
set(nii_view.axi_xhair.lx,'visible','off');
set(nii_view.axi_xhair.ly,'visible','off');
set(nii_view.cor_xhair.lx,'visible','off');
set(nii_view.cor_xhair.ly,'visible','off');
set(nii_view.sag_xhair.lx,'visible','off');
set(nii_view.sag_xhair.ly,'visible','off');
else
set(nii_view.axi_xhair.lx,'visible','on');
set(nii_view.axi_xhair.ly,'visible','on');
set(nii_view.cor_xhair.lx,'visible','on');
set(nii_view.cor_xhair.ly,'visible','on');
set(nii_view.sag_xhair.lx,'visible','on');
set(nii_view.sag_xhair.ly,'visible','on');
set(nii_view.handles.axial_axes,'selected','on');
set(nii_view.handles.axial_axes,'selected','off');
set(nii_view.handles.coronal_axes,'selected','on');
set(nii_view.handles.coronal_axes,'selected','off');
set(nii_view.handles.sagittal_axes,'selected','on');
set(nii_view.handles.sagittal_axes,'selected','off');
end
case 'xhair_color',
old_color = get(gcbo,'user');
new_color = uisetcolor(old_color);
update_crosshaircolor(fig, new_color);
case {'color','contrast_def'}
nii_view = getappdata(fig,'nii_view');
if nii_view.numscan == 1
if get(nii_view.handles.colorindex,'value') == 2
set(nii_view.handles.contrast,'value',128);
elseif get(nii_view.handles.colorindex,'value') == 3
set(nii_view.handles.contrast,'value',1);
end
end
[custom_color_map, custom_colorindex] = change_colormap(fig);
if strcmpi(command, 'color')
setcolorlevel = nii_view.colorlevel;
if ~isempty(custom_color_map) % isfield(nii_view, 'color_map')
setcolormap = custom_color_map; % nii_view.color_map;
else
setcolormap = [];
end
if isfield(nii_view, 'highcolor')
sethighcolor = nii_view.highcolor;
else
sethighcolor = [];
end
redraw_cbar(fig, setcolorlevel, setcolormap, sethighcolor);
if nii_view.numscan == 1 & ...
(custom_colorindex < 2 | custom_colorindex > 3)
contrastopt.enablecontrast = 0;
else
contrastopt.enablecontrast = 1;
end
update_enable(fig, contrastopt);
end
case {'neg_color','brightness','contrast'}
change_colormap(fig);
case {'brightness_def'}
nii_view = getappdata(fig,'nii_view');
set(nii_view.handles.brightness,'value',0);
change_colormap(fig);
case 'hist_plot'
hist_plot(fig);
case 'hist_eq'
hist_eq(fig);
case 'move_cursor'
move_cursor(fig);
case 'edit_change_scan'
change_scan('edit_change_scan');
case 'slider_change_scan'
change_scan('slider_change_scan');
end
return; % view_nii
%----------------------------------------------------------------
function fig = init(nii, fig, area, setunit, setviewpoint, setscanid, buttondown, ...
colorindex, color_map, colorlevel, highcolor, cbarminmax, ...
usecolorbar, usepanel, usecrosshair, usestretch, useimagesc, ...
useinterp, setvalue, glblocminmax, setcrosshaircolor, ...
setcomplex)
% Support data type COMPLEX64 & COMPLEX128
%
if nii.hdr.dime.datatype == 32 | nii.hdr.dime.datatype == 1792
switch setcomplex,
case 0,
nii.img = real(nii.img);
case 1,
nii.img = imag(nii.img);
case 2,
if isa(nii.img, 'double')
nii.img = abs(double(nii.img));
else
nii.img = single(abs(double(nii.img)));
end
end
end
if isempty(area)
area = [0.05 0.05 0.9 0.9];
end
if isempty(setscanid)
setscanid = 1;
else
setscanid = round(setscanid);
if setscanid < 1
setscanid = 1;
end
if setscanid > nii.hdr.dime.dim(5)
setscanid = nii.hdr.dime.dim(5);
end
end
if nii.hdr.dime.datatype == 128 | nii.hdr.dime.datatype == 511
usecolorbar = 0;
elseif isempty(usecolorbar)
usecolorbar = 1;
end
if isempty(usepanel)
usepanel = 1;
end
if isempty(usestretch)
usestretch = 1;
end
if isempty(useimagesc)
useimagesc = 1;
end
if isempty(useinterp)
useinterp = 0;
end
if isempty(colorindex)
tmp = min(nii.img(:,:,:,setscanid));
if min(tmp(:)) < 0
colorindex = 2;
setcrosshaircolor = [1 1 0];
else
colorindex = 3;
end
end
if isempty(color_map) | ischar(color_map)
color_map = [];
else
colorindex = 1;
end
bgimg = [];
if ~isempty(glblocminmax)
minvalue = glblocminmax(1);
maxvalue = glblocminmax(2);
else
minvalue = nii.img(:,:,:,setscanid);
minvalue = double(minvalue(:));
minvalue = min(minvalue(~isnan(minvalue)));
maxvalue = nii.img(:,:,:,setscanid);
maxvalue = double(maxvalue(:));
maxvalue = max(maxvalue(~isnan(maxvalue)));
end
if ~isempty(setvalue)
if ~isempty(glblocminmax)
minvalue = glblocminmax(1);
maxvalue = glblocminmax(2);
else
minvalue = double(min(setvalue.val));
maxvalue = double(max(setvalue.val));
end
bgimg = double(nii.img);
minbg = double(min(bgimg(:)));
maxbg = double(max(bgimg(:)));
bgimg = scale_in(bgimg, minbg, maxbg, 55) + 200; % scale to 201~256
% 56 level for brain structure
%
% highcolor = [zeros(1,3);gray(55)];
highcolor = gray(56);
cbarminmax = [minvalue maxvalue];
if useinterp
% scale signal data to 1~200
%
nii.img = repmat(nan, size(nii.img));
nii.img(setvalue.idx) = setvalue.val;
% 200 level for source image
%
bgimg = single(scale_out(bgimg, cbarminmax(1), cbarminmax(2), 199));
else
bgimg(setvalue.idx) = NaN;
minbg = double(min(bgimg(:)));
maxbg = double(max(bgimg(:)));
bgimg(setvalue.idx) = minbg;
% bgimg must be normalized to [201 256]
%
bgimg = 55 * (bgimg-min(bgimg(:))) / (max(bgimg(:))-min(bgimg(:))) + 201;
bgimg(setvalue.idx) = 0;
% scale signal data to 1~200
%
nii.img = zeros(size(nii.img));
nii.img(setvalue.idx) = scale_in(setvalue.val, minvalue, maxvalue, 199);
nii.img = nii.img + bgimg;
bgimg = [];
nii.img = scale_out(nii.img, cbarminmax(1), cbarminmax(2), 199);
minvalue = double(nii.img(:));
minvalue = min(minvalue(~isnan(minvalue)));
maxvalue = double(nii.img(:));
maxvalue = max(maxvalue(~isnan(maxvalue)));
if ~isempty(glblocminmax) % maxvalue is gray
minvalue = glblocminmax(1);
end
end
colorindex = 2;
setcrosshaircolor = [1 1 0];
end
if isempty(highcolor) | ischar(highcolor)
highcolor = [];
num_highcolor = 0;
else
num_highcolor = size(highcolor,1);
end
if isempty(colorlevel)
colorlevel = 256 - num_highcolor;
end
if usecolorbar
cbar_area = area;
cbar_area(1) = area(1) + area(3)*0.93;
cbar_area(3) = area(3)*0.04;
area(3) = area(3)*0.9; % 90% used for main axes
else
cbar_area = [];
end
% init color (gray) scaling to make sure the slice clim take the
% global clim [min(nii.img(:)) max(nii.img(:))]
%
if isempty(bgimg)
clim = [minvalue maxvalue];
else
clim = [minvalue double(max(bgimg(:)))];
end
if clim(1) == clim(2)
clim(2) = clim(1) + 0.000001;
end
if isempty(cbarminmax)
cbarminmax = [minvalue maxvalue];
end
xdim = size(nii.img, 1);
ydim = size(nii.img, 2);
zdim = size(nii.img, 3);
dims = [xdim ydim zdim];
voxel_size = abs(nii.hdr.dime.pixdim(2:4)); % vol in mm
if any(voxel_size <= 0)
voxel_size(find(voxel_size <= 0)) = 1;
end
origin = abs(nii.hdr.hist.originator(1:3));
if isempty(origin) | all(origin == 0) % according to SPM
origin = (dims+1)/2;
end;
origin = round(origin);
if any(origin > dims) % simulate fMRI
origin(find(origin > dims)) = dims(find(origin > dims));
end
if any(origin <= 0)
origin(find(origin <= 0)) = 1;
end
nii_view.dims = dims;
nii_view.voxel_size = voxel_size;
nii_view.origin = origin;
nii_view.slices.sag = 1;
nii_view.slices.cor = 1;
nii_view.slices.axi = 1;
if xdim > 1, nii_view.slices.sag = origin(1); end
if ydim > 1, nii_view.slices.cor = origin(2); end
if zdim > 1, nii_view.slices.axi = origin(3); end
nii_view.area = area;
nii_view.fig = fig;
nii_view.nii = nii; % image data
nii_view.bgimg = bgimg; % background
nii_view.setvalue = setvalue;
nii_view.minvalue = minvalue;
nii_view.maxvalue = maxvalue;
nii_view.numscan = nii.hdr.dime.dim(5);
nii_view.scanid = setscanid;
Font.FontUnits = 'point';
Font.FontSize = 12;
% create axes for colorbar
%
[cbar_axes cbarminmax_axes] = create_cbar_axes(fig, cbar_area);
if isempty(cbar_area)
nii_view.cbar_area = [];
else
nii_view.cbar_area = cbar_area;
end
% create axes for top/front/side view
%
vol_size = voxel_size .* dims;
[top_ax, front_ax, side_ax] ...
= create_ax(fig, area, vol_size, usestretch);
top_pos = get(top_ax,'position');
front_pos = get(front_ax,'position');
side_pos = get(side_ax,'position');
% Sagittal Slider
%
x = side_pos(1);
y = top_pos(2) + top_pos(4);
w = side_pos(3);
h = (front_pos(2) - y) / 2;
y = y + h;
pos = [x y w h];
if xdim > 1,
slider_step(1) = 1/(xdim);
slider_step(2) = 1.00001/(xdim);
handles.sagittal_slider = uicontrol('Parent',fig, ...
'Style','slider','Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment','center',...
'BackgroundColor',[0.5 0.5 0.5],'ForegroundColor',[0 0 0],...
'BusyAction','queue',...
'TooltipString','Sagittal slice navigation',...
'Min',1,'Max',xdim,'SliderStep',slider_step, ...
'Value',nii_view.slices.sag,...
'Callback','view_nii(''sagittal_slider'');');
set(handles.sagittal_slider,'position',pos); % linux66
end
% Coronal Slider
%
x = top_pos(1);
y = top_pos(2) + top_pos(4);
w = top_pos(3);
h = (front_pos(2) - y) / 2;
y = y + h;
pos = [x y w h];
if ydim > 1,
slider_step(1) = 1/(ydim);
slider_step(2) = 1.00001/(ydim);
slider_val = nii_view.dims(2) - nii_view.slices.cor + 1;
handles.coronal_slider = uicontrol('Parent',fig, ...
'Style','slider','Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment','center',...
'BackgroundColor',[0.5 0.5 0.5],'ForegroundColor',[0 0 0],...
'BusyAction','queue',...
'TooltipString','Coronal slice navigation',...
'Min',1,'Max',ydim,'SliderStep',slider_step, ...
'Value',slider_val,...
'Callback','view_nii(''coronal_slider'');');
set(handles.coronal_slider,'position',pos); % linux66
end
% Axial Slider
%
% x = front_pos(1) + front_pos(3);
% y = front_pos(2);
% w = side_pos(1) - x;
% h = front_pos(4);
x = top_pos(1);
y = area(2);
w = top_pos(3);
h = top_pos(2) - y;
pos = [x y w h];
if zdim > 1,
slider_step(1) = 1/(zdim);
slider_step(2) = 1.00001/(zdim);
handles.axial_slider = uicontrol('Parent',fig, ...
'Style','slider','Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment','center',...
'BackgroundColor',[0.5 0.5 0.5],'ForegroundColor',[0 0 0],...
'BusyAction','queue',...
'TooltipString','Axial slice navigation',...
'Min',1,'Max',zdim,'SliderStep',slider_step, ...
'Value',nii_view.slices.axi,...
'Callback','view_nii(''axial_slider'');');
set(handles.axial_slider,'position',pos); % linux66
end
% plot info view
%
% info_pos = [side_pos([1,3]); top_pos([2,4])];
% info_pos = info_pos(:);
gap = side_pos(1)-(top_pos(1)+top_pos(3));
info_pos(1) = side_pos(1) + gap;
info_pos(2) = area(2);
info_pos(3) = side_pos(3) - gap;
info_pos(4) = top_pos(2) + top_pos(4) - area(2) - gap;
num_inputline = 10;
inputline_space =info_pos(4) / num_inputline;
% for any info_area change, update_usestretch should also be changed
% Image Intensity Value at Cursor
%
x = info_pos(1);
y = info_pos(2);
w = info_pos(3)*0.5;
h = inputline_space*0.6;
pos = [x y w h];
handles.Timvalcur = uicontrol('Parent',fig,'Style','text', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'left',...
'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'visible','off', ...
'String','Value at cursor:');
if usepanel
set(handles.Timvalcur, 'visible', 'on');
end
x = x + w;
w = info_pos(3)*0.5;
pos = [x y w h];
handles.imvalcur = uicontrol('Parent',fig,'Style','text', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'right',...
'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'visible','off', ...
'String',' ');
if usepanel
set(handles.imvalcur, 'visible', 'on');
end
% Position at Cursor
%
x = info_pos(1);
y = y + inputline_space;
w = info_pos(3)*0.5;
pos = [x y w h];
handles.Timposcur = uicontrol('Parent',fig,'Style','text', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'left',...
'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'visible','off', ...
'String','[X Y Z] at cursor:');
if usepanel
set(handles.Timposcur, 'visible', 'on');
end
x = x + w;
w = info_pos(3)*0.5;
pos = [x y w h];
handles.imposcur = uicontrol('Parent',fig,'Style','text', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'right',...
'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'visible','off', ...
'String',' ','Value',[0 0 0]);
if usepanel
set(handles.imposcur, 'visible', 'on');
end
% Image Intensity Value at Mouse Click
%
x = info_pos(1);
y = y + inputline_space;
w = info_pos(3)*0.5;
pos = [x y w h];
handles.Timval = uicontrol('Parent',fig,'Style','text', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'left',...
'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'visible','off', ...
'String','Value at crosshair:');
if usepanel
set(handles.Timval, 'visible', 'on');
end
x = x + w;
w = info_pos(3)*0.5;
pos = [x y w h];
handles.imval = uicontrol('Parent',fig,'Style','text', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'right',...
'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'visible','off', ...
'String',' ');
if usepanel
set(handles.imval, 'visible', 'on');
end
% Viewpoint Position at Mouse Click
%
x = info_pos(1);
y = y + inputline_space;
w = info_pos(3)*0.5;
pos = [x y w h];
handles.Timpos = uicontrol('Parent',fig,'Style','text', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'left',...
'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'visible','off', ...
'String','[X Y Z] at crosshair:');
if usepanel
set(handles.Timpos, 'visible', 'on');
end
x = x + w + 0.005;
y = y - 0.008;
w = info_pos(3)*0.5;
h = inputline_space*0.9;
pos = [x y w h];
handles.impos = uicontrol('Parent',fig,'Style','edit', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'right',...
'BackgroundColor', [1 1 1], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'Callback','view_nii(''impos_edit'');', ...
'TooltipString','Viewpoint Location in Axes Unit', ...
'visible','off', ...
'String',' ','Value',[0 0 0]);
if usepanel
set(handles.impos, 'visible', 'on');
end
% Origin Position
%
x = info_pos(1);
y = y + inputline_space*1.2;
w = info_pos(3)*0.5;
h = inputline_space*0.6;
pos = [x y w h];
handles.Torigin = uicontrol('Parent',fig,'Style','text', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'left',...
'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'visible','off', ...
'String','[X Y Z] at origin:');
if usepanel
set(handles.Torigin, 'visible', 'on');
end
x = x + w;
w = info_pos(3)*0.5;
pos = [x y w h];
handles.origin = uicontrol('Parent',fig,'Style','text', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'right',...
'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'visible','off', ...
'String',' ','Value',[0 0 0]);
if usepanel
set(handles.origin, 'visible', 'on');
end
if 0
% Voxel Unit
%
x = info_pos(1);
y = y + inputline_space;
w = info_pos(3)*0.5;
pos = [x y w h];
handles.Tcoord = uicontrol('Parent',fig,'Style','text', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'left',...
'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'visible','off', ...
'String','Axes Unit:');
if usepanel
set(handles.Tcoord, 'visible', 'on');
end
x = x + w + 0.005;
w = info_pos(3)*0.5 - 0.005;
pos = [x y w h];
Font.FontSize = 8;
handles.coord = uicontrol('Parent',fig,'Style','popupmenu', ...
'Units','Normalized', Font, ...
'Position',pos, ...
'BackgroundColor', [1 1 1], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'TooltipString','Choose Voxel or Millimeter',...
'String',{'Voxel','Millimeter'},...
'visible','off', ...
'Callback','view_nii(''coordinates'');');
% 'TooltipString','Choose Voxel, MNI or Talairach Coordinates',...
% 'String',{'Voxel','MNI (mm)','Talairach (mm)'},...
Font.FontSize = 12;
if usepanel
set(handles.coord, 'visible', 'on');
end
end
% Crosshair
%
x = info_pos(1);
y = y + inputline_space;
w = info_pos(3)*0.4;
pos = [x y w h];
handles.Txhair = uicontrol('Parent',fig,'Style','text', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'left',...
'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'visible','off', ...
'String','Crosshair:');
if usepanel
set(handles.Txhair, 'visible', 'on');
end
x = info_pos(1) + info_pos(3)*0.5;
w = info_pos(3)*0.2;
h = inputline_space*0.7;
pos = [x y w h];
Font.FontSize = 8;
handles.xhair_color = uicontrol('Parent',fig,'Style','push', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'center',...
'TooltipString','Crosshair Color',...
'User',[1 0 0],...
'String','Color',...
'visible','off', ...
'Callback','view_nii(''xhair_color'');');
if usepanel
set(handles.xhair_color, 'visible', 'on');
end
x = info_pos(1) + info_pos(3)*0.7;
w = info_pos(3)*0.3;
pos = [x y w h];
handles.xhair = uicontrol('Parent',fig,'Style','popupmenu', ...
'Units','Normalized', Font, ...
'Position',pos, ...
'BackgroundColor', [1 1 1], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'TooltipString','Display or Hide Crosshair',...
'String',{'On','Off'},...
'visible','off', ...
'Callback','view_nii(''crosshair'');');
if usepanel
set(handles.xhair, 'visible', 'on');
end
% Histogram & Color
%
x = info_pos(1);
w = info_pos(3)*0.45;
h = inputline_space * 1.5;
pos = [x, y+inputline_space*0.9, w, h];
handles.hist_frame = uicontrol('Parent',fig, ...
'Units','normal', ...
'BackgroundColor',[0.8 0.8 0.8], ...
'Position',pos, ...
'visible','off', ...
'Style','frame');
if usepanel
% set(handles.hist_frame, 'visible', 'on');
end
handles.coord_frame = uicontrol('Parent',fig, ...
'Units','normal', ...
'BackgroundColor',[0.8 0.8 0.8], ...
'Position',pos, ...
'visible','off', ...
'Style','frame');
if usepanel
set(handles.coord_frame, 'visible', 'on');
end
x = info_pos(1) + info_pos(3)*0.475;
w = info_pos(3)*0.525;
h = inputline_space * 1.5;
pos = [x, y+inputline_space*0.9, w, h];
handles.color_frame = uicontrol('Parent',fig, ...
'Units','normal', ...
'BackgroundColor',[0.8 0.8 0.8], ...
'Position',pos, ...
'visible','off', ...
'Style','frame');
if usepanel
set(handles.color_frame, 'visible', 'on');
end
x = info_pos(1) + info_pos(3)*0.025;
y = y + inputline_space*1.2;
w = info_pos(3)*0.2;
h = inputline_space*0.7;
pos = [x y w h];
Font.FontSize = 8;
handles.hist_eq = uicontrol('Parent',fig,'Style','toggle', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'center',...
'TooltipString','Histogram Equalization',...
'String','Hist EQ',...
'visible','off', ...
'Callback','view_nii(''hist_eq'');');
if usepanel
% set(handles.hist_eq, 'visible', 'on');
end
x = x + w;
w = info_pos(3)*0.2;
pos = [x y w h];
handles.hist_plot = uicontrol('Parent',fig,'Style','push', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'center',...
'TooltipString','Histogram Plot',...
'String','Hist Plot',...
'visible','off', ...
'Callback','view_nii(''hist_plot'');');
if usepanel
% set(handles.hist_plot, 'visible', 'on');
end
x = info_pos(1) + info_pos(3)*0.025;
w = info_pos(3)*0.4;
pos = [x y w h];
handles.coord = uicontrol('Parent',fig,'Style','popupmenu', ...
'Units','Normalized', Font, ...
'Position',pos, ...
'BackgroundColor', [1 1 1], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'TooltipString','Choose Voxel or Millimeter',...
'String',{'Voxel','Millimeter'},...
'visible','off', ...
'Callback','view_nii(''coordinates'');');
% 'TooltipString','Choose Voxel, MNI or Talairach Coordinates',...
% 'String',{'Voxel','MNI (mm)','Talairach (mm)'},...
if usepanel
set(handles.coord, 'visible', 'on');
end
x = info_pos(1) + info_pos(3)*0.5;
w = info_pos(3)*0.2;
pos = [x y w h];
handles.neg_color = uicontrol('Parent',fig,'Style','toggle', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'center',...
'TooltipString','Negative Colormap',...
'String','Negative',...
'visible','off', ...
'Callback','view_nii(''neg_color'');');
if usepanel
set(handles.neg_color, 'visible', 'on');
end
if nii.hdr.dime.datatype == 128 | nii.hdr.dime.datatype == 511
set(handles.neg_color, 'enable', 'off');
end
x = info_pos(1) + info_pos(3)*0.7;
w = info_pos(3)*0.275;
pos = [x y w h];
handles.colorindex = uicontrol('Parent',fig,'Style','popupmenu', ...
'Units','Normalized', Font, ...
'Position',pos, ...
'BackgroundColor', [1 1 1], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'TooltipString','Change Colormap',...
'String',{'Custom','Bipolar','Gray','Jet','Cool','Bone','Hot','Copper','Pink'},...
'value', colorindex, ...
'visible','off', ...
'Callback','view_nii(''color'');');
if usepanel
set(handles.colorindex, 'visible', 'on');
end
if nii.hdr.dime.datatype == 128 | nii.hdr.dime.datatype == 511
set(handles.colorindex, 'enable', 'off');
end
x = info_pos(1) + info_pos(3)*0.1;
y = y + inputline_space;
w = info_pos(3)*0.28;
h = inputline_space*0.6;
pos = [x y w h];
Font.FontSize = 8;
handles.Thist = uicontrol('Parent',fig,'Style','text', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'center',...
'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'visible','off', ...
'String','Histogram');
handles.Tcoord = uicontrol('Parent',fig,'Style','text', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'center',...
'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'visible','off', ...
'String','Axes Unit');
if usepanel
% set(handles.Thist, 'visible', 'on');
set(handles.Tcoord, 'visible', 'on');
end
x = info_pos(1) + info_pos(3)*0.60;
w = info_pos(3)*0.28;
pos = [x y w h];
handles.Tcolor = uicontrol('Parent',fig,'Style','text', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'center',...
'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'visible','off', ...
'String','Colormap');
if usepanel
set(handles.Tcolor, 'visible', 'on');
end
if nii.hdr.dime.datatype == 128 | nii.hdr.dime.datatype == 511
set(handles.Tcolor, 'enable', 'off');
end
% Contrast Frame
%
x = info_pos(1);
w = info_pos(3)*0.45;
h = inputline_space * 2;
pos = [x, y+inputline_space*0.8, w, h];
handles.contrast_frame = uicontrol('Parent',fig, ...
'Units','normal', ...
'BackgroundColor',[0.8 0.8 0.8], ...
'Position',pos, ...
'visible','off', ...
'Style','frame');
if usepanel
set(handles.contrast_frame, 'visible', 'on');
end
if colorindex < 2 | colorindex > 3
set(handles.contrast_frame, 'visible', 'off');
end
% Brightness Frame
%
x = info_pos(1) + info_pos(3)*0.475;
w = info_pos(3)*0.525;
pos = [x, y+inputline_space*0.8, w, h];
handles.brightness_frame = uicontrol('Parent',fig, ...
'Units','normal', ...
'BackgroundColor',[0.8 0.8 0.8], ...
'Position',pos, ...
'visible','off', ...
'Style','frame');
if usepanel
set(handles.brightness_frame, 'visible', 'on');
end
% Contrast
%
x = info_pos(1) + info_pos(3)*0.025;
y = y + inputline_space;
w = info_pos(3)*0.4;
h = inputline_space*0.6;
pos = [x y w h];
Font.FontSize = 12;
slider_step(1) = 5/255;
slider_step(2) = 5.00001/255;
handles.contrast = uicontrol('Parent',fig, ...
'Style','slider','Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'left',...
'BackgroundColor',[0.5 0.5 0.5],'ForegroundColor',[0 0 0],...
'BusyAction','queue',...
'TooltipString','Change contrast',...
'Min',1,'Max',256,'SliderStep',slider_step, ...
'Value',1, ...
'visible','off', ...
'Callback','view_nii(''contrast'');');
if usepanel
set(handles.contrast, 'visible', 'on');
end
if (nii.hdr.dime.datatype == 128 | nii.hdr.dime.datatype == 511) & nii_view.numscan <= 1
set(handles.contrast, 'enable', 'off');
end
if nii_view.numscan > 1
set(handles.contrast, 'min', 1, 'max', nii_view.numscan, ...
'sliderstep',[1/(nii_view.numscan-1) 1.00001/(nii_view.numscan-1)], ...
'Callback', 'view_nii(''slider_change_scan'');');
elseif colorindex < 2 | colorindex > 3
set(handles.contrast, 'visible', 'off');
elseif colorindex == 2
set(handles.contrast,'value',128);
end
set(handles.contrast,'position',pos); % linux66
% Brightness
%
x = info_pos(1) + info_pos(3)*0.5;
w = info_pos(3)*0.475;
pos = [x y w h];
Font.FontSize = 12;
slider_step(1) = 1/50;
slider_step(2) = 1.00001/50;
handles.brightness = uicontrol('Parent',fig, ...
'Style','slider','Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'left',...
'BackgroundColor',[0.5 0.5 0.5],'ForegroundColor',[0 0 0],...
'BusyAction','queue',...
'TooltipString','Change brightness',...
'Min',-1,'Max',1,'SliderStep',slider_step, ...
'Value',0, ...
'visible','off', ...
'Callback','view_nii(''brightness'');');
if usepanel
set(handles.brightness, 'visible', 'on');
end
if nii.hdr.dime.datatype == 128 | nii.hdr.dime.datatype == 511
set(handles.brightness, 'enable', 'off');
end
set(handles.brightness,'position',pos); % linux66
% Contrast text/def
%
x = info_pos(1) + info_pos(3)*0.025;
y = y + inputline_space;
w = info_pos(3)*0.22;
pos = [x y w h];
handles.Tcontrast = uicontrol('Parent',fig,'Style','text', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'left',...
'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'visible','off', ...
'String','Contrast:');
if usepanel
set(handles.Tcontrast, 'visible', 'on');
end
if (nii.hdr.dime.datatype == 128 | nii.hdr.dime.datatype == 511) & nii_view.numscan <= 1
set(handles.Tcontrast, 'enable', 'off');
end
if nii_view.numscan > 1
set(handles.Tcontrast, 'string', 'Scan ID:');
set(handles.contrast, 'TooltipString', 'Change Scan ID');
elseif colorindex < 2 | colorindex > 3
set(handles.Tcontrast, 'visible', 'off');
end
x = x + w;
w = info_pos(3)*0.18;
pos = [x y w h];
Font.FontSize = 8;
handles.contrast_def = uicontrol('Parent',fig,'Style','push', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'center',...
'TooltipString','Restore initial contrast',...
'String','Reset',...
'visible','off', ...
'Callback','view_nii(''contrast_def'');');
if usepanel
set(handles.contrast_def, 'visible', 'on');
end
if (nii.hdr.dime.datatype == 128 | nii.hdr.dime.datatype == 511) & nii_view.numscan <= 1
set(handles.contrast_def, 'enable', 'off');
end
if nii_view.numscan > 1
set(handles.contrast_def, 'style', 'edit', 'background', 'w', ...
'TooltipString','Scan (or volume) index in the time series',...
'string', '1', 'Callback', 'view_nii(''edit_change_scan'');');
elseif colorindex < 2 | colorindex > 3
set(handles.contrast_def, 'visible', 'off');
end
% Brightness text/def
%
x = info_pos(1) + info_pos(3)*0.5;
w = info_pos(3)*0.295;
pos = [x y w h];
Font.FontSize = 12;
handles.Tbrightness = uicontrol('Parent',fig,'Style','text', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'left',...
'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'visible','off', ...
'String','Brightness:');
if usepanel
set(handles.Tbrightness, 'visible', 'on');
end
if nii.hdr.dime.datatype == 128 | nii.hdr.dime.datatype == 511
set(handles.Tbrightness, 'enable', 'off');
end
x = x + w;
w = info_pos(3)*0.18;
pos = [x y w h];
Font.FontSize = 8;
handles.brightness_def = uicontrol('Parent',fig,'Style','push', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'center',...
'TooltipString','Restore initial brightness',...
'String','Reset',...
'visible','off', ...
'Callback','view_nii(''brightness_def'');');
if usepanel
set(handles.brightness_def, 'visible', 'on');
end
if nii.hdr.dime.datatype == 128 | nii.hdr.dime.datatype == 511
set(handles.brightness_def, 'enable', 'off');
end
% init image handles
%
handles.axial_image = [];
handles.coronal_image = [];
handles.sagittal_image = [];
% plot axial view
%
if ~isempty(nii_view.bgimg)
bg_slice = squeeze(bgimg(:,:,nii_view.slices.axi));
h1 = plot_view(fig, xdim, ydim, top_ax, bg_slice', clim, cbarminmax, ...
handles, useimagesc, colorindex, color_map, ...
colorlevel, highcolor, useinterp, nii_view.numscan);
handles.axial_bg = h1;
else
handles.axial_bg = [];
end
if nii.hdr.dime.datatype == 128 | nii.hdr.dime.datatype == 511
img_slice = squeeze(nii.img(:,:,nii_view.slices.axi,:,setscanid));
img_slice = permute(img_slice, [2 1 3]);
else
img_slice = squeeze(nii.img(:,:,nii_view.slices.axi,setscanid));
img_slice = img_slice';
end
h1 = plot_view(fig, xdim, ydim, top_ax, img_slice, clim, cbarminmax, ...
handles, useimagesc, colorindex, color_map, ...
colorlevel, highcolor, useinterp, nii_view.numscan);
set(h1,'buttondown','view_nii(''axial_image'');');
handles.axial_image = h1;
handles.axial_axes = top_ax;
if size(img_slice,1) == 1 | size(img_slice,2) == 1
set(top_ax,'visible','off');
if isfield(handles,'sagittal_slider') & ishandle(handles.sagittal_slider)
set(handles.sagittal_slider, 'visible', 'off');
end
if isfield(handles,'coronal_slider') & ishandle(handles.coronal_slider)
set(handles.coronal_slider, 'visible', 'off');
end
if isfield(handles,'axial_slider') & ishandle(handles.axial_slider)
set(handles.axial_slider, 'visible', 'off');
end
end
% plot coronal view
%
if ~isempty(nii_view.bgimg)
bg_slice = squeeze(bgimg(:,nii_view.slices.cor,:));
h1 = plot_view(fig, xdim, zdim, front_ax, bg_slice', clim, cbarminmax, ...
handles, useimagesc, colorindex, color_map, ...
colorlevel, highcolor, useinterp, nii_view.numscan);
handles.coronal_bg = h1;
else
handles.coronal_bg = [];
end
if nii.hdr.dime.datatype == 128 | nii.hdr.dime.datatype == 511
img_slice = squeeze(nii.img(:,nii_view.slices.cor,:,:,setscanid));
img_slice = permute(img_slice, [2 1 3]);
else
img_slice = squeeze(nii.img(:,nii_view.slices.cor,:,setscanid));
img_slice = img_slice';
end
h1 = plot_view(fig, xdim, zdim, front_ax, img_slice, clim, cbarminmax, ...
handles, useimagesc, colorindex, color_map, ...
colorlevel, highcolor, useinterp, nii_view.numscan);
set(h1,'buttondown','view_nii(''coronal_image'');');
handles.coronal_image = h1;
handles.coronal_axes = front_ax;
if size(img_slice,1) == 1 | size(img_slice,2) == 1
set(front_ax,'visible','off');
if isfield(handles,'sagittal_slider') & ishandle(handles.sagittal_slider)
set(handles.sagittal_slider, 'visible', 'off');
end
if isfield(handles,'coronal_slider') & ishandle(handles.coronal_slider)
set(handles.coronal_slider, 'visible', 'off');
end
if isfield(handles,'axial_slider') & ishandle(handles.axial_slider)
set(handles.axial_slider, 'visible', 'off');
end
end
% plot sagittal view
%
if ~isempty(nii_view.bgimg)
bg_slice = squeeze(bgimg(nii_view.slices.sag,:,:));
h1 = plot_view(fig, ydim, zdim, side_ax, bg_slice', clim, cbarminmax, ...
handles, useimagesc, colorindex, color_map, ...
colorlevel, highcolor, useinterp, nii_view.numscan);
handles.sagittal_bg = h1;
else
handles.sagittal_bg = [];
end
if nii.hdr.dime.datatype == 128 | nii.hdr.dime.datatype == 511
img_slice = squeeze(nii.img(nii_view.slices.sag,:,:,:,setscanid));
img_slice = permute(img_slice, [2 1 3]);
else
img_slice = squeeze(nii.img(nii_view.slices.sag,:,:,setscanid));
img_slice = img_slice';
end
h1 = plot_view(fig, ydim, zdim, side_ax, img_slice, clim, cbarminmax, ...
handles, useimagesc, colorindex, color_map, ...
colorlevel, highcolor, useinterp, nii_view.numscan);
set(h1,'buttondown','view_nii(''sagittal_image'');');
set(side_ax,'Xdir', 'reverse');
handles.sagittal_image = h1;
handles.sagittal_axes = side_ax;
if size(img_slice,1) == 1 | size(img_slice,2) == 1
set(side_ax,'visible','off');
if isfield(handles,'sagittal_slider') & ishandle(handles.sagittal_slider)
set(handles.sagittal_slider, 'visible', 'off');
end
if isfield(handles,'coronal_slider') & ishandle(handles.coronal_slider)
set(handles.coronal_slider, 'visible', 'off');
end
if isfield(handles,'axial_slider') & ishandle(handles.axial_slider)
set(handles.axial_slider, 'visible', 'off');
end
end
[top1_label, top2_label, side1_label, side2_label] = ...
dir_label(fig, top_ax, front_ax, side_ax);
% store label handles
%
handles.top1_label = top1_label;
handles.top2_label = top2_label;
handles.side1_label = side1_label;
handles.side2_label = side2_label;
% plot colorbar
%
if ~isempty(cbar_axes) & ~isempty(cbarminmax_axes)
if 0
if isempty(color_map)
level = colorlevel + num_highcolor;
else
level = size([color_map; highcolor], 1);
end
end
if isempty(color_map)
level = colorlevel;
else
level = size([color_map], 1);
end
niiclass = class(nii.img);
h1 = plot_cbar(fig, cbar_axes, cbarminmax_axes, cbarminmax, ...
level, handles, useimagesc, colorindex, color_map, ...
colorlevel, highcolor, niiclass, nii_view.numscan);
handles.cbar_image = h1;
handles.cbar_axes = cbar_axes;
handles.cbarminmax_axes = cbarminmax_axes;
end
nii_view.handles = handles; % store handles
nii_view.usepanel = usepanel; % whole panel at low right cornor
nii_view.usestretch = usestretch; % stretch display of voxel_size
nii_view.useinterp = useinterp; % use interpolation
nii_view.colorindex = colorindex; % store colorindex variable
nii_view.buttondown = buttondown; % command after button down click
nii_view.cbarminmax = cbarminmax; % store min max value for colorbar
set_coordinates(nii_view,useinterp); % coord unit
if ~isfield(nii_view, 'axi_xhair') | ...
~isfield(nii_view, 'cor_xhair') | ...
~isfield(nii_view, 'sag_xhair')
nii_view.axi_xhair = []; % top cross hair
nii_view.cor_xhair = []; % front cross hair
nii_view.sag_xhair = []; % side cross hair
end
if ~isempty(color_map)
nii_view.color_map = color_map;
end
if ~isempty(colorlevel)
nii_view.colorlevel = colorlevel;
end
if ~isempty(highcolor)
nii_view.highcolor = highcolor;
end
update_nii_view(nii_view);
if ~isempty(setunit)
update_unit(fig, setunit);
end
if ~isempty(setviewpoint)
update_viewpoint(fig, setviewpoint);
end
if ~isempty(setcrosshaircolor)
update_crosshaircolor(fig, setcrosshaircolor);
end
if ~isempty(usecrosshair)
update_usecrosshair(fig, usecrosshair);
end
nii_menu = getappdata(fig, 'nii_menu');
if ~isempty(nii_menu)
if nii.hdr.dime.datatype == 128 | nii.hdr.dime.datatype == 511
set(nii_menu.Minterp,'Userdata',1,'Label','Interp on','enable','off');
elseif useinterp
set(nii_menu.Minterp,'Userdata',0,'Label','Interp off');
else
set(nii_menu.Minterp,'Userdata',1,'Label','Interp on');
end
end
windowbuttonmotion = get(fig, 'windowbuttonmotion');
windowbuttonmotion = [windowbuttonmotion '; view_nii(''move_cursor'');'];
set(fig, 'windowbuttonmotion', windowbuttonmotion);
return; % init
%----------------------------------------------------------------
function fig = update_img(img, fig, opt)
nii_menu = getappdata(fig,'nii_menu');
if ~isempty(nii_menu)
set(nii_menu.Mzoom,'Userdata',1,'Label','Zoom on');
set(fig,'pointer','arrow');
zoom off;
end
nii_view = getappdata(fig,'nii_view');
change_interp = 0;
if isfield(opt, 'useinterp') & opt.useinterp ~= nii_view.useinterp
nii_view.useinterp = opt.useinterp;
change_interp = 1;
end
setscanid = 1;
if isfield(opt, 'setscanid')
setscanid = round(opt.setscanid);
if setscanid < 1
setscanid = 1;
end
if setscanid > nii_view.numscan
setscanid = nii_view.numscan;
end
end
if isfield(opt, 'glblocminmax') & ~isempty(opt.glblocminmax)
minvalue = opt.glblocminmax(1);
maxvalue = opt.glblocminmax(2);
else
minvalue = img(:,:,:,setscanid);
minvalue = double(minvalue(:));
minvalue = min(minvalue(~isnan(minvalue)));
maxvalue = img(:,:,:,setscanid);
maxvalue = double(maxvalue(:));
maxvalue = max(maxvalue(~isnan(maxvalue)));
end
if isfield(opt, 'setvalue')
setvalue = opt.setvalue;
if isfield(opt, 'glblocminmax') & ~isempty(opt.glblocminmax)
minvalue = opt.glblocminmax(1);
maxvalue = opt.glblocminmax(2);
else
minvalue = double(min(setvalue.val));
maxvalue = double(max(setvalue.val));
end
bgimg = double(img);
minbg = double(min(bgimg(:)));
maxbg = double(max(bgimg(:)));
bgimg = scale_in(bgimg, minbg, maxbg, 55) + 200; % scale to 201~256
cbarminmax = [minvalue maxvalue];
if nii_view.useinterp
% scale signal data to 1~200
%
img = repmat(nan, size(img));
img(setvalue.idx) = setvalue.val;
% 200 level for source image
%
bgimg = single(scale_out(bgimg, cbarminmax(1), cbarminmax(2), 199));
else
bgimg(setvalue.idx) = NaN;
minbg = double(min(bgimg(:)));
maxbg = double(max(bgimg(:)));
bgimg(setvalue.idx) = minbg;
% bgimg must be normalized to [201 256]
%
bgimg = 55 * (bgimg-min(bgimg(:))) / (max(bgimg(:))-min(bgimg(:))) + 201;
bgimg(setvalue.idx) = 0;
% scale signal data to 1~200
%
img = zeros(size(img));
img(setvalue.idx) = scale_in(setvalue.val, minvalue, maxvalue, 199);
img = img + bgimg;
bgimg = [];
img = scale_out(img, cbarminmax(1), cbarminmax(2), 199);
minvalue = double(min(img(:)));
maxvalue = double(max(img(:)));
if isfield(opt,'glblocminmax') & ~isempty(opt.glblocminmax)
minvalue = opt.glblocminmax(1);
end
end
nii_view.bgimg = bgimg;
nii_view.setvalue = setvalue;
else
cbarminmax = [minvalue maxvalue];
end
update_cbarminmax(fig, cbarminmax);
nii_view.cbarminmax = cbarminmax;
nii_view.nii.img = img;
nii_view.minvalue = minvalue;
nii_view.maxvalue = maxvalue;
nii_view.scanid = setscanid;
change_colormap(fig);
% init color (gray) scaling to make sure the slice clim take the
% global clim [min(nii.img(:)) max(nii.img(:))]
%
if isempty(nii_view.bgimg)
clim = [minvalue maxvalue];
else
clim = [minvalue double(max(nii_view.bgimg(:)))];
end
if clim(1) == clim(2)
clim(2) = clim(1) + 0.000001;
end
if strcmpi(get(nii_view.handles.axial_image,'cdatamapping'), 'direct')
useimagesc = 0;
else
useimagesc = 1;
end
if ~isempty(nii_view.bgimg) % with interpolation
Saxi = squeeze(nii_view.bgimg(:,:,nii_view.slices.axi));
if isfield(nii_view.handles,'axial_bg') & ~isempty(nii_view.handles.axial_bg)
set(nii_view.handles.axial_bg,'CData',double(Saxi)');
else
axes(nii_view.handles.axial_axes);
if useimagesc
nii_view.handles.axial_bg = surface(zeros(size(Saxi')),double(Saxi'),'edgecolor','none','facecolor','interp');
else
nii_view.handles.axial_bg = surface(zeros(size(Saxi')),double(Saxi'),'cdatamapping','direct','edgecolor','none','facecolor','interp');
end
order = get(gca,'child');
order(find(order == nii_view.handles.axial_bg)) = [];
order = [order; nii_view.handles.axial_bg];
set(gca, 'child', order);
end
end
if isfield(nii_view.handles,'axial_image'),
if nii_view.nii.hdr.dime.datatype == 128 | nii_view.nii.hdr.dime.datatype == 511
Saxi = squeeze(nii_view.nii.img(:,:,nii_view.slices.axi,:,setscanid));
Saxi = permute(Saxi, [2 1 3]);
else
Saxi = squeeze(nii_view.nii.img(:,:,nii_view.slices.axi,setscanid));
Saxi = Saxi';
end
set(nii_view.handles.axial_image,'CData',double(Saxi));
end
set(nii_view.handles.axial_axes,'CLim',clim);
if ~isempty(nii_view.bgimg)
Scor = squeeze(nii_view.bgimg(:,nii_view.slices.cor,:));
if isfield(nii_view.handles,'coronal_bg') & ~isempty(nii_view.handles.coronal_bg)
set(nii_view.handles.coronal_bg,'CData',double(Scor)');
else
axes(nii_view.handles.coronal_axes);
if useimagesc
nii_view.handles.coronal_bg = surface(zeros(size(Scor')),double(Scor'),'edgecolor','none','facecolor','interp');
else
nii_view.handles.coronal_bg = surface(zeros(size(Scor')),double(Scor'),'cdatamapping','direct','edgecolor','none','facecolor','interp');
end
order = get(gca,'child');
order(find(order == nii_view.handles.coronal_bg)) = [];
order = [order; nii_view.handles.coronal_bg];
set(gca, 'child', order);
end
end
if isfield(nii_view.handles,'coronal_image'),
if nii_view.nii.hdr.dime.datatype == 128 | nii_view.nii.hdr.dime.datatype == 511
Scor = squeeze(nii_view.nii.img(:,nii_view.slices.cor,:,:,setscanid));
Scor = permute(Scor, [2 1 3]);
else
Scor = squeeze(nii_view.nii.img(:,nii_view.slices.cor,:,setscanid));
Scor = Scor';
end
set(nii_view.handles.coronal_image,'CData',double(Scor));
end
set(nii_view.handles.coronal_axes,'CLim',clim);
if ~isempty(nii_view.bgimg)
Ssag = squeeze(nii_view.bgimg(nii_view.slices.sag,:,:));
if isfield(nii_view.handles,'sagittal_bg') & ~isempty(nii_view.handles.sagittal_bg)
set(nii_view.handles.sagittal_bg,'CData',double(Ssag)');
else
axes(nii_view.handles.sagittal_axes);
if useimagesc
nii_view.handles.sagittal_bg = surface(zeros(size(Ssag')),double(Ssag'),'edgecolor','none','facecolor','interp');
else
nii_view.handles.sagittal_bg = surface(zeros(size(Ssag')),double(Ssag'),'cdatamapping','direct','edgecolor','none','facecolor','interp');
end
order = get(gca,'child');
order(find(order == nii_view.handles.sagittal_bg)) = [];
order = [order; nii_view.handles.sagittal_bg];
set(gca, 'child', order);
end
end
if isfield(nii_view.handles,'sagittal_image'),
if nii_view.nii.hdr.dime.datatype == 128 | nii_view.nii.hdr.dime.datatype == 511
Ssag = squeeze(nii_view.nii.img(nii_view.slices.sag,:,:,:,setscanid));
Ssag = permute(Ssag, [2 1 3]);
else
Ssag = squeeze(nii_view.nii.img(nii_view.slices.sag,:,:,setscanid));
Ssag = Ssag';
end
set(nii_view.handles.sagittal_image,'CData',double(Ssag));
end
set(nii_view.handles.sagittal_axes,'CLim',clim);
update_nii_view(nii_view);
if isfield(opt, 'setvalue')
if ~isfield(nii_view,'highcolor') | ~isequal(size(nii_view.highcolor),[56 3])
% 55 level for brain structure (paded 0 for highcolor level 1, i.e. normal level 201, to make 56 highcolor)
%
update_highcolor(fig, [zeros(1,3);gray(55)], []);
end
if nii_view.colorindex ~= 2
update_colorindex(fig, 2);
end
old_color = get(nii_view.handles.xhair_color,'user');
if isequal(old_color, [1 0 0])
update_crosshaircolor(fig, [1 1 0]);
end
% if change_interp
% update_useinterp(fig, nii_view.useinterp);
% end
end
if change_interp
update_useinterp(fig, nii_view.useinterp);
end
return; % update_img
%----------------------------------------------------------------
function [top_pos, front_pos, side_pos] = ...
axes_pos(fig,area,vol_size,usestretch)
set(fig,'unit','pixel');
fig_pos = get(fig,'position');
gap_x = 15/fig_pos(3); % width of vertical scrollbar
gap_y = 15/fig_pos(4); % width of horizontal scrollbar
a = (area(3) - gap_x * 1.3) * fig_pos(3) / (vol_size(1) + vol_size(2)); % no crosshair lost in zoom
b = (area(4) - gap_y * 3) * fig_pos(4) / (vol_size(2) + vol_size(3));
c = min([a b]); % make sure 'ax' is inside 'area'
top_w = vol_size(1) * c / fig_pos(3);
side_w = vol_size(2) * c / fig_pos(3);
top_h = vol_size(2) * c / fig_pos(4);
side_h = vol_size(3) * c / fig_pos(4);
side_x = area(1) + top_w + gap_x * 1.3; % no crosshair lost in zoom
side_y = area(2) + top_h + gap_y * 3;
if usestretch
if a > b % top touched ceiling, use b
d = (area(3) - gap_x * 1.3) / (top_w + side_w); % no crosshair lost in zoom
top_w = top_w * d;
side_w = side_w * d;
side_x = area(1) + top_w + gap_x * 1.3; % no crosshair lost in zoom
else
d = (area(4) - gap_y * 3) / (top_h + side_h);
top_h = top_h * d;
side_h = side_h * d;
side_y = area(2) + top_h + gap_y * 3;
end
end
top_pos = [area(1) area(2)+gap_y top_w top_h];
front_pos = [area(1) side_y top_w side_h];
side_pos = [side_x side_y side_w side_h];
set(fig,'unit','normal');
return; % axes_pos
%----------------------------------------------------------------
function [top_ax, front_ax, side_ax] ...
= create_ax(fig, area, vol_size, usestretch)
cur_fig = gcf; % save h_wait fig
figure(fig);
[top_pos, front_pos, side_pos] = ...
axes_pos(fig,area,vol_size,usestretch);
nii_view = getappdata(fig, 'nii_view');
if isempty(nii_view)
top_ax = axes('position', top_pos);
front_ax = axes('position', front_pos);
side_ax = axes('position', side_pos);
else
top_ax = nii_view.handles.axial_axes;
front_ax = nii_view.handles.coronal_axes;
side_ax = nii_view.handles.sagittal_axes;
set(top_ax, 'position', top_pos);
set(front_ax, 'position', front_pos);
set(side_ax, 'position', side_pos);
end
figure(cur_fig);
return; % create_ax
%----------------------------------------------------------------
function [cbar_axes, cbarminmax_axes] = create_cbar_axes(fig, cbar_area, nii_view)
if isempty(cbar_area) % without_cbar
cbar_axes = [];
cbarminmax_axes = [];
return;
end
cur_fig = gcf; % save h_wait fig
figure(fig);
if ~exist('nii_view', 'var')
nii_view = getappdata(fig, 'nii_view');
end
if isempty(nii_view) | ~isfield(nii_view.handles,'cbar_axes') | isempty(nii_view.handles.cbar_axes)
cbarminmax_axes = axes('position', cbar_area);
cbar_axes = axes('position', cbar_area);
else
cbarminmax_axes = nii_view.handles.cbarminmax_axes;
cbar_axes = nii_view.handles.cbar_axes;
set(cbarminmax_axes, 'position', cbar_area);
set(cbar_axes, 'position', cbar_area);
end
figure(cur_fig);
return; % create_cbar_axes
%----------------------------------------------------------------
function h1 = plot_view(fig, x, y, img_ax, img_slice, clim, ...
cbarminmax, handles, useimagesc, colorindex, color_map, ...
colorlevel, highcolor, useinterp, numscan)
h1 = [];
if x > 1 & y > 1,
axes(img_ax);
nii_view = getappdata(fig, 'nii_view');
if isempty(nii_view)
% set colormap first
%
nii.handles = handles;
nii.handles.axial_axes = img_ax;
nii.colorindex = colorindex;
nii.color_map = color_map;
nii.colorlevel = colorlevel;
nii.highcolor = highcolor;
nii.numscan = numscan;
change_colormap(fig, nii, colorindex, cbarminmax);
if useinterp
if useimagesc
h1 = surface(zeros(size(img_slice)),double(img_slice),'edgecolor','none','facecolor','interp');
else
h1 = surface(zeros(size(img_slice)),double(img_slice),'cdatamapping','direct','edgecolor','none','facecolor','interp');
end
set(gca,'clim',clim);
else
if useimagesc
h1 = imagesc(img_slice,clim);
else
h1 = image(img_slice);
end
set(gca,'clim',clim);
end
else
h1 = nii_view.handles.axial_image;
if ~isequal(get(h1,'parent'), img_ax)
h1 = nii_view.handles.coronal_image;
end
if ~isequal(get(h1,'parent'), img_ax)
h1 = nii_view.handles.sagittal_image;
end
set(h1, 'cdata', double(img_slice));
set(h1, 'xdata', 1:size(img_slice,2));
set(h1, 'ydata', 1:size(img_slice,1));
end
set(img_ax,'YDir','normal','XLimMode','manual','YLimMode','manual',...
'ClimMode','manual','visible','off', ...
'xtick',[],'ytick',[], 'clim', clim);
end
return; % plot_view
%----------------------------------------------------------------
function h1 = plot_cbar(fig, cbar_axes, cbarminmax_axes, cbarminmax, ...
level, handles, useimagesc, colorindex, color_map, ...
colorlevel, highcolor, niiclass, numscan, nii_view)
cbar_image = [1:level]';
% In a uint8 or uint16 indexed image, 0 points to the first row
% in the colormap
%
if 0 % strcmpi(niiclass,'uint8') | strcmpi(niiclass,'uint16')
% we use single for display anyway
ylim = [0, level-1];
else
ylim = [1, level];
end
axes(cbarminmax_axes);
plot([0 0], cbarminmax, 'w');
axis tight;
set(cbarminmax_axes,'YDir','normal', ...
'XLimMode','manual','YLimMode','manual','YColor',[0 0 0], ...
'XColor',[0 0 0],'xtick',[],'YAxisLocation','right');
ylimb = get(cbarminmax_axes,'ylim');
ytickb = get(cbarminmax_axes,'ytick');
ytick=(ylim(2)-ylim(1))*(ytickb-ylimb(1))/(ylimb(2)-ylimb(1))+ylim(1);
axes(cbar_axes);
if ~exist('nii_view', 'var')
nii_view = getappdata(fig, 'nii_view');
end
if isempty(nii_view) | ~isfield(nii_view.handles,'cbar_image') | isempty(nii_view.handles.cbar_image)
% set colormap first
%
nii.handles = handles;
nii.colorindex = colorindex;
nii.color_map = color_map;
nii.colorlevel = colorlevel;
nii.highcolor = highcolor;
nii.numscan = numscan;
change_colormap(fig, nii, colorindex, cbarminmax);
h1 = image([0,1], [ylim(1),ylim(2)], cbar_image);
else
h1 = nii_view.handles.cbar_image;
set(h1, 'cdata', double(cbar_image));
end
set(cbar_axes,'YDir','normal','XLimMode','manual', ...
'YLimMode','manual','YColor',[0 0 0],'XColor',[0 0 0],'xtick',[], ...
'YAxisLocation','right','ylim',ylim,'ytick',ytick,'yticklabel','');
return; % plot_cbar
%----------------------------------------------------------------
function set_coordinates(nii_view,useinterp)
imgPlim.vox = nii_view.dims;
imgNlim.vox = [1 1 1];
if useinterp
xdata_ax = [imgNlim.vox(1) imgPlim.vox(1)];
ydata_ax = [imgNlim.vox(2) imgPlim.vox(2)];
zdata_ax = [imgNlim.vox(3) imgPlim.vox(3)];
else
xdata_ax = [imgNlim.vox(1)-0.5 imgPlim.vox(1)+0.5];
ydata_ax = [imgNlim.vox(2)-0.5 imgPlim.vox(2)+0.5];
zdata_ax = [imgNlim.vox(3)-0.5 imgPlim.vox(3)+0.5];
end
if isfield(nii_view.handles,'axial_image') & ~isempty(nii_view.handles.axial_image)
set(nii_view.handles.axial_axes,'Xlim',xdata_ax);
set(nii_view.handles.axial_axes,'Ylim',ydata_ax);
end;
if isfield(nii_view.handles,'coronal_image') & ~isempty(nii_view.handles.coronal_image)
set(nii_view.handles.coronal_axes,'Xlim',xdata_ax);
set(nii_view.handles.coronal_axes,'Ylim',zdata_ax);
end;
if isfield(nii_view.handles,'sagittal_image') & ~isempty(nii_view.handles.sagittal_image)
set(nii_view.handles.sagittal_axes,'Xlim',ydata_ax);
set(nii_view.handles.sagittal_axes,'Ylim',zdata_ax);
end;
return % set_coordinates
%----------------------------------------------------------------
function set_image_value(nii_view),
% get coordinates of selected voxel and the image intensity there
%
sag = round(nii_view.slices.sag);
cor = round(nii_view.slices.cor);
axi = round(nii_view.slices.axi);
if 0 % isfield(nii_view, 'disp')
img = nii_view.disp;
else
img = nii_view.nii.img;
end
if nii_view.nii.hdr.dime.datatype == 128
imgvalue = [double(img(sag,cor,axi,1,nii_view.scanid)) double(img(sag,cor,axi,2,nii_view.scanid)) double(img(sag,cor,axi,3,nii_view.scanid))];
set(nii_view.handles.imval,'Value',imgvalue);
set(nii_view.handles.imval,'String',sprintf('%7.4g %7.4g %7.4g',imgvalue));
elseif nii_view.nii.hdr.dime.datatype == 511
R = double(img(sag,cor,axi,1,nii_view.scanid)) * (nii_view.nii.hdr.dime.glmax - ...
nii_view.nii.hdr.dime.glmin) + nii_view.nii.hdr.dime.glmin;
G = double(img(sag,cor,axi,2,nii_view.scanid)) * (nii_view.nii.hdr.dime.glmax - ...
nii_view.nii.hdr.dime.glmin) + nii_view.nii.hdr.dime.glmin;
B = double(img(sag,cor,axi,3,nii_view.scanid)) * (nii_view.nii.hdr.dime.glmax - ...
nii_view.nii.hdr.dime.glmin) + nii_view.nii.hdr.dime.glmin;
imgvalue = [double(img(sag,cor,axi,1,nii_view.scanid)) double(img(sag,cor,axi,2,nii_view.scanid)) double(img(sag,cor,axi,3,nii_view.scanid))];
set(nii_view.handles.imval,'Value',imgvalue);
imgvalue = [R G B];
set(nii_view.handles.imval,'String',sprintf('%7.4g %7.4g %7.4g',imgvalue));
else
imgvalue = double(img(sag,cor,axi,nii_view.scanid));
set(nii_view.handles.imval,'Value',imgvalue);
if isnan(imgvalue) | imgvalue > nii_view.cbarminmax(2)
imgvalue = 0;
end
set(nii_view.handles.imval,'String',sprintf('%.6g',imgvalue));
end
% Now update the coordinates of the selected voxel
nii_view = update_imgXYZ(nii_view);
if get(nii_view.handles.coord,'value') == 1,
sag = nii_view.imgXYZ.vox(1);
cor = nii_view.imgXYZ.vox(2);
axi = nii_view.imgXYZ.vox(3);
org = nii_view.origin;
elseif get(nii_view.handles.coord,'value') == 2,
sag = nii_view.imgXYZ.mm(1);
cor = nii_view.imgXYZ.mm(2);
axi = nii_view.imgXYZ.mm(3);
org = [0 0 0];
elseif get(nii_view.handles.coord,'value') == 3,
sag = nii_view.imgXYZ.tal(1);
cor = nii_view.imgXYZ.tal(2);
axi = nii_view.imgXYZ.tal(3);
org = [0 0 0];
end
set(nii_view.handles.impos,'Value',[sag,cor,axi]);
if get(nii_view.handles.coord,'value') == 1,
string = sprintf('%7.0f %7.0f %7.0f',sag,cor,axi);
org_str = sprintf('%7.0f %7.0f %7.0f', org(1), org(2), org(3));
else
string = sprintf('%7.1f %7.1f %7.1f',sag,cor,axi);
org_str = sprintf('%7.1f %7.1f %7.1f', org(1), org(2), org(3));
end;
set(nii_view.handles.impos,'String',string);
set(nii_view.handles.origin, 'string', org_str);
return % set_image_value
%----------------------------------------------------------------
function nii_view = get_slice_position(nii_view,view),
% obtain slices that is in correct unit, then update slices
%
slices = nii_view.slices;
switch view,
case 'sag',
currentpoint = get(nii_view.handles.sagittal_axes,'CurrentPoint');
slices.cor = currentpoint(1,1);
slices.axi = currentpoint(1,2);
case 'cor',
currentpoint = get(nii_view.handles.coronal_axes,'CurrentPoint');
slices.sag = currentpoint(1,1);
slices.axi = currentpoint(1,2);
case 'axi',
currentpoint = get(nii_view.handles.axial_axes,'CurrentPoint');
slices.sag = currentpoint(1,1);
slices.cor = currentpoint(1,2);
end
% update nii_view.slices with the updated slices
%
nii_view.slices.axi = round(slices.axi);
nii_view.slices.cor = round(slices.cor);
nii_view.slices.sag = round(slices.sag);
return % get_slice_position
%----------------------------------------------------------------
function nii_view = get_slider_position(nii_view),
[nii_view.slices.sag,nii_view.slices.cor,nii_view.slices.axi] = deal(0);
if isfield(nii_view.handles,'sagittal_slider'),
if ishandle(nii_view.handles.sagittal_slider),
nii_view.slices.sag = ...
round(get(nii_view.handles.sagittal_slider,'Value'));
end
end
if isfield(nii_view.handles,'coronal_slider'),
if ishandle(nii_view.handles.coronal_slider),
nii_view.slices.cor = ...
round(nii_view.dims(2) - ...
get(nii_view.handles.coronal_slider,'Value') + 1);
end
end
if isfield(nii_view.handles,'axial_slider'),
if ishandle(nii_view.handles.axial_slider),
nii_view.slices.axi = ...
round(get(nii_view.handles.axial_slider,'Value'));
end
end
nii_view = check_slices(nii_view);
return % get_slider_position
%----------------------------------------------------------------
function nii_view = update_imgXYZ(nii_view),
nii_view.imgXYZ.vox = ...
[nii_view.slices.sag,nii_view.slices.cor,nii_view.slices.axi];
nii_view.imgXYZ.mm = ...
(nii_view.imgXYZ.vox - nii_view.origin) .* nii_view.voxel_size;
% nii_view.imgXYZ.tal = mni2tal(nii_view.imgXYZ.mni);
return % update_imgXYZ
%----------------------------------------------------------------
function nii_view = convert2voxel(nii_view,slices),
if get(nii_view.handles.coord,'value') == 1,
% [slices.axi, slices.cor, slices.sag] are in vox
%
nii_view.slices.axi = round(slices.axi);
nii_view.slices.cor = round(slices.cor);
nii_view.slices.sag = round(slices.sag);
elseif get(nii_view.handles.coord,'value') == 2,
% [slices.axi, slices.cor, slices.sag] are in mm
%
xpix = nii_view.voxel_size(1);
ypix = nii_view.voxel_size(2);
zpix = nii_view.voxel_size(3);
nii_view.slices.axi = round(slices.axi / zpix + nii_view.origin(3));
nii_view.slices.cor = round(slices.cor / ypix + nii_view.origin(2));
nii_view.slices.sag = round(slices.sag / xpix + nii_view.origin(1));
elseif get(nii_view.handles.coord,'value') == 3,
% [slices.axi, slices.cor, slices.sag] are in talairach
%
xpix = nii_view.voxel_size(1);
ypix = nii_view.voxel_size(2);
zpix = nii_view.voxel_size(3);
xyz_tal = [slices.sag, slices.cor, slices.axi];
xyz_mni = tal2mni(xyz_tal);
nii_view.slices.axi = round(xyz_mni(3) / zpix + nii_view.origin(3));
nii_view.slices.cor = round(xyz_mni(2) / ypix + nii_view.origin(2));
nii_view.slices.sag = round(xyz_mni(1) / xpix + nii_view.origin(1));
end
return % convert2voxel
%----------------------------------------------------------------
function nii_view = check_slices(nii_view),
img = nii_view.nii.img;
[ SagSize, CorSize, AxiSize, TimeSize ] = size(img);
if nii_view.slices.sag > SagSize, nii_view.slices.sag = SagSize; end;
if nii_view.slices.sag < 1, nii_view.slices.sag = 1; end;
if nii_view.slices.cor > CorSize, nii_view.slices.cor = CorSize; end;
if nii_view.slices.cor < 1, nii_view.slices.cor = 1; end;
if nii_view.slices.axi > AxiSize, nii_view.slices.axi = AxiSize; end;
if nii_view.slices.axi < 1, nii_view.slices.axi = 1; end;
if nii_view.scanid > TimeSize, nii_view.scanid = TimeSize; end;
if nii_view.scanid < 1, nii_view.scanid = 1; end;
return % check_slices
%----------------------------------------------------------------
%
% keep this function small, since it will be called for every click
%
function nii_view = update_nii_view(nii_view)
% add imgXYZ into nii_view struct
%
nii_view = check_slices(nii_view);
nii_view = update_imgXYZ(nii_view);
% update xhair
%
p_axi = nii_view.imgXYZ.vox([1 2]);
p_cor = nii_view.imgXYZ.vox([1 3]);
p_sag = nii_view.imgXYZ.vox([2 3]);
nii_view.axi_xhair = ...
rri_xhair(p_axi, nii_view.axi_xhair, nii_view.handles.axial_axes);
nii_view.cor_xhair = ...
rri_xhair(p_cor, nii_view.cor_xhair, nii_view.handles.coronal_axes);
nii_view.sag_xhair = ...
rri_xhair(p_sag, nii_view.sag_xhair, nii_view.handles.sagittal_axes);
setappdata(nii_view.fig, 'nii_view', nii_view);
set_image_value(nii_view);
return; % update_nii_view
%----------------------------------------------------------------
function hist_plot(fig)
nii_view = getappdata(fig,'nii_view');
if isfield(nii_view, 'disp')
img = nii_view.disp;
else
img = nii_view.nii.img;
end
img = double(img(:));
if length(unique(round(img))) == length(unique(img))
is_integer = 1;
range = max(img) - min(img) + 1;
figure; hist(img, range);
set(gca, 'xlim', [-range/5, max(img)]);
else
is_integer = 0;
figure; hist(img);
end
xlabel('Voxel Intensity');
ylabel('Voxel Numbers for Each Intensity');
set(gcf, 'NumberTitle','off','Name','Histogram Plot');
return; % hist_plot
%----------------------------------------------------------------
function hist_eq(fig)
nii_view = getappdata(fig,'nii_view');
old_pointer = get(fig,'Pointer');
set(fig,'Pointer','watch');
if get(nii_view.handles.hist_eq,'value')
max_img = double(max(nii_view.nii.img(:)));
tmp = double(nii_view.nii.img) / max_img; % normalize for histeq
tmp = histeq(tmp(:));
nii_view.disp = reshape(tmp, size(nii_view.nii.img));
min_disp = min(nii_view.disp(:));
nii_view.disp = (nii_view.disp - min_disp); % range having eq hist
nii_view.disp = nii_view.disp * max_img / max(nii_view.disp(:));
nii_view.disp = single(nii_view.disp);
else
if isfield(nii_view, 'disp')
nii_view.disp = nii_view.nii.img;
else
set(fig,'Pointer',old_pointer);
return;
end
end
% update axial view
%
img_slice = squeeze(double(nii_view.disp(:,:,nii_view.slices.axi)));
h1 = nii_view.handles.axial_image;
set(h1, 'cdata', double(img_slice)');
% update coronal view
%
img_slice = squeeze(double(nii_view.disp(:,nii_view.slices.cor,:)));
h1 = nii_view.handles.coronal_image;
set(h1, 'cdata', double(img_slice)');
% update sagittal view
%
img_slice = squeeze(double(nii_view.disp(nii_view.slices.sag,:,:)));
h1 = nii_view.handles.sagittal_image;
set(h1, 'cdata', double(img_slice)');
% remove disp field if un-check 'histeq' button
%
if ~get(nii_view.handles.hist_eq,'value') & isfield(nii_view, 'disp')
nii_view = rmfield(nii_view, 'disp');
end
update_nii_view(nii_view);
set(fig,'Pointer',old_pointer);
return; % hist_eq
%----------------------------------------------------------------
function [top1_label, top2_label, side1_label, side2_label] = ...
dir_label(fig, top_ax, front_ax, side_ax)
nii_view = getappdata(fig,'nii_view');
top_pos = get(top_ax,'position');
front_pos = get(front_ax,'position');
side_pos = get(side_ax,'position');
top_gap_x = (side_pos(1)-top_pos(1)-top_pos(3)) / (2*top_pos(3));
top_gap_y = (front_pos(2)-top_pos(2)-top_pos(4)) / (2*top_pos(4));
side_gap_x = (side_pos(1)-top_pos(1)-top_pos(3)) / (2*side_pos(3));
side_gap_y = (front_pos(2)-top_pos(2)-top_pos(4)) / (2*side_pos(4));
top1_label_pos = [0, 1]; % rot0
top2_label_pos = [1, 0]; % rot90
side1_label_pos = [1, - side_gap_y]; % rot0
side2_label_pos = [0, 0]; % rot90
if isempty(nii_view)
axes(top_ax);
top1_label = text(double(top1_label_pos(1)),double(top1_label_pos(2)), ...
'== X =>', ...
'vertical', 'bottom', ...
'unit', 'normal', 'fontsize', 8);
axes(top_ax);
top2_label = text(double(top2_label_pos(1)),double(top2_label_pos(2)), ...
'== Y =>', ...
'rotation', 90, 'vertical', 'top', ...
'unit', 'normal', 'fontsize', 8);
axes(side_ax);
side1_label = text(double(side1_label_pos(1)),double(side1_label_pos(2)), ...
'<= Y ==', ...
'horizontal', 'right', 'vertical', 'top', ...
'unit', 'normal', 'fontsize', 8);
axes(side_ax);
side2_label = text(double(side2_label_pos(1)),double(side2_label_pos(2)), ...
'== Z =>', ...
'rotation', 90, 'vertical', 'bottom', ...
'unit', 'normal', 'fontsize', 8);
else
top1_label = nii_view.handles.top1_label;
top2_label = nii_view.handles.top2_label;
side1_label = nii_view.handles.side1_label;
side2_label = nii_view.handles.side2_label;
set(top1_label, 'position', [top1_label_pos 0]);
set(top2_label, 'position', [top2_label_pos 0]);
set(side1_label, 'position', [side1_label_pos 0]);
set(side2_label, 'position', [side2_label_pos 0]);
end
return; % dir_label
%----------------------------------------------------------------
function update_enable(h, opt);
nii_view = getappdata(h,'nii_view');
handles = nii_view.handles;
if isfield(opt,'enablecursormove')
if opt.enablecursormove
v = 'on';
else
v = 'off';
end
set(handles.Timposcur, 'visible', v);
set(handles.imposcur, 'visible', v);
set(handles.Timvalcur, 'visible', v);
set(handles.imvalcur, 'visible', v);
end
if isfield(opt,'enableviewpoint')
if opt.enableviewpoint
v = 'on';
else
v = 'off';
end
set(handles.Timpos, 'visible', v);
set(handles.impos, 'visible', v);
set(handles.Timval, 'visible', v);
set(handles.imval, 'visible', v);
end
if isfield(opt,'enableorigin')
if opt.enableorigin
v = 'on';
else
v = 'off';
end
set(handles.Torigin, 'visible', v);
set(handles.origin, 'visible', v);
end
if isfield(opt,'enableunit')
if opt.enableunit
v = 'on';
else
v = 'off';
end
set(handles.Tcoord, 'visible', v);
set(handles.coord_frame, 'visible', v);
set(handles.coord, 'visible', v);
end
if isfield(opt,'enablecrosshair')
if opt.enablecrosshair
v = 'on';
else
v = 'off';
end
set(handles.Txhair, 'visible', v);
set(handles.xhair_color, 'visible', v);
set(handles.xhair, 'visible', v);
end
if isfield(opt,'enablehistogram')
if opt.enablehistogram
v = 'on';
vv = 'off';
else
v = 'off';
vv = 'on';
end
set(handles.Tcoord, 'visible', vv);
set(handles.coord_frame, 'visible', vv);
set(handles.coord, 'visible', vv);
set(handles.Thist, 'visible', v);
set(handles.hist_frame, 'visible', v);
set(handles.hist_eq, 'visible', v);
set(handles.hist_plot, 'visible', v);
end
if isfield(opt,'enablecolormap')
if opt.enablecolormap
v = 'on';
else
v = 'off';
end
set(handles.Tcolor, 'visible', v);
set(handles.color_frame, 'visible', v);
set(handles.neg_color, 'visible', v);
set(handles.colorindex, 'visible', v);
end
if isfield(opt,'enablecontrast')
if opt.enablecontrast
v = 'on';
else
v = 'off';
end
set(handles.Tcontrast, 'visible', v);
set(handles.contrast_frame, 'visible', v);
set(handles.contrast_def, 'visible', v);
set(handles.contrast, 'visible', v);
end
if isfield(opt,'enablebrightness')
if opt.enablebrightness
v = 'on';
else
v = 'off';
end
set(handles.Tbrightness, 'visible', v);
set(handles.brightness_frame, 'visible', v);
set(handles.brightness_def, 'visible', v);
set(handles.brightness, 'visible', v);
end
if isfield(opt,'enabledirlabel')
if opt.enabledirlabel
v = 'on';
else
v = 'off';
end
set(handles.top1_label, 'visible', v);
set(handles.top2_label, 'visible', v);
set(handles.side1_label, 'visible', v);
set(handles.side2_label, 'visible', v);
end
if isfield(opt,'enableslider')
if opt.enableslider
v = 'on';
else
v = 'off';
end
if isfield(handles,'sagittal_slider') & ishandle(handles.sagittal_slider)
set(handles.sagittal_slider, 'visible', v);
end
if isfield(handles,'coronal_slider') & ishandle(handles.coronal_slider)
set(handles.coronal_slider, 'visible', v);
end
if isfield(handles,'axial_slider') & ishandle(handles.axial_slider)
set(handles.axial_slider, 'visible', v);
end
end
return; % update_enable
%----------------------------------------------------------------
function update_usepanel(fig, usepanel)
if isempty(usepanel)
return;
end
if usepanel
opt.enablecursormove = 1;
opt.enableviewpoint = 1;
opt.enableorigin = 1;
opt.enableunit = 1;
opt.enablecrosshair = 1;
% opt.enablehistogram = 1;
opt.enablecolormap = 1;
opt.enablecontrast = 1;
opt.enablebrightness = 1;
else
opt.enablecursormove = 0;
opt.enableviewpoint = 0;
opt.enableorigin = 0;
opt.enableunit = 0;
opt.enablecrosshair = 0;
% opt.enablehistogram = 0;
opt.enablecolormap = 0;
opt.enablecontrast = 0;
opt.enablebrightness = 0;
end
update_enable(fig, opt);
nii_view = getappdata(fig,'nii_view');
nii_view.usepanel = usepanel;
setappdata(fig,'nii_view',nii_view);
return; % update_usepanel
%----------------------------------------------------------------
function update_usecrosshair(fig, usecrosshair)
if isempty(usecrosshair)
return;
end
if usecrosshair
v=1;
else
v=2;
end
nii_view = getappdata(fig,'nii_view');
set(nii_view.handles.xhair,'value',v);
opt.command = 'crosshair';
view_nii(fig, opt);
return; % update_usecrosshair
%----------------------------------------------------------------
function update_usestretch(fig, usestretch)
nii_view = getappdata(fig,'nii_view');
handles = nii_view.handles;
fig = nii_view.fig;
area = nii_view.area;
vol_size = nii_view.voxel_size .* nii_view.dims;
% Three Axes & label
%
[top_ax, front_ax, side_ax] = ...
create_ax(fig, area, vol_size, usestretch);
dir_label(fig, top_ax, front_ax, side_ax);
top_pos = get(top_ax,'position');
front_pos = get(front_ax,'position');
side_pos = get(side_ax,'position');
% Sagittal Slider
%
x = side_pos(1);
y = top_pos(2) + top_pos(4);
w = side_pos(3);
h = (front_pos(2) - y) / 2;
y = y + h;
pos = [x y w h];
if isfield(handles,'sagittal_slider') & ishandle(handles.sagittal_slider)
set(handles.sagittal_slider,'position',pos);
end
% Coronal Slider
%
x = top_pos(1);
y = top_pos(2) + top_pos(4);
w = top_pos(3);
h = (front_pos(2) - y) / 2;
y = y + h;
pos = [x y w h];
if isfield(handles,'coronal_slider') & ishandle(handles.coronal_slider)
set(handles.coronal_slider,'position',pos);
end
% Axial Slider
%
x = top_pos(1);
y = area(2);
w = top_pos(3);
h = top_pos(2) - y;
pos = [x y w h];
if isfield(handles,'axial_slider') & ishandle(handles.axial_slider)
set(handles.axial_slider,'position',pos);
end
% plot info view
%
% info_pos = [side_pos([1,3]); top_pos([2,4])];
% info_pos = info_pos(:);
gap = side_pos(1)-(top_pos(1)+top_pos(3));
info_pos(1) = side_pos(1) + gap;
info_pos(2) = area(2);
info_pos(3) = side_pos(3) - gap;
info_pos(4) = top_pos(2) + top_pos(4) - area(2) - gap;
num_inputline = 10;
inputline_space =info_pos(4) / num_inputline;
% Image Intensity Value at Cursor
%
x = info_pos(1);
y = info_pos(2);
w = info_pos(3)*0.5;
h = inputline_space*0.6;
pos = [x y w h];
set(handles.Timvalcur,'position',pos);
x = x + w;
w = info_pos(3)*0.5;
pos = [x y w h];
set(handles.imvalcur,'position',pos);
% Position at Cursor
%
x = info_pos(1);
y = y + inputline_space;
w = info_pos(3)*0.5;
pos = [x y w h];
set(handles.Timposcur,'position',pos);
x = x + w;
w = info_pos(3)*0.5;
pos = [x y w h];
set(handles.imposcur,'position',pos);
% Image Intensity Value at Mouse Click
%
x = info_pos(1);
y = y + inputline_space;
w = info_pos(3)*0.5;
pos = [x y w h];
set(handles.Timval,'position',pos);
x = x + w;
w = info_pos(3)*0.5;
pos = [x y w h];
set(handles.imval,'position',pos);
% Viewpoint Position at Mouse Click
%
x = info_pos(1);
y = y + inputline_space;
w = info_pos(3)*0.5;
pos = [x y w h];
set(handles.Timpos,'position',pos);
x = x + w + 0.005;
y = y - 0.008;
w = info_pos(3)*0.5;
h = inputline_space*0.9;
pos = [x y w h];
set(handles.impos,'position',pos);
% Origin Position
%
x = info_pos(1);
y = y + inputline_space*1.2;
w = info_pos(3)*0.5;
h = inputline_space*0.6;
pos = [x y w h];
set(handles.Torigin,'position',pos);
x = x + w;
w = info_pos(3)*0.5;
pos = [x y w h];
set(handles.origin,'position',pos);
if 0
% Axes Unit
%
x = info_pos(1);
y = y + inputline_space;
w = info_pos(3)*0.5;
pos = [x y w h];
set(handles.Tcoord,'position',pos);
x = x + w + 0.005;
w = info_pos(3)*0.5 - 0.005;
pos = [x y w h];
set(handles.coord,'position',pos);
end
% Crosshair
%
x = info_pos(1);
y = y + inputline_space;
w = info_pos(3)*0.4;
pos = [x y w h];
set(handles.Txhair,'position',pos);
x = info_pos(1) + info_pos(3)*0.5;
w = info_pos(3)*0.2;
h = inputline_space*0.7;
pos = [x y w h];
set(handles.xhair_color,'position',pos);
x = info_pos(1) + info_pos(3)*0.7;
w = info_pos(3)*0.3;
pos = [x y w h];
set(handles.xhair,'position',pos);
% Histogram & Color
%
x = info_pos(1);
w = info_pos(3)*0.45;
h = inputline_space * 1.5;
pos = [x, y+inputline_space*0.9, w, h];
set(handles.hist_frame,'position',pos);
set(handles.coord_frame,'position',pos);
x = info_pos(1) + info_pos(3)*0.475;
w = info_pos(3)*0.525;
h = inputline_space * 1.5;
pos = [x, y+inputline_space*0.9, w, h];
set(handles.color_frame,'position',pos);
x = info_pos(1) + info_pos(3)*0.025;
y = y + inputline_space*1.2;
w = info_pos(3)*0.2;
h = inputline_space*0.7;
pos = [x y w h];
set(handles.hist_eq,'position',pos);
x = x + w;
w = info_pos(3)*0.2;
pos = [x y w h];
set(handles.hist_plot,'position',pos);
x = info_pos(1) + info_pos(3)*0.025;
w = info_pos(3)*0.4;
pos = [x y w h];
set(handles.coord,'position',pos);
x = info_pos(1) + info_pos(3)*0.5;
w = info_pos(3)*0.2;
pos = [x y w h];
set(handles.neg_color,'position',pos);
x = info_pos(1) + info_pos(3)*0.7;
w = info_pos(3)*0.275;
pos = [x y w h];
set(handles.colorindex,'position',pos);
x = info_pos(1) + info_pos(3)*0.1;
y = y + inputline_space;
w = info_pos(3)*0.28;
h = inputline_space*0.6;
pos = [x y w h];
set(handles.Thist,'position',pos);
set(handles.Tcoord,'position',pos);
x = info_pos(1) + info_pos(3)*0.60;
w = info_pos(3)*0.28;
pos = [x y w h];
set(handles.Tcolor,'position',pos);
% Contrast Frame
%
x = info_pos(1);
w = info_pos(3)*0.45;
h = inputline_space * 2;
pos = [x, y+inputline_space*0.8, w, h];
set(handles.contrast_frame,'position',pos);
% Brightness Frame
%
x = info_pos(1) + info_pos(3)*0.475;
w = info_pos(3)*0.525;
pos = [x, y+inputline_space*0.8, w, h];
set(handles.brightness_frame,'position',pos);
% Contrast
%
x = info_pos(1) + info_pos(3)*0.025;
y = y + inputline_space;
w = info_pos(3)*0.4;
h = inputline_space*0.6;
pos = [x y w h];
set(handles.contrast,'position',pos);
% Brightness
%
x = info_pos(1) + info_pos(3)*0.5;
w = info_pos(3)*0.475;
pos = [x y w h];
set(handles.brightness,'position',pos);
% Contrast text/def
%
x = info_pos(1) + info_pos(3)*0.025;
y = y + inputline_space;
w = info_pos(3)*0.22;
pos = [x y w h];
set(handles.Tcontrast,'position',pos);
x = x + w;
w = info_pos(3)*0.18;
pos = [x y w h];
set(handles.contrast_def,'position',pos);
% Brightness text/def
%
x = info_pos(1) + info_pos(3)*0.5;
w = info_pos(3)*0.295;
pos = [x y w h];
set(handles.Tbrightness,'position',pos);
x = x + w;
w = info_pos(3)*0.18;
pos = [x y w h];
set(handles.brightness_def,'position',pos);
return; % update_usestretch
%----------------------------------------------------------------
function update_useinterp(fig, useinterp)
if isempty(useinterp)
return;
end
nii_menu = getappdata(fig, 'nii_menu');
if ~isempty(nii_menu)
if get(nii_menu.Minterp,'user')
set(nii_menu.Minterp,'Userdata',0,'Label','Interp off');
else
set(nii_menu.Minterp,'Userdata',1,'Label','Interp on');
end
end
nii_view = getappdata(fig, 'nii_view');
nii_view.useinterp = useinterp;
if ~isempty(nii_view.handles.axial_image)
if strcmpi(get(nii_view.handles.axial_image,'cdatamapping'), 'direct')
useimagesc = 0;
else
useimagesc = 1;
end
elseif ~isempty(nii_view.handles.coronal_image)
if strcmpi(get(nii_view.handles.coronal_image,'cdatamapping'), 'direct')
useimagesc = 0;
else
useimagesc = 1;
end
else
if strcmpi(get(nii_view.handles.sagittal_image,'cdatamapping'), 'direct')
useimagesc = 0;
else
useimagesc = 1;
end
end
if ~isempty(nii_view.handles.axial_image)
img_slice = get(nii_view.handles.axial_image, 'cdata');
delete(nii_view.handles.axial_image);
axes(nii_view.handles.axial_axes);
clim = get(gca,'clim');
if useinterp
if useimagesc
nii_view.handles.axial_image = surface(zeros(size(img_slice)),double(img_slice),'edgecolor','none','facecolor','interp');
else
nii_view.handles.axial_image = surface(zeros(size(img_slice)),double(img_slice),'cdatamapping','direct','edgecolor','none','facecolor','interp');
end
else
if useimagesc
nii_view.handles.axial_image = imagesc('cdata',img_slice);
else
nii_view.handles.axial_image = image('cdata',img_slice);
end
end
set(gca,'clim',clim);
order = get(gca,'child');
order(find(order == nii_view.handles.axial_image)) = [];
order = [order; nii_view.handles.axial_image];
if isfield(nii_view.handles,'axial_bg') & ~isempty(nii_view.handles.axial_bg)
order(find(order == nii_view.handles.axial_bg)) = [];
order = [order; nii_view.handles.axial_bg];
end
set(gca, 'child', order);
if ~useinterp
if isfield(nii_view.handles,'axial_bg') & ~isempty(nii_view.handles.axial_bg)
delete(nii_view.handles.axial_bg);
nii_view.handles.axial_bg = [];
end
end
set(nii_view.handles.axial_image,'buttondown','view_nii(''axial_image'');');
end
if ~isempty(nii_view.handles.coronal_image)
img_slice = get(nii_view.handles.coronal_image, 'cdata');
delete(nii_view.handles.coronal_image);
axes(nii_view.handles.coronal_axes);
clim = get(gca,'clim');
if useinterp
if useimagesc
nii_view.handles.coronal_image = surface(zeros(size(img_slice)),double(img_slice),'edgecolor','none','facecolor','interp');
else
nii_view.handles.coronal_image = surface(zeros(size(img_slice)),double(img_slice),'cdatamapping','direct','edgecolor','none','facecolor','interp');
end
else
if useimagesc
nii_view.handles.coronal_image = imagesc('cdata',img_slice);
else
nii_view.handles.coronal_image = image('cdata',img_slice);
end
end
set(gca,'clim',clim);
order = get(gca,'child');
order(find(order == nii_view.handles.coronal_image)) = [];
order = [order; nii_view.handles.coronal_image];
if isfield(nii_view.handles,'coronal_bg') & ~isempty(nii_view.handles.coronal_bg)
order(find(order == nii_view.handles.coronal_bg)) = [];
order = [order; nii_view.handles.coronal_bg];
end
set(gca, 'child', order);
if ~useinterp
if isfield(nii_view.handles,'coronal_bg') & ~isempty(nii_view.handles.coronal_bg)
delete(nii_view.handles.coronal_bg);
nii_view.handles.coronal_bg = [];
end
end
set(nii_view.handles.coronal_image,'buttondown','view_nii(''coronal_image'');');
end
if ~isempty(nii_view.handles.sagittal_image)
img_slice = get(nii_view.handles.sagittal_image, 'cdata');
delete(nii_view.handles.sagittal_image);
axes(nii_view.handles.sagittal_axes);
clim = get(gca,'clim');
if useinterp
if useimagesc
nii_view.handles.sagittal_image = surface(zeros(size(img_slice)),double(img_slice),'edgecolor','none','facecolor','interp');
else
nii_view.handles.sagittal_image = surface(zeros(size(img_slice)),double(img_slice),'cdatamapping','direct','edgecolor','none','facecolor','interp');
end
else
if useimagesc
nii_view.handles.sagittal_image = imagesc('cdata',img_slice);
else
nii_view.handles.sagittal_image = image('cdata',img_slice);
end
end
set(gca,'clim',clim);
order = get(gca,'child');
order(find(order == nii_view.handles.sagittal_image)) = [];
order = [order; nii_view.handles.sagittal_image];
if isfield(nii_view.handles,'sagittal_bg') & ~isempty(nii_view.handles.sagittal_bg)
order(find(order == nii_view.handles.sagittal_bg)) = [];
order = [order; nii_view.handles.sagittal_bg];
end
set(gca, 'child', order);
if ~useinterp
if isfield(nii_view.handles,'sagittal_bg') & ~isempty(nii_view.handles.sagittal_bg)
delete(nii_view.handles.sagittal_bg);
nii_view.handles.sagittal_bg = [];
end
end
set(nii_view.handles.sagittal_image,'buttondown','view_nii(''sagittal_image'');');
end
if ~useinterp
nii_view.bgimg = [];
end
set_coordinates(nii_view,useinterp);
setappdata(fig, 'nii_view', nii_view);
return; % update_useinterp
%----------------------------------------------------------------
function update_useimagesc(fig, useimagesc)
if isempty(useimagesc)
return;
end
if useimagesc
v='scaled';
else
v='direct';
end
nii_view = getappdata(fig,'nii_view');
handles = nii_view.handles;
if isfield(handles,'cbar_image') & ishandle(handles.cbar_image)
% set(handles.cbar_image,'cdatamapping',v);
end
set(handles.axial_image,'cdatamapping',v);
set(handles.coronal_image,'cdatamapping',v);
set(handles.sagittal_image,'cdatamapping',v);
return; % update_useimagesc
%----------------------------------------------------------------
function update_shape(fig, area, usecolorbar, usestretch, useimagesc)
nii_view = getappdata(fig,'nii_view');
if isempty(usestretch) % no change, get usestretch
stretchchange = 0;
usestretch = nii_view.usestretch;
else % change, set usestretch
stretchchange = 1;
nii_view.usestretch = usestretch;
end
if isempty(area) % no change, get area
areachange = 0;
area = nii_view.area;
elseif ~isempty(nii_view.cbar_area) % change, set area & cbar_area
areachange = 1;
cbar_area = area;
cbar_area(1) = area(1) + area(3)*0.93;
cbar_area(3) = area(3)*0.04;
area(3) = area(3)*0.9; % 90% used for main axes
[cbar_axes cbarminmax_axes] = create_cbar_axes(fig, cbar_area);
nii_view.area = area;
nii_view.cbar_area = cbar_area;
else % change, set area only
areachange = 1;
nii_view.area = area;
end
% Add colorbar
%
if ~isempty(usecolorbar) & usecolorbar & isempty(nii_view.cbar_area)
colorbarchange = 1;
cbar_area = area;
cbar_area(1) = area(1) + area(3)*0.93;
cbar_area(3) = area(3)*0.04;
area(3) = area(3)*0.9; % 90% used for main axes
% create axes for colorbar
%
[cbar_axes cbarminmax_axes] = create_cbar_axes(fig, cbar_area);
nii_view.area = area;
nii_view.cbar_area = cbar_area;
% useimagesc follows axial image
%
if isempty(useimagesc)
if strcmpi(get(nii_view.handles.axial_image,'cdatamap'),'scaled')
useimagesc = 1;
else
useimagesc = 0;
end
end
if isfield(nii_view, 'highcolor') & ~isempty(highcolor)
num_highcolor = size(nii_view.highcolor,1);
else
num_highcolor = 0;
end
if isfield(nii_view, 'colorlevel') & ~isempty(nii_view.colorlevel)
colorlevel = nii_view.colorlevel;
else
colorlevel = 256 - num_highcolor;
end
if isfield(nii_view, 'color_map')
color_map = nii_view.color_map;
else
color_map = [];
end
if isfield(nii_view, 'highcolor')
highcolor = nii_view.highcolor;
else
highcolor = [];
end
% plot colorbar
%
if 0
if isempty(color_map)
level = colorlevel + num_highcolor;
else
level = size([color_map; highcolor], 1);
end
end
if isempty(color_map)
level = colorlevel;
else
level = size([color_map], 1);
end
cbar_image = [1:level]';
niiclass = class(nii_view.nii.img);
h1 = plot_cbar(fig, cbar_axes, cbarminmax_axes, nii_view.cbarminmax, ...
level, nii_view.handles, useimagesc, nii_view.colorindex, ...
color_map, colorlevel, highcolor, niiclass, nii_view.numscan);
nii_view.handles.cbar_image = h1;
nii_view.handles.cbar_axes = cbar_axes;
nii_view.handles.cbarminmax_axes = cbar_axes;
% remove colorbar
%
elseif ~isempty(usecolorbar) & ~usecolorbar & ~isempty(nii_view.cbar_area)
colorbarchange = 1;
area(3) = area(3) / 0.9;
nii_view.area = area;
nii_view.cbar_area = [];
nii_view.handles = rmfield(nii_view.handles,'cbar_image');
delete(nii_view.handles.cbarminmax_axes);
nii_view.handles = rmfield(nii_view.handles,'cbarminmax_axes');
delete(nii_view.handles.cbar_axes);
nii_view.handles = rmfield(nii_view.handles,'cbar_axes');
else
colorbarchange = 0;
end
if colorbarchange | stretchchange | areachange
setappdata(fig,'nii_view',nii_view);
update_usestretch(fig, usestretch);
end
return; % update_shape
%----------------------------------------------------------------
function update_unit(fig, setunit)
if isempty(setunit)
return;
end
if strcmpi(setunit,'mm') | strcmpi(setunit,'millimeter') | strcmpi(setunit,'mni')
v = 2;
% elseif strcmpi(setunit,'tal') | strcmpi(setunit,'talairach')
% v = 3;
elseif strcmpi(setunit,'vox') | strcmpi(setunit,'voxel')
v = 1;
else
v = 1;
end
nii_view = getappdata(fig,'nii_view');
set(nii_view.handles.coord, 'value', v);
set_image_value(nii_view);
return; % update_unit
%----------------------------------------------------------------
function update_viewpoint(fig, setviewpoint)
if isempty(setviewpoint)
return;
end
nii_view = getappdata(fig,'nii_view');
if length(setviewpoint) ~= 3
error('Viewpoint position should contain [x y z]');
end
set(nii_view.handles.impos,'string',num2str(setviewpoint));
opt.command = 'impos_edit';
view_nii(fig, opt);
set(nii_view.handles.axial_axes,'selected','on');
set(nii_view.handles.axial_axes,'selected','off');
set(nii_view.handles.coronal_axes,'selected','on');
set(nii_view.handles.coronal_axes,'selected','off');
set(nii_view.handles.sagittal_axes,'selected','on');
set(nii_view.handles.sagittal_axes,'selected','off');
return; % update_viewpoint
%----------------------------------------------------------------
function update_scanid(fig, setscanid)
if isempty(setscanid)
return;
end
nii_view = getappdata(fig,'nii_view');
if setscanid < 1
setscanid = 1;
end
if setscanid > nii_view.numscan
setscanid = nii_view.numscan;
end
set(nii_view.handles.contrast_def,'string',num2str(setscanid));
set(nii_view.handles.contrast,'value',setscanid);
opt.command = 'updateimg';
opt.setscanid = setscanid;
view_nii(fig, nii_view.nii.img, opt);
return; % update_scanid
%----------------------------------------------------------------
function update_crosshaircolor(fig, new_color)
if isempty(new_color)
return;
end
nii_view = getappdata(fig,'nii_view');
xhair_color = nii_view.handles.xhair_color;
set(xhair_color,'user',new_color);
set(nii_view.axi_xhair.lx,'color',new_color);
set(nii_view.axi_xhair.ly,'color',new_color);
set(nii_view.cor_xhair.lx,'color',new_color);
set(nii_view.cor_xhair.ly,'color',new_color);
set(nii_view.sag_xhair.lx,'color',new_color);
set(nii_view.sag_xhair.ly,'color',new_color);
return; % update_crosshaircolor
%----------------------------------------------------------------
function update_colorindex(fig, colorindex)
if isempty(colorindex)
return;
end
nii_view = getappdata(fig,'nii_view');
nii_view.colorindex = colorindex;
setappdata(fig, 'nii_view', nii_view);
set(nii_view.handles.colorindex,'value',colorindex);
opt.command = 'color';
view_nii(fig, opt);
return; % update_colorindex
%----------------------------------------------------------------
function redraw_cbar(fig, colorlevel, color_map, highcolor)
nii_view = getappdata(fig,'nii_view');
if isempty(nii_view.cbar_area)
return;
end
colorindex = nii_view.colorindex;
if isempty(highcolor)
num_highcolor = 0;
else
num_highcolor = size(highcolor,1);
end
if isempty(colorlevel)
colorlevel=256;
end
if colorindex == 1
colorlevel = size(color_map, 1);
end
% level = colorlevel + num_highcolor;
level = colorlevel;
cbar_image = [1:level]';
cbar_area = nii_view.cbar_area;
% useimagesc follows axial image
%
if strcmpi(get(nii_view.handles.axial_image,'cdatamap'),'scaled')
useimagesc = 1;
else
useimagesc = 0;
end
niiclass = class(nii_view.nii.img);
delete(nii_view.handles.cbar_image);
delete(nii_view.handles.cbar_axes);
delete(nii_view.handles.cbarminmax_axes);
[nii_view.handles.cbar_axes nii_view.handles.cbarminmax_axes] = ...
create_cbar_axes(fig, cbar_area, []);
nii_view.handles.cbar_image = plot_cbar(fig, ...
nii_view.handles.cbar_axes, nii_view.handles.cbarminmax_axes, ...
nii_view.cbarminmax, level, nii_view.handles, useimagesc, ...
colorindex, color_map, colorlevel, highcolor, niiclass, ...
nii_view.numscan, []);
setappdata(fig, 'nii_view', nii_view);
return; % redraw_cbar
%----------------------------------------------------------------
function update_buttondown(fig, setbuttondown)
if isempty(setbuttondown)
return;
end
nii_view = getappdata(fig,'nii_view');
nii_view.buttondown = setbuttondown;
setappdata(fig, 'nii_view', nii_view);
return; % update_buttondown
%----------------------------------------------------------------
function update_cbarminmax(fig, cbarminmax)
if isempty(cbarminmax)
return;
end
nii_view = getappdata(fig, 'nii_view');
if ~isfield(nii_view.handles, 'cbarminmax_axes')
return;
end
nii_view.cbarminmax = cbarminmax;
setappdata(fig, 'nii_view', nii_view);
axes(nii_view.handles.cbarminmax_axes);
plot([0 0], cbarminmax, 'w');
axis tight;
set(nii_view.handles.cbarminmax_axes,'YDir','normal', ...
'XLimMode','manual','YLimMode','manual','YColor',[0 0 0], ...
'XColor',[0 0 0],'xtick',[],'YAxisLocation','right');
ylim = get(nii_view.handles.cbar_axes,'ylim');
ylimb = get(nii_view.handles.cbarminmax_axes,'ylim');
ytickb = get(nii_view.handles.cbarminmax_axes,'ytick');
ytick=(ylim(2)-ylim(1))*(ytickb-ylimb(1))/(ylimb(2)-ylimb(1))+ylim(1);
axes(nii_view.handles.cbar_axes);
set(nii_view.handles.cbar_axes,'YDir','normal','XLimMode','manual', ...
'YLimMode','manual','YColor',[0 0 0],'XColor',[0 0 0],'xtick',[], ...
'YAxisLocation','right','ylim',ylim,'ytick',ytick,'yticklabel','');
return; % update_cbarminmax
%----------------------------------------------------------------
function update_highcolor(fig, highcolor, colorlevel)
nii_view = getappdata(fig,'nii_view');
if ischar(highcolor) & (isempty(colorlevel) | nii_view.colorindex == 1)
return;
end
if ~ischar(highcolor)
nii_view.highcolor = highcolor;
if isempty(highcolor)
nii_view = rmfield(nii_view, 'highcolor');
end
else
highcolor = [];
end
if isempty(colorlevel) | nii_view.colorindex == 1
nii_view.colorlevel = nii_view.colorlevel - size(highcolor,1);
else
nii_view.colorlevel = colorlevel;
end
setappdata(fig, 'nii_view', nii_view);
if isfield(nii_view,'color_map')
color_map = nii_view.color_map;
else
color_map = [];
end
redraw_cbar(fig, nii_view.colorlevel, color_map, highcolor);
change_colormap(fig);
return; % update_highcolor
%----------------------------------------------------------------
function update_colormap(fig, color_map)
if ischar(color_map)
return;
end
nii_view = getappdata(fig,'nii_view');
nii = nii_view.nii;
minvalue = nii_view.minvalue;
if isempty(color_map)
if minvalue < 0
colorindex = 2;
else
colorindex = 3;
end
nii_view = rmfield(nii_view, 'color_map');
setappdata(fig,'nii_view',nii_view);
update_colorindex(fig, colorindex);
return;
else
colorindex = 1;
nii_view.color_map = color_map;
nii_view.colorindex = colorindex;
setappdata(fig,'nii_view',nii_view);
set(nii_view.handles.colorindex,'value',colorindex);
end
colorlevel = nii_view.colorlevel;
if isfield(nii_view, 'highcolor')
highcolor = nii_view.highcolor;
else
highcolor = [];
end
redraw_cbar(fig, colorlevel, color_map, highcolor);
change_colormap(fig);
opt.enablecontrast = 0;
update_enable(fig, opt);
return; % update_colormap
%----------------------------------------------------------------
function status = get_status(h);
nii_view = getappdata(h,'nii_view');
status.fig = h;
status.area = nii_view.area;
if isempty(nii_view.cbar_area)
status.usecolorbar = 0;
else
status.usecolorbar = 1;
width = status.area(3) / 0.9;
status.area(3) = width;
end
if strcmpi(get(nii_view.handles.imval,'visible'), 'on')
status.usepanel = 1;
else
status.usepanel = 0;
end
if get(nii_view.handles.xhair,'value') == 1
status.usecrosshair = 1;
else
status.usecrosshair = 0;
end
status.usestretch = nii_view.usestretch;
if strcmpi(get(nii_view.handles.axial_image,'cdatamapping'), 'direct')
status.useimagesc = 0;
else
status.useimagesc = 1;
end
status.useinterp = nii_view.useinterp;
if get(nii_view.handles.coord,'value') == 1
status.unit = 'vox';
elseif get(nii_view.handles.coord,'value') == 2
status.unit = 'mm';
elseif get(nii_view.handles.coord,'value') == 3
status.unit = 'tal';
end
status.viewpoint = get(nii_view.handles.impos,'value');
status.scanid = nii_view.scanid;
status.intensity = get(nii_view.handles.imval,'value');
status.colorindex = get(nii_view.handles.colorindex,'value');
if isfield(nii_view,'color_map')
status.colormap = nii_view.color_map;
else
status.colormap = [];
end
status.colorlevel = nii_view.colorlevel;
if isfield(nii_view,'highcolor')
status.highcolor = nii_view.highcolor;
else
status.highcolor = [];
end
status.cbarminmax = nii_view.cbarminmax;
status.buttondown = nii_view.buttondown;
return; % get_status
%----------------------------------------------------------------
function [custom_color_map, colorindex] ...
= change_colormap(fig, nii, colorindex, cbarminmax)
custom_color_map = [];
if ~exist('nii', 'var')
nii_view = getappdata(fig,'nii_view');
else
nii_view = nii;
end
if ~exist('colorindex', 'var')
colorindex = get(nii_view.handles.colorindex,'value');
end
if ~exist('cbarminmax', 'var')
cbarminmax = nii_view.cbarminmax;
end
if isfield(nii_view, 'highcolor') & ~isempty(nii_view.highcolor)
highcolor = nii_view.highcolor;
num_highcolor = size(highcolor,1);
else
highcolor = [];
num_highcolor = 0;
end
% if isfield(nii_view, 'colorlevel') & ~isempty(nii_view.colorlevel)
if nii_view.colorlevel < 256
num_color = nii_view.colorlevel;
else
num_color = 256 - num_highcolor;
end
contrast = [];
if colorindex == 3 % for gray
if nii_view.numscan > 1
contrast = 1;
else
contrast = (num_color-1)*(get(nii_view.handles.contrast,'value')-1)/255+1;
contrast = floor(contrast);
end
elseif colorindex == 2 % for bipolar
if nii_view.numscan > 1
contrast = 128;
else
contrast = get(nii_view.handles.contrast,'value');
end
end
if isfield(nii_view,'color_map') & ~isempty(nii_view.color_map)
color_map = nii_view.color_map;
custom_color_map = color_map;
elseif colorindex == 1
[f p] = uigetfile('*.txt', 'Input colormap text file');
if p==0
colorindex = nii_view.colorindex;
set(nii_view.handles.colorindex,'value',colorindex);
return;
end;
try
custom_color_map = load(fullfile(p,f));
loadfail = 0;
catch
loadfail = 1;
end
if loadfail | isempty(custom_color_map) | size(custom_color_map,2)~=3 ...
| min(custom_color_map(:)) < 0 | max(custom_color_map(:)) > 1
msg = 'Colormap should be a Mx3 matrix with value between 0 and 1';
msgbox(msg,'Error in colormap file');
colorindex = nii_view.colorindex;
set(nii_view.handles.colorindex,'value',colorindex);
return;
end
color_map = custom_color_map;
nii_view.color_map = color_map;
end
switch colorindex
case {2}
color_map = bipolar(num_color, cbarminmax(1), cbarminmax(2), contrast);
case {3}
color_map = gray(num_color - contrast + 1);
case {4}
color_map = jet(num_color);
case {5}
color_map = cool(num_color);
case {6}
color_map = bone(num_color);
case {7}
color_map = hot(num_color);
case {8}
color_map = copper(num_color);
case {9}
color_map = pink(num_color);
end
nii_view.colorindex = colorindex;
if ~exist('nii', 'var')
setappdata(fig,'nii_view',nii_view);
end
if colorindex == 3
color_map = [zeros(contrast,3); color_map(2:end,:)];
end
if get(nii_view.handles.neg_color,'value') & isempty(highcolor)
color_map = flipud(color_map);
elseif get(nii_view.handles.neg_color,'value') & ~isempty(highcolor)
highcolor = flipud(highcolor);
end
brightness = get(nii_view.handles.brightness,'value');
color_map = brighten(color_map, brightness);
color_map = [color_map; highcolor];
set(fig, 'colormap', color_map);
return; % change_colormap
%----------------------------------------------------------------
function move_cursor(fig)
nii_view = getappdata(fig, 'nii_view');
if isempty(nii_view)
return;
end
axi = get(nii_view.handles.axial_axes, 'pos');
cor = get(nii_view.handles.coronal_axes, 'pos');
sag = get(nii_view.handles.sagittal_axes, 'pos');
curr = get(fig, 'currentpoint');
if curr(1) >= axi(1) & curr(1) <= axi(1)+axi(3) & ...
curr(2) >= axi(2) & curr(2) <= axi(2)+axi(4)
curr = get(nii_view.handles.axial_axes, 'current');
sag = curr(1,1);
cor = curr(1,2);
axi = nii_view.slices.axi;
elseif curr(1) >= cor(1) & curr(1) <= cor(1)+cor(3) & ...
curr(2) >= cor(2) & curr(2) <= cor(2)+cor(4)
curr = get(nii_view.handles.coronal_axes, 'current');
sag = curr(1,1);
cor = nii_view.slices.cor;
axi = curr(1,2);
elseif curr(1) >= sag(1) & curr(1) <= sag(1)+sag(3) & ...
curr(2) >= sag(2) & curr(2) <= sag(2)+sag(4)
curr = get(nii_view.handles.sagittal_axes, 'current');
sag = nii_view.slices.sag;
cor = curr(1,1);
axi = curr(1,2);
else
set(nii_view.handles.imvalcur,'String',' ');
set(nii_view.handles.imposcur,'String',' ');
return;
end
sag = round(sag);
cor = round(cor);
axi = round(axi);
if sag < 1
sag = 1;
elseif sag > nii_view.dims(1)
sag = nii_view.dims(1);
end
if cor < 1
cor = 1;
elseif cor > nii_view.dims(2)
cor = nii_view.dims(2);
end
if axi < 1
axi = 1;
elseif axi > nii_view.dims(3)
axi = nii_view.dims(3);
end
if 0 % isfield(nii_view, 'disp')
img = nii_view.disp;
else
img = nii_view.nii.img;
end
if nii_view.nii.hdr.dime.datatype == 128
imgvalue = [double(img(sag,cor,axi,1,nii_view.scanid)) double(img(sag,cor,axi,2,nii_view.scanid)) double(img(sag,cor,axi,3,nii_view.scanid))];
set(nii_view.handles.imvalcur,'String',sprintf('%7.4g %7.4g %7.4g',imgvalue));
elseif nii_view.nii.hdr.dime.datatype == 511
R = double(img(sag,cor,axi,1,nii_view.scanid)) * (nii_view.nii.hdr.dime.glmax - ...
nii_view.nii.hdr.dime.glmin) + nii_view.nii.hdr.dime.glmin;
G = double(img(sag,cor,axi,2,nii_view.scanid)) * (nii_view.nii.hdr.dime.glmax - ...
nii_view.nii.hdr.dime.glmin) + nii_view.nii.hdr.dime.glmin;
B = double(img(sag,cor,axi,3,nii_view.scanid)) * (nii_view.nii.hdr.dime.glmax - ...
nii_view.nii.hdr.dime.glmin) + nii_view.nii.hdr.dime.glmin;
imgvalue = [R G B];
set(nii_view.handles.imvalcur,'String',sprintf('%7.4g %7.4g %7.4g',imgvalue));
else
imgvalue = double(img(sag,cor,axi,nii_view.scanid));
if isnan(imgvalue) | imgvalue > nii_view.cbarminmax(2)
imgvalue = 0;
end
set(nii_view.handles.imvalcur,'String',sprintf('%.6g',imgvalue));
end
nii_view.slices.sag = sag;
nii_view.slices.cor = cor;
nii_view.slices.axi = axi;
nii_view = update_imgXYZ(nii_view);
if get(nii_view.handles.coord,'value') == 1,
sag = nii_view.imgXYZ.vox(1);
cor = nii_view.imgXYZ.vox(2);
axi = nii_view.imgXYZ.vox(3);
elseif get(nii_view.handles.coord,'value') == 2,
sag = nii_view.imgXYZ.mm(1);
cor = nii_view.imgXYZ.mm(2);
axi = nii_view.imgXYZ.mm(3);
elseif get(nii_view.handles.coord,'value') == 3,
sag = nii_view.imgXYZ.tal(1);
cor = nii_view.imgXYZ.tal(2);
axi = nii_view.imgXYZ.tal(3);
end
if get(nii_view.handles.coord,'value') == 1,
string = sprintf('%7.0f %7.0f %7.0f',sag,cor,axi);
else
string = sprintf('%7.1f %7.1f %7.1f',sag,cor,axi);
end;
set(nii_view.handles.imposcur,'String',string);
return; % move_cursor
%----------------------------------------------------------------
function change_scan(hdl_str)
fig = gcbf;
nii_view = getappdata(fig,'nii_view');
if strcmpi(hdl_str, 'edit_change_scan') % edit
hdl = nii_view.handles.contrast_def;
setscanid = round(str2num(get(hdl, 'string')));
else % slider
hdl = nii_view.handles.contrast;
setscanid = round(get(hdl, 'value'));
end
update_scanid(fig, setscanid);
return; % change_scan
%----------------------------------------------------------------
function val = scale_in(val, minval, maxval, range)
% scale value into range
%
val = range*(double(val)-double(minval))/(double(maxval)-double(minval))+1;
return; % scale_in
%----------------------------------------------------------------
function val = scale_out(val, minval, maxval, range)
% according to [minval maxval] and range of color levels (e.g. 199)
% scale val back from any thing between 1~256 to a small number that
% is corresonding to [minval maxval].
%
val = (double(val)-1)*(double(maxval)-double(minval))/range+double(minval);
return; % scale_out
|
github
|
changken1/IDH_Prediction-master
|
mat_into_hdr.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/mat_into_hdr.m
| 2,608 |
utf_8
|
d53006b93ff90a4a5561d16ff2f4e9a6
|
%MAT_INTO_HDR The old versions of SPM (any version before SPM5) store
% an affine matrix of the SPM Reoriented image into a matlab file
% (.mat extension). The file name of this SPM matlab file is the
% same as the SPM Reoriented image file (.img/.hdr extension).
%
% This program will convert the ANALYZE 7.5 SPM Reoriented image
% file into NIfTI format, and integrate the affine matrix in the
% SPM matlab file into its header file (.hdr extension).
%
% WARNING: Before you run this program, please save the header
% file (.hdr extension) into another file name or into another
% folder location, because all header files (.hdr extension)
% will be overwritten after they are converted into NIfTI
% format.
%
% Usage: mat_into_hdr(filename);
%
% filename: file name(s) with .hdr or .mat file extension, like:
% '*.hdr', or '*.mat', or a single .hdr or .mat file.
% e.g. mat_into_hdr('T1.hdr')
% mat_into_hdr('*.mat')
%
% - Jimmy Shen ([email protected])
%
%-------------------------------------------------------------------------
function mat_into_hdr(files)
pn = fileparts(files);
file_lst = dir(files);
file_lst = {file_lst.name};
file1 = file_lst{1};
[p n e]= fileparts(file1);
for i=1:length(file_lst)
[p n e]= fileparts(file_lst{i});
disp(['working on file ', num2str(i) ,' of ', num2str(length(file_lst)), ': ', n,e]);
process=1;
if isequal(e,'.hdr')
mat=fullfile(pn, [n,'.mat']);
hdr=fullfile(pn, file_lst{i});
if ~exist(mat,'file')
warning(['Cannot find file "',mat , '". File "', n, e, '" will not be processed.']);
process=0;
end
elseif isequal(e,'.mat')
hdr=fullfile(pn, [n,'.hdr']);
mat=fullfile(pn, file_lst{i});
if ~exist(hdr,'file')
warning(['Can not find file "',hdr , '". File "', n, e, '" will not be processed.']);
process=0;
end
else
warning(['Input file must have .mat or .hdr extension. File "', n, e, '" will not be processed.']);
process=0;
end
if process
load(mat);
R=M(1:3,1:3);
T=M(1:3,4);
T=R*ones(3,1)+T;
M(1:3,4)=T;
[h filetype fileprefix machine]=load_nii_hdr(hdr);
h.hist.qform_code=0;
h.hist.sform_code=1;
h.hist.srow_x=M(1,:);
h.hist.srow_y=M(2,:);
h.hist.srow_z=M(3,:);
h.hist.magic='ni1';
fid = fopen(hdr,'w',machine);
save_nii_hdr(h,fid);
fclose(fid);
end
end
return; % mat_into_hdr
|
github
|
changken1/IDH_Prediction-master
|
xform_nii.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/xform_nii.m
| 18,107 |
utf_8
|
29a1cff91c944d6a93e5101946a5da4d
|
% internal function
% 'xform_nii.m' is an internal function called by "load_nii.m", so
% you do not need run this program by yourself. It does simplified
% NIfTI sform/qform affine transform, and supports some of the
% affine transforms, including translation, reflection, and
% orthogonal rotation (N*90 degree).
%
% For other affine transforms, e.g. any degree rotation, shearing
% etc. you will have to use the included 'reslice_nii.m' program
% to reslice the image volume. 'reslice_nii.m' is not called by
% any other program, and you have to run 'reslice_nii.m' explicitly
% for those NIfTI files that you want to reslice them.
%
% Since 'xform_nii.m' does not involve any interpolation or any
% slice change, the original image volume is supposed to be
% untouched, although it is translated, reflected, or even
% orthogonally rotated, based on the affine matrix in the
% NIfTI header.
%
% However, the affine matrix in the header of a lot NIfTI files
% contain slightly non-orthogonal rotation. Therefore, optional
% input parameter 'tolerance' is used to allow some distortion
% in the loaded image for any non-orthogonal rotation or shearing
% of NIfTI affine matrix. If you set 'tolerance' to 0, it means
% that you do not allow any distortion. If you set 'tolerance' to
% 1, it means that you do not care any distortion. The image will
% fail to be loaded if it can not be tolerated. The tolerance will
% be set to 0.1 (10%), if it is default or empty.
%
% Because 'reslice_nii.m' has to perform 3D interpolation, it can
% be slow depending on image size and affine matrix in the header.
%
% After you perform the affine transform, the 'nii' structure
% generated from 'xform_nii.m' or new NIfTI file created from
% 'reslice_nii.m' will be in RAS orientation, i.e. X axis from
% Left to Right, Y axis from Posterior to Anterior, and Z axis
% from Inferior to Superior.
%
% NOTE: This function should be called immediately after load_nii.
%
% Usage: [ nii ] = xform_nii(nii, [tolerance], [preferredForm])
%
% nii - NIFTI structure (returned from load_nii)
%
% tolerance (optional) - distortion allowed for non-orthogonal rotation
% or shearing in NIfTI affine matrix. It will be set to 0.1 (10%),
% if it is default or empty.
%
% preferredForm (optional) - selects which transformation from voxels
% to RAS coordinates; values are s,q,S,Q. Lower case s,q indicate
% "prefer sform or qform, but use others if preferred not present".
% Upper case indicate the program is forced to use the specificied
% tranform or fail loading. 'preferredForm' will be 's', if it is
% default or empty. - Jeff Gunter
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function nii = xform_nii(nii, tolerance, preferredForm)
% save a copy of the header as it was loaded. This is the
% header before any sform, qform manipulation is done.
%
nii.original.hdr = nii.hdr;
if ~exist('tolerance','var') | isempty(tolerance)
tolerance = 0.1;
elseif(tolerance<=0)
tolerance = eps;
end
if ~exist('preferredForm','var') | isempty(preferredForm)
preferredForm= 's'; % Jeff
end
% if scl_slope field is nonzero, then each voxel value in the
% dataset should be scaled as: y = scl_slope * x + scl_inter
% I bring it here because hdr will be modified by change_hdr.
%
if nii.hdr.dime.scl_slope ~= 0 & ...
ismember(nii.hdr.dime.datatype, [2,4,8,16,64,256,512,768]) & ...
(nii.hdr.dime.scl_slope ~= 1 | nii.hdr.dime.scl_inter ~= 0)
nii.img = ...
nii.hdr.dime.scl_slope * double(nii.img) + nii.hdr.dime.scl_inter;
if nii.hdr.dime.datatype == 64
nii.hdr.dime.datatype = 64;
nii.hdr.dime.bitpix = 64;
else
nii.img = single(nii.img);
nii.hdr.dime.datatype = 16;
nii.hdr.dime.bitpix = 32;
end
nii.hdr.dime.glmax = max(double(nii.img(:)));
nii.hdr.dime.glmin = min(double(nii.img(:)));
% set scale to non-use, because it is applied in xform_nii
%
nii.hdr.dime.scl_slope = 0;
end
% However, the scaling is to be ignored if datatype is DT_RGB24.
% If datatype is a complex type, then the scaling is to be applied
% to both the real and imaginary parts.
%
if nii.hdr.dime.scl_slope ~= 0 & ...
ismember(nii.hdr.dime.datatype, [32,1792])
nii.img = ...
nii.hdr.dime.scl_slope * double(nii.img) + nii.hdr.dime.scl_inter;
if nii.hdr.dime.datatype == 32
nii.img = single(nii.img);
end
nii.hdr.dime.glmax = max(double(nii.img(:)));
nii.hdr.dime.glmin = min(double(nii.img(:)));
% set scale to non-use, because it is applied in xform_nii
%
nii.hdr.dime.scl_slope = 0;
end
% There is no need for this program to transform Analyze data
%
if nii.filetype == 0 & exist([nii.fileprefix '.mat'],'file')
load([nii.fileprefix '.mat']); % old SPM affine matrix
R=M(1:3,1:3);
T=M(1:3,4);
T=R*ones(3,1)+T;
M(1:3,4)=T;
nii.hdr.hist.qform_code=0;
nii.hdr.hist.sform_code=1;
nii.hdr.hist.srow_x=M(1,:);
nii.hdr.hist.srow_y=M(2,:);
nii.hdr.hist.srow_z=M(3,:);
elseif nii.filetype == 0
nii.hdr.hist.rot_orient = [];
nii.hdr.hist.flip_orient = [];
return; % no sform/qform for Analyze format
end
hdr = nii.hdr;
[hdr,orient]=change_hdr(hdr,tolerance,preferredForm);
% flip and/or rotate image data
%
if ~isequal(orient, [1 2 3])
old_dim = hdr.dime.dim([2:4]);
% More than 1 time frame
%
if ndims(nii.img) > 3
pattern = 1:prod(old_dim);
else
pattern = [];
end
if ~isempty(pattern)
pattern = reshape(pattern, old_dim);
end
% calculate for rotation after flip
%
rot_orient = mod(orient + 2, 3) + 1;
% do flip:
%
flip_orient = orient - rot_orient;
for i = 1:3
if flip_orient(i)
if ~isempty(pattern)
pattern = flipdim(pattern, i);
else
nii.img = flipdim(nii.img, i);
end
end
end
% get index of orient (rotate inversely)
%
[tmp rot_orient] = sort(rot_orient);
new_dim = old_dim;
new_dim = new_dim(rot_orient);
hdr.dime.dim([2:4]) = new_dim;
new_pixdim = hdr.dime.pixdim([2:4]);
new_pixdim = new_pixdim(rot_orient);
hdr.dime.pixdim([2:4]) = new_pixdim;
% re-calculate originator
%
tmp = hdr.hist.originator([1:3]);
tmp = tmp(rot_orient);
flip_orient = flip_orient(rot_orient);
for i = 1:3
if flip_orient(i) & ~isequal(tmp(i), 0)
tmp(i) = new_dim(i) - tmp(i) + 1;
end
end
hdr.hist.originator([1:3]) = tmp;
hdr.hist.rot_orient = rot_orient;
hdr.hist.flip_orient = flip_orient;
% do rotation:
%
if ~isempty(pattern)
pattern = permute(pattern, rot_orient);
pattern = pattern(:);
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792 | ...
hdr.dime.datatype == 128 | hdr.dime.datatype == 511
tmp = reshape(nii.img(:,:,:,1), [prod(new_dim) hdr.dime.dim(5:8)]);
tmp = tmp(pattern, :);
nii.img(:,:,:,1) = reshape(tmp, [new_dim hdr.dime.dim(5:8)]);
tmp = reshape(nii.img(:,:,:,2), [prod(new_dim) hdr.dime.dim(5:8)]);
tmp = tmp(pattern, :);
nii.img(:,:,:,2) = reshape(tmp, [new_dim hdr.dime.dim(5:8)]);
if hdr.dime.datatype == 128 | hdr.dime.datatype == 511
tmp = reshape(nii.img(:,:,:,3), [prod(new_dim) hdr.dime.dim(5:8)]);
tmp = tmp(pattern, :);
nii.img(:,:,:,3) = reshape(tmp, [new_dim hdr.dime.dim(5:8)]);
end
else
nii.img = reshape(nii.img, [prod(new_dim) hdr.dime.dim(5:8)]);
nii.img = nii.img(pattern, :);
nii.img = reshape(nii.img, [new_dim hdr.dime.dim(5:8)]);
end
else
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792 | ...
hdr.dime.datatype == 128 | hdr.dime.datatype == 511
nii.img(:,:,:,1) = permute(nii.img(:,:,:,1), rot_orient);
nii.img(:,:,:,2) = permute(nii.img(:,:,:,2), rot_orient);
if hdr.dime.datatype == 128 | hdr.dime.datatype == 511
nii.img(:,:,:,3) = permute(nii.img(:,:,:,3), rot_orient);
end
else
nii.img = permute(nii.img, rot_orient);
end
end
else
hdr.hist.rot_orient = [];
hdr.hist.flip_orient = [];
end
nii.hdr = hdr;
return; % xform_nii
%-----------------------------------------------------------------------
function [hdr, orient] = change_hdr(hdr, tolerance, preferredForm)
orient = [1 2 3];
affine_transform = 1;
% NIFTI can have both sform and qform transform. This program
% will check sform_code prior to qform_code by default.
%
% If user specifys "preferredForm", user can then choose the
% priority. - Jeff
%
useForm=[]; % Jeff
if isequal(preferredForm,'S')
if isequal(hdr.hist.sform_code,0)
error('User requires sform, sform not set in header');
else
useForm='s';
end
end % Jeff
if isequal(preferredForm,'Q')
if isequal(hdr.hist.qform_code,0)
error('User requires qform, qform not set in header');
else
useForm='q';
end
end % Jeff
if isequal(preferredForm,'s')
if hdr.hist.sform_code > 0
useForm='s';
elseif hdr.hist.qform_code > 0
useForm='q';
end
end % Jeff
if isequal(preferredForm,'q')
if hdr.hist.qform_code > 0
useForm='q';
elseif hdr.hist.sform_code > 0
useForm='s';
end
end % Jeff
if isequal(useForm,'s')
R = [hdr.hist.srow_x(1:3)
hdr.hist.srow_y(1:3)
hdr.hist.srow_z(1:3)];
T = [hdr.hist.srow_x(4)
hdr.hist.srow_y(4)
hdr.hist.srow_z(4)];
if det(R) == 0 | ~isequal(R(find(R)), sum(R)')
hdr.hist.old_affine = [ [R;[0 0 0]] [T;1] ];
R_sort = sort(abs(R(:)));
R( find( abs(R) < tolerance*min(R_sort(end-2:end)) ) ) = 0;
hdr.hist.new_affine = [ [R;[0 0 0]] [T;1] ];
if det(R) == 0 | ~isequal(R(find(R)), sum(R)')
msg = [char(10) char(10) ' Non-orthogonal rotation or shearing '];
msg = [msg 'found inside the affine matrix' char(10)];
msg = [msg ' in this NIfTI file. You have 3 options:' char(10) char(10)];
msg = [msg ' 1. Using included ''reslice_nii.m'' program to reslice the NIfTI' char(10)];
msg = [msg ' file. I strongly recommand this, because it will not cause' char(10)];
msg = [msg ' negative effect, as long as you remember not to do slice' char(10)];
msg = [msg ' time correction after using ''reslice_nii.m''.' char(10) char(10)];
msg = [msg ' 2. Using included ''load_untouch_nii.m'' program to load image' char(10)];
msg = [msg ' without applying any affine geometric transformation or' char(10)];
msg = [msg ' voxel intensity scaling. This is only for people who want' char(10)];
msg = [msg ' to do some image processing regardless of image orientation' char(10)];
msg = [msg ' and to save data back with the same NIfTI header.' char(10) char(10)];
msg = [msg ' 3. Increasing the tolerance to allow more distortion in loaded' char(10)];
msg = [msg ' image, but I don''t suggest this.' char(10) char(10)];
msg = [msg ' To get help, please type:' char(10) char(10) ' help reslice_nii.m' char(10)];
msg = [msg ' help load_untouch_nii.m' char(10) ' help load_nii.m'];
error(msg);
end
end
elseif isequal(useForm,'q')
b = hdr.hist.quatern_b;
c = hdr.hist.quatern_c;
d = hdr.hist.quatern_d;
if 1.0-(b*b+c*c+d*d) < 0
if abs(1.0-(b*b+c*c+d*d)) < 1e-5
a = 0;
else
error('Incorrect quaternion values in this NIFTI data.');
end
else
a = sqrt(1.0-(b*b+c*c+d*d));
end
qfac = hdr.dime.pixdim(1);
if qfac==0, qfac = 1; end
i = hdr.dime.pixdim(2);
j = hdr.dime.pixdim(3);
k = qfac * hdr.dime.pixdim(4);
R = [a*a+b*b-c*c-d*d 2*b*c-2*a*d 2*b*d+2*a*c
2*b*c+2*a*d a*a+c*c-b*b-d*d 2*c*d-2*a*b
2*b*d-2*a*c 2*c*d+2*a*b a*a+d*d-c*c-b*b];
T = [hdr.hist.qoffset_x
hdr.hist.qoffset_y
hdr.hist.qoffset_z];
% qforms are expected to generate rotation matrices R which are
% det(R) = 1; we'll make sure that happens.
%
% now we make the same checks as were done above for sform data
% BUT we do it on a transform that is in terms of voxels not mm;
% after we figure out the angles and squash them to closest
% rectilinear direction. After that, the voxel sizes are then
% added.
%
% This part is modified by Jeff Gunter.
%
if det(R) == 0 | ~isequal(R(find(R)), sum(R)')
% det(R) == 0 is not a common trigger for this ---
% R(find(R)) is a list of non-zero elements in R; if that
% is straight (not oblique) then it should be the same as
% columnwise summation. Could just as well have checked the
% lengths of R(find(R)) and sum(R)' (which should be 3)
%
hdr.hist.old_affine = [ [R * diag([i j k]);[0 0 0]] [T;1] ];
R_sort = sort(abs(R(:)));
R( find( abs(R) < tolerance*min(R_sort(end-2:end)) ) ) = 0;
R = R * diag([i j k]);
hdr.hist.new_affine = [ [R;[0 0 0]] [T;1] ];
if det(R) == 0 | ~isequal(R(find(R)), sum(R)')
msg = [char(10) char(10) ' Non-orthogonal rotation or shearing '];
msg = [msg 'found inside the affine matrix' char(10)];
msg = [msg ' in this NIfTI file. You have 3 options:' char(10) char(10)];
msg = [msg ' 1. Using included ''reslice_nii.m'' program to reslice the NIfTI' char(10)];
msg = [msg ' file. I strongly recommand this, because it will not cause' char(10)];
msg = [msg ' negative effect, as long as you remember not to do slice' char(10)];
msg = [msg ' time correction after using ''reslice_nii.m''.' char(10) char(10)];
msg = [msg ' 2. Using included ''load_untouch_nii.m'' program to load image' char(10)];
msg = [msg ' without applying any affine geometric transformation or' char(10)];
msg = [msg ' voxel intensity scaling. This is only for people who want' char(10)];
msg = [msg ' to do some image processing regardless of image orientation' char(10)];
msg = [msg ' and to save data back with the same NIfTI header.' char(10) char(10)];
msg = [msg ' 3. Increasing the tolerance to allow more distortion in loaded' char(10)];
msg = [msg ' image, but I don''t suggest this.' char(10) char(10)];
msg = [msg ' To get help, please type:' char(10) char(10) ' help reslice_nii.m' char(10)];
msg = [msg ' help load_untouch_nii.m' char(10) ' help load_nii.m'];
error(msg);
end
else
R = R * diag([i j k]);
end % 1st det(R)
else
affine_transform = 0; % no sform or qform transform
end
if affine_transform == 1
voxel_size = abs(sum(R,1));
inv_R = inv(R);
originator = inv_R*(-T)+1;
orient = get_orient(inv_R);
% modify pixdim and originator
%
hdr.dime.pixdim(2:4) = voxel_size;
hdr.hist.originator(1:3) = originator;
% set sform or qform to non-use, because they have been
% applied in xform_nii
%
hdr.hist.qform_code = 0;
hdr.hist.sform_code = 0;
end
% apply space_unit to pixdim if not 1 (mm)
%
space_unit = get_units(hdr);
if space_unit ~= 1
hdr.dime.pixdim(2:4) = hdr.dime.pixdim(2:4) * space_unit;
% set space_unit of xyzt_units to millimeter, because
% voxel_size has been re-scaled
%
hdr.dime.xyzt_units = char(bitset(hdr.dime.xyzt_units,1,0));
hdr.dime.xyzt_units = char(bitset(hdr.dime.xyzt_units,2,1));
hdr.dime.xyzt_units = char(bitset(hdr.dime.xyzt_units,3,0));
end
hdr.dime.pixdim = abs(hdr.dime.pixdim);
return; % change_hdr
%-----------------------------------------------------------------------
function orient = get_orient(R)
orient = [];
for i = 1:3
switch find(R(i,:)) * sign(sum(R(i,:)))
case 1
orient = [orient 1]; % Left to Right
case 2
orient = [orient 2]; % Posterior to Anterior
case 3
orient = [orient 3]; % Inferior to Superior
case -1
orient = [orient 4]; % Right to Left
case -2
orient = [orient 5]; % Anterior to Posterior
case -3
orient = [orient 6]; % Superior to Inferior
end
end
return; % get_orient
%-----------------------------------------------------------------------
function [space_unit, time_unit] = get_units(hdr)
switch bitand(hdr.dime.xyzt_units, 7) % mask with 0x07
case 1
space_unit = 1e+3; % meter, m
case 3
space_unit = 1e-3; % micrometer, um
otherwise
space_unit = 1; % millimeter, mm
end
switch bitand(hdr.dime.xyzt_units, 56) % mask with 0x38
case 16
time_unit = 1e-3; % millisecond, ms
case 24
time_unit = 1e-6; % microsecond, us
otherwise
time_unit = 1; % second, s
end
return; % get_units
|
github
|
changken1/IDH_Prediction-master
|
make_ana.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/make_ana.m
| 5,455 |
utf_8
|
2f62999cbcad72129c892135ff492a1e
|
% Make ANALYZE 7.5 data structure specified by a 3D or 4D matrix.
% Optional parameters can also be included, such as: voxel_size,
% origin, datatype, and description.
%
% Once the ANALYZE structure is made, it can be saved into ANALYZE 7.5
% format data file using "save_untouch_nii" command (for more detail,
% type: help save_untouch_nii).
%
% Usage: ana = make_ana(img, [voxel_size], [origin], [datatype], [description])
%
% Where:
%
% img: a 3D matrix [x y z], or a 4D matrix with time
% series [x y z t]. When image is in RGB format,
% make sure that the size of 4th dimension is
% always 3 (i.e. [R G B]). In that case, make
% sure that you must specify RGB datatype to 128.
%
% voxel_size (optional): Voxel size in millimeter for each
% dimension. Default is [1 1 1].
%
% origin (optional): The AC origin. Default is [0 0 0].
%
% datatype (optional): Storage data type:
% 2 - uint8, 4 - int16, 8 - int32, 16 - float32,
% 64 - float64, 128 - RGB24
% Default will use the data type of 'img' matrix
% For RGB image, you must specify it to 128.
%
% description (optional): Description of data. Default is ''.
%
% e.g.:
% origin = [33 44 13]; datatype = 64;
% ana = make_ana(img, [], origin, datatype); % default voxel_size
%
% ANALYZE 7.5 format: http://www.rotman-baycrest.on.ca/~jimmy/ANALYZE75.pdf
%
% - Jimmy Shen ([email protected])
%
function ana = make_ana(varargin)
ana.img = varargin{1};
dims = size(ana.img);
dims = [4 dims ones(1,8)];
dims = dims(1:8);
voxel_size = [0 ones(1,3) zeros(1,4)];
origin = zeros(1,5);
descrip = '';
switch class(ana.img)
case 'uint8'
datatype = 2;
case 'int16'
datatype = 4;
case 'int32'
datatype = 8;
case 'single'
datatype = 16;
case 'double'
datatype = 64;
otherwise
error('Datatype is not supported by make_ana.');
end
if nargin > 1 & ~isempty(varargin{2})
voxel_size(2:4) = double(varargin{2});
end
if nargin > 2 & ~isempty(varargin{3})
origin(1:3) = double(varargin{3});
end
if nargin > 3 & ~isempty(varargin{4})
datatype = double(varargin{4});
if datatype == 128 | datatype == 511
dims(5) = [];
dims = [dims 1];
end
end
if nargin > 4 & ~isempty(varargin{5})
descrip = varargin{5};
end
if ndims(ana.img) > 4
error('NIfTI only allows a maximum of 4 Dimension matrix.');
end
maxval = round(double(max(ana.img(:))));
minval = round(double(min(ana.img(:))));
ana.hdr = make_header(dims, voxel_size, origin, datatype, ...
descrip, maxval, minval);
ana.filetype = 0;
ana.ext = [];
ana.untouch = 1;
switch ana.hdr.dime.datatype
case 2
ana.img = uint8(ana.img);
case 4
ana.img = int16(ana.img);
case 8
ana.img = int32(ana.img);
case 16
ana.img = single(ana.img);
case 64
ana.img = double(ana.img);
case 128
ana.img = uint8(ana.img);
otherwise
error('Datatype is not supported by make_ana.');
end
return; % make_ana
%---------------------------------------------------------------------
function hdr = make_header(dims, voxel_size, origin, datatype, ...
descrip, maxval, minval)
hdr.hk = header_key;
hdr.dime = image_dimension(dims, voxel_size, datatype, maxval, minval);
hdr.hist = data_history(origin, descrip);
return; % make_header
%---------------------------------------------------------------------
function hk = header_key
hk.sizeof_hdr = 348; % must be 348!
hk.data_type = '';
hk.db_name = '';
hk.extents = 0;
hk.session_error = 0;
hk.regular = 'r';
hk.hkey_un0 = '0';
return; % header_key
%---------------------------------------------------------------------
function dime = image_dimension(dims, voxel_size, datatype, maxval, minval)
dime.dim = dims;
dime.vox_units = 'mm';
dime.cal_units = '';
dime.unused1 = 0;
dime.datatype = datatype;
switch dime.datatype
case 2,
dime.bitpix = 8; precision = 'uint8';
case 4,
dime.bitpix = 16; precision = 'int16';
case 8,
dime.bitpix = 32; precision = 'int32';
case 16,
dime.bitpix = 32; precision = 'float32';
case 64,
dime.bitpix = 64; precision = 'float64';
case 128
dime.bitpix = 24; precision = 'uint8';
otherwise
error('Datatype is not supported by make_ana.');
end
dime.dim_un0 = 0;
dime.pixdim = voxel_size;
dime.vox_offset = 0;
dime.roi_scale = 1;
dime.funused1 = 0;
dime.funused2 = 0;
dime.cal_max = 0;
dime.cal_min = 0;
dime.compressed = 0;
dime.verified = 0;
dime.glmax = maxval;
dime.glmin = minval;
return; % image_dimension
%---------------------------------------------------------------------
function hist = data_history(origin, descrip)
hist.descrip = descrip;
hist.aux_file = 'none';
hist.orient = 0;
hist.originator = origin;
hist.generated = '';
hist.scannum = '';
hist.patient_id = '';
hist.exp_date = '';
hist.exp_time = '';
hist.hist_un0 = '';
hist.views = 0;
hist.vols_added = 0;
hist.start_field = 0;
hist.field_skip = 0;
hist.omax = 0;
hist.omin = 0;
hist.smax = 0;
hist.smin = 0;
return; % data_history
|
github
|
changken1/IDH_Prediction-master
|
extra_nii_hdr.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/extra_nii_hdr.m
| 7,830 |
utf_8
|
853f39f00cbf133e90d0f2cf08d79488
|
% Decode extra NIFTI header information into hdr.extra
%
% Usage: hdr = extra_nii_hdr(hdr)
%
% hdr can be obtained from load_nii_hdr
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function hdr = extra_nii_hdr(hdr)
switch hdr.dime.datatype
case 1
extra.NIFTI_DATATYPES = 'DT_BINARY';
case 2
extra.NIFTI_DATATYPES = 'DT_UINT8';
case 4
extra.NIFTI_DATATYPES = 'DT_INT16';
case 8
extra.NIFTI_DATATYPES = 'DT_INT32';
case 16
extra.NIFTI_DATATYPES = 'DT_FLOAT32';
case 32
extra.NIFTI_DATATYPES = 'DT_COMPLEX64';
case 64
extra.NIFTI_DATATYPES = 'DT_FLOAT64';
case 128
extra.NIFTI_DATATYPES = 'DT_RGB24';
case 256
extra.NIFTI_DATATYPES = 'DT_INT8';
case 512
extra.NIFTI_DATATYPES = 'DT_UINT16';
case 768
extra.NIFTI_DATATYPES = 'DT_UINT32';
case 1024
extra.NIFTI_DATATYPES = 'DT_INT64';
case 1280
extra.NIFTI_DATATYPES = 'DT_UINT64';
case 1536
extra.NIFTI_DATATYPES = 'DT_FLOAT128';
case 1792
extra.NIFTI_DATATYPES = 'DT_COMPLEX128';
case 2048
extra.NIFTI_DATATYPES = 'DT_COMPLEX256';
otherwise
extra.NIFTI_DATATYPES = 'DT_UNKNOWN';
end
switch hdr.dime.intent_code
case 2
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_CORREL';
case 3
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_TTEST';
case 4
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_FTEST';
case 5
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_ZSCORE';
case 6
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_CHISQ';
case 7
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_BETA';
case 8
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_BINOM';
case 9
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_GAMMA';
case 10
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_POISSON';
case 11
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_NORMAL';
case 12
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_FTEST_NONC';
case 13
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_CHISQ_NONC';
case 14
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_LOGISTIC';
case 15
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_LAPLACE';
case 16
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_UNIFORM';
case 17
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_TTEST_NONC';
case 18
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_WEIBULL';
case 19
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_CHI';
case 20
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_INVGAUSS';
case 21
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_EXTVAL';
case 22
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_PVAL';
case 23
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_LOGPVAL';
case 24
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_LOG10PVAL';
case 1001
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_ESTIMATE';
case 1002
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_LABEL';
case 1003
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_NEURONAME';
case 1004
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_GENMATRIX';
case 1005
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_SYMMATRIX';
case 1006
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_DISPVECT';
case 1007
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_VECTOR';
case 1008
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_POINTSET';
case 1009
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_TRIANGLE';
case 1010
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_QUATERNION';
case 1011
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_DIMLESS';
otherwise
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_NONE';
end
extra.NIFTI_INTENT_NAMES = hdr.hist.intent_name;
if hdr.hist.sform_code > 0
switch hdr.hist.sform_code
case 1
extra.NIFTI_SFORM_CODES = 'NIFTI_XFORM_SCANNER_ANAT';
case 2
extra.NIFTI_SFORM_CODES = 'NIFTI_XFORM_ALIGNED_ANAT';
case 3
extra.NIFTI_SFORM_CODES = 'NIFTI_XFORM_TALAIRACH';
case 4
extra.NIFTI_SFORM_CODES = 'NIFTI_XFORM_MNI_152';
otherwise
extra.NIFTI_SFORM_CODES = 'NIFTI_XFORM_UNKNOWN';
end
extra.NIFTI_QFORM_CODES = 'NIFTI_XFORM_UNKNOWN';
elseif hdr.hist.qform_code > 0
extra.NIFTI_SFORM_CODES = 'NIFTI_XFORM_UNKNOWN';
switch hdr.hist.qform_code
case 1
extra.NIFTI_QFORM_CODES = 'NIFTI_XFORM_SCANNER_ANAT';
case 2
extra.NIFTI_QFORM_CODES = 'NIFTI_XFORM_ALIGNED_ANAT';
case 3
extra.NIFTI_QFORM_CODES = 'NIFTI_XFORM_TALAIRACH';
case 4
extra.NIFTI_QFORM_CODES = 'NIFTI_XFORM_MNI_152';
otherwise
extra.NIFTI_QFORM_CODES = 'NIFTI_XFORM_UNKNOWN';
end
else
extra.NIFTI_SFORM_CODES = 'NIFTI_XFORM_UNKNOWN';
extra.NIFTI_QFORM_CODES = 'NIFTI_XFORM_UNKNOWN';
end
switch bitand(hdr.dime.xyzt_units, 7) % mask with 0x07
case 1
extra.NIFTI_SPACE_UNIT = 'NIFTI_UNITS_METER';
case 2
extra.NIFTI_SPACE_UNIT = 'NIFTI_UNITS_MM'; % millimeter
case 3
extra.NIFTI_SPACE_UNIT = 'NIFTI_UNITS_MICRO';
otherwise
extra.NIFTI_SPACE_UNIT = 'NIFTI_UNITS_UNKNOWN';
end
switch bitand(hdr.dime.xyzt_units, 56) % mask with 0x38
case 8
extra.NIFTI_TIME_UNIT = 'NIFTI_UNITS_SEC';
case 16
extra.NIFTI_TIME_UNIT = 'NIFTI_UNITS_MSEC';
case 24
extra.NIFTI_TIME_UNIT = 'NIFTI_UNITS_USEC'; % microsecond
otherwise
extra.NIFTI_TIME_UNIT = 'NIFTI_UNITS_UNKNOWN';
end
switch hdr.dime.xyzt_units
case 32
extra.NIFTI_SPECTRAL_UNIT = 'NIFTI_UNITS_HZ';
case 40
extra.NIFTI_SPECTRAL_UNIT = 'NIFTI_UNITS_PPM'; % part per million
case 48
extra.NIFTI_SPECTRAL_UNIT = 'NIFTI_UNITS_RADS'; % radians per second
otherwise
extra.NIFTI_SPECTRAL_UNIT = 'NIFTI_UNITS_UNKNOWN';
end
% MRI-specific spatial and temporal information
%
dim_info = hdr.hk.dim_info;
extra.NIFTI_FREQ_DIM = bitand(dim_info, 3);
extra.NIFTI_PHASE_DIM = bitand(bitshift(dim_info, -2), 3);
extra.NIFTI_SLICE_DIM = bitand(bitshift(dim_info, -4), 3);
% Check slice code
%
switch hdr.dime.slice_code
case 1
extra.NIFTI_SLICE_ORDER = 'NIFTI_SLICE_SEQ_INC'; % sequential increasing
case 2
extra.NIFTI_SLICE_ORDER = 'NIFTI_SLICE_SEQ_DEC'; % sequential decreasing
case 3
extra.NIFTI_SLICE_ORDER = 'NIFTI_SLICE_ALT_INC'; % alternating increasing
case 4
extra.NIFTI_SLICE_ORDER = 'NIFTI_SLICE_ALT_DEC'; % alternating decreasing
case 5
extra.NIFTI_SLICE_ORDER = 'NIFTI_SLICE_ALT_INC2'; % ALT_INC # 2
case 6
extra.NIFTI_SLICE_ORDER = 'NIFTI_SLICE_ALT_DEC2'; % ALT_DEC # 2
otherwise
extra.NIFTI_SLICE_ORDER = 'NIFTI_SLICE_UNKNOWN';
end
% Check NIFTI version
%
if ~isempty(hdr.hist.magic) & strcmp(hdr.hist.magic(1),'n') & ...
( strcmp(hdr.hist.magic(2),'i') | strcmp(hdr.hist.magic(2),'+') ) & ...
str2num(hdr.hist.magic(3)) >= 1 & str2num(hdr.hist.magic(3)) <= 9
extra.NIFTI_VERSION = str2num(hdr.hist.magic(3));
else
extra.NIFTI_VERSION = 0;
end
% Check if data stored in the same file (*.nii) or separate
% files (*.hdr/*.img)
%
if isempty(hdr.hist.magic)
extra.NIFTI_ONEFILE = 0;
else
extra.NIFTI_ONEFILE = strcmp(hdr.hist.magic(2), '+');
end
% Swap has been taken care of by checking whether sizeof_hdr is
% 348 (machine is 'ieee-le' or 'ieee-be' etc)
%
% extra.NIFTI_NEEDS_SWAP = (hdr.dime.dim(1) < 0 | hdr.dime.dim(1) > 7);
% Check NIFTI header struct contains a 5th (vector) dimension
%
if hdr.dime.dim(1) > 4 & hdr.dime.dim(6) > 1
extra.NIFTI_5TH_DIM = hdr.dime.dim(6);
else
extra.NIFTI_5TH_DIM = 0;
end
hdr.extra = extra;
return; % extra_nii_hdr
|
github
|
changken1/IDH_Prediction-master
|
rri_xhair.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/rri_xhair.m
| 2,208 |
utf_8
|
b3ae9df90d43e5d9538b6b135fa8af20
|
% rri_xhair: create a pair of full_cross_hair at point [x y] in
% axes h_ax, and return xhair struct
%
% Usage: xhair = rri_xhair([x y], xhair, h_ax);
%
% If omit xhair, rri_xhair will create a pair of xhair; otherwise,
% rri_xhair will update the xhair. If omit h_ax, current axes will
% be used.
%
% 24-nov-2003 jimmy ([email protected])
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function xhair = rri_xhair(varargin)
if nargin == 0
error('Please enter a point position as first argument');
return;
end
if nargin > 0
p = varargin{1};
if ~isnumeric(p) | length(p) ~= 2
error('Invalid point position');
return;
else
xhair = [];
end
end
if nargin > 1
xhair = varargin{2};
if ~isempty(xhair)
if ~isstruct(xhair)
error('Invalid xhair struct');
return;
elseif ~isfield(xhair,'lx') | ~isfield(xhair,'ly')
error('Invalid xhair struct');
return;
elseif ~ishandle(xhair.lx) | ~ishandle(xhair.ly)
error('Invalid xhair struct');
return;
end
lx = xhair.lx;
ly = xhair.ly;
else
lx = [];
ly = [];
end
end
if nargin > 2
h_ax = varargin{3};
if ~ishandle(h_ax)
error('Invalid axes handle');
return;
elseif ~strcmp(lower(get(h_ax,'type')), 'axes')
error('Invalid axes handle');
return;
end
else
h_ax = gca;
end
x_range = get(h_ax,'xlim');
y_range = get(h_ax,'ylim');
if ~isempty(xhair)
set(lx, 'ydata', [p(2) p(2)]);
set(ly, 'xdata', [p(1) p(1)]);
set(h_ax, 'selected', 'on');
set(h_ax, 'selected', 'off');
else
figure(get(h_ax,'parent'));
axes(h_ax);
xhair.lx = line('xdata', x_range, 'ydata', [p(2) p(2)], ...
'zdata', [11 11], 'color', [1 0 0], 'hittest', 'off');
xhair.ly = line('xdata', [p(1) p(1)], 'ydata', y_range, ...
'zdata', [11 11], 'color', [1 0 0], 'hittest', 'off');
end
set(h_ax,'xlim',x_range);
set(h_ax,'ylim',y_range);
return;
|
github
|
changken1/IDH_Prediction-master
|
save_untouch_nii_hdr.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/save_untouch_nii_hdr.m
| 8,514 |
utf_8
|
582f82c471a9a8826eda59354f61dd1a
|
% internal function
% - Jimmy Shen ([email protected])
function save_nii_hdr(hdr, fid)
if ~isequal(hdr.hk.sizeof_hdr,348),
error('hdr.hk.sizeof_hdr must be 348.');
end
write_header(hdr, fid);
return; % save_nii_hdr
%---------------------------------------------------------------------
function write_header(hdr, fid)
% Original header structures
% struct dsr /* dsr = hdr */
% {
% struct header_key hk; /* 0 + 40 */
% struct image_dimension dime; /* 40 + 108 */
% struct data_history hist; /* 148 + 200 */
% }; /* total= 348 bytes*/
header_key(fid, hdr.hk);
image_dimension(fid, hdr.dime);
data_history(fid, hdr.hist);
% check the file size is 348 bytes
%
fbytes = ftell(fid);
if ~isequal(fbytes,348),
msg = sprintf('Header size is not 348 bytes.');
warning(msg);
end
return; % write_header
%---------------------------------------------------------------------
function header_key(fid, hk)
fseek(fid,0,'bof');
% Original header structures
% struct header_key /* header key */
% { /* off + size */
% int sizeof_hdr /* 0 + 4 */
% char data_type[10]; /* 4 + 10 */
% char db_name[18]; /* 14 + 18 */
% int extents; /* 32 + 4 */
% short int session_error; /* 36 + 2 */
% char regular; /* 38 + 1 */
% char dim_info; % char hkey_un0; /* 39 + 1 */
% }; /* total=40 bytes */
fwrite(fid, hk.sizeof_hdr(1), 'int32'); % must be 348.
% data_type = sprintf('%-10s',hk.data_type); % ensure it is 10 chars from left
% fwrite(fid, data_type(1:10), 'uchar');
pad = zeros(1, 10-length(hk.data_type));
hk.data_type = [hk.data_type char(pad)];
fwrite(fid, hk.data_type(1:10), 'uchar');
% db_name = sprintf('%-18s', hk.db_name); % ensure it is 18 chars from left
% fwrite(fid, db_name(1:18), 'uchar');
pad = zeros(1, 18-length(hk.db_name));
hk.db_name = [hk.db_name char(pad)];
fwrite(fid, hk.db_name(1:18), 'uchar');
fwrite(fid, hk.extents(1), 'int32');
fwrite(fid, hk.session_error(1), 'int16');
fwrite(fid, hk.regular(1), 'uchar'); % might be uint8
% fwrite(fid, hk.hkey_un0(1), 'uchar');
% fwrite(fid, hk.hkey_un0(1), 'uint8');
fwrite(fid, hk.dim_info(1), 'uchar');
return; % header_key
%---------------------------------------------------------------------
function image_dimension(fid, dime)
% Original header structures
% struct image_dimension
% { /* off + size */
% short int dim[8]; /* 0 + 16 */
% float intent_p1; % char vox_units[4]; /* 16 + 4 */
% float intent_p2; % char cal_units[8]; /* 20 + 4 */
% float intent_p3; % char cal_units[8]; /* 24 + 4 */
% short int intent_code; % short int unused1; /* 28 + 2 */
% short int datatype; /* 30 + 2 */
% short int bitpix; /* 32 + 2 */
% short int slice_start; % short int dim_un0; /* 34 + 2 */
% float pixdim[8]; /* 36 + 32 */
% /*
% pixdim[] specifies the voxel dimensions:
% pixdim[1] - voxel width
% pixdim[2] - voxel height
% pixdim[3] - interslice distance
% pixdim[4] - volume timing, in msec
% ..etc
% */
% float vox_offset; /* 68 + 4 */
% float scl_slope; % float roi_scale; /* 72 + 4 */
% float scl_inter; % float funused1; /* 76 + 4 */
% short slice_end; % float funused2; /* 80 + 2 */
% char slice_code; % float funused2; /* 82 + 1 */
% char xyzt_units; % float funused2; /* 83 + 1 */
% float cal_max; /* 84 + 4 */
% float cal_min; /* 88 + 4 */
% float slice_duration; % int compressed; /* 92 + 4 */
% float toffset; % int verified; /* 96 + 4 */
% int glmax; /* 100 + 4 */
% int glmin; /* 104 + 4 */
% }; /* total=108 bytes */
fwrite(fid, dime.dim(1:8), 'int16');
fwrite(fid, dime.intent_p1(1), 'float32');
fwrite(fid, dime.intent_p2(1), 'float32');
fwrite(fid, dime.intent_p3(1), 'float32');
fwrite(fid, dime.intent_code(1), 'int16');
fwrite(fid, dime.datatype(1), 'int16');
fwrite(fid, dime.bitpix(1), 'int16');
fwrite(fid, dime.slice_start(1), 'int16');
fwrite(fid, dime.pixdim(1:8), 'float32');
fwrite(fid, dime.vox_offset(1), 'float32');
fwrite(fid, dime.scl_slope(1), 'float32');
fwrite(fid, dime.scl_inter(1), 'float32');
fwrite(fid, dime.slice_end(1), 'int16');
fwrite(fid, dime.slice_code(1), 'uchar');
fwrite(fid, dime.xyzt_units(1), 'uchar');
fwrite(fid, dime.cal_max(1), 'float32');
fwrite(fid, dime.cal_min(1), 'float32');
fwrite(fid, dime.slice_duration(1), 'float32');
fwrite(fid, dime.toffset(1), 'float32');
fwrite(fid, dime.glmax(1), 'int32');
fwrite(fid, dime.glmin(1), 'int32');
return; % image_dimension
%---------------------------------------------------------------------
function data_history(fid, hist)
% Original header structures
%struct data_history
% { /* off + size */
% char descrip[80]; /* 0 + 80 */
% char aux_file[24]; /* 80 + 24 */
% short int qform_code; /* 104 + 2 */
% short int sform_code; /* 106 + 2 */
% float quatern_b; /* 108 + 4 */
% float quatern_c; /* 112 + 4 */
% float quatern_d; /* 116 + 4 */
% float qoffset_x; /* 120 + 4 */
% float qoffset_y; /* 124 + 4 */
% float qoffset_z; /* 128 + 4 */
% float srow_x[4]; /* 132 + 16 */
% float srow_y[4]; /* 148 + 16 */
% float srow_z[4]; /* 164 + 16 */
% char intent_name[16]; /* 180 + 16 */
% char magic[4]; % int smin; /* 196 + 4 */
% }; /* total=200 bytes */
% descrip = sprintf('%-80s', hist.descrip); % 80 chars from left
% fwrite(fid, descrip(1:80), 'uchar');
pad = zeros(1, 80-length(hist.descrip));
hist.descrip = [hist.descrip char(pad)];
fwrite(fid, hist.descrip(1:80), 'uchar');
% aux_file = sprintf('%-24s', hist.aux_file); % 24 chars from left
% fwrite(fid, aux_file(1:24), 'uchar');
pad = zeros(1, 24-length(hist.aux_file));
hist.aux_file = [hist.aux_file char(pad)];
fwrite(fid, hist.aux_file(1:24), 'uchar');
fwrite(fid, hist.qform_code, 'int16');
fwrite(fid, hist.sform_code, 'int16');
fwrite(fid, hist.quatern_b, 'float32');
fwrite(fid, hist.quatern_c, 'float32');
fwrite(fid, hist.quatern_d, 'float32');
fwrite(fid, hist.qoffset_x, 'float32');
fwrite(fid, hist.qoffset_y, 'float32');
fwrite(fid, hist.qoffset_z, 'float32');
fwrite(fid, hist.srow_x(1:4), 'float32');
fwrite(fid, hist.srow_y(1:4), 'float32');
fwrite(fid, hist.srow_z(1:4), 'float32');
% intent_name = sprintf('%-16s', hist.intent_name); % 16 chars from left
% fwrite(fid, intent_name(1:16), 'uchar');
pad = zeros(1, 16-length(hist.intent_name));
hist.intent_name = [hist.intent_name char(pad)];
fwrite(fid, hist.intent_name(1:16), 'uchar');
% magic = sprintf('%-4s', hist.magic); % 4 chars from left
% fwrite(fid, magic(1:4), 'uchar');
pad = zeros(1, 4-length(hist.magic));
hist.magic = [hist.magic char(pad)];
fwrite(fid, hist.magic(1:4), 'uchar');
return; % data_history
|
github
|
changken1/IDH_Prediction-master
|
expand_nii_scan.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/expand_nii_scan.m
| 1,333 |
utf_8
|
748da05d09c1a005401c67270c4b94ab
|
% Expand a multiple-scan NIFTI file into multiple single-scan NIFTI files
%
% Usage: expand_nii_scan(multi_scan_filename, [img_idx], [path_to_save])
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function expand_nii_scan(filename, img_idx, newpath)
v = version;
% Check file extension. If .gz, unpack it into temp folder
%
if length(filename) > 2 & strcmp(filename(end-2:end), '.gz')
if ~strcmp(filename(end-6:end), '.img.gz') & ...
~strcmp(filename(end-6:end), '.hdr.gz') & ...
~strcmp(filename(end-6:end), '.nii.gz')
error('Please check filename.');
end
if str2num(v(1:3)) < 7.1 | ~usejava('jvm')
error('Please use MATLAB 7.1 (with java) and above, or run gunzip outside MATLAB.');
else
gzFile = 1;
end
end
if ~exist('newpath','var') | isempty(newpath), newpath = pwd; end
if ~exist('img_idx','var') | isempty(img_idx), img_idx = 1:get_nii_frame(filename); end
for i=img_idx
nii_i = load_untouch_nii(filename, i);
fn = [nii_i.fileprefix '_' sprintf('%04d',i)];
pnfn = fullfile(newpath, fn);
if exist('gzFile', 'var')
pnfn = [pnfn '.nii.gz'];
end
save_untouch_nii(nii_i, pnfn);
end
return; % expand_nii_scan
|
github
|
changken1/IDH_Prediction-master
|
load_untouch_header_only.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/load_untouch_header_only.m
| 7,068 |
utf_8
|
8996c72db42b01029c92a4ecd88f4b21
|
% Load NIfTI / Analyze header without applying any appropriate affine
% geometric transform or voxel intensity scaling. It is equivalent to
% hdr field when using load_untouch_nii to load dataset. Support both
% *.nii and *.hdr file extension. If file extension is not provided,
% *.hdr will be used as default.
%
% Usage: [header, ext, filetype, machine] = load_untouch_header_only(filename)
%
% filename - NIfTI / Analyze file name.
%
% Returned values:
%
% header - struct with NIfTI / Analyze header fields.
%
% ext - NIfTI extension if it is not empty.
%
% filetype - 0 for Analyze format (*.hdr/*.img);
% 1 for NIFTI format in 2 files (*.hdr/*.img);
% 2 for NIFTI format in 1 file (*.nii).
%
% machine - a string, see below for details. The default here is 'ieee-le'.
%
% 'native' or 'n' - local machine format - the default
% 'ieee-le' or 'l' - IEEE floating point with little-endian
% byte ordering
% 'ieee-be' or 'b' - IEEE floating point with big-endian
% byte ordering
% 'vaxd' or 'd' - VAX D floating point and VAX ordering
% 'vaxg' or 'g' - VAX G floating point and VAX ordering
% 'cray' or 'c' - Cray floating point with big-endian
% byte ordering
% 'ieee-le.l64' or 'a' - IEEE floating point with little-endian
% byte ordering and 64 bit long data type
% 'ieee-be.l64' or 's' - IEEE floating point with big-endian byte
% ordering and 64 bit long data type.
%
% Part of this file is copied and modified from:
% http://www.mathworks.com/matlabcentral/fileexchange/1878-mri-analyze-tools
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function [hdr, ext, filetype, machine] = load_untouch_header_only(filename)
if ~exist('filename','var')
error('Usage: [header, ext, filetype, machine] = load_untouch_header_only(filename)');
end
v = version;
% Check file extension. If .gz, unpack it into temp folder
%
if length(filename) > 2 & strcmp(filename(end-2:end), '.gz')
if ~strcmp(filename(end-6:end), '.img.gz') & ...
~strcmp(filename(end-6:end), '.hdr.gz') & ...
~strcmp(filename(end-6:end), '.nii.gz')
error('Please check filename.');
end
if str2num(v(1:3)) < 7.1 | ~usejava('jvm')
error('Please use MATLAB 7.1 (with java) and above, or run gunzip outside MATLAB.');
elseif strcmp(filename(end-6:end), '.img.gz')
filename1 = filename;
filename2 = filename;
filename2(end-6:end) = '';
filename2 = [filename2, '.hdr.gz'];
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename1 = gunzip(filename1, tmpDir);
filename2 = gunzip(filename2, tmpDir);
filename = char(filename1); % convert from cell to string
elseif strcmp(filename(end-6:end), '.hdr.gz')
filename1 = filename;
filename2 = filename;
filename2(end-6:end) = '';
filename2 = [filename2, '.img.gz'];
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename1 = gunzip(filename1, tmpDir);
filename2 = gunzip(filename2, tmpDir);
filename = char(filename1); % convert from cell to string
elseif strcmp(filename(end-6:end), '.nii.gz')
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename = gunzip(filename, tmpDir);
filename = char(filename); % convert from cell to string
end
end
% Read the dataset header
%
[hdr, filetype, fileprefix, machine] = load_nii_hdr(filename);
if filetype == 0
hdr = load_untouch0_nii_hdr(fileprefix, machine);
ext = [];
else
hdr = load_untouch_nii_hdr(fileprefix, machine, filetype);
% Read the header extension
%
ext = load_nii_ext(filename);
end
% Set bitpix according to datatype
%
% /*Acceptable values for datatype are*/
%
% 0 None (Unknown bit per voxel) % DT_NONE, DT_UNKNOWN
% 1 Binary (ubit1, bitpix=1) % DT_BINARY
% 2 Unsigned char (uchar or uint8, bitpix=8) % DT_UINT8, NIFTI_TYPE_UINT8
% 4 Signed short (int16, bitpix=16) % DT_INT16, NIFTI_TYPE_INT16
% 8 Signed integer (int32, bitpix=32) % DT_INT32, NIFTI_TYPE_INT32
% 16 Floating point (single or float32, bitpix=32) % DT_FLOAT32, NIFTI_TYPE_FLOAT32
% 32 Complex, 2 float32 (Use float32, bitpix=64) % DT_COMPLEX64, NIFTI_TYPE_COMPLEX64
% 64 Double precision (double or float64, bitpix=64) % DT_FLOAT64, NIFTI_TYPE_FLOAT64
% 128 uint8 RGB (Use uint8, bitpix=24) % DT_RGB24, NIFTI_TYPE_RGB24
% 256 Signed char (schar or int8, bitpix=8) % DT_INT8, NIFTI_TYPE_INT8
% 511 Single RGB (Use float32, bitpix=96) % DT_RGB96, NIFTI_TYPE_RGB96
% 512 Unsigned short (uint16, bitpix=16) % DT_UNINT16, NIFTI_TYPE_UNINT16
% 768 Unsigned integer (uint32, bitpix=32) % DT_UNINT32, NIFTI_TYPE_UNINT32
% 1024 Signed long long (int64, bitpix=64) % DT_INT64, NIFTI_TYPE_INT64
% 1280 Unsigned long long (uint64, bitpix=64) % DT_UINT64, NIFTI_TYPE_UINT64
% 1536 Long double, float128 (Unsupported, bitpix=128) % DT_FLOAT128, NIFTI_TYPE_FLOAT128
% 1792 Complex128, 2 float64 (Use float64, bitpix=128) % DT_COMPLEX128, NIFTI_TYPE_COMPLEX128
% 2048 Complex256, 2 float128 (Unsupported, bitpix=256) % DT_COMPLEX128, NIFTI_TYPE_COMPLEX128
%
switch hdr.dime.datatype
case 1,
hdr.dime.bitpix = 1; precision = 'ubit1';
case 2,
hdr.dime.bitpix = 8; precision = 'uint8';
case 4,
hdr.dime.bitpix = 16; precision = 'int16';
case 8,
hdr.dime.bitpix = 32; precision = 'int32';
case 16,
hdr.dime.bitpix = 32; precision = 'float32';
case 32,
hdr.dime.bitpix = 64; precision = 'float32';
case 64,
hdr.dime.bitpix = 64; precision = 'float64';
case 128,
hdr.dime.bitpix = 24; precision = 'uint8';
case 256
hdr.dime.bitpix = 8; precision = 'int8';
case 511
hdr.dime.bitpix = 96; precision = 'float32';
case 512
hdr.dime.bitpix = 16; precision = 'uint16';
case 768
hdr.dime.bitpix = 32; precision = 'uint32';
case 1024
hdr.dime.bitpix = 64; precision = 'int64';
case 1280
hdr.dime.bitpix = 64; precision = 'uint64';
case 1792,
hdr.dime.bitpix = 128; precision = 'float64';
otherwise
error('This datatype is not supported');
end
tmp = hdr.dime.dim(2:end);
tmp(find(tmp < 1)) = 1;
hdr.dime.dim(2:end) = tmp;
% Clean up after gunzip
%
if exist('gzFileName', 'var')
rmdir(tmpDir,'s');
end
return % load_untouch_header_only
|
github
|
changken1/IDH_Prediction-master
|
bipolar.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/bipolar.m
| 2,145 |
utf_8
|
295f87ece96ca4c5dff8dce4cd912a34
|
%BIPOLAR returns an M-by-3 matrix containing a blue-red colormap, in
% in which red stands for positive, blue stands for negative,
% and white stands for 0.
%
% Usage: cmap = bipolar(M, lo, hi, contrast); or cmap = bipolar;
%
% cmap: output M-by-3 matrix for BIPOLAR colormap.
% M: number of shades in the colormap. By default, it is the
% same length as the current colormap.
% lo: the lowest value to represent.
% hi: the highest value to represent.
%
% Inspired from the LORETA PASCAL program:
% http://www.unizh.ch/keyinst/NewLORETA
%
% [email protected]
%
%----------------------------------------------------------------
function cmap = bipolar(M, lo, hi, contrast)
if ~exist('contrast','var')
contrast = 128;
end
if ~exist('lo','var')
lo = -1;
end
if ~exist('hi','var')
hi = 1;
end
if ~exist('M','var')
cmap = colormap;
M = size(cmap,1);
end
steepness = 10 ^ (1 - (contrast-1)/127);
pos_infs = 1e-99;
neg_infs = -1e-99;
doubleredc = [];
doublebluec = [];
if lo >= 0 % all positive
if lo == 0
lo = pos_infs;
end
for i=linspace(hi/M, hi, M)
t = exp(log(i/hi)*steepness);
doubleredc = [doubleredc; [(1-t)+t,(1-t)+0,(1-t)+0]];
end
cmap = doubleredc;
elseif hi <= 0 % all negative
if hi == 0
hi = neg_infs;
end
for i=linspace(abs(lo)/M, abs(lo), M)
t = exp(log(i/abs(lo))*steepness);
doublebluec = [doublebluec; [(1-t)+0,(1-t)+0,(1-t)+t]];
end
cmap = flipud(doublebluec);
else
if hi > abs(lo)
maxc = hi;
else
maxc = abs(lo);
end
for i=linspace(maxc/M, hi, round(M*hi/(hi-lo)))
t = exp(log(i/maxc)*steepness);
doubleredc = [doubleredc; [(1-t)+t,(1-t)+0,(1-t)+0]];
end
for i=linspace(maxc/M, abs(lo), round(M*abs(lo)/(hi-lo)))
t = exp(log(i/maxc)*steepness);
doublebluec = [doublebluec; [(1-t)+0,(1-t)+0,(1-t)+t]];
end
cmap = [flipud(doublebluec); doubleredc];
end
return; % bipolar
|
github
|
changken1/IDH_Prediction-master
|
save_nii_hdr.m
|
.m
|
IDH_Prediction-master/MatlabScripts/NIFTI/save_nii_hdr.m
| 9,270 |
utf_8
|
f97c194f5bfc667eb4f96edf12be02a7
|
% internal function
% - Jimmy Shen ([email protected])
function save_nii_hdr(hdr, fid)
if ~exist('hdr','var') | ~exist('fid','var')
error('Usage: save_nii_hdr(hdr, fid)');
end
if ~isequal(hdr.hk.sizeof_hdr,348),
error('hdr.hk.sizeof_hdr must be 348.');
end
if hdr.hist.qform_code == 0 & hdr.hist.sform_code == 0
hdr.hist.sform_code = 1;
hdr.hist.srow_x(1) = hdr.dime.pixdim(2);
hdr.hist.srow_x(2) = 0;
hdr.hist.srow_x(3) = 0;
hdr.hist.srow_y(1) = 0;
hdr.hist.srow_y(2) = hdr.dime.pixdim(3);
hdr.hist.srow_y(3) = 0;
hdr.hist.srow_z(1) = 0;
hdr.hist.srow_z(2) = 0;
hdr.hist.srow_z(3) = hdr.dime.pixdim(4);
hdr.hist.srow_x(4) = (1-hdr.hist.originator(1))*hdr.dime.pixdim(2);
hdr.hist.srow_y(4) = (1-hdr.hist.originator(2))*hdr.dime.pixdim(3);
hdr.hist.srow_z(4) = (1-hdr.hist.originator(3))*hdr.dime.pixdim(4);
end
write_header(hdr, fid);
return; % save_nii_hdr
%---------------------------------------------------------------------
function write_header(hdr, fid)
% Original header structures
% struct dsr /* dsr = hdr */
% {
% struct header_key hk; /* 0 + 40 */
% struct image_dimension dime; /* 40 + 108 */
% struct data_history hist; /* 148 + 200 */
% }; /* total= 348 bytes*/
header_key(fid, hdr.hk);
image_dimension(fid, hdr.dime);
data_history(fid, hdr.hist);
% check the file size is 348 bytes
%
fbytes = ftell(fid);
if ~isequal(fbytes,348),
msg = sprintf('Header size is not 348 bytes.');
warning(msg);
end
return; % write_header
%---------------------------------------------------------------------
function header_key(fid, hk)
fseek(fid,0,'bof');
% Original header structures
% struct header_key /* header key */
% { /* off + size */
% int sizeof_hdr /* 0 + 4 */
% char data_type[10]; /* 4 + 10 */
% char db_name[18]; /* 14 + 18 */
% int extents; /* 32 + 4 */
% short int session_error; /* 36 + 2 */
% char regular; /* 38 + 1 */
% char dim_info; % char hkey_un0; /* 39 + 1 */
% }; /* total=40 bytes */
fwrite(fid, hk.sizeof_hdr(1), 'int32'); % must be 348.
% data_type = sprintf('%-10s',hk.data_type); % ensure it is 10 chars from left
% fwrite(fid, data_type(1:10), 'uchar');
pad = zeros(1, 10-length(hk.data_type));
hk.data_type = [hk.data_type char(pad)];
fwrite(fid, hk.data_type(1:10), 'uchar');
% db_name = sprintf('%-18s', hk.db_name); % ensure it is 18 chars from left
% fwrite(fid, db_name(1:18), 'uchar');
pad = zeros(1, 18-length(hk.db_name));
hk.db_name = [hk.db_name char(pad)];
fwrite(fid, hk.db_name(1:18), 'uchar');
fwrite(fid, hk.extents(1), 'int32');
fwrite(fid, hk.session_error(1), 'int16');
fwrite(fid, hk.regular(1), 'uchar'); % might be uint8
% fwrite(fid, hk.hkey_un0(1), 'uchar');
% fwrite(fid, hk.hkey_un0(1), 'uint8');
fwrite(fid, hk.dim_info(1), 'uchar');
return; % header_key
%---------------------------------------------------------------------
function image_dimension(fid, dime)
% Original header structures
% struct image_dimension
% { /* off + size */
% short int dim[8]; /* 0 + 16 */
% float intent_p1; % char vox_units[4]; /* 16 + 4 */
% float intent_p2; % char cal_units[8]; /* 20 + 4 */
% float intent_p3; % char cal_units[8]; /* 24 + 4 */
% short int intent_code; % short int unused1; /* 28 + 2 */
% short int datatype; /* 30 + 2 */
% short int bitpix; /* 32 + 2 */
% short int slice_start; % short int dim_un0; /* 34 + 2 */
% float pixdim[8]; /* 36 + 32 */
% /*
% pixdim[] specifies the voxel dimensions:
% pixdim[1] - voxel width
% pixdim[2] - voxel height
% pixdim[3] - interslice distance
% pixdim[4] - volume timing, in msec
% ..etc
% */
% float vox_offset; /* 68 + 4 */
% float scl_slope; % float roi_scale; /* 72 + 4 */
% float scl_inter; % float funused1; /* 76 + 4 */
% short slice_end; % float funused2; /* 80 + 2 */
% char slice_code; % float funused2; /* 82 + 1 */
% char xyzt_units; % float funused2; /* 83 + 1 */
% float cal_max; /* 84 + 4 */
% float cal_min; /* 88 + 4 */
% float slice_duration; % int compressed; /* 92 + 4 */
% float toffset; % int verified; /* 96 + 4 */
% int glmax; /* 100 + 4 */
% int glmin; /* 104 + 4 */
% }; /* total=108 bytes */
fwrite(fid, dime.dim(1:8), 'int16');
fwrite(fid, dime.intent_p1(1), 'float32');
fwrite(fid, dime.intent_p2(1), 'float32');
fwrite(fid, dime.intent_p3(1), 'float32');
fwrite(fid, dime.intent_code(1), 'int16');
fwrite(fid, dime.datatype(1), 'int16');
fwrite(fid, dime.bitpix(1), 'int16');
fwrite(fid, dime.slice_start(1), 'int16');
fwrite(fid, dime.pixdim(1:8), 'float32');
fwrite(fid, dime.vox_offset(1), 'float32');
fwrite(fid, dime.scl_slope(1), 'float32');
fwrite(fid, dime.scl_inter(1), 'float32');
fwrite(fid, dime.slice_end(1), 'int16');
fwrite(fid, dime.slice_code(1), 'uchar');
fwrite(fid, dime.xyzt_units(1), 'uchar');
fwrite(fid, dime.cal_max(1), 'float32');
fwrite(fid, dime.cal_min(1), 'float32');
fwrite(fid, dime.slice_duration(1), 'float32');
fwrite(fid, dime.toffset(1), 'float32');
fwrite(fid, dime.glmax(1), 'int32');
fwrite(fid, dime.glmin(1), 'int32');
return; % image_dimension
%---------------------------------------------------------------------
function data_history(fid, hist)
% Original header structures
%struct data_history
% { /* off + size */
% char descrip[80]; /* 0 + 80 */
% char aux_file[24]; /* 80 + 24 */
% short int qform_code; /* 104 + 2 */
% short int sform_code; /* 106 + 2 */
% float quatern_b; /* 108 + 4 */
% float quatern_c; /* 112 + 4 */
% float quatern_d; /* 116 + 4 */
% float qoffset_x; /* 120 + 4 */
% float qoffset_y; /* 124 + 4 */
% float qoffset_z; /* 128 + 4 */
% float srow_x[4]; /* 132 + 16 */
% float srow_y[4]; /* 148 + 16 */
% float srow_z[4]; /* 164 + 16 */
% char intent_name[16]; /* 180 + 16 */
% char magic[4]; % int smin; /* 196 + 4 */
% }; /* total=200 bytes */
% descrip = sprintf('%-80s', hist.descrip); % 80 chars from left
% fwrite(fid, descrip(1:80), 'uchar');
pad = zeros(1, 80-length(hist.descrip));
hist.descrip = [hist.descrip char(pad)];
fwrite(fid, hist.descrip(1:80), 'uchar');
% aux_file = sprintf('%-24s', hist.aux_file); % 24 chars from left
% fwrite(fid, aux_file(1:24), 'uchar');
pad = zeros(1, 24-length(hist.aux_file));
hist.aux_file = [hist.aux_file char(pad)];
fwrite(fid, hist.aux_file(1:24), 'uchar');
fwrite(fid, hist.qform_code, 'int16');
fwrite(fid, hist.sform_code, 'int16');
fwrite(fid, hist.quatern_b, 'float32');
fwrite(fid, hist.quatern_c, 'float32');
fwrite(fid, hist.quatern_d, 'float32');
fwrite(fid, hist.qoffset_x, 'float32');
fwrite(fid, hist.qoffset_y, 'float32');
fwrite(fid, hist.qoffset_z, 'float32');
fwrite(fid, hist.srow_x(1:4), 'float32');
fwrite(fid, hist.srow_y(1:4), 'float32');
fwrite(fid, hist.srow_z(1:4), 'float32');
% intent_name = sprintf('%-16s', hist.intent_name); % 16 chars from left
% fwrite(fid, intent_name(1:16), 'uchar');
pad = zeros(1, 16-length(hist.intent_name));
hist.intent_name = [hist.intent_name char(pad)];
fwrite(fid, hist.intent_name(1:16), 'uchar');
% magic = sprintf('%-4s', hist.magic); % 4 chars from left
% fwrite(fid, magic(1:4), 'uchar');
pad = zeros(1, 4-length(hist.magic));
hist.magic = [hist.magic char(pad)];
fwrite(fid, hist.magic(1:4), 'uchar');
return; % data_history
|
github
|
andersfp/XFrFT-master
|
frfft1gpusp.m
|
.m
|
XFrFT-master/frfft1gpusp.m
| 6,380 |
utf_8
|
fac15f6a9321b677486717088b80aa5a
|
function res = frfft1gpusp(fc,a)
% Calculate the 1D fractional Fourier transform along the first dimension
% of the input (fc). The transform order is given by the second input (a).
% The input (fc) must have an even number of rows.
% Single precision only. Requires a compatible GPU.
%
% Example of usage:
% res = frfft1gpusp(fc,a)
%
% The function supports single precision input only.
%
% This implementation is performs the central algorithm on a GPU, giving
% significant speedup over a CPU. The algorithm breaks up the array into a
% size that has the highest FFT performance. This function has been
% optimized for an Nvidia GTX Titan X (Pascal), for which the optimum
% number of elements for FFT is elmax = 2*4.98e7. This number might be
% different other GPUs, so for optimal performance this should be tested
% and the elmax parameter in this function should be changed.
%
% The basic algorithm is based on an implementation by M. A. Kutay, based
% on the following works:
% Haldun M. Ozaktas, Orhan Arikan, M. Alper Kutay, and Gozde Bozdagi,
% Digital computation of the fractional Fourier transform,
% IEEE Transactions on Signal Processing, 44:2141--2150, 1996.
% Haldun M. Ozaktas, Zeev Zalevsky, and M. Alper Kutay,
% The Fractional Fourier Transform with Applications in Optics and
% Signal Processing, Wiley, 2000, chapter 6, page 298.
%
% Some suggestions A. Bultheel and H. E. M. Sulbaran have been used:
% Bultheel, A.; Martinez Sulbaran, H. E. Computation of the Fractional
% Fourier Transform. Applied and Computational Harmonic Analysis 2004,
% 16 (3), 182-202.
%
% Significant speedups and adaptation to 2D array have been made by Anders
% F. Pedersen.
%
% Author: Anders F. Pedersen
%
% Number of data points in the transform direction
N = size(fc,1);
% Check that the input length is even
if mod(N,2) == 1
error('Length of the input vector should be even.');
end
% Change a to the interval [-2:2[
a = mod(a + 2,4) - 2;
% Deal with special cases
if a == 0
res = fc;
return
elseif a == 2 || a == -2
res = flip(fc,1);
return
end
% Reshape ND array to 2D
s = size(fc);
fc = reshape(fc,s(1),prod(s(2:end)));
% Number of data points in the non-transform direction
M = size(fc,2);
% Split the array to optimize FFT computation
%elmax = 2*4.98e7; % This is the number of elements that maximize the FFT performance on an Nvidia Titan X (Pascal) GPU with 12 GB VRAM
elmax = 49152000;
m = floor(elmax/(2^nextpow2(16*N)));
k = ceil(M/m);
i1 = (0:(k - 1))*m + 1;
i2 = (1:k)*m;
i2(end) = M;
% Pre-allocate memory for the result
res = zeros(N,M,'single');
% Make shift array to shift data
shft = single([(4*N/2+1):(4*N) 1:(4*N/2)]);
for i = 1:k
% Send data to GPU
fg = gpuArray(fc(:,i1(i):i2(i)));
% Make local version of the a-parameter
ag = a;
% Interpolate the input function
fg = bizinter(fg);
% Zeropad the array
mg = size(fg,2);
fg = cat(1,zeros(N,mg,'single','gpuArray'),fg,zeros(N,mg,'single','gpuArray'));
% Map a onto the interval 0.5 <= |a| <= 1.5
if ((ag > 0) && (ag < 0.5)) || ((ag > 1.5) && (ag < 2))
ag = ag - 1;
fg(shft,:) = fft(fg(shft,:))/sqrt(4*N);
elseif ((ag > -0.5) && (ag < 0)) || ((ag > -2) && (ag < -1.5))
ag = ag + 1;
fg(shft,:) = ifft(fg(shft,:))*sqrt(4*N);
end
% Calculate the transform at reduced interval a
fg = corefrmod2(fg,ag);
% Deinterpolate the result
fg = fg(N+1:2:3*N,:);
% Return the result to the CPU
res(:,i1(i):i2(i)) = gather(fg);
end
% Transform output from 2D to ND
res = reshape(res,s);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function res = corefrmod2(fc,a)
% Core function for computing the fractional Fourier transform.
% Valid only when 0.5 <= abs(a) <= 1.5
% Decomposition used:
% chirp mutiplication - chirp convolution - chirp mutiplication
% Calculate scalar parameters
N = size(fc,1);
M = size(fc,2);
deltax = single(sqrt(N));
phi = a*pi/2;
beta = 1/sin(phi);
% Calculate chirp vectors
x = (-ceil(N/2):fix(N/2)-1).'/deltax;
chrp1 = exp(-1i*pi*tan(phi/2)*x.^2);
t = (-N+1:N-1).'/deltax;
chrp2 = exp(1i*pi*beta*t.^2);
% Get lengths of chirp and fft length
N2 = 2*N - 1;
N3 = 2^nextpow2(N2 + N - 1);
% Zeropad chirp for convolution
chrp2 = cat(1,chrp2,zeros(N3 - N2,1));
% Fourier transform chirp
chrp2 = fft(chrp2);
% Send chirps to the GPU
chrp1 = gpuArray(single(chrp1));
chrp2 = gpuArray(single(chrp2));
% Calculate amplitude
Aphi = single(exp(-1i*(pi*sign(sin(phi))/4-phi/2))/sqrt(abs(sin(phi))));
% Multiply by chirp
fc = bsxfun(@times,fc,chrp1);
% Zeropad array for convolution
fc = cat(1,fc,zeros(N3 - N,M,'single','gpuArray'));
% Perform chirp convolution
fc = fft(fc);
fc = bsxfun(@times,fc,chrp2);
fc = ifft(fc);
fc = fc(N:2*N-1,:);
% Apply amplitude and chirp multiplication
res = bsxfun(@times,fc,chrp1).*(Aphi./deltax);
% Shift array if odd sized array
if rem(N,2) == 1
res = circshift(res,-1);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function xint = bizinter(x)
% Get the number of data points
N = single(size(x,1));
M = single(size(x,2));
% Determine if input is complex, and split real and complex parts
im = 0;
if ~all(isreal(x(:)))
im = 1;
imx = imag(x);
x = real(x);
end;
% Process the real part
xint = bizintercore(x);
% Process the imaginary part
if im == 1
xmint = bizintercore(imx);
xint = xint + single(1i)*xmint;
end
% Add core function
function xint = bizintercore(x2)
% Add zeros at every other element
x2 = cat(3,x2,zeros(N,M,'single','gpuArray'));
x2 = permute(x2,[3 1 2]);
x2 = reshape(x2,2*N,M);
% Fourier transform the array
xf = fft(x2);
% Inverse Fourier transform
if rem(N,2) == 1
N1 = fix(N/2+1);
N2 = 2*N - fix(N/2) + 1;
xf = cat(1,xf(1:N1,:),zeros(N,M,'single','gpuArray'),xf(N2:2*N,:));
xint = ifft(xf);
xint = 2*real(xint);
else
xf(N/2+1:2*N-N/2,:) = 0;
xint = ifft(xf);
xint = 2*real(xint);
end
end
end
|
github
|
andersfp/XFrFT-master
|
frfft1gpu.m
|
.m
|
XFrFT-master/frfft1gpu.m
| 6,255 |
utf_8
|
a4578bd00d2773bfabb86d55717ae285
|
function res = frfft1gpu(fc,a)
% Calculate the 1D fractional Fourier transform along the first dimension
% of the input (fc). The transform order is given by the second input (a).
% The input (fc) must have an even number of rows.
% Requires a compatible GPU.
%
% Example of usage:
% res = frfft1gpu(fc,a)
%
% The function supports double precision input only.
%
% This implementation is performs the central algorithm on a GPU, giving
% significant speedup over a CPU. The algorithm breaks up the array into a
% size that has the highest FFT performance. This function has been
% optimized for an Nvidia GTX Titan X (Pascal), for which the optimum
% number of elements for FFT is elmax = 4.98e7. This number might be
% different other GPUs, so for optimal performance this should be tested
% and the elmax parameter in this function should be changed.
%
% The basic algorithm is based on an implementation by M. A. Kutay, based
% on the following works:
% Haldun M. Ozaktas, Orhan Arikan, M. Alper Kutay, and Gozde Bozdagi,
% Digital computation of the fractional Fourier transform,
% IEEE Transactions on Signal Processing, 44:2141--2150, 1996.
% Haldun M. Ozaktas, Zeev Zalevsky, and M. Alper Kutay,
% The Fractional Fourier Transform with Applications in Optics and
% Signal Processing, Wiley, 2000, chapter 6, page 298.
%
% Some suggestions A. Bultheel and H. E. M. Sulbaran have been used:
% Bultheel, A.; Martinez Sulbaran, H. E. Computation of the Fractional
% Fourier Transform. Applied and Computational Harmonic Analysis 2004,
% 16 (3), 182-202.
%
% Significant speedups and adaptation to 2D array have been made by Anders
% F. Pedersen.
%
% Author: Anders F. Pedersen
%
% Number of data points in the transform direction
N = size(fc,1);
% Check that the input length is even
if mod(N,2) == 1
error('Length of the input vector should be even.');
end
% Change a to the interval [-2:2[
a = mod(a + 2,4) - 2;
% Deal with special cases
if a == 0
res = fc;
return
elseif a == 2 || a == -2
res = flip(fc,1);
return
end
% Reshape ND array to 2D
s = size(fc);
fc = reshape(fc,s(1),prod(s(2:end)));
% Number of data points in the non-transform direction
M = size(fc,2);
% Split the array to optimize FFT computation
elmax = 4.98e7; % This is the number of elements that maximize the FFT performance on an Nvidia Titan X (Pascal) GPU with 12 GB VRAM
m = floor(elmax/(2^nextpow2(8*N)));
k = ceil(M/m);
i1 = (0:(k - 1))*m + 1;
i2 = (1:k)*m;
i2(end) = M;
% Pre-allocate memory for the result
res = zeros(N,M);
% Make shift array to shift data
shft = [(4*N/2+1):(4*N) 1:(4*N/2)];
for i = 1:k
% Send data to GPU
fg = gpuArray(fc(:,i1(i):i2(i)));
% Make local version of the a-parameter
ag = a;
% Interpolate the input function
fg = bizinter(fg);
% Zeropad the array
mg = size(fg,2);
fg = cat(1,zeros(N,mg,'double','gpuArray'),fg,zeros(N,mg,'double','gpuArray'));
% Map a onto the interval 0.5 <= |a| <= 1.5
if ((ag > 0) && (ag < 0.5)) || ((ag > 1.5) && (ag < 2))
ag = ag - 1;
fg(shft,:) = fft(fg(shft,:))/sqrt(4*N);
elseif ((ag > -0.5) && (ag < 0)) || ((ag > -2) && (ag < -1.5))
ag = ag + 1;
fg(shft,:) = ifft(fg(shft,:))*sqrt(4*N);
end
% Calculate the transform at reduced interval a
fg = corefrmod2(fg,ag);
% Deinterpolate the result
fg = fg(N+1:2:3*N,:);
% Return the result to the CPU
res(:,i1(i):i2(i)) = gather(fg);
end
% Transform output from 2D to ND
res = reshape(res,s);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function res = corefrmod2(fc,a)
% Core function for computing the fractional Fourier transform.
% Valid only when 0.5 <= abs(a) <= 1.5
% Decomposition used:
% chirp mutiplication - chirp convolution - chirp mutiplication
% Calculate scalar parameters
N = size(fc,1);
M = size(fc,2);
deltax = sqrt(N);
phi = a*pi/2;
beta = 1/sin(phi);
% Calculate chirp vectors
x = (-ceil(N/2):fix(N/2)-1).'/deltax;
chrp1 = exp(-1i*pi*tan(phi/2)*x.^2);
t = (-N+1:N-1).'/deltax;
chrp2 = exp(1i*pi*beta*t.^2);
% Get lengths of chirp and fft length
N2 = 2*N - 1;
N3 = 2^nextpow2(N2 + N - 1);
% Zeropad chirp for convolution
chrp2 = cat(1,chrp2,zeros(N3 - N2,1));
% Fourier transform chirp
chrp2 = fft(chrp2);
% Send chirps to the GPU
chrp1 = gpuArray(chrp1);
chrp2 = gpuArray(chrp2);
% Calculate amplitude
Aphi = exp(-1i*(pi*sign(sin(phi))/4-phi/2))/sqrt(abs(sin(phi)));
% Multiply by chirp
fc = bsxfun(@times,fc,chrp1);
% Zeropad array for convolution
fc = cat(1,fc,zeros(N3 - N,M,'double','gpuArray'));
% Perform chirp convolution
fc = fft(fc);
fc = bsxfun(@times,fc,chrp2);
fc = ifft(fc);
fc = fc(N:2*N-1,:);
% Apply amplitude and chirp multiplication
res = bsxfun(@times,fc,chrp1).*(Aphi./deltax);
% Shift array if odd sized array
if rem(N,2) == 1
res = circshift(res,-1);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function xint = bizinter(x)
% Get the number of data points
N = size(x,1);
M = size(x,2);
% Determine if input is complex, and split real and complex parts
im = 0;
if ~all(isreal(x(:)))
im = 1;
imx = imag(x);
x = real(x);
end;
% Process the real part
xint = bizintercore(x);
% Process the imaginary part
if im == 1
xmint = bizintercore(imx);
xint = xint + 1i*xmint;
end
% Add core function
function xint = bizintercore(x2)
% Add zeros at every other element
x2 = cat(3,x2,zeros(N,M,'double','gpuArray'));
x2 = permute(x2,[3 1 2]);
x2 = reshape(x2,2*N,M);
% Fourier transform the array
xf = fft(x2);
% Inverse Fourier transform
if rem(N,2) == 1
N1 = fix(N/2+1);
N2 = 2*N - fix(N/2) + 1;
xf = cat(1,xf(1:N1,:),zeros(N,M,'double','gpuArray'),xf(N2:2*N,:));
xint = ifft(xf);
xint = 2*real(xint);
else
xf(N/2+1:2*N-N/2,:) = 0;
xint = ifft(xf);
xint = 2*real(xint);
end
end
end
|
github
|
andersfp/XFrFT-master
|
frfft1for.m
|
.m
|
XFrFT-master/frfft1for.m
| 5,202 |
utf_8
|
8eb3e984f45dc5b013b411432b393e76
|
function res = frfft1for(fc,a)
% Calculate the 1D fractional Fourier transform along the first dimension
% of the input (fc). The transform order is given by the second input (a).
% The input (fc) must have an even number of rows.
%
% Example of usage:
% res = frfft1for(fc,a)
%
% The function supports double and single precision inputs.
%
% This implementation is based on a for-loop over each column of the input.
%
% The basic algorithm is based on an implementation by M. A. Kutay, based
% on the following works:
% Haldun M. Ozaktas, Orhan Arikan, M. Alper Kutay, and Gozde Bozdagi,
% Digital computation of the fractional Fourier transform,
% IEEE Transactions on Signal Processing, 44:2141--2150, 1996.
% Haldun M. Ozaktas, Zeev Zalevsky, and M. Alper Kutay,
% The Fractional Fourier Transform with Applications in Optics and
% Signal Processing, Wiley, 2000, chapter 6, page 298.
%
% Some suggestions A. Bultheel and H. E. M. Sulbaran have been used:
% Bultheel, A.; Martinez Sulbaran, H. E. Computation of the Fractional
% Fourier Transform. Applied and Computational Harmonic Analysis 2004,
% 16 (3), 182-202.
%
% Significant speedups and adaptation to 2D array have been made by Anders
% F. Pedersen.
%
% Author: Anders F. Pedersen
%
% Number of data points in the transform direction
N = size(fc,1);
% Check that the input length is even
if mod(N,2) == 1
error('Length of the input vector should be even.');
end
% Change a to the interval [-2:2[
a = mod(a + 2,4) - 2;
% Deal with special cases
if a == 0
res = fc;
return
elseif a == 2 || a == -2
res = flip(fc,1);
return
end
% Reshape ND array to 2D
s = size(fc);
fc = reshape(fc,s(1),prod(s(2:end)));
% Number of data points in the non-transform direction
M = size(fc,2);
% Interpolate the input function
fc = bizinter(fc);
fc = cat(1,zeros(N,M,'like',fc),fc,zeros(N,M,'like',fc));
% Map a onto the interval 0.5 <= |a| <= 1.5
if ((a > 0) && (a < 0.5)) || ((a > 1.5) && (a < 2))
a = a - 1;
res = ifftshift(fft(fftshift(fc,1)),1)/sqrt(4*N);
elseif ((a > -0.5) && (a < 0)) || ((a > -2) && (a < -1.5))
a = a + 1;
res = ifftshift(ifft(fftshift(fc,1)),1)*sqrt(4*N);
else
res = fc;
end
% Calculate the transform at reduced interval a
res = corefrmod2(res,a);
% Deinterpolate the result
res = res(N+1:2:3*N,:);
% Transform output from 2D to ND
res = reshape(res,s);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function res = corefrmod2(fc,a)
% Core function for computing the fractional Fourier transform.
% Valid only when 0.5 <= abs(a) <= 1.5
% Decomposition used:
% chirp mutiplication - chirp convolution - chirp mutiplication
% Calculate scalar parameters
N = size(fc,1);
M = size(fc,2);
deltax = sqrt(N);
phi = a*pi/2;
beta = 1/sin(phi);
% Calculate chirp vectors
x = (-ceil(N/2):fix(N/2)-1).'/deltax;
chrp1 = exp(-1i*pi*tan(phi/2)*x.^2);
t = (-N+1:N-1).'/deltax;
chrp2 = exp(1i*pi*beta*t.^2);
clear x;
clear t;
chrp1 = cast(chrp1,'like',fc);
chrp2 = cast(chrp2,'like',fc);
% Get lengths of chirp and fft length
N2 = 2*N - 1;
N3 = 2^nextpow2(N2 + N - 1);
% Zeropad chirp for convolution
chrp2 = cat(1,chrp2,zeros(N3 - N2,1,'like',chrp2));
% Fourier transform chirp
chrp2 = fft(chrp2);
% Calculate amplitude
Aphi = exp(-1i*(pi*sign(sin(phi))/4-phi/2))/sqrt(abs(sin(phi)));
% Run the central multiply-convolute-multiply algorithm
res = zeros(N,M,'like',fc);
for i = 1:M
% Multiply by chirp
fci = fc(:,i).*chrp1;
% Zeropad array for convolution
fci = cat(1,fci,zeros(N3 - N,1,'like',fci));
% Perform chirp convolution
fci = ifft(fft(fci).*chrp2);
fci = fci(N:2*N-1,:);
% Apply amplitude and chirp multiplication
res(:,i) = (chrp1.*fci).*(Aphi./deltax);
end
% Shift array if odd sized array
if rem(N,2) == 1
res = circshift(res,-1);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function xint = bizinter(x)
% Get the number of data points
N = size(x,1);
M = size(x,2);
% Determine if input is complex, and split real and complex parts
im = 0;
if ~all(isreal(x(:)))
im = 1;
imx = imag(x);
x = real(x);
end;
% Process the real part
xint = bizintercore(x);
% Process the imaginary part
if im == 1
xmint = bizintercore(imx);
xint = xint + 1i*xmint;
end
% Add core function
function xint = bizintercore(x2)
xint = zeros(2*N,M,'like',x2);
if rem(N,2) == 1
N1 = fix(N/2+1);
N2 = 2*N - fix(N/2) + 1;
for i = 1:M
xt = cat(1,x2(:,i).',zeros(1,N,'like',x2));
xt = xt(:);
xf = fft(xt);
xf = cat(1,xf(1:N1,:),zeros(N,1,'like',xf),xf(N2:2*N,:));
xint(:,i) = 2*real(ifft(xf));
end
else
for i = 1:M
xt = cat(1,x2(:,i).',zeros(1,N,'like',x2));
xt = xt(:);
xf = fft(xt);
xf(N/2+1:2*N-N/2) = 0;
xint(:,i) = 2*real(ifft(xf));
end
end
end
end
|
github
|
andersfp/XFrFT-master
|
frfft1par.m
|
.m
|
XFrFT-master/frfft1par.m
| 5,309 |
utf_8
|
d55fcfb57c8b274ace60a1b495fe0284
|
function res = frfft1par(fc,a)
% Calculate the 1D fractional Fourier transform along the first dimension
% of the input (fc). The transform order is given by the second input (a).
% The input (fc) must have an even number of rows.
% Requires Parallel Toolbox.
%
% Example of usage:
% res = frfft1par(fc,a)
%
% The function supports double and single precision inputs.
%
% This implementation is based on a parallel for-loop over each column of
% the input, and therefore require the Parallel Toolbox.
%
% The basic algorithm is based on an implementation by M. A. Kutay, based
% on the following works:
% Haldun M. Ozaktas, Orhan Arikan, M. Alper Kutay, and Gozde Bozdagi,
% Digital computation of the fractional Fourier transform,
% IEEE Transactions on Signal Processing, 44:2141--2150, 1996.
% Haldun M. Ozaktas, Zeev Zalevsky, and M. Alper Kutay,
% The Fractional Fourier Transform with Applications in Optics and
% Signal Processing, Wiley, 2000, chapter 6, page 298.
%
% Some suggestions A. Bultheel and H. E. M. Sulbaran have been used:
% Bultheel, A.; Martinez Sulbaran, H. E. Computation of the Fractional
% Fourier Transform. Applied and Computational Harmonic Analysis 2004,
% 16 (3), 182-202.
%
% Significant speedups and adaptation to 2D array have been made by Anders
% F. Pedersen.
%
% Author: Anders F. Pedersen
%
% Number of data points in the transform direction
N = size(fc,1);
% Check that the input length is even
if mod(N,2) == 1
error('Length of the input vector should be even.');
end
% Change a to the interval [-2:2[
a = mod(a + 2,4) - 2;
% Deal with special cases
if a == 0
res = fc;
return
elseif a == 2 || a == -2
res = flip(fc,1);
return
end
% Reshape ND array to 2D
s = size(fc);
fc = reshape(fc,s(1),prod(s(2:end)));
% Number of data points in the non-transform direction
M = size(fc,2);
% Interpolate the input function
fc = bizinter(fc);
fc = cat(1,zeros(N,M,'like',fc),fc,zeros(N,M,'like',fc));
% Map a onto the interval 0.5 <= |a| <= 1.5
if ((a > 0) && (a < 0.5)) || ((a > 1.5) && (a < 2))
a = a - 1;
res = ifftshift(fft(fftshift(fc,1)),1)/sqrt(4*N);
elseif ((a > -0.5) && (a < 0)) || ((a > -2) && (a < -1.5))
a = a + 1;
res = ifftshift(ifft(fftshift(fc,1)),1)*sqrt(4*N);
else
res = fc;
end
% Calculate the transform at reduced interval a
res = corefrmod2(res,a);
% Deinterpolate the result
res = res(N+1:2:3*N,:);
% Transform output from 2D to ND
res = reshape(res,s);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function res = corefrmod2(fc,a)
% Core function for computing the fractional Fourier transform.
% Valid only when 0.5 <= abs(a) <= 1.5
% Decomposition used:
% chirp mutiplication - chirp convolution - chirp mutiplication
% Calculate scalar parameters
N = size(fc,1);
M = size(fc,2);
deltax = sqrt(N);
phi = a*pi/2;
beta = 1/sin(phi);
% Calculate chirp vectors
x = (-ceil(N/2):fix(N/2)-1).'/deltax;
chrp1 = exp(-1i*pi*tan(phi/2)*x.^2);
t = (-N+1:N-1).'/deltax;
chrp2 = exp(1i*pi*beta*t.^2);
clear x;
clear t;
chrp1 = cast(chrp1,'like',fc);
chrp2 = cast(chrp2,'like',fc);
% Get lengths of chirp and fft length
N2 = 2*N - 1;
N3 = 2^nextpow2(N2 + N - 1);
% Zeropad chirp for convolution
chrp2 = cat(1,chrp2,zeros(N3 - N2,1,'like',chrp2));
% Fourier transform chirp
chrp2 = fft(chrp2);
% Calculate amplitude
Aphi = exp(-1i*(pi*sign(sin(phi))/4-phi/2))/sqrt(abs(sin(phi)));
% Run the central multiply-colnvolute-multiply algorithm
res = zeros(N,M,'like',fc);
parfor i = 1:M
% Multiply by chirp
fci = fc(:,i).*chrp1;
% Zeropad array for convolution
fci = cat(1,fci,zeros(N3 - N,1,'like',fci));
% Perform chirp convolution
fci = ifft(fft(fci).*chrp2);
fci = fci(N:2*N-1,:);
% Apply amplitude and chirp multiplication
res(:,i) = (chrp1.*fci).*(Aphi./deltax);
end
% Shift array if odd sized array
if rem(N,2) == 1
res = circshift(res,-1);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function xint = bizinter(x)
% Get the number of data points
N = size(x,1);
M = size(x,2);
% Determine if input is complex, and split real and complex parts
im = 0;
if ~all(isreal(x(:)))
im = 1;
imx = imag(x);
x = real(x);
end;
% Process the real part
xint = bizintercore(x);
% Process the imaginary part
if im == 1
xmint = bizintercore(imx);
xint = xint + 1i*xmint;
end
% Add core function
function xint = bizintercore(x2)
xint = zeros(2*N,M,'like',x2);
if rem(N,2) == 1
N1 = fix(N/2+1);
N2 = 2*N - fix(N/2) + 1;
parfor i = 1:M
xt = cat(1,x2(:,i).',zeros(1,N,'like',x2(:,i)));
xt = xt(:);
xf = fft(xt);
xf = cat(1,xf(1:N1,:),zeros(N,1,'like',xf),xf(N2:2*N,:));
xint(:,i) = 2*real(ifft(xf));
end
else
parfor i = 1:M
xt = cat(1,x2(:,i).',zeros(1,N,'like',x2(:,i)));
xt = xt(:);
xf = fft(xt);
xf(N/2+1:2*N-N/2) = 0;
xint(:,i) = 2*real(ifft(xf));
end
end
end
end
|
github
|
andersfp/XFrFT-master
|
frfft1vec.m
|
.m
|
XFrFT-master/frfft1vec.m
| 4,977 |
utf_8
|
5d684293c100ed266a413c558f649f2c
|
function res = frfft1vec(fc,a)
% Calculate the 1D fractional Fourier transform along the first dimension
% of the input (fc). The transform order is given by the second input (a).
% The input (fc) must have an even number of rows.
%
% Example of usage:
% res = frfft1vec(fc,a)
%
% The function supports double and single precision inputs.
%
% This implementation is based on vectorizing the operations.
%
% The basic algorithm is based on an implementation by M. A. Kutay, based
% on the following works:
% Haldun M. Ozaktas, Orhan Arikan, M. Alper Kutay, and Gozde Bozdagi,
% Digital computation of the fractional Fourier transform,
% IEEE Transactions on Signal Processing, 44:2141--2150, 1996.
% Haldun M. Ozaktas, Zeev Zalevsky, and M. Alper Kutay,
% The Fractional Fourier Transform with Applications in Optics and
% Signal Processing, Wiley, 2000, chapter 6, page 298.
%
% Some suggestions A. Bultheel and H. E. M. Sulbaran have been used:
% Bultheel, A.; Martinez Sulbaran, H. E. Computation of the Fractional
% Fourier Transform. Applied and Computational Harmonic Analysis 2004,
% 16 (3), 182-202.
%
% Significant speedups and adaptation to ND array have been made by Anders
% F. Pedersen.
%
% Author: Anders F. Pedersen
%
% Number of data points in the transform direction
N = size(fc,1);
% Check that the input length is even
if mod(N,2) == 1
error('Length of the input vector should be even.');
end
% Change a to the interval [-2:2[
a = mod(a + 2,4) - 2;
% Deal with special cases
if a == 0
res = fc;
return
elseif a == 2 || a == -2
res = flip(fc,1);
return
end
% Reshape ND array to 2D
s = size(fc);
fc = reshape(fc,s(1),prod(s(2:end)));
% Number of data points in the non-transform direction
M = size(fc,2);
% Interpolate the input function
fc = bizinter(fc);
fc = cat(1,zeros(N,M,'like',fc),fc,zeros(N,M,'like',fc));
% Map a onto the interval 0.5 <= |a| <= 1.5
if ((a > 0) && (a < 0.5)) || ((a > 1.5) && (a < 2))
a = a - 1;
res = ifftshift(fft(fftshift(fc,1)),1)/sqrt(4*N);
elseif ((a > -0.5) && (a < 0)) || ((a > -2) && (a < -1.5))
a = a + 1;
res = ifftshift(ifft(fftshift(fc,1)),1)*sqrt(4*N);
else
res = fc;
end
clear fc;
% Calculate the transform at reduced interval a
res = corefrmod2(res,a);
% Deinterpolate the result
res = res(N+1:2:3*N,:);
% Transform output from 2D to ND
res = reshape(res,s);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function res = corefrmod2(fc,a)
% Core function for computing the fractional Fourier transform.
% Valid only when 0.5 <= abs(a) <= 1.5
% Decomposition used:
% chirp mutiplication - chirp convolution - chirp mutiplication
% Calculate scalar parameters
N = size(fc,1);
M = size(fc,2);
deltax = sqrt(N);
phi = a*pi/2;
beta = 1/sin(phi);
% Calculate chirp vectors
x = (-ceil(N/2):fix(N/2)-1).'/deltax;
chrp1 = exp(-1i*pi*tan(phi/2)*x.^2);
t = (-N+1:N-1).'/deltax;
chrp2 = exp(1i*pi*beta*t.^2);
clear x;
clear t;
chrp1 = cast(chrp1,'like',fc);
chrp2 = cast(chrp2,'like',fc);
% Get lengths of chirp and fft length
N2 = 2*N - 1;
N3 = 2^nextpow2(N2 + N - 1);
% Zeropad chirp for convolution
chrp2 = cat(1,chrp2,zeros(N3 - N2,1,'like',chrp2));
% Fourier transform chirp
chrp2 = fft(chrp2);
% Calculate amplitude
Aphi = exp(-1i*(pi*sign(sin(phi))/4-phi/2))/sqrt(abs(sin(phi)));
% Multiply by chirp
fc = bsxfun(@times,fc,chrp1);
% Zeropad array for convolution
fc = cat(1,fc,zeros(N3 - N,M,'like',fc));
% Perform chirp convolution
fc = fft(fc);
fc = bsxfun(@times,fc,chrp2);
fc = ifft(fc);
fc = fc(N:2*N-1,:);
% Apply amplitude and chirp multiplication
res = bsxfun(@times,fc,chrp1).*(Aphi./deltax);
% Shift array if odd sized array
if rem(N,2) == 1
res = circshift(res,-1);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function xint = bizinter(x)
% Get the number of data points
N = size(x,1);
M = size(x,2);
% Determine if input is complex, and split real and complex parts
im = 0;
if ~all(isreal(x(:)))
im = 1;
imx = imag(x);
x = real(x);
end;
% Process the real part
xint = bizintercore(x);
% Process the imaginary part
if im == 1
xmint = bizintercore(imx);
xint = xint + 1i*xmint;
end
% Add core function
function xint = bizintercore(x2)
% Add zeros at every other element
x2 = cat(3,x2,zeros(N,M,'like',x2));
x2 = permute(x2,[3 1 2]);
x2 = reshape(x2,2*N,M);
% Fourier transform the array
xf = fft(x2);
% Inverse Fourier transform
if rem(N,2) == 1
N1 = fix(N/2+1);
N2 = 2*N - fix(N/2) + 1;
xf = cat(1,xf(1:N1,:),zeros(N,M,'like',xf),xf(N2:2*N,:));
xint = 2*real(ifft(xf));
else
xf(N/2+1:2*N-N/2,:) = 0;
xint = 2*real(ifft(xf));
end
end
end
|
github
|
Hadisalman/stoec-master
|
SMC_Update.m
|
.m
|
stoec-master/code/Fig_1_comparisons/SMC/SMC_Update.m
| 2,618 |
utf_8
|
1474d6577f0d7a61f9d8455eb5b86202
|
function [pose, Ck] = SMC_Update(pose, Ck, time, opt)
%% parameters needed from options(opt)
Lx = opt.L(1);
Ly = opt.L(2);
xmin = opt.DomainBounds.xmin;
ymin = opt.DomainBounds.ymin;
dt = opt.sim.dt;
Nagents = opt.nagents;
KX = opt.erg.KX;
KY= opt.erg.KY;
LK = opt.erg.LK;
HK= opt.erg.HK;
muk = opt.erg.muk;
%%
%Calculating the fourier coefficients of time average statistics distribution
for iagent = 1:Nagents
xrel = pose.x(iagent) - xmin;
yrel = pose.y(iagent) - ymin;
Ck = Ck + cos(KX * pi * xrel/Lx) .* cos(KY * pi * yrel/Ly) * opt.sim.dt ./ HK';
end
for iagent = 1:Nagents
xrel = pose.x(iagent) - xmin;
yrel = pose.y(iagent) - ymin;
Bjx = sum(sum(LK./ HK' .* (Ck - Nagents*time*muk) .* (-KX *pi/Lx .*sin(KX * pi * xrel/Lx) .* cos(KY *pi * yrel/Ly))));
Bjy = sum(sum(LK./ HK' .* (Ck - Nagents*time*muk) .* (-KY *pi/Ly .*cos(KX * pi * xrel/Lx) .* sin(KY *pi * yrel/Ly))));
% Bjnorm = sqrt(Bjx*Bjx + Bjy*Bjy);
GammaV = Bjx*cos(pose.theta(iagent)) + Bjy*sin(pose.theta(iagent));
GammaW = -Bjx*sin(pose.theta(iagent)) + Bjy*cos(pose.theta(iagent));
% Updating agent location based on SMC feedback control law
if GammaV >= 0
v = opt.vlb(iagent);
else
v = opt.vub(iagent);
end
if GammaW >= 0
w = opt.wlb(iagent);
else
w = opt.wub(iagent);
end
%velocity motion model
if(abs(w) < 1e-10 )
pose.x(iagent) = pose.x(iagent) + v*dt*cos(pose.theta(iagent));
pose.y(iagent) = pose.y(iagent) + v*dt*sin(pose.theta(iagent));
else
pose.x(iagent) = pose.x(iagent) + v/w*(sin(pose.theta(iagent) + w*dt) - sin(pose.theta(iagent)));
pose.y(iagent) = pose.y(iagent) + v/w*(cos(pose.theta(iagent)) - cos(pose.theta(iagent)+ w*dt));
end
pose.theta(iagent) = pose.theta(iagent)+ w*dt;
%No Need for this! % reflecting agent in case it goes out of domain bounds
% [pose.x(iagent),pose.y(iagent)] = reflect_agent(pose.x(iagent),pose.y(iagent), opt.DomainBounds);
end
end
function [agentx, agenty] = reflect_agent(agentx,agenty, DomainBounds)
xmin = DomainBounds.xmin;
xmax = DomainBounds.xmax;
ymin = DomainBounds.ymin;
ymax = DomainBounds.ymax;
if agentx < xmin
agentx = xmin + (xmin - agentx);
end
if agentx > xmax
agentx = xmax - (agentx - xmax);
end
if agenty < ymin
agenty = ymin + (ymin - agenty);
end
if agenty > ymax
agenty = ymax - (agenty - ymax);
end
end
|
github
|
Hadisalman/stoec-master
|
freezeColors.m
|
.m
|
stoec-master/code/Include/freezeColors.m
| 9,815 |
utf_8
|
2068d7a4f7a74d251e2519c4c5c1c171
|
function freezeColors(varargin)
% freezeColors Lock colors of plot, enabling multiple colormaps per figure. (v2.3)
%
% Problem: There is only one colormap per figure. This function provides
% an easy solution when plots using different colomaps are desired
% in the same figure.
%
% freezeColors freezes the colors of graphics objects in the current axis so
% that subsequent changes to the colormap (or caxis) will not change the
% colors of these objects. freezeColors works on any graphics object
% with CData in indexed-color mode: surfaces, images, scattergroups,
% bargroups, patches, etc. It works by converting CData to true-color rgb
% based on the colormap active at the time freezeColors is called.
%
% The original indexed color data is saved, and can be restored using
% unfreezeColors, making the plot once again subject to the colormap and
% caxis.
%
%
% Usage:
% freezeColors applies to all objects in current axis (gca),
% freezeColors(axh) same, but works on axis axh.
%
% Example:
% subplot(2,1,1); imagesc(X); colormap hot; freezeColors
% subplot(2,1,2); imagesc(Y); colormap hsv; freezeColors etc...
%
% Note: colorbars must also be frozen. Due to Matlab 'improvements' this can
% no longer be done with freezeColors. Instead, please
% use the function CBFREEZE by Carlos Adrian Vargas Aguilera
% that can be downloaded from the MATLAB File Exchange
% (http://www.mathworks.com/matlabcentral/fileexchange/24371)
%
% h=colorbar; cbfreeze(h), or simply cbfreeze(colorbar)
%
% For additional examples, see test/test_main.m
%
% Side effect on render mode: freezeColors does not work with the painters
% renderer, because Matlab doesn't support rgb color data in
% painters mode. If the current renderer is painters, freezeColors
% changes it to zbuffer. This may have unexpected effects on other aspects
% of your plots.
%
% See also unfreezeColors, freezeColors_pub.html, cbfreeze.
%
%
% John Iversen ([email protected]) 3/23/05
%
% Changes:
% JRI ([email protected]) 4/19/06 Correctly handles scaled integer cdata
% JRI 9/1/06 should now handle all objects with cdata: images, surfaces,
% scatterplots. (v 2.1)
% JRI 11/11/06 Preserves NaN colors. Hidden option (v 2.2, not uploaded)
% JRI 3/17/07 Preserve caxis after freezing--maintains colorbar scale (v 2.3)
% JRI 4/12/07 Check for painters mode as Matlab doesn't support rgb in it.
% JRI 4/9/08 Fix preserving caxis for objects within hggroups (e.g. contourf)
% JRI 4/7/10 Change documentation for colorbars
% Hidden option for NaN colors:
% Missing data are often represented by NaN in the indexed color
% data, which renders transparently. This transparency will be preserved
% when freezing colors. If instead you wish such gaps to be filled with
% a real color, add 'nancolor',[r g b] to the end of the arguments. E.g.
% freezeColors('nancolor',[r g b]) or freezeColors(axh,'nancolor',[r g b]),
% where [r g b] is a color vector. This works on images & pcolor, but not on
% surfaces.
% Thanks to Fabiano Busdraghi and Jody Klymak for the suggestions. Bugfixes
% attributed in the code.
% Free for all uses, but please retain the following:
% Original Author:
% John Iversen, 2005-10
% [email protected]
appdatacode = 'JRI__freezeColorsData';
[h, nancolor] = checkArgs(varargin);
%gather all children with scaled or indexed CData
cdatah = getCDataHandles(h);
%current colormap
cmap = colormap;
nColors = size(cmap,1);
cax = caxis;
% convert object color indexes into colormap to true-color data using
% current colormap
for hh = cdatah',
g = get(hh);
%preserve parent axis clim
parentAx = getParentAxes(hh);
originalClim = get(parentAx, 'clim');
% Note: Special handling of patches: For some reason, setting
% cdata on patches created by bar() yields an error,
% so instead we'll set facevertexcdata instead for patches.
if ~strcmp(g.Type,'patch'),
cdata = g.CData;
else
cdata = g.FaceVertexCData;
end
%get cdata mapping (most objects (except scattergroup) have it)
if isfield(g,'CDataMapping'),
scalemode = g.CDataMapping;
else
scalemode = 'scaled';
end
%save original indexed data for use with unfreezeColors
siz = size(cdata);
setappdata(hh, appdatacode, {cdata scalemode});
%convert cdata to indexes into colormap
if strcmp(scalemode,'scaled'),
%4/19/06 JRI, Accommodate scaled display of integer cdata:
% in MATLAB, uint * double = uint, so must coerce cdata to double
% Thanks to O Yamashita for pointing this need out
idx = ceil( (double(cdata) - cax(1)) / (cax(2)-cax(1)) * nColors);
else %direct mapping
idx = cdata;
%10/8/09 in case direct data is non-int (e.g. image;freezeColors)
% (Floor mimics how matlab converts data into colormap index.)
% Thanks to D Armyr for the catch
idx = floor(idx);
end
%clamp to [1, nColors]
idx(idx<1) = 1;
idx(idx>nColors) = nColors;
%handle nans in idx
nanmask = isnan(idx);
idx(nanmask)=1; %temporarily replace w/ a valid colormap index
%make true-color data--using current colormap
realcolor = zeros(siz);
for i = 1:3,
c = cmap(idx,i);
c = reshape(c,siz);
c(nanmask) = nancolor(i); %restore Nan (or nancolor if specified)
realcolor(:,:,i) = c;
end
%apply new true-color color data
%true-color is not supported in painters renderer, so switch out of that
if strcmp(get(gcf,'renderer'), 'painters'),
set(gcf,'renderer','zbuffer');
end
%replace original CData with true-color data
if ~strcmp(g.Type,'patch'),
set(hh,'CData',realcolor);
else
set(hh,'faceVertexCData',permute(realcolor,[1 3 2]))
end
%restore clim (so colorbar will show correct limits)
if ~isempty(parentAx),
set(parentAx,'clim',originalClim)
end
end %loop on indexed-color objects
% ============================================================================ %
% Local functions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% getCDataHandles -- get handles of all descendents with indexed CData
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function hout = getCDataHandles(h)
% getCDataHandles Find all objects with indexed CData
%recursively descend object tree, finding objects with indexed CData
% An exception: don't include children of objects that themselves have CData:
% for example, scattergroups are non-standard hggroups, with CData. Changing
% such a group's CData automatically changes the CData of its children,
% (as well as the children's handles), so there's no need to act on them.
error(nargchk(1,1,nargin,'struct'))
hout = [];
if isempty(h),return;end
ch = get(h,'children');
for hh = ch'
g = get(hh);
if isfield(g,'CData'), %does object have CData?
%is it indexed/scaled?
if ~isempty(g.CData) && isnumeric(g.CData) && size(g.CData,3)==1,
hout = [hout; hh]; %#ok<AGROW> %yes, add to list
end
else %no CData, see if object has any interesting children
hout = [hout; getCDataHandles(hh)]; %#ok<AGROW>
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% getParentAxes -- return handle of axes object to which a given object belongs
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function hAx = getParentAxes(h)
% getParentAxes Return enclosing axes of a given object (could be self)
error(nargchk(1,1,nargin,'struct'))
%object itself may be an axis
if strcmp(get(h,'type'),'axes'),
hAx = h;
return
end
parent = get(h,'parent');
if (strcmp(get(parent,'type'), 'axes')),
hAx = parent;
else
hAx = getParentAxes(parent);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% checkArgs -- Validate input arguments
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [h, nancolor] = checkArgs(args)
% checkArgs Validate input arguments to freezeColors
nargs = length(args);
error(nargchk(0,3,nargs,'struct'))
%grab handle from first argument if we have an odd number of arguments
if mod(nargs,2),
h = args{1};
if ~ishandle(h),
error('JRI:freezeColors:checkArgs:invalidHandle',...
'The first argument must be a valid graphics handle (to an axis)')
end
% 4/2010 check if object to be frozen is a colorbar
if strcmp(get(h,'Tag'),'Colorbar'),
if ~exist('cbfreeze.m'),
warning('JRI:freezeColors:checkArgs:cannotFreezeColorbar',...
['You seem to be attempting to freeze a colorbar. This no longer'...
'works. Please read the help for freezeColors for the solution.'])
else
cbfreeze(h);
return
end
end
args{1} = [];
nargs = nargs-1;
else
h = gca;
end
%set nancolor if that option was specified
nancolor = [nan nan nan];
if nargs == 2,
if strcmpi(args{end-1},'nancolor'),
nancolor = args{end};
if ~all(size(nancolor)==[1 3]),
error('JRI:freezeColors:checkArgs:badColorArgument',...
'nancolor must be [r g b] vector');
end
nancolor(nancolor>1) = 1; nancolor(nancolor<0) = 0;
else
error('JRI:freezeColors:checkArgs:unrecognizedOption',...
'Unrecognized option (%s). Only ''nancolor'' is valid.',args{end-1})
end
end
|
github
|
Hadisalman/stoec-master
|
arrow.m
|
.m
|
stoec-master/code/Include/arrow.m
| 55,176 |
utf_8
|
408035a3cb41890dbada1861c1ec78e7
|
function [h,yy,zz] = arrow(varargin)
% ARROW Draw a line with an arrowhead.
%
% ARROW(Start,Stop) draws a line with an arrow from Start to Stop (points
% should be vectors of length 2 or 3, or matrices with 2 or 3
% columns), and returns the graphics handle of the arrow(s).
%
% ARROW uses the mouse (click-drag) to create an arrow.
%
% ARROW DEMO & ARROW DEMO2 show 3-D & 2-D demos of the capabilities of ARROW.
%
% ARROW may be called with a normal argument list or a property-based list.
% ARROW(Start,Stop,Length,BaseAngle,TipAngle,Width,Page,CrossDir) is
% the full normal argument list, where all but the Start and Stop
% points are optional. If you need to specify a later argument (e.g.,
% Page) but want default values of earlier ones (e.g., TipAngle),
% pass an empty matrix for the earlier ones (e.g., TipAngle=[]).
%
% ARROW('Property1',PropVal1,'Property2',PropVal2,...) creates arrows with the
% given properties, using default values for any unspecified or given as
% 'default' or NaN. Some properties used for line and patch objects are
% used in a modified fashion, others are passed directly to LINE, PATCH,
% or SET. For a detailed properties explanation, call ARROW PROPERTIES.
%
% Start The starting points. B
% Stop The end points. /|\ ^
% Length Length of the arrowhead in pixels. /|||\ |
% BaseAngle Base angle in degrees (ADE). //|||\\ L|
% TipAngle Tip angle in degrees (ABC). ///|||\\\ e|
% Width Width of the base in pixels. ////|||\\\\ n|
% Page Use hardcopy proportions. /////|D|\\\\\ g|
% CrossDir Vector || to arrowhead plane. //// ||| \\\\ t|
% NormalDir Vector out of arrowhead plane. /// ||| \\\ h|
% Ends Which end has an arrowhead. //<----->|| \\ |
% ObjectHandles Vector of handles to update. / base ||| \ V
% E angle||<-------->C
% ARROW(H,'Prop1',PropVal1,...), where H is a |||tipangle
% vector of handles to previously-created arrows |||
% and/or line objects, will update the previously- |||
% created arrows according to the current view -->|A|<-- width
% and any specified properties, and will convert
% two-point line objects to corresponding arrows. ARROW(H) will update
% the arrows if the current view has changed. Root, figure, or axes
% handles included in H are replaced by all descendant Arrow objects.
%
% A property list can follow any specified normal argument list, e.g.,
% ARROW([1 2 3],[0 0 0],36,'BaseAngle',60) creates an arrow from (1,2,3) to
% the origin, with an arrowhead of length 36 pixels and 60-degree base angle.
%
% The basic arguments or properties can generally be vectorized to create
% multiple arrows with the same call. This is done by passing a property
% with one row per arrow, or, if all arrows are to have the same property
% value, just one row may be specified.
%
% You may want to execute AXIS(AXIS) before calling ARROW so it doesn't change
% the axes on you; ARROW determines the sizes of arrow components BEFORE the
% arrow is plotted, so if ARROW changes axis limits, arrows may be malformed.
%
% This version of ARROW uses features of MATLAB 6.x and is incompatible with
% earlier MATLAB versions (ARROW for MATLAB 4.2c is available separately);
% some problems with perspective plots still exist.
% Copyright (c)1995-2009, Dr. Erik A. Johnson <[email protected]>, 5/20/2009
% http://www.usc.edu/civil_eng/johnsone/
% Revision history:
% 5/20/09 EAJ Fix view direction in (3D) demo.
% 6/26/08 EAJ Replace eval('trycmd','catchcmd') with try, trycmd; catch,
% catchcmd; end; -- break's MATLAB 5 compatibility.
% 8/26/03 EAJ Eliminate OpenGL attempted fix since it didn't fix anyway.
% 11/15/02 EAJ Accomodate how MATLAB 6.5 handles NaN and logicals
% 7/28/02 EAJ Tried (but failed) work-around for MATLAB 6.x / OpenGL bug
% if zero 'Width' or not double-ended
% 11/10/99 EAJ Add logical() to eliminate zero index problem in MATLAB 5.3.
% 11/10/99 EAJ Corrected warning if axis limits changed on multiple axes.
% 11/10/99 EAJ Update e-mail address.
% 2/10/99 EAJ Some documentation updating.
% 2/24/98 EAJ Fixed bug if Start~=Stop but both colinear with viewpoint.
% 8/14/97 EAJ Added workaround for MATLAB 5.1 scalar logical transpose bug.
% 7/21/97 EAJ Fixed a few misc bugs.
% 7/14/97 EAJ Make arrow([],'Prop',...) do nothing (no old handles)
% 6/23/97 EAJ MATLAB 5 compatible version, release.
% 5/27/97 EAJ Added Line Arrows back in. Corrected a few bugs.
% 5/26/97 EAJ Changed missing Start/Stop to mouse-selected arrows.
% 5/19/97 EAJ MATLAB 5 compatible version, beta.
% 4/13/97 EAJ MATLAB 5 compatible version, alpha.
% 1/31/97 EAJ Fixed bug with multiple arrows and unspecified Z coords.
% 12/05/96 EAJ Fixed one more bug with log plots and NormalDir specified
% 10/24/96 EAJ Fixed bug with log plots and NormalDir specified
% 11/13/95 EAJ Corrected handling for 'reverse' axis directions
% 10/06/95 EAJ Corrected occasional conflict with SUBPLOT
% 4/24/95 EAJ A major rewrite.
% Fall 94 EAJ Original code.
% Things to be done:
% - in the arrow_clicks section, prompt by printing to the screen so that
% the user knows what's going on; also make sure the figure is brought
% to the front.
% - segment parsing, computing, and plotting into separate subfunctions
% - change computing from Xform to Camera paradigms
% + this will help especially with 3-D perspective plots
% + if the WarpToFill section works right, remove warning code
% + when perpsective works properly, remove perspective warning code
% - add cell property values and struct property name/values (like get/set)
% - get rid of NaN as the "default" data label
% + perhaps change userdata to a struct and don't include (or leave
% empty) the values specified as default; or use a cell containing
% an empty matrix for a default value
% - add functionality of GET to retrieve current values of ARROW properties
% Many thanks to Keith Rogers <[email protected]> for his many excellent
% suggestions and beta testing. Check out his shareware package MATDRAW
% (at ftp://ftp.mathworks.com/pub/contrib/v5/graphics/matdraw/) -- he has
% permission to distribute ARROW with MATDRAW.
% Permission is granted to distribute ARROW with the toolboxes for the book
% "Solving Solid Mechanics Problems with MATLAB 5", by F. Golnaraghi et al.
% (Prentice Hall, 1999).
% Permission is granted to Dr. Josef Bigun to distribute ARROW with his
% software to reproduce the figures in his image analysis text.
% global variable initialization
global ARROW_PERSP_WARN ARROW_STRETCH_WARN ARROW_AXLIMITS
if isempty(ARROW_PERSP_WARN ), ARROW_PERSP_WARN =1; end;
if isempty(ARROW_STRETCH_WARN), ARROW_STRETCH_WARN=1; end;
% Handle callbacks
if (nargin>0 & isstr(varargin{1}) & strcmp(lower(varargin{1}),'callback')),
arrow_callback(varargin{2:end}); return;
end;
% Are we doing the demo?
c = sprintf('\n');
if (nargin==1 & isstr(varargin{1})),
arg1 = lower(varargin{1});
if strncmp(arg1,'prop',4), arrow_props;
elseif strncmp(arg1,'demo',4)
clf reset
demo_info = arrow_demo;
if ~strncmp(arg1,'demo2',5),
hh=arrow_demo3(demo_info);
else,
hh=arrow_demo2(demo_info);
end;
if (nargout>=1), h=hh; end;
elseif strncmp(arg1,'fixlimits',3),
arrow_fixlimits(ARROW_AXLIMITS);
ARROW_AXLIMITS=[];
elseif strncmp(arg1,'help',4),
disp(help(mfilename));
else,
error([upper(mfilename) ' got an unknown single-argument string ''' deblank(arg1) '''.']);
end;
return;
end;
% Check # of arguments
if (nargout>3), error([upper(mfilename) ' produces at most 3 output arguments.']); end;
% find first property number
firstprop = nargin+1;
for k=1:length(varargin), if ~isnumeric(varargin{k}), firstprop=k; break; end; end;
lastnumeric = firstprop-1;
% check property list
if (firstprop<=nargin),
for k=firstprop:2:nargin,
curarg = varargin{k};
if ~isstr(curarg) | sum(size(curarg)>1)>1,
error([upper(mfilename) ' requires that a property name be a single string.']);
end;
end;
if (rem(nargin-firstprop,2)~=1),
error([upper(mfilename) ' requires that the property ''' ...
varargin{nargin} ''' be paired with a property value.']);
end;
end;
% default output
if (nargout>0), h=[]; end;
if (nargout>1), yy=[]; end;
if (nargout>2), zz=[]; end;
% set values to empty matrices
start = [];
stop = [];
len = [];
baseangle = [];
tipangle = [];
wid = [];
page = [];
crossdir = [];
ends = [];
ax = [];
oldh = [];
ispatch = [];
defstart = [NaN NaN NaN];
defstop = [NaN NaN NaN];
deflen = 16;
defbaseangle = 90;
deftipangle = 16;
defwid = 0;
defpage = 0;
defcrossdir = [NaN NaN NaN];
defends = 1;
defoldh = [];
defispatch = 1;
% The 'Tag' we'll put on our arrows
ArrowTag = 'Arrow';
% check for oldstyle arguments
if (firstprop==2),
% assume arg1 is a set of handles
oldh = varargin{1}(:);
if isempty(oldh), return; end;
elseif (firstprop>9),
error([upper(mfilename) ' takes at most 8 non-property arguments.']);
elseif (firstprop>2),
{start,stop,len,baseangle,tipangle,wid,page,crossdir};
args = [varargin(1:firstprop-1) cell(1,length(ans)-(firstprop-1))];
[start,stop,len,baseangle,tipangle,wid,page,crossdir] = deal(args{:});
end;
% parse property pairs
extraprops={};
for k=firstprop:2:nargin,
prop = varargin{k};
val = varargin{k+1};
prop = [lower(prop(:)') ' '];
if strncmp(prop,'start' ,5), start = val;
elseif strncmp(prop,'stop' ,4), stop = val;
elseif strncmp(prop,'len' ,3), len = val(:);
elseif strncmp(prop,'base' ,4), baseangle = val(:);
elseif strncmp(prop,'tip' ,3), tipangle = val(:);
elseif strncmp(prop,'wid' ,3), wid = val(:);
elseif strncmp(prop,'page' ,4), page = val;
elseif strncmp(prop,'cross' ,5), crossdir = val;
elseif strncmp(prop,'norm' ,4), if (isstr(val)), crossdir=val; else, crossdir=val*sqrt(-1); end;
elseif strncmp(prop,'end' ,3), ends = val;
elseif strncmp(prop,'object',6), oldh = val(:);
elseif strncmp(prop,'handle',6), oldh = val(:);
elseif strncmp(prop,'type' ,4), ispatch = val;
elseif strncmp(prop,'userd' ,5), %ignore it
else,
% make sure it is a valid patch or line property
try
get(0,['DefaultPatch' varargin{k}]);
catch
errstr = lasterr;
try
get(0,['DefaultLine' varargin{k}]);
catch
errstr(1:max(find(errstr==char(13)|errstr==char(10)))) = '';
error([upper(mfilename) ' got ' errstr]);
end
end;
extraprops={extraprops{:},varargin{k},val};
end;
end;
% Check if we got 'default' values
start = arrow_defcheck(start ,defstart ,'Start' );
stop = arrow_defcheck(stop ,defstop ,'Stop' );
len = arrow_defcheck(len ,deflen ,'Length' );
baseangle = arrow_defcheck(baseangle,defbaseangle,'BaseAngle' );
tipangle = arrow_defcheck(tipangle ,deftipangle ,'TipAngle' );
wid = arrow_defcheck(wid ,defwid ,'Width' );
crossdir = arrow_defcheck(crossdir ,defcrossdir ,'CrossDir' );
page = arrow_defcheck(page ,defpage ,'Page' );
ends = arrow_defcheck(ends ,defends ,'' );
oldh = arrow_defcheck(oldh ,[] ,'ObjectHandles');
ispatch = arrow_defcheck(ispatch ,defispatch ,'' );
% check transpose on arguments
[m,n]=size(start ); if any(m==[2 3])&(n==1|n>3), start = start'; end;
[m,n]=size(stop ); if any(m==[2 3])&(n==1|n>3), stop = stop'; end;
[m,n]=size(crossdir); if any(m==[2 3])&(n==1|n>3), crossdir = crossdir'; end;
% convert strings to numbers
if ~isempty(ends) & isstr(ends),
endsorig = ends;
[m,n] = size(ends);
col = lower([ends(:,1:min(3,n)) ones(m,max(0,3-n))*' ']);
ends = NaN*ones(m,1);
oo = ones(1,m);
ii=find(all(col'==['non']'*oo)'); if ~isempty(ii), ends(ii)=ones(length(ii),1)*0; end;
ii=find(all(col'==['sto']'*oo)'); if ~isempty(ii), ends(ii)=ones(length(ii),1)*1; end;
ii=find(all(col'==['sta']'*oo)'); if ~isempty(ii), ends(ii)=ones(length(ii),1)*2; end;
ii=find(all(col'==['bot']'*oo)'); if ~isempty(ii), ends(ii)=ones(length(ii),1)*3; end;
if any(isnan(ends)),
ii = min(find(isnan(ends)));
error([upper(mfilename) ' does not recognize ''' deblank(endsorig(ii,:)) ''' as a valid ''Ends'' value.']);
end;
else,
ends = ends(:);
end;
if ~isempty(ispatch) & isstr(ispatch),
col = lower(ispatch(:,1));
patchchar='p'; linechar='l'; defchar=' ';
mask = col~=patchchar & col~=linechar & col~=defchar;
if any(mask),
error([upper(mfilename) ' does not recognize ''' deblank(ispatch(min(find(mask)),:)) ''' as a valid ''Type'' value.']);
end;
ispatch = (col==patchchar)*1 + (col==linechar)*0 + (col==defchar)*defispatch;
else,
ispatch = ispatch(:);
end;
oldh = oldh(:);
% check object handles
if ~all(ishandle(oldh)), error([upper(mfilename) ' got invalid object handles.']); end;
% expand root, figure, and axes handles
if ~isempty(oldh),
ohtype = get(oldh,'Type');
mask = strcmp(ohtype,'root') | strcmp(ohtype,'figure') | strcmp(ohtype,'axes');
if any(mask),
oldh = num2cell(oldh);
for ii=find(mask)',
oldh(ii) = {findobj(oldh{ii},'Tag',ArrowTag)};
end;
oldh = cat(1,oldh{:});
if isempty(oldh), return; end; % no arrows to modify, so just leave
end;
end;
% largest argument length
[mstart,junk]=size(start); [mstop,junk]=size(stop); [mcrossdir,junk]=size(crossdir);
argsizes = [length(oldh) mstart mstop ...
length(len) length(baseangle) length(tipangle) ...
length(wid) length(page) mcrossdir length(ends) ];
args=['length(ObjectHandle) '; ...
'#rows(Start) '; ...
'#rows(Stop) '; ...
'length(Length) '; ...
'length(BaseAngle) '; ...
'length(TipAngle) '; ...
'length(Width) '; ...
'length(Page) '; ...
'#rows(CrossDir) '; ...
'#rows(Ends) '];
if (any(imag(crossdir(:))~=0)),
args(9,:) = '#rows(NormalDir) ';
end;
if isempty(oldh),
narrows = max(argsizes);
else,
narrows = length(oldh);
end;
if (narrows<=0), narrows=1; end;
% Check size of arguments
ii = find((argsizes~=0)&(argsizes~=1)&(argsizes~=narrows));
if ~isempty(ii),
s = args(ii',:);
while ((size(s,2)>1)&((abs(s(:,size(s,2)))==0)|(abs(s(:,size(s,2)))==abs(' ')))),
s = s(:,1:size(s,2)-1);
end;
s = [ones(length(ii),1)*[upper(mfilename) ' requires that '] s ...
ones(length(ii),1)*[' equal the # of arrows (' num2str(narrows) ').' c]];
s = s';
s = s(:)';
s = s(1:length(s)-1);
error(setstr(s));
end;
% check element length in Start, Stop, and CrossDir
if ~isempty(start),
[m,n] = size(start);
if (n==2),
start = [start NaN*ones(m,1)];
elseif (n~=3),
error([upper(mfilename) ' requires 2- or 3-element Start points.']);
end;
end;
if ~isempty(stop),
[m,n] = size(stop);
if (n==2),
stop = [stop NaN*ones(m,1)];
elseif (n~=3),
error([upper(mfilename) ' requires 2- or 3-element Stop points.']);
end;
end;
if ~isempty(crossdir),
[m,n] = size(crossdir);
if (n<3),
crossdir = [crossdir NaN*ones(m,3-n)];
elseif (n~=3),
if (all(imag(crossdir(:))==0)),
error([upper(mfilename) ' requires 2- or 3-element CrossDir vectors.']);
else,
error([upper(mfilename) ' requires 2- or 3-element NormalDir vectors.']);
end;
end;
end;
% fill empty arguments
if isempty(start ), start = [Inf Inf Inf]; end;
if isempty(stop ), stop = [Inf Inf Inf]; end;
if isempty(len ), len = Inf; end;
if isempty(baseangle ), baseangle = Inf; end;
if isempty(tipangle ), tipangle = Inf; end;
if isempty(wid ), wid = Inf; end;
if isempty(page ), page = Inf; end;
if isempty(crossdir ), crossdir = [Inf Inf Inf]; end;
if isempty(ends ), ends = Inf; end;
if isempty(ispatch ), ispatch = Inf; end;
% expand single-column arguments
o = ones(narrows,1);
if (size(start ,1)==1), start = o * start ; end;
if (size(stop ,1)==1), stop = o * stop ; end;
if (length(len )==1), len = o * len ; end;
if (length(baseangle )==1), baseangle = o * baseangle ; end;
if (length(tipangle )==1), tipangle = o * tipangle ; end;
if (length(wid )==1), wid = o * wid ; end;
if (length(page )==1), page = o * page ; end;
if (size(crossdir ,1)==1), crossdir = o * crossdir ; end;
if (length(ends )==1), ends = o * ends ; end;
if (length(ispatch )==1), ispatch = o * ispatch ; end;
ax = repmat(gca,narrows,1);
% if we've got handles, get the defaults from the handles
if ~isempty(oldh),
for k=1:narrows,
oh = oldh(k);
ud = get(oh,'UserData');
ax(k) = get(oh,'Parent');
ohtype = get(oh,'Type');
if strcmp(get(oh,'Tag'),ArrowTag), % if it's an arrow already
if isinf(ispatch(k)), ispatch(k)=strcmp(ohtype,'patch'); end;
% arrow UserData format: [start' stop' len base tip wid page crossdir' ends]
start0 = ud(1:3);
stop0 = ud(4:6);
if (isinf(len(k))), len(k) = ud( 7); end;
if (isinf(baseangle(k))), baseangle(k) = ud( 8); end;
if (isinf(tipangle(k))), tipangle(k) = ud( 9); end;
if (isinf(wid(k))), wid(k) = ud(10); end;
if (isinf(page(k))), page(k) = ud(11); end;
if (isinf(crossdir(k,1))), crossdir(k,1) = ud(12); end;
if (isinf(crossdir(k,2))), crossdir(k,2) = ud(13); end;
if (isinf(crossdir(k,3))), crossdir(k,3) = ud(14); end;
if (isinf(ends(k))), ends(k) = ud(15); end;
elseif strcmp(ohtype,'line')|strcmp(ohtype,'patch'), % it's a non-arrow line or patch
convLineToPatch = 1; %set to make arrow patches when converting from lines.
if isinf(ispatch(k)), ispatch(k)=convLineToPatch|strcmp(ohtype,'patch'); end;
x=get(oh,'XData'); x=x(~isnan(x(:))); if isempty(x), x=NaN; end;
y=get(oh,'YData'); y=y(~isnan(y(:))); if isempty(y), y=NaN; end;
z=get(oh,'ZData'); z=z(~isnan(z(:))); if isempty(z), z=NaN; end;
start0 = [x(1) y(1) z(1) ];
stop0 = [x(end) y(end) z(end)];
else,
error([upper(mfilename) ' cannot convert ' ohtype ' objects.']);
end;
ii=find(isinf(start(k,:))); if ~isempty(ii), start(k,ii)=start0(ii); end;
ii=find(isinf(stop( k,:))); if ~isempty(ii), stop( k,ii)=stop0( ii); end;
end;
end;
% convert Inf's to NaN's
start( isinf(start )) = NaN;
stop( isinf(stop )) = NaN;
len( isinf(len )) = NaN;
baseangle( isinf(baseangle)) = NaN;
tipangle( isinf(tipangle )) = NaN;
wid( isinf(wid )) = NaN;
page( isinf(page )) = NaN;
crossdir( isinf(crossdir )) = NaN;
ends( isinf(ends )) = NaN;
ispatch( isinf(ispatch )) = NaN;
% set up the UserData data (here so not corrupted by log10's and such)
ud = [start stop len baseangle tipangle wid page crossdir ends];
% Set Page defaults
page = ~isnan(page) & trueornan(page);
% Get axes limits, range, min; correct for aspect ratio and log scale
axm = zeros(3,narrows);
axr = zeros(3,narrows);
axrev = zeros(3,narrows);
ap = zeros(2,narrows);
xyzlog = zeros(3,narrows);
limmin = zeros(2,narrows);
limrange = zeros(2,narrows);
oldaxlims = zeros(narrows,7);
oneax = all(ax==ax(1));
if (oneax),
T = zeros(4,4);
invT = zeros(4,4);
else,
T = zeros(16,narrows);
invT = zeros(16,narrows);
end;
axnotdone = logical(ones(size(ax)));
while (any(axnotdone)),
ii = min(find(axnotdone));
curax = ax(ii);
curpage = page(ii);
% get axes limits and aspect ratio
axl = [get(curax,'XLim'); get(curax,'YLim'); get(curax,'ZLim')];
oldaxlims(min(find(oldaxlims(:,1)==0)),:) = [ii reshape(axl',1,6)];
% get axes size in pixels (points)
u = get(curax,'Units');
axposoldunits = get(curax,'Position');
really_curpage = curpage & strcmp(u,'normalized');
if (really_curpage),
curfig = get(curax,'Parent');
pu = get(curfig,'PaperUnits');
set(curfig,'PaperUnits','points');
pp = get(curfig,'PaperPosition');
set(curfig,'PaperUnits',pu);
set(curax,'Units','pixels');
curapscreen = get(curax,'Position');
set(curax,'Units','normalized');
curap = pp.*get(curax,'Position');
else,
set(curax,'Units','pixels');
curapscreen = get(curax,'Position');
curap = curapscreen;
end;
set(curax,'Units',u);
set(curax,'Position',axposoldunits);
% handle non-stretched axes position
str_stretch = { 'DataAspectRatioMode' ; ...
'PlotBoxAspectRatioMode' ; ...
'CameraViewAngleMode' };
str_camera = { 'CameraPositionMode' ; ...
'CameraTargetMode' ; ...
'CameraViewAngleMode' ; ...
'CameraUpVectorMode' };
notstretched = strcmp(get(curax,str_stretch),'manual');
manualcamera = strcmp(get(curax,str_camera),'manual');
if ~arrow_WarpToFill(notstretched,manualcamera,curax),
% give a warning that this has not been thoroughly tested
if 0 & ARROW_STRETCH_WARN,
ARROW_STRETCH_WARN = 0;
strs = {str_stretch{1:2},str_camera{:}};
strs = [char(ones(length(strs),1)*sprintf('\n ')) char(strs)]';
warning([upper(mfilename) ' may not yet work quite right ' ...
'if any of the following are ''manual'':' strs(:).']);
end;
% find the true pixel size of the actual axes
texttmp = text(axl(1,[1 2 2 1 1 2 2 1]), ...
axl(2,[1 1 2 2 1 1 2 2]), ...
axl(3,[1 1 1 1 2 2 2 2]),'');
set(texttmp,'Units','points');
textpos = get(texttmp,'Position');
delete(texttmp);
textpos = cat(1,textpos{:});
textpos = max(textpos(:,1:2)) - min(textpos(:,1:2));
% adjust the axes position
if (really_curpage),
% adjust to printed size
textpos = textpos * min(curap(3:4)./textpos);
curap = [curap(1:2)+(curap(3:4)-textpos)/2 textpos];
else,
% adjust for pixel roundoff
textpos = textpos * min(curapscreen(3:4)./textpos);
curap = [curap(1:2)+(curap(3:4)-textpos)/2 textpos];
end;
end;
if ARROW_PERSP_WARN & ~strcmp(get(curax,'Projection'),'orthographic'),
ARROW_PERSP_WARN = 0;
warning([upper(mfilename) ' does not yet work right for 3-D perspective projection.']);
end;
% adjust limits for log scale on axes
curxyzlog = [strcmp(get(curax,'XScale'),'log'); ...
strcmp(get(curax,'YScale'),'log'); ...
strcmp(get(curax,'ZScale'),'log')];
if (any(curxyzlog)),
ii = find([curxyzlog;curxyzlog]);
if (any(axl(ii)<=0)),
error([upper(mfilename) ' does not support non-positive limits on log-scaled axes.']);
else,
axl(ii) = log10(axl(ii));
end;
end;
% correct for 'reverse' direction on axes;
curreverse = [strcmp(get(curax,'XDir'),'reverse'); ...
strcmp(get(curax,'YDir'),'reverse'); ...
strcmp(get(curax,'ZDir'),'reverse')];
ii = find(curreverse);
if ~isempty(ii),
axl(ii,[1 2])=-axl(ii,[2 1]);
end;
% compute the range of 2-D values
[azA,elA] = view(curax);
curT = viewmtx(azA,elA);
lim = curT*[0 1 0 1 0 1 0 1;0 0 1 1 0 0 1 1;0 0 0 0 1 1 1 1;1 1 1 1 1 1 1 1];
lim = lim(1:2,:)./([1;1]*lim(4,:));
curlimmin = min(lim')';
curlimrange = max(lim')' - curlimmin;
curinvT = inv(curT);
if (~oneax),
curT = curT.';
curinvT = curinvT.';
curT = curT(:);
curinvT = curinvT(:);
end;
% check which arrows to which cur corresponds
ii = find((ax==curax)&(page==curpage));
oo = ones(1,length(ii));
axr(:,ii) = diff(axl')' * oo;
axm(:,ii) = axl(:,1) * oo;
axrev(:,ii) = curreverse * oo;
ap(:,ii) = curap(3:4)' * oo;
xyzlog(:,ii) = curxyzlog * oo;
limmin(:,ii) = curlimmin * oo;
limrange(:,ii) = curlimrange * oo;
if (oneax),
T = curT;
invT = curinvT;
else,
T(:,ii) = curT * oo;
invT(:,ii) = curinvT * oo;
end;
axnotdone(ii) = zeros(1,length(ii));
end;
oldaxlims(oldaxlims(:,1)==0,:)=[];
% correct for log scales
curxyzlog = xyzlog.';
ii = find(curxyzlog(:));
if ~isempty(ii),
start( ii) = real(log10(start( ii)));
stop( ii) = real(log10(stop( ii)));
if (all(imag(crossdir)==0)), % pulled (ii) subscript on crossdir, 12/5/96 eaj
crossdir(ii) = real(log10(crossdir(ii)));
end;
end;
% correct for reverse directions
ii = find(axrev.');
if ~isempty(ii),
start( ii) = -start( ii);
stop( ii) = -stop( ii);
crossdir(ii) = -crossdir(ii);
end;
% transpose start/stop values
start = start.';
stop = stop.';
% take care of defaults, page was done above
ii=find(isnan(start(:) )); if ~isempty(ii), start(ii) = axm(ii)+axr(ii)/2; end;
ii=find(isnan(stop(:) )); if ~isempty(ii), stop(ii) = axm(ii)+axr(ii)/2; end;
ii=find(isnan(crossdir(:) )); if ~isempty(ii), crossdir(ii) = zeros(length(ii),1); end;
ii=find(isnan(len )); if ~isempty(ii), len(ii) = ones(length(ii),1)*deflen; end;
ii=find(isnan(baseangle )); if ~isempty(ii), baseangle(ii) = ones(length(ii),1)*defbaseangle; end;
ii=find(isnan(tipangle )); if ~isempty(ii), tipangle(ii) = ones(length(ii),1)*deftipangle; end;
ii=find(isnan(wid )); if ~isempty(ii), wid(ii) = ones(length(ii),1)*defwid; end;
ii=find(isnan(ends )); if ~isempty(ii), ends(ii) = ones(length(ii),1)*defends; end;
% transpose rest of values
len = len.';
baseangle = baseangle.';
tipangle = tipangle.';
wid = wid.';
page = page.';
crossdir = crossdir.';
ends = ends.';
ax = ax.';
% given x, a 3xN matrix of points in 3-space;
% want to convert to X, the corresponding 4xN 2-space matrix
%
% tmp1=[(x-axm)./axr; ones(1,size(x,1))];
% if (oneax), X=T*tmp1;
% else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T.*tmp1;
% tmp2=zeros(4,4*N); tmp2(:)=tmp1(:);
% X=zeros(4,N); X(:)=sum(tmp2)'; end;
% X = X ./ (ones(4,1)*X(4,:));
% for all points with start==stop, start=stop-(verysmallvalue)*(up-direction);
ii = find(all(start==stop));
if ~isempty(ii),
% find an arrowdir vertical on screen and perpendicular to viewer
% transform to 2-D
tmp1 = [(stop(:,ii)-axm(:,ii))./axr(:,ii);ones(1,length(ii))];
if (oneax), twoD=T*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T(:,ii).*tmp1;
tmp2=zeros(4,4*length(ii)); tmp2(:)=tmp1(:);
twoD=zeros(4,length(ii)); twoD(:)=sum(tmp2)'; end;
twoD=twoD./(ones(4,1)*twoD(4,:));
% move the start point down just slightly
tmp1 = twoD + [0;-1/1000;0;0]*(limrange(2,ii)./ap(2,ii));
% transform back to 3-D
if (oneax), threeD=invT*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT(:,ii).*tmp1;
tmp2=zeros(4,4*length(ii)); tmp2(:)=tmp1(:);
threeD=zeros(4,length(ii)); threeD(:)=sum(tmp2)'; end;
start(:,ii) = (threeD(1:3,:)./(ones(3,1)*threeD(4,:))).*axr(:,ii)+axm(:,ii);
end;
% compute along-arrow points
% transform Start points
tmp1=[(start-axm)./axr;ones(1,narrows)];
if (oneax), X0=T*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T.*tmp1;
tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:);
X0=zeros(4,narrows); X0(:)=sum(tmp2)'; end;
X0=X0./(ones(4,1)*X0(4,:));
% transform Stop points
tmp1=[(stop-axm)./axr;ones(1,narrows)];
if (oneax), Xf=T*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T.*tmp1;
tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:);
Xf=zeros(4,narrows); Xf(:)=sum(tmp2)'; end;
Xf=Xf./(ones(4,1)*Xf(4,:));
% compute pixel distance between points
D = sqrt(sum(((Xf(1:2,:)-X0(1:2,:)).*(ap./limrange)).^2));
D = D + (D==0); %eaj new 2/24/98
% compute and modify along-arrow distances
len1 = len;
len2 = len - (len.*tan(tipangle/180*pi)-wid/2).*tan((90-baseangle)/180*pi);
slen0 = zeros(1,narrows);
slen1 = len1 .* ((ends==2)|(ends==3));
slen2 = len2 .* ((ends==2)|(ends==3));
len0 = zeros(1,narrows);
len1 = len1 .* ((ends==1)|(ends==3));
len2 = len2 .* ((ends==1)|(ends==3));
% for no start arrowhead
ii=find((ends==1)&(D<len2));
if ~isempty(ii),
slen0(ii) = D(ii)-len2(ii);
end;
% for no end arrowhead
ii=find((ends==2)&(D<slen2));
if ~isempty(ii),
len0(ii) = D(ii)-slen2(ii);
end;
len1 = len1 + len0;
len2 = len2 + len0;
slen1 = slen1 + slen0;
slen2 = slen2 + slen0;
% note: the division by D below will probably not be accurate if both
% of the following are true:
% 1. the ratio of the line length to the arrowhead
% length is large
% 2. the view is highly perspective.
% compute stoppoints
tmp1=X0.*(ones(4,1)*(len0./D))+Xf.*(ones(4,1)*(1-len0./D));
if (oneax), tmp3=invT*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1;
tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:);
tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end;
stoppoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm;
% compute tippoints
tmp1=X0.*(ones(4,1)*(len1./D))+Xf.*(ones(4,1)*(1-len1./D));
if (oneax), tmp3=invT*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1;
tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:);
tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end;
tippoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm;
% compute basepoints
tmp1=X0.*(ones(4,1)*(len2./D))+Xf.*(ones(4,1)*(1-len2./D));
if (oneax), tmp3=invT*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1;
tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:);
tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end;
basepoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm;
% compute startpoints
tmp1=X0.*(ones(4,1)*(1-slen0./D))+Xf.*(ones(4,1)*(slen0./D));
if (oneax), tmp3=invT*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1;
tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:);
tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end;
startpoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm;
% compute stippoints
tmp1=X0.*(ones(4,1)*(1-slen1./D))+Xf.*(ones(4,1)*(slen1./D));
if (oneax), tmp3=invT*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1;
tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:);
tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end;
stippoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm;
% compute sbasepoints
tmp1=X0.*(ones(4,1)*(1-slen2./D))+Xf.*(ones(4,1)*(slen2./D));
if (oneax), tmp3=invT*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1;
tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:);
tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end;
sbasepoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm;
% compute cross-arrow directions for arrows with NormalDir specified
if (any(imag(crossdir(:))~=0)),
ii = find(any(imag(crossdir)~=0));
crossdir(:,ii) = cross((stop(:,ii)-start(:,ii))./axr(:,ii), ...
imag(crossdir(:,ii))).*axr(:,ii);
end;
% compute cross-arrow directions
basecross = crossdir + basepoint;
tipcross = crossdir + tippoint;
sbasecross = crossdir + sbasepoint;
stipcross = crossdir + stippoint;
ii = find(all(crossdir==0)|any(isnan(crossdir)));
if ~isempty(ii),
numii = length(ii);
% transform start points
tmp1 = [basepoint(:,ii) tippoint(:,ii) sbasepoint(:,ii) stippoint(:,ii)];
tmp1 = (tmp1-axm(:,[ii ii ii ii])) ./ axr(:,[ii ii ii ii]);
tmp1 = [tmp1; ones(1,4*numii)];
if (oneax), X0=T*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T(:,[ii ii ii ii]).*tmp1;
tmp2=zeros(4,16*numii); tmp2(:)=tmp1(:);
X0=zeros(4,4*numii); X0(:)=sum(tmp2)'; end;
X0=X0./(ones(4,1)*X0(4,:));
% transform stop points
tmp1 = [(2*stop(:,ii)-start(:,ii)-axm(:,ii))./axr(:,ii);ones(1,numii)];
tmp1 = [tmp1 tmp1 tmp1 tmp1];
if (oneax), Xf=T*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T(:,[ii ii ii ii]).*tmp1;
tmp2=zeros(4,16*numii); tmp2(:)=tmp1(:);
Xf=zeros(4,4*numii); Xf(:)=sum(tmp2)'; end;
Xf=Xf./(ones(4,1)*Xf(4,:));
% compute perpendicular directions
pixfact = ((limrange(1,ii)./limrange(2,ii)).*(ap(2,ii)./ap(1,ii))).^2;
pixfact = [pixfact pixfact pixfact pixfact];
pixfact = [pixfact;1./pixfact];
[dummyval,jj] = max(abs(Xf(1:2,:)-X0(1:2,:)));
jj1 = ((1:4)'*ones(1,length(jj))==ones(4,1)*jj);
jj2 = ((1:4)'*ones(1,length(jj))==ones(4,1)*(3-jj));
jj3 = jj1(1:2,:);
Xf(jj1)=Xf(jj1)+(Xf(jj1)-X0(jj1)==0); %eaj new 2/24/98
Xp = X0;
Xp(jj2) = X0(jj2) + ones(sum(jj2(:)),1);
Xp(jj1) = X0(jj1) - (Xf(jj2)-X0(jj2))./(Xf(jj1)-X0(jj1)) .* pixfact(jj3);
% inverse transform the cross points
if (oneax), Xp=invT*Xp;
else, tmp1=[Xp;Xp;Xp;Xp]; tmp1=invT(:,[ii ii ii ii]).*tmp1;
tmp2=zeros(4,16*numii); tmp2(:)=tmp1(:);
Xp=zeros(4,4*numii); Xp(:)=sum(tmp2)'; end;
Xp=(Xp(1:3,:)./(ones(3,1)*Xp(4,:))).*axr(:,[ii ii ii ii])+axm(:,[ii ii ii ii]);
basecross(:,ii) = Xp(:,0*numii+(1:numii));
tipcross(:,ii) = Xp(:,1*numii+(1:numii));
sbasecross(:,ii) = Xp(:,2*numii+(1:numii));
stipcross(:,ii) = Xp(:,3*numii+(1:numii));
end;
% compute all points
% compute start points
axm11 = [axm axm axm axm axm axm axm axm axm axm axm];
axr11 = [axr axr axr axr axr axr axr axr axr axr axr];
st = [stoppoint tippoint basepoint sbasepoint stippoint startpoint stippoint sbasepoint basepoint tippoint stoppoint];
tmp1 = (st - axm11) ./ axr11;
tmp1 = [tmp1; ones(1,size(tmp1,2))];
if (oneax), X0=T*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=[T T T T T T T T T T T].*tmp1;
tmp2=zeros(4,44*narrows); tmp2(:)=tmp1(:);
X0=zeros(4,11*narrows); X0(:)=sum(tmp2)'; end;
X0=X0./(ones(4,1)*X0(4,:));
% compute stop points
tmp1 = ([start tipcross basecross sbasecross stipcross stop stipcross sbasecross basecross tipcross start] ...
- axm11) ./ axr11;
tmp1 = [tmp1; ones(1,size(tmp1,2))];
if (oneax), Xf=T*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=[T T T T T T T T T T T].*tmp1;
tmp2=zeros(4,44*narrows); tmp2(:)=tmp1(:);
Xf=zeros(4,11*narrows); Xf(:)=sum(tmp2)'; end;
Xf=Xf./(ones(4,1)*Xf(4,:));
% compute lengths
len0 = len.*((ends==1)|(ends==3)).*tan(tipangle/180*pi);
slen0 = len.*((ends==2)|(ends==3)).*tan(tipangle/180*pi);
le = [zeros(1,narrows) len0 wid/2 wid/2 slen0 zeros(1,narrows) -slen0 -wid/2 -wid/2 -len0 zeros(1,narrows)];
aprange = ap./limrange;
aprange = [aprange aprange aprange aprange aprange aprange aprange aprange aprange aprange aprange];
D = sqrt(sum(((Xf(1:2,:)-X0(1:2,:)).*aprange).^2));
Dii=find(D==0); if ~isempty(Dii), D=D+(D==0); le(Dii)=zeros(1,length(Dii)); end; %should fix DivideByZero warnings
tmp1 = X0.*(ones(4,1)*(1-le./D)) + Xf.*(ones(4,1)*(le./D));
% inverse transform
if (oneax), tmp3=invT*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=[invT invT invT invT invT invT invT invT invT invT invT].*tmp1;
tmp2=zeros(4,44*narrows); tmp2(:)=tmp1(:);
tmp3=zeros(4,11*narrows); tmp3(:)=sum(tmp2)'; end;
pts = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)) .* axr11 + axm11;
% correct for ones where the crossdir was specified
ii = find(~(all(crossdir==0)|any(isnan(crossdir))));
if ~isempty(ii),
D1 = [pts(:,1*narrows+ii)-pts(:,9*narrows+ii) ...
pts(:,2*narrows+ii)-pts(:,8*narrows+ii) ...
pts(:,3*narrows+ii)-pts(:,7*narrows+ii) ...
pts(:,4*narrows+ii)-pts(:,6*narrows+ii) ...
pts(:,6*narrows+ii)-pts(:,4*narrows+ii) ...
pts(:,7*narrows+ii)-pts(:,3*narrows+ii) ...
pts(:,8*narrows+ii)-pts(:,2*narrows+ii) ...
pts(:,9*narrows+ii)-pts(:,1*narrows+ii)]/2;
ii = ii'*ones(1,8) + ones(length(ii),1)*[1:4 6:9]*narrows;
ii = ii(:)';
pts(:,ii) = st(:,ii) + D1;
end;
% readjust for reverse directions
iicols=(1:narrows)'; iicols=iicols(:,ones(1,11)); iicols=iicols(:).';
tmp1=axrev(:,iicols);
ii = find(tmp1(:)); if ~isempty(ii), pts(ii)=-pts(ii); end;
% readjust for log scale on axes
tmp1=xyzlog(:,iicols);
ii = find(tmp1(:)); if ~isempty(ii), pts(ii)=10.^pts(ii); end;
% compute the x,y,z coordinates of the patches;
ii = narrows*(0:10)'*ones(1,narrows) + ones(11,1)*(1:narrows);
ii = ii(:)';
x = zeros(11,narrows);
y = zeros(11,narrows);
z = zeros(11,narrows);
x(:) = pts(1,ii)';
y(:) = pts(2,ii)';
z(:) = pts(3,ii)';
% do the output
if (nargout<=1),
% % create or modify the patches
newpatch = trueornan(ispatch) & (isempty(oldh)|~strcmp(get(oldh,'Type'),'patch'));
newline = ~trueornan(ispatch) & (isempty(oldh)|~strcmp(get(oldh,'Type'),'line'));
if isempty(oldh), H=zeros(narrows,1); else, H=oldh; end;
% % make or modify the arrows
for k=1:narrows,
if all(isnan(ud(k,[3 6])))&arrow_is2DXY(ax(k)), zz=[]; else, zz=z(:,k); end;
xx=x(:,k); yy=y(:,k);
if (0), % this fix didn't work, so let's not use it -- 8/26/03
% try to work around a MATLAB 6.x OpenGL bug -- 7/28/02
mask=any([ones(1,2+size(zz,2));diff([xx yy zz],[],1)],2);
xx=xx(mask); yy=yy(mask); if ~isempty(zz), zz=zz(mask); end;
end;
% plot the patch or line
xyz = {'XData',xx,'YData',yy,'ZData',zz,'Tag',ArrowTag};
if newpatch(k)|newline(k),
if newpatch(k),
H(k) = patch(xyz{:});
else,
H(k) = line(xyz{:});
end;
if ~isempty(oldh), arrow_copyprops(oldh(k),H(k)); end;
else,
if ispatch(k), xyz={xyz{:},'CData',[]}; end;
set(H(k),xyz{:});
end;
end;
if ~isempty(oldh), delete(oldh(oldh~=H)); end;
% % additional properties
set(H,'Clipping','off');
set(H,{'UserData'},num2cell(ud,2));
if (length(extraprops)>0), set(H,extraprops{:}); end;
% handle choosing arrow Start and/or Stop locations if unspecified
[H,oldaxlims,errstr] = arrow_clicks(H,ud,x,y,z,ax,oldaxlims);
if ~isempty(errstr), error([upper(mfilename) ' got ' errstr]); end;
% set the output
if (nargout>0), h=H; end;
% make sure the axis limits did not change
if isempty(oldaxlims),
ARROW_AXLIMITS = [];
else
lims = get(ax(oldaxlims(:,1)),{'XLim','YLim','ZLim'})';
lims = reshape(cat(2,lims{:}),6,size(lims,2));
mask = arrow_is2DXY(ax(oldaxlims(:,1)));
oldaxlims(mask,6:7) = lims(5:6,mask)';
ARROW_AXLIMITS = oldaxlims(find(any(oldaxlims(:,2:7)'~=lims)),:);
if ~isempty(ARROW_AXLIMITS),
warning(arrow_warnlimits(ARROW_AXLIMITS,narrows));
end;
end;
else
% don't create the patch, just return the data
h=x;
yy=y;
zz=z;
end;
function out = arrow_defcheck(in,def,prop)
% check if we got 'default' values
out = in;
if ~isstr(in), return; end;
if size(in,1)==1 & strncmp(lower(in),'def',3),
out = def;
elseif ~isempty(prop),
error([upper(mfilename) ' does not recognize ''' in(:)' ''' as a valid ''' prop ''' string.']);
end;
function [H,oldaxlims,errstr] = arrow_clicks(H,ud,x,y,z,ax,oldaxlims)
% handle choosing arrow Start and/or Stop locations if necessary
errstr = '';
if isempty(H)|isempty(ud)|isempty(x), return; end;
% determine which (if any) need Start and/or Stop
needStart = all(isnan(ud(:,1:3)'))';
needStop = all(isnan(ud(:,4:6)'))';
mask = any(needStart|needStop);
if ~any(mask), return; end;
ud(~mask,:)=[]; ax(:,~mask)=[];
x(:,~mask)=[]; y(:,~mask)=[]; z(:,~mask)=[];
% make them invisible for the time being
set(H,'Visible','off');
% save the current axes and limits modes; set to manual for the time being
oldAx = gca;
limModes=get(ax(:),{'XLimMode','YLimMode','ZLimMode'});
set(ax(:),{'XLimMode','YLimMode','ZLimMode'},{'manual','manual','manual'});
% loop over each arrow that requires attention
jj = find(mask);
for ii=1:length(jj),
h = H(jj(ii));
axes(ax(ii));
% figure out correct call
if needStart(ii), prop='Start'; else, prop='Stop'; end;
[wasInterrupted,errstr] = arrow_click(needStart(ii)&needStop(ii),h,prop,ax(ii));
% handle errors and control-C
if wasInterrupted,
delete(H(jj(ii:end)));
H(jj(ii:end))=[];
oldaxlims(jj(ii:end),:)=[];
break;
end;
end;
% restore the axes and limit modes
axes(oldAx);
set(ax(:),{'XLimMode','YLimMode','ZLimMode'},limModes);
function [wasInterrupted,errstr] = arrow_click(lockStart,H,prop,ax)
% handle the clicks for one arrow
fig = get(ax,'Parent');
% save some things
oldFigProps = {'Pointer','WindowButtonMotionFcn','WindowButtonUpFcn'};
oldFigValue = get(fig,oldFigProps);
global ARROW_CLICK_H ARROW_CLICK_PROP ARROW_CLICK_AX ARROW_CLICK_USE_Z
ARROW_CLICK_H=H; ARROW_CLICK_PROP=prop; ARROW_CLICK_AX=ax;
ARROW_CLICK_USE_Z=~arrow_is2DXY(ax)|~arrow_planarkids(ax);
set(fig,'Pointer','crosshair');
% set up the WindowButtonMotion so we can see the arrow while moving around
set(fig,'WindowButtonUpFcn','set(gcf,''WindowButtonUpFcn'','''')', ...
'WindowButtonMotionFcn','');
if ~lockStart,
set(H,'Visible','on');
set(fig,'WindowButtonMotionFcn',[mfilename '(''callback'',''motion'');']);
end;
% wait for the button to be pressed
[wasKeyPress,wasInterrupted,errstr] = arrow_wfbdown(fig);
% if we wanted to click-drag, set the Start point
if lockStart & ~wasInterrupted,
pt = arrow_point(ARROW_CLICK_AX,ARROW_CLICK_USE_Z);
feval(mfilename,H,'Start',pt,'Stop',pt);
set(H,'Visible','on');
ARROW_CLICK_PROP='Stop';
set(fig,'WindowButtonMotionFcn',[mfilename '(''callback'',''motion'');']);
% wait for the mouse button to be released
try
waitfor(fig,'WindowButtonUpFcn','');
catch
errstr = lasterr;
wasInterrupted = 1;
end;
end;
if ~wasInterrupted, feval(mfilename,'callback','motion'); end;
% restore some things
set(gcf,oldFigProps,oldFigValue);
function arrow_callback(varargin)
% handle redrawing callbacks
if nargin==0, return; end;
str = varargin{1};
if ~isstr(str), error([upper(mfilename) ' got an invalid Callback command.']); end;
s = lower(str);
if strcmp(s,'motion'),
% motion callback
global ARROW_CLICK_H ARROW_CLICK_PROP ARROW_CLICK_AX ARROW_CLICK_USE_Z
feval(mfilename,ARROW_CLICK_H,ARROW_CLICK_PROP,arrow_point(ARROW_CLICK_AX,ARROW_CLICK_USE_Z));
drawnow;
else,
error([upper(mfilename) ' does not recognize ''' str(:).' ''' as a valid Callback option.']);
end;
function out = arrow_point(ax,use_z)
% return the point on the given axes
if nargin==0, ax=gca; end;
if nargin<2, use_z=~arrow_is2DXY(ax)|~arrow_planarkids(ax); end;
out = get(ax,'CurrentPoint');
out = out(1,:);
if ~use_z, out=out(1:2); end;
function [wasKeyPress,wasInterrupted,errstr] = arrow_wfbdown(fig)
% wait for button down ignoring object ButtonDownFcn's
if nargin==0, fig=gcf; end;
errstr = '';
% save ButtonDownFcn values
objs = findobj(fig);
buttonDownFcns = get(objs,'ButtonDownFcn');
mask=~strcmp(buttonDownFcns,''); objs=objs(mask); buttonDownFcns=buttonDownFcns(mask);
set(objs,'ButtonDownFcn','');
% save other figure values
figProps = {'KeyPressFcn','WindowButtonDownFcn'};
figValue = get(fig,figProps);
% do the real work
set(fig,'KeyPressFcn','set(gcf,''KeyPressFcn'','''',''WindowButtonDownFcn'','''');', ...
'WindowButtonDownFcn','set(gcf,''WindowButtonDownFcn'','''')');
lasterr('');
try
waitfor(fig,'WindowButtonDownFcn','');
wasInterrupted = 0;
catch
wasInterrupted = 1;
end
wasKeyPress = ~wasInterrupted & strcmp(get(fig,'KeyPressFcn'),'');
if wasInterrupted, errstr=lasterr; end;
% restore ButtonDownFcn and other figure values
set(objs,'ButtonDownFcn',buttonDownFcns);
set(fig,figProps,figValue);
function [out,is2D] = arrow_is2DXY(ax)
% check if axes are 2-D X-Y plots
% may not work for modified camera angles, etc.
out = logical(zeros(size(ax))); % 2-D X-Y plots
is2D = out; % any 2-D plots
views = get(ax(:),{'View'});
views = cat(1,views{:});
out(:) = abs(views(:,2))==90;
is2D(:) = out(:) | all(rem(views',90)==0)';
function out = arrow_planarkids(ax)
% check if axes descendents all have empty ZData (lines,patches,surfaces)
out = logical(ones(size(ax)));
allkids = get(ax(:),{'Children'});
for k=1:length(allkids),
kids = get([findobj(allkids{k},'flat','Type','line')
findobj(allkids{k},'flat','Type','patch')
findobj(allkids{k},'flat','Type','surface')],{'ZData'});
for j=1:length(kids),
if ~isempty(kids{j}), out(k)=logical(0); break; end;
end;
end;
function arrow_fixlimits(axlimits)
% reset the axis limits as necessary
if isempty(axlimits), disp([upper(mfilename) ' does not remember any axis limits to reset.']); end;
for k=1:size(axlimits,1),
if any(get(axlimits(k,1),'XLim')~=axlimits(k,2:3)), set(axlimits(k,1),'XLim',axlimits(k,2:3)); end;
if any(get(axlimits(k,1),'YLim')~=axlimits(k,4:5)), set(axlimits(k,1),'YLim',axlimits(k,4:5)); end;
if any(get(axlimits(k,1),'ZLim')~=axlimits(k,6:7)), set(axlimits(k,1),'ZLim',axlimits(k,6:7)); end;
end;
function out = arrow_WarpToFill(notstretched,manualcamera,curax)
% check if we are in "WarpToFill" mode.
out = strcmp(get(curax,'WarpToFill'),'on');
% 'WarpToFill' is undocumented, so may need to replace this by
% out = ~( any(notstretched) & any(manualcamera) );
function out = arrow_warnlimits(axlimits,narrows)
% create a warning message if we've changed the axis limits
msg = '';
switch (size(axlimits,1))
case 1, msg='';
case 2, msg='on two axes ';
otherwise, msg='on several axes ';
end;
msg = [upper(mfilename) ' changed the axis limits ' msg ...
'when adding the arrow'];
if (narrows>1), msg=[msg 's']; end;
out = [msg '.' sprintf('\n') ' Call ' upper(mfilename) ...
' FIXLIMITS to reset them now.'];
function arrow_copyprops(fm,to)
% copy line properties to patches
props = {'EraseMode','LineStyle','LineWidth','Marker','MarkerSize',...
'MarkerEdgeColor','MarkerFaceColor','ButtonDownFcn', ...
'Clipping','DeleteFcn','BusyAction','HandleVisibility', ...
'Selected','SelectionHighlight','Visible'};
lineprops = {'Color', props{:}};
patchprops = {'EdgeColor',props{:}};
patch2props = {'FaceColor',patchprops{:}};
fmpatch = strcmp(get(fm,'Type'),'patch');
topatch = strcmp(get(to,'Type'),'patch');
set(to( fmpatch& topatch),patch2props,get(fm( fmpatch& topatch),patch2props)); %p->p
set(to(~fmpatch&~topatch),lineprops, get(fm(~fmpatch&~topatch),lineprops )); %l->l
set(to( fmpatch&~topatch),lineprops, get(fm( fmpatch&~topatch),patchprops )); %p->l
set(to(~fmpatch& topatch),patchprops, get(fm(~fmpatch& topatch),lineprops) ,'FaceColor','none'); %l->p
function arrow_props
% display further help info about ARROW properties
c = sprintf('\n');
disp([c ...
'ARROW Properties: Default values are given in [square brackets], and other' c ...
' acceptable equivalent property names are in (parenthesis).' c c ...
' Start The starting points. For N arrows, B' c ...
' this should be a Nx2 or Nx3 matrix. /|\ ^' c ...
' Stop The end points. For N arrows, this /|||\ |' c ...
' should be a Nx2 or Nx3 matrix. //|||\\ L|' c ...
' Length Length of the arrowhead (in pixels on ///|||\\\ e|' c ...
' screen, points on a page). [16] (Len) ////|||\\\\ n|' c ...
' BaseAngle Angle (degrees) of the base angle /////|D|\\\\\ g|' c ...
' ADE. For a simple stick arrow, use //// ||| \\\\ t|' c ...
' BaseAngle=TipAngle. [90] (Base) /// ||| \\\ h|' c ...
' TipAngle Angle (degrees) of tip angle ABC. //<----->|| \\ |' c ...
' [16] (Tip) / base ||| \ V' c ...
' Width Width of the base in pixels. Not E angle ||<-------->C' c ...
' the ''LineWidth'' prop. [0] (Wid) |||tipangle' c ...
' Page If provided, non-empty, and not NaN, |||' c ...
' this causes ARROW to use hardcopy |||' c ...
' rather than onscreen proportions. A' c ...
' This is important if screen aspect --> <-- width' c ...
' ratio and hardcopy aspect ratio are ----CrossDir---->' c ...
' vastly different. []' c...
' CrossDir A vector giving the direction towards which the fletches' c ...
' on the arrow should go. [computed such that it is perpen-' c ...
' dicular to both the arrow direction and the view direction' c ...
' (i.e., as if it was pasted on a normal 2-D graph)] (Note' c ...
' that CrossDir is a vector. Also note that if an axis is' c ...
' plotted on a log scale, then the corresponding component' c ...
' of CrossDir must also be set appropriately, i.e., to 1 for' c ...
' no change in that direction, >1 for a positive change, >0' c ...
' and <1 for negative change.)' c ...
' NormalDir A vector normal to the fletch direction (CrossDir is then' c ...
' computed by the vector cross product [Line]x[NormalDir]). []' c ...
' (Note that NormalDir is a vector. Unlike CrossDir,' c ...
' NormalDir is used as is regardless of log-scaled axes.)' c ...
' Ends Set which end has an arrowhead. Valid values are ''none'',' c ...
' ''stop'', ''start'', and ''both''. [''stop''] (End)' c...
' ObjectHandles Vector of handles to previously-created arrows to be' c ...
' updated or line objects to be converted to arrows.' c ...
' [] (Object,Handle)' c ]);
function out = arrow_demo
% demo
% create the data
[x,y,z] = peaks;
[ddd,out.iii]=max(z(:));
out.axlim = [min(x(:)) max(x(:)) min(y(:)) max(y(:)) min(z(:)) max(z(:))];
% modify it by inserting some NaN's
[m,n] = size(z);
m = floor(m/2);
n = floor(n/2);
z(1:m,1:n) = NaN*ones(m,n);
% graph it
clf('reset');
out.hs=surf(x,y,z);
out.x=x; out.y=y; out.z=z;
xlabel('x'); ylabel('y');
function h = arrow_demo3(in)
% set the view
axlim = in.axlim;
axis(axlim);
zlabel('z');
%set(in.hs,'FaceColor','interp');
view(3); % view(viewmtx(-37.5,30,20));
title(['Demo of the capabilities of the ARROW function in 3-D']);
% Normal blue arrow
h1 = feval(mfilename,[axlim(1) axlim(4) 4],[-.8 1.2 4], ...
'EdgeColor','b','FaceColor','b');
% Normal white arrow, clipped by the surface
h2 = feval(mfilename,axlim([1 4 6]),[0 2 4]);
t=text(-2.4,2.7,7.7,'arrow clipped by surf');
% Baseangle<90
h3 = feval(mfilename,[3 .125 3.5],[1.375 0.125 3.5],30,50);
t2=text(3.1,.125,3.5,'local maximum');
% Baseangle<90, fill and edge colors different
h4 = feval(mfilename,axlim(1:2:5)*.5,[0 0 0],36,60,25, ...
'EdgeColor','b','FaceColor','c');
t3=text(axlim(1)*.5,axlim(3)*.5,axlim(5)*.5-.75,'origin');
set(t3,'HorizontalAlignment','center');
% Baseangle>90, black fill
h5 = feval(mfilename,[-2.9 2.9 3],[-1.3 .4 3.2],30,120,[],6, ...
'EdgeColor','r','FaceColor','k','LineWidth',2);
% Baseangle>90, no fill
h6 = feval(mfilename,[-2.9 2.9 1.3],[-1.3 .4 1.5],30,120,[],6, ...
'EdgeColor','r','FaceColor','none','LineWidth',2);
% Stick arrow
h7 = feval(mfilename,[-1.6 -1.65 -6.5],[0 -1.65 -6.5],[],16,16);
t4=text(-1.5,-1.65,-7.25,'global mininum');
set(t4,'HorizontalAlignment','center');
% Normal, black fill
h8 = feval(mfilename,[-1.4 0 -7.2],[-1.4 0 -3],'FaceColor','k');
t5=text(-1.5,0,-7.75,'local minimum');
set(t5,'HorizontalAlignment','center');
% Gray fill, crossdir specified, 'LineStyle' --
h9 = feval(mfilename,[-3 2.2 -6],[-3 2.2 -.05],36,[],27,6,[],[0 -1 0], ...
'EdgeColor','k','FaceColor',.75*[1 1 1],'LineStyle','--');
% a series of normal arrows, linearly spaced, crossdir specified
h10y=(0:4)'/3;
h10 = feval(mfilename,[-3*ones(size(h10y)) h10y -6.5*ones(size(h10y))], ...
[-3*ones(size(h10y)) h10y -.05*ones(size(h10y))], ...
12,[],[],[],[],[0 -1 0]);
% a series of normal arrows, linearly spaced
h11x=(1:.33:2.8)';
h11 = feval(mfilename,[h11x -3*ones(size(h11x)) 6.5*ones(size(h11x))], ...
[h11x -3*ones(size(h11x)) -.05*ones(size(h11x))]);
% series of magenta arrows, radially oriented, crossdir specified
h12x=2; h12y=-3; h12z=axlim(5)/2; h12xr=1; h12zr=h12z; ir=.15;or=.81;
h12t=(0:11)'/6*pi;
h12 = feval(mfilename, ...
[h12x+h12xr*cos(h12t)*ir h12y*ones(size(h12t)) ...
h12z+h12zr*sin(h12t)*ir],[h12x+h12xr*cos(h12t)*or ...
h12y*ones(size(h12t)) h12z+h12zr*sin(h12t)*or], ...
10,[],[],[],[], ...
[-h12xr*sin(h12t) zeros(size(h12t)) h12zr*cos(h12t)],...
'FaceColor','none','EdgeColor','m');
% series of normal arrows, tangentially oriented, crossdir specified
or13=.91; h13t=(0:.5:12)'/6*pi;
locs = [h12x+h12xr*cos(h13t)*or13 h12y*ones(size(h13t)) h12z+h12zr*sin(h13t)*or13];
h13 = feval(mfilename,locs(1:end-1,:),locs(2:end,:),6);
% arrow with no line ==> oriented downwards
h14 = feval(mfilename,[3 3 .100001],[3 3 .1],30);
t6=text(3,3,3.6,'no line'); set(t6,'HorizontalAlignment','center');
% arrow with arrowheads at both ends
h15 = feval(mfilename,[-.5 -3 -3],[1 -3 -3],'Ends','both','FaceColor','g', ...
'Length',20,'Width',3,'CrossDir',[0 0 1],'TipAngle',25);
h=[h1;h2;h3;h4;h5;h6;h7;h8;h9;h10;h11;h12;h13;h14;h15];
function h = arrow_demo2(in)
axlim = in.axlim;
dolog = 1;
if (dolog), set(in.hs,'YData',10.^get(in.hs,'YData')); end;
shading('interp');
view(2);
title(['Demo of the capabilities of the ARROW function in 2-D']);
hold on; [C,H]=contour(in.x,in.y,in.z,20,'-'); hold off;
for k=H',
set(k,'ZData',(axlim(6)+1)*ones(size(get(k,'XData'))),'Color','k');
if (dolog), set(k,'YData',10.^get(k,'YData')); end;
end;
if (dolog), axis([axlim(1:2) 10.^axlim(3:4)]); set(gca,'YScale','log');
else, axis(axlim(1:4)); end;
% Normal blue arrow
start = [axlim(1) axlim(4) axlim(6)+2];
stop = [in.x(in.iii) in.y(in.iii) axlim(6)+2];
if (dolog), start(:,2)=10.^start(:,2); stop(:,2)=10.^stop(:,2); end;
h1 = feval(mfilename,start,stop,'EdgeColor','b','FaceColor','b');
% three arrows with varying fill, width, and baseangle
start = [-3 -3 10; -3 -1.5 10; -1.5 -3 10];
stop = [-.03 -.03 10; -.03 -1.5 10; -1.5 -.03 10];
if (dolog), start(:,2)=10.^start(:,2); stop(:,2)=10.^stop(:,2); end;
h2 = feval(mfilename,start,stop,24,[90;60;120],[],[0;0;4],'Ends',str2mat('both','stop','stop'));
set(h2(2),'EdgeColor',[0 .35 0],'FaceColor',[0 .85 .85]);
set(h2(3),'EdgeColor','r','FaceColor',[1 .5 1]);
h=[h1;h2];
function out = trueornan(x)
if isempty(x),
out=x;
else,
out = isnan(x);
out(~out) = x(~out);
end;
|
github
|
Hadisalman/stoec-master
|
TruncatedGaussian.m
|
.m
|
stoec-master/code/Include/TruncatedGaussian.m
| 6,804 |
utf_8
|
125bc65500771dd6664b2327487ba9dd
|
function [X meaneffective sigmaeffective] = TruncatedGaussian(sigma, range, varargin)
% function X = TruncatedGaussian(sigma, range)
% X = TruncatedGaussian(sigma, range, n)
%
% Purpose: generate a pseudo-random vector X of size n, X are drawn from
% the truncated Gaussian distribution in a RANGE braket; and satisfies
% std(X)=sigma.
% RANGE is of the form [left,right] defining the braket where X belongs.
% For a scalar input RANGE, the braket is [-RANGE,RANGE].
%
% X = TruncatedGaussian(..., 'double') or
% X = TruncatedGaussian(..., 'single') return an array X of of the
% specified class.
%
% If input SIGMA is negative, X will be forced to have the same "shape" of
% distribution function than the unbounded Gaussian with standard deviation
% -SIGMA: N(0,-SIGMA). It is similar to calling RANDN and throw away values
% ouside RANGE. In this case, the standard deviation of the truncated
% Gaussian will be different than -SIGMA. The *effective* mean and
% the effective standard deviation can be obtained by calling:
% [X meaneffective sigmaeffective] = TruncatedGaussian(...)
%
% Example:
%
% sigma=2;
% range=[-3 5]
%
% [X meaneff sigmaeff] = TruncatedGaussian(sigma, range, [1 1e6]);
%
% stdX=std(X);
% fprintf('mean(X)=%g, estimated=%g\n',meaneff, mean(X))
% fprintf('sigma=%g, effective=%g, estimated=%g\n', sigma, sigmaeff, stdX)
% hist(X,64)
%
% Author: Bruno Luong <[email protected]>
% Last update: 19/April/2009
% 12-Aug-2010, use asymptotic formula for unbalanced
% range to avoid round-off error issue
% We keep track this variables so as to avoid calling fzero if
% TruncatedGaussian is called succesively with the same sigma and range
persistent PREVSIGMA PREVRANGE PREVSIGMAC
% shape preserving?
shapeflag = (sigma<0);
% Force inputs to be double class
range = double(range);
if isscalar(range)
% make sure it's positive
range=abs(range);
range=[-range range];
else
range=sort(range); % right order
end
sigma = abs(double(sigma));
n=varargin;
if shapeflag
% Prevent the same pdf as with the normal distribution N(0,sigma)
sigmac = sigma;
else
if diff(range)^2<12*sigma^2 % This imposes a limit of sigma wrt range
warning('TruncatedGaussian:RangeSigmaIncompatible', ...
'TruncatedGaussian: range and sigma are incompatible\n');
sigmac = Inf;
elseif isequal([sigma range], [PREVSIGMA PREVRANGE]) % See line #80
sigmac = PREVSIGMAC; % Do not need to call fzero
else
% Search for "sigmac" such that the truncated Gaussian having
% sigmac in the formula of its pdf gives a standard deviation
% equal to sigma
[sigmac res flag] = fzero(@scz,sigma,[],...
sigma^2,range(1),range(2)); %#ok
sigmac = abs(sigmac); % Force it to be positive
if flag<0 % Someting is wrong
error('TruncatedGaussian:fzerofailled', ...
'Could not estimate sigmac\n');
end
% Backup the solution
[PREVSIGMA PREVRANGE PREVSIGMAC] = deal(sigma,range,sigmac);
end
end
% Compute effective standard deviation
meaneffective=meantrunc(range(1), range(2), sigmac);
sigmaeffective=stdtrunc(range(1), range(2), sigmac);
% Inverse of the cdf functions
if isinf(sigmac)
% Uniform distribution to maximize the standard deviation within the
% range. It is like a Gaussian with infinity standard deviation
if any(strcmpi(n,'single'))
range = single(range);
end
cdfinv = @(y) range(1)+y*diff(range);
else
c = sqrt(2)*sigmac;
rn = range/c;
asymthreshold = 4;
if any(strcmpi(n,'single'))
% cdfinv will be single class
c = single(c);
%e = single(e);
end
% Unbalanced range
if prod(sign(rn))>0 && all(abs(rn)>=asymthreshold)
% Use asymptotic expansion
% based on a Sergei Winitzi's paper "A handly approximation for the
% error function and its inverse", Feb 6, 2008.
c = c*sign(rn(1));
rn = abs(rn);
left = min(rn);
right = max(rn);
a = 0.147;
x2 = left*left;
ax2 = a*x2;
e1 = (4/pi+ax2) ./ (1+ax2);
e1 = exp(-x2.*e1); % e1 < 3.0539e-008 for asymthreshold = 4
x2 = right*right;
ax2 = a*x2;
e2 = (4/pi+ax2) ./ (1+ax2);
e2 = exp(-x2.*e2); % e2 < 3.0539e-008 for asymthreshold = 4
% Taylor series of erf(right)-erf(left) ~= sqrt(1-e2)-sqrt(1-e1)
de = -0.5*(e2-e1) -0.125*(e2-e1)*(e2+e1);
% Taylor series of erf1 := erf(left)-1 ~= sqrt(1-e1)-1
erf1 = (-0.5*e1 - 0.125*e1^2);
cdfinv = @(y) c*asymcdfinv(y, erf1, de, a);
else
e = erf(range/c);
cdfinv = @(y) c*erfinv(e(1)+diff(e)*y);
end
end
% Generate random variable
X = cdfinv(rand(n{:}));
% Clip to prevent some nasty numerical issues with of erfinv function
% when argument gets close to +/-1
X = max(min(X,range(2)),range(1));
return
end % TruncatedGaussian
%%
function x = asymcdfinv(y, erf1, de, a)
% z = erf(left) + de*y = 1 + erf1 + de*y, input argument of erfinv(.)
f = erf1 + de*y; % = z - 1; thus z = 1+f
% 1 - z^2 = -2f-f^2
l = log(-f.*(2 + f)); % log(-2f-f^2) = log(1-z.^2);
b = 2/(pi*a) + l/2;
x = sqrt(-b + sqrt(b.^2-l/a));
end % asymcdfinv
function m=meantrunc(lower, upper, s)
% Compute the mean of a trunctated gaussian distribution
if isinf(s)
m = (upper+lower)/2;
else
a = (lower/sqrt(2))./s;
b = (upper/sqrt(2))./s;
corr = sqrt(2/pi)*(-exp(-b.^2)+exp(-a.^2))./(erf(b)-erf(a));
m = s.*corr;
end
end % vartrunc
function v=vartrunc(lower, upper, s)
% Compute the variance of a trunctated gaussian distribution
if isinf(s)
v = (upper-lower)^2/12;
else
a = (lower/sqrt(2))./s;
b = (upper/sqrt(2))./s;
if isinf(a)
ea=0;
else
ea = a.*exp(-a.^2);
end
if isinf(b)
eb = 0;
else
eb = b.*exp(-b.^2);
end
corr = 1 - (2/sqrt(pi))*(eb-ea)./(erf(b)-erf(a));
v = s.^2.*corr;
end
end % vartrunc
function stdt=stdtrunc(lower, upper, s)
% Standard deviation of a trunctated gaussian distribution
arg = vartrunc(lower, upper, s)-meantrunc(lower, upper, s).^2;
%arg = max(arg,0);
stdt = sqrt(arg);
end % stdtrunc
function res=scz(sc, targetsigma2, lower, upper)
% Gateway for fzero, aim the standard deviation to a target value
res = vartrunc(lower, upper, sc) - targetsigma2 - ...
meantrunc(lower, upper, sc).^2;
end % scz
% End of file TruncatedGaussian.m
|
github
|
Hadisalman/stoec-master
|
gridfit.m
|
.m
|
stoec-master/code/Include/gridfit.m
| 34,995 |
utf_8
|
e58c0dba921cb156ee39a27dd18a4d1c
|
function [zgrid,xgrid,ygrid] = gridfit(x,y,z,xnodes,ynodes,varargin)
% gridfit: estimates a surface on a 2d grid, based on scattered data
% Replicates are allowed. All methods extrapolate to the grid
% boundaries. Gridfit uses a modified ridge estimator to
% generate the surface, where the bias is toward smoothness.
%
% Gridfit is not an interpolant. Its goal is a smooth surface
% that approximates your data, but allows you to control the
% amount of smoothing.
%
% usage #1: zgrid = gridfit(x,y,z,xnodes,ynodes);
% usage #2: [zgrid,xgrid,ygrid] = gridfit(x,y,z,xnodes,ynodes);
% usage #3: zgrid = gridfit(x,y,z,xnodes,ynodes,prop,val,prop,val,...);
%
% Arguments: (input)
% x,y,z - vectors of equal lengths, containing arbitrary scattered data
% The only constraint on x and y is they cannot ALL fall on a
% single line in the x-y plane. Replicate points will be treated
% in a least squares sense.
%
% ANY points containing a NaN are ignored in the estimation
%
% xnodes - vector defining the nodes in the grid in the independent
% variable (x). xnodes need not be equally spaced. xnodes
% must completely span the data. If they do not, then the
% 'extend' property is applied, adjusting the first and last
% nodes to be extended as necessary. See below for a complete
% description of the 'extend' property.
%
% If xnodes is a scalar integer, then it specifies the number
% of equally spaced nodes between the min and max of the data.
%
% ynodes - vector defining the nodes in the grid in the independent
% variable (y). ynodes need not be equally spaced.
%
% If ynodes is a scalar integer, then it specifies the number
% of equally spaced nodes between the min and max of the data.
%
% Also see the extend property.
%
% Additional arguments follow in the form of property/value pairs.
% Valid properties are:
% 'smoothness', 'interp', 'regularizer', 'solver', 'maxiter'
% 'extend', 'tilesize', 'overlap'
%
% Any UNAMBIGUOUS shortening (even down to a single letter) is
% valid for property names. All properties have default values,
% chosen (I hope) to give a reasonable result out of the box.
%
% 'smoothness' - scalar or vector of length 2 - determines the
% eventual smoothness of the estimated surface. A larger
% value here means the surface will be smoother. Smoothness
% must be a non-negative real number.
%
% If this parameter is a vector of length 2, then it defines
% the relative smoothing to be associated with the x and y
% variables. This allows the user to apply a different amount
% of smoothing in the x dimension compared to the y dimension.
%
% Note: the problem is normalized in advance so that a
% smoothness of 1 MAY generate reasonable results. If you
% find the result is too smooth, then use a smaller value
% for this parameter. Likewise, bumpy surfaces suggest use
% of a larger value. (Sometimes, use of an iterative solver
% with too small a limit on the maximum number of iterations
% will result in non-convergence.)
%
% DEFAULT: 1
%
%
% 'interp' - character, denotes the interpolation scheme used
% to interpolate the data.
%
% DEFAULT: 'triangle'
%
% 'bilinear' - use bilinear interpolation within the grid
% (also known as tensor product linear interpolation)
%
% 'triangle' - split each cell in the grid into a triangle,
% then linear interpolation inside each triangle
%
% 'nearest' - nearest neighbor interpolation. This will
% rarely be a good choice, but I included it
% as an option for completeness.
%
%
% 'regularizer' - character flag, denotes the regularization
% paradignm to be used. There are currently three options.
%
% DEFAULT: 'gradient'
%
% 'diffusion' or 'laplacian' - uses a finite difference
% approximation to the Laplacian operator (i.e, del^2).
%
% We can think of the surface as a plate, wherein the
% bending rigidity of the plate is specified by the user
% as a number relative to the importance of fidelity to
% the data. A stiffer plate will result in a smoother
% surface overall, but fit the data less well. I've
% modeled a simple plate using the Laplacian, del^2. (A
% projected enhancement is to do a better job with the
% plate equations.)
%
% We can also view the regularizer as a diffusion problem,
% where the relative thermal conductivity is supplied.
% Here interpolation is seen as a problem of finding the
% steady temperature profile in an object, given a set of
% points held at a fixed temperature. Extrapolation will
% be linear. Both paradigms are appropriate for a Laplacian
% regularizer.
%
% 'gradient' - attempts to ensure the gradient is as smooth
% as possible everywhere. Its subtly different from the
% 'diffusion' option, in that here the directional
% derivatives are biased to be smooth across cell
% boundaries in the grid.
%
% The gradient option uncouples the terms in the Laplacian.
% Think of it as two coupled PDEs instead of one PDE. Why
% are they different at all? The terms in the Laplacian
% can balance each other.
%
% 'springs' - uses a spring model connecting nodes to each
% other, as well as connecting data points to the nodes
% in the grid. This choice will cause any extrapolation
% to be as constant as possible.
%
% Here the smoothing parameter is the relative stiffness
% of the springs connecting the nodes to each other compared
% to the stiffness of a spting connecting the lattice to
% each data point. Since all springs have a rest length
% (length at which the spring has zero potential energy)
% of zero, any extrapolation will be minimized.
%
% Note: The 'springs' regularizer tends to drag the surface
% towards the mean of all the data, so too large a smoothing
% parameter may be a problem.
%
%
% 'solver' - character flag - denotes the solver used for the
% resulting linear system. Different solvers will have
% different solution times depending upon the specific
% problem to be solved. Up to a certain size grid, the
% direct \ solver will often be speedy, until memory
% swaps causes problems.
%
% What solver should you use? Problems with a significant
% amount of extrapolation should avoid lsqr. \ may be
% best numerically for small smoothnesss parameters and
% high extents of extrapolation.
%
% Large numbers of points will slow down the direct
% \, but when applied to the normal equations, \ can be
% quite fast. Since the equations generated by these
% methods will tend to be well conditioned, the normal
% equations are not a bad choice of method to use. Beware
% when a small smoothing parameter is used, since this will
% make the equations less well conditioned.
%
% DEFAULT: 'normal'
%
% '\' - uses matlab's backslash operator to solve the sparse
% system. 'backslash' is an alternate name.
%
% 'symmlq' - uses matlab's iterative symmlq solver
%
% 'lsqr' - uses matlab's iterative lsqr solver
%
% 'normal' - uses \ to solve the normal equations.
%
%
% 'maxiter' - only applies to iterative solvers - defines the
% maximum number of iterations for an iterative solver
%
% DEFAULT: min(10000,length(xnodes)*length(ynodes))
%
%
% 'extend' - character flag - controls whether the first and last
% nodes in each dimension are allowed to be adjusted to
% bound the data, and whether the user will be warned if
% this was deemed necessary to happen.
%
% DEFAULT: 'warning'
%
% 'warning' - Adjust the first and/or last node in
% x or y if the nodes do not FULLY contain
% the data. Issue a warning message to this
% effect, telling the amount of adjustment
% applied.
%
% 'never' - Issue an error message when the nodes do
% not absolutely contain the data.
%
% 'always' - automatically adjust the first and last
% nodes in each dimension if necessary.
% No warning is given when this option is set.
%
%
% 'tilesize' - grids which are simply too large to solve for
% in one single estimation step can be built as a set
% of tiles. For example, a 1000x1000 grid will require
% the estimation of 1e6 unknowns. This is likely to
% require more memory (and time) than you have available.
% But if your data is dense enough, then you can model
% it locally using smaller tiles of the grid.
%
% My recommendation for a reasonable tilesize is
% roughly 100 to 200. Tiles of this size take only
% a few seconds to solve normally, so the entire grid
% can be modeled in a finite amount of time. The minimum
% tilesize can never be less than 3, although even this
% size tile is so small as to be ridiculous.
%
% If your data is so sparse than some tiles contain
% insufficient data to model, then those tiles will
% be left as NaNs.
%
% DEFAULT: inf
%
%
% 'overlap' - Tiles in a grid have some overlap, so they
% can minimize any problems along the edge of a tile.
% In this overlapped region, the grid is built using a
% bi-linear combination of the overlapping tiles.
%
% The overlap is specified as a fraction of the tile
% size, so an overlap of 0.20 means there will be a 20%
% overlap of successive tiles. I do allow a zero overlap,
% but it must be no more than 1/2.
%
% 0 <= overlap <= 0.5
%
% Overlap is ignored if the tilesize is greater than the
% number of nodes in both directions.
%
% DEFAULT: 0.20
%
%
% 'autoscale' - Some data may have widely different scales on
% the respective x and y axes. If this happens, then
% the regularization may experience difficulties.
%
% autoscale = 'on' will cause gridfit to scale the x
% and y node intervals to a unit length. This should
% improve the regularization procedure. The scaling is
% purely internal.
%
% autoscale = 'off' will disable automatic scaling
%
% DEFAULT: 'on'
%
%
% Arguments: (output)
% zgrid - (nx,ny) array containing the fitted surface
%
% xgrid, ygrid - as returned by meshgrid(xnodes,ynodes)
%
%
% Speed considerations:
% Remember that gridfit must solve a LARGE system of linear
% equations. There will be as many unknowns as the total
% number of nodes in the final lattice. While these equations
% may be sparse, solving a system of 10000 equations may take
% a second or so. Very large problems may benefit from the
% iterative solvers or from tiling.
%
%
% Example usage:
%
% x = rand(100,1);
% y = rand(100,1);
% z = exp(x+2*y);
% xnodes = 0:.1:1;
% ynodes = 0:.1:1;
%
% g = gridfit(x,y,z,xnodes,ynodes);
%
% Note: this is equivalent to the following call:
%
% g = gridfit(x,y,z,xnodes,ynodes, ...
% 'smooth',1, ...
% 'interp','triangle', ...
% 'solver','normal', ...
% 'regularizer','gradient', ...
% 'extend','warning', ...
% 'tilesize',inf);
%
%
% Author: John D'Errico
% e-mail address: [email protected]
% Release: 2.0
% Release date: 5/23/06
% set defaults
params.smoothness = 1;
params.interp = 'triangle';
params.regularizer = 'gradient';
params.solver = 'backslash';
params.maxiter = [];
params.extend = 'warning';
params.tilesize = inf;
params.overlap = 0.20;
params.mask = [];
params.autoscale = 'on';
params.xscale = 1;
params.yscale = 1;
% was the params struct supplied?
if ~isempty(varargin)
if isstruct(varargin{1})
% params is only supplied if its a call from tiled_gridfit
params = varargin{1};
if length(varargin)>1
% check for any overrides
params = parse_pv_pairs(params,varargin{2:end});
end
else
% check for any overrides of the defaults
params = parse_pv_pairs(params,varargin);
end
end
% check the parameters for acceptability
params = check_params(params);
% ensure all of x,y,z,xnodes,ynodes are column vectors,
% also drop any NaN data
x=x(:);
y=y(:);
z=z(:);
k = isnan(x) | isnan(y) | isnan(z);
if any(k)
x(k)=[];
y(k)=[];
z(k)=[];
end
xmin = min(x);
xmax = max(x);
ymin = min(y);
ymax = max(y);
% did they supply a scalar for the nodes?
if length(xnodes)==1
xnodes = linspace(xmin,xmax,xnodes)';
xnodes(end) = xmax; % make sure it hits the max
end
if length(ynodes)==1
ynodes = linspace(ymin,ymax,ynodes)';
ynodes(end) = ymax; % make sure it hits the max
end
xnodes=xnodes(:);
ynodes=ynodes(:);
dx = diff(xnodes);
dy = diff(ynodes);
nx = length(xnodes);
ny = length(ynodes);
ngrid = nx*ny;
% set the scaling if autoscale was on
if strcmpi(params.autoscale,'on')
params.xscale = mean(dx);
params.yscale = mean(dy);
params.autoscale = 'off';
end
% check to see if any tiling is necessary
if (params.tilesize < max(nx,ny))
% split it into smaller tiles. compute zgrid and ygrid
% at the very end if requested
zgrid = tiled_gridfit(x,y,z,xnodes,ynodes,params);
else
% its a single tile.
% mask must be either an empty array, or a boolean
% aray of the same size as the final grid.
nmask = size(params.mask);
if ~isempty(params.mask) && ((nmask(2)~=nx) || (nmask(1)~=ny))
if ((nmask(2)==ny) || (nmask(1)==nx))
error 'Mask array is probably transposed from proper orientation.'
else
error 'Mask array must be the same size as the final grid.'
end
end
if ~isempty(params.mask)
params.maskflag = 1;
else
params.maskflag = 0;
end
% default for maxiter?
if isempty(params.maxiter)
params.maxiter = min(10000,nx*ny);
end
% check lengths of the data
n = length(x);
if (length(y)~=n) || (length(z)~=n)
error 'Data vectors are incompatible in size.'
end
if n<3
error 'Insufficient data for surface estimation.'
end
% verify the nodes are distinct
if any(diff(xnodes)<=0) || any(diff(ynodes)<=0)
error 'xnodes and ynodes must be monotone increasing'
end
% do we need to tweak the first or last node in x or y?
if xmin<xnodes(1)
switch params.extend
case 'always'
xnodes(1) = xmin;
case 'warning'
warning('GRIDFIT:extend',['xnodes(1) was decreased by: ',num2str(xnodes(1)-xmin),', new node = ',num2str(xmin)])
xnodes(1) = xmin;
case 'never'
error(['Some x (',num2str(xmin),') falls below xnodes(1) by: ',num2str(xnodes(1)-xmin)])
end
end
if xmax>xnodes(end)
switch params.extend
case 'always'
xnodes(end) = xmax;
case 'warning'
warning('GRIDFIT:extend',['xnodes(end) was increased by: ',num2str(xmax-xnodes(end)),', new node = ',num2str(xmax)])
xnodes(end) = xmax;
case 'never'
error(['Some x (',num2str(xmax),') falls above xnodes(end) by: ',num2str(xmax-xnodes(end))])
end
end
if ymin<ynodes(1)
switch params.extend
case 'always'
ynodes(1) = ymin;
case 'warning'
warning('GRIDFIT:extend',['ynodes(1) was decreased by: ',num2str(ynodes(1)-ymin),', new node = ',num2str(ymin)])
ynodes(1) = ymin;
case 'never'
error(['Some y (',num2str(ymin),') falls below ynodes(1) by: ',num2str(ynodes(1)-ymin)])
end
end
if ymax>ynodes(end)
switch params.extend
case 'always'
ynodes(end) = ymax;
case 'warning'
warning('GRIDFIT:extend',['ynodes(end) was increased by: ',num2str(ymax-ynodes(end)),', new node = ',num2str(ymax)])
ynodes(end) = ymax;
case 'never'
error(['Some y (',num2str(ymax),') falls above ynodes(end) by: ',num2str(ymax-ynodes(end))])
end
end
% determine which cell in the array each point lies in
[junk,indx] = histc(x,xnodes); %#ok
[junk,indy] = histc(y,ynodes); %#ok
% any point falling at the last node is taken to be
% inside the last cell in x or y.
k=(indx==nx);
indx(k)=indx(k)-1;
k=(indy==ny);
indy(k)=indy(k)-1;
ind = indy + ny*(indx-1);
% Do we have a mask to apply?
if params.maskflag
% if we do, then we need to ensure that every
% cell with at least one data point also has at
% least all of its corners unmasked.
params.mask(ind) = 1;
params.mask(ind+1) = 1;
params.mask(ind+ny) = 1;
params.mask(ind+ny+1) = 1;
end
% interpolation equations for each point
tx = min(1,max(0,(x - xnodes(indx))./dx(indx)));
ty = min(1,max(0,(y - ynodes(indy))./dy(indy)));
% Future enhancement: add cubic interpolant
switch params.interp
case 'triangle'
% linear interpolation inside each triangle
k = (tx > ty);
L = ones(n,1);
L(k) = ny;
t1 = min(tx,ty);
t2 = max(tx,ty);
A = sparse(repmat((1:n)',1,3),[ind,ind+ny+1,ind+L], ...
[1-t2,t1,t2-t1],n,ngrid);
case 'nearest'
% nearest neighbor interpolation in a cell
k = round(1-ty) + round(1-tx)*ny;
A = sparse((1:n)',ind+k,ones(n,1),n,ngrid);
case 'bilinear'
% bilinear interpolation in a cell
A = sparse(repmat((1:n)',1,4),[ind,ind+1,ind+ny,ind+ny+1], ...
[(1-tx).*(1-ty), (1-tx).*ty, tx.*(1-ty), tx.*ty], ...
n,ngrid);
end
rhs = z;
% do we have relative smoothing parameters?
if numel(params.smoothness) == 1
% it was scalar, so treat both dimensions equally
smoothparam = params.smoothness;
xyRelativeStiffness = [1;1];
else
% It was a vector, so anisotropy reigns.
% I've already checked that the vector was of length 2
smoothparam = sqrt(prod(params.smoothness));
xyRelativeStiffness = params.smoothness(:)./smoothparam;
end
% Build regularizer. Add del^4 regularizer one day.
switch params.regularizer
case 'springs'
% zero "rest length" springs
[i,j] = meshgrid(1:nx,1:(ny-1));
ind = j(:) + ny*(i(:)-1);
m = nx*(ny-1);
stiffness = 1./(dy/params.yscale);
Areg = sparse(repmat((1:m)',1,2),[ind,ind+1], ...
xyRelativeStiffness(2)*stiffness(j(:))*[-1 1], ...
m,ngrid);
[i,j] = meshgrid(1:(nx-1),1:ny);
ind = j(:) + ny*(i(:)-1);
m = (nx-1)*ny;
stiffness = 1./(dx/params.xscale);
Areg = [Areg;sparse(repmat((1:m)',1,2),[ind,ind+ny], ...
xyRelativeStiffness(1)*stiffness(i(:))*[-1 1],m,ngrid)];
[i,j] = meshgrid(1:(nx-1),1:(ny-1));
ind = j(:) + ny*(i(:)-1);
m = (nx-1)*(ny-1);
stiffness = 1./sqrt((dx(i(:))/params.xscale/xyRelativeStiffness(1)).^2 + ...
(dy(j(:))/params.yscale/xyRelativeStiffness(2)).^2);
Areg = [Areg;sparse(repmat((1:m)',1,2),[ind,ind+ny+1], ...
stiffness*[-1 1],m,ngrid)];
Areg = [Areg;sparse(repmat((1:m)',1,2),[ind+1,ind+ny], ...
stiffness*[-1 1],m,ngrid)];
case {'diffusion' 'laplacian'}
% thermal diffusion using Laplacian (del^2)
[i,j] = meshgrid(1:nx,2:(ny-1));
ind = j(:) + ny*(i(:)-1);
dy1 = dy(j(:)-1)/params.yscale;
dy2 = dy(j(:))/params.yscale;
Areg = sparse(repmat(ind,1,3),[ind-1,ind,ind+1], ...
xyRelativeStiffness(2)*[-2./(dy1.*(dy1+dy2)), ...
2./(dy1.*dy2), -2./(dy2.*(dy1+dy2))],ngrid,ngrid);
[i,j] = meshgrid(2:(nx-1),1:ny);
ind = j(:) + ny*(i(:)-1);
dx1 = dx(i(:)-1)/params.xscale;
dx2 = dx(i(:))/params.xscale;
Areg = Areg + sparse(repmat(ind,1,3),[ind-ny,ind,ind+ny], ...
xyRelativeStiffness(1)*[-2./(dx1.*(dx1+dx2)), ...
2./(dx1.*dx2), -2./(dx2.*(dx1+dx2))],ngrid,ngrid);
case 'gradient'
% Subtly different from the Laplacian. A point for future
% enhancement is to do it better for the triangle interpolation
% case.
[i,j] = meshgrid(1:nx,2:(ny-1));
ind = j(:) + ny*(i(:)-1);
dy1 = dy(j(:)-1)/params.yscale;
dy2 = dy(j(:))/params.yscale;
Areg = sparse(repmat(ind,1,3),[ind-1,ind,ind+1], ...
xyRelativeStiffness(2)*[-2./(dy1.*(dy1+dy2)), ...
2./(dy1.*dy2), -2./(dy2.*(dy1+dy2))],ngrid,ngrid);
[i,j] = meshgrid(2:(nx-1),1:ny);
ind = j(:) + ny*(i(:)-1);
dx1 = dx(i(:)-1)/params.xscale;
dx2 = dx(i(:))/params.xscale;
Areg = [Areg;sparse(repmat(ind,1,3),[ind-ny,ind,ind+ny], ...
xyRelativeStiffness(1)*[-2./(dx1.*(dx1+dx2)), ...
2./(dx1.*dx2), -2./(dx2.*(dx1+dx2))],ngrid,ngrid)];
end
nreg = size(Areg,1);
% Append the regularizer to the interpolation equations,
% scaling the problem first. Use the 1-norm for speed.
NA = norm(A,1);
NR = norm(Areg,1);
A = [A;Areg*(smoothparam*NA/NR)];
rhs = [rhs;zeros(nreg,1)];
% do we have a mask to apply?
if params.maskflag
unmasked = find(params.mask);
end
% solve the full system, with regularizer attached
switch params.solver
case {'\' 'backslash'}
if params.maskflag
% there is a mask to use
zgrid=nan(ny,nx);
zgrid(unmasked) = A(:,unmasked)\rhs;
else
% no mask
zgrid = reshape(A\rhs,ny,nx);
end
case 'normal'
% The normal equations, solved with \. Can be faster
% for huge numbers of data points, but reasonably
% sized grids. The regularizer makes A well conditioned
% so the normal equations are not a terribly bad thing
% here.
if params.maskflag
% there is a mask to use
Aunmasked = A(:,unmasked);
zgrid=nan(ny,nx);
zgrid(unmasked) = (Aunmasked'*Aunmasked)\(Aunmasked'*rhs);
else
zgrid = reshape((A'*A)\(A'*rhs),ny,nx);
end
case 'symmlq'
% iterative solver - symmlq - requires a symmetric matrix,
% so use it to solve the normal equations. No preconditioner.
tol = abs(max(z)-min(z))*1.e-13;
if params.maskflag
% there is a mask to use
zgrid=nan(ny,nx);
[zgrid(unmasked),flag] = symmlq(A(:,unmasked)'*A(:,unmasked), ...
A(:,unmasked)'*rhs,tol,params.maxiter);
else
[zgrid,flag] = symmlq(A'*A,A'*rhs,tol,params.maxiter);
zgrid = reshape(zgrid,ny,nx);
end
% display a warning if convergence problems
switch flag
case 0
% no problems with convergence
case 1
% SYMMLQ iterated MAXIT times but did not converge.
warning('GRIDFIT:solver',['Symmlq performed ',num2str(params.maxiter), ...
' iterations but did not converge.'])
case 3
% SYMMLQ stagnated, successive iterates were the same
warning('GRIDFIT:solver','Symmlq stagnated without apparent convergence.')
otherwise
warning('GRIDFIT:solver',['One of the scalar quantities calculated in',...
' symmlq was too small or too large to continue computing.'])
end
case 'lsqr'
% iterative solver - lsqr. No preconditioner here.
tol = abs(max(z)-min(z))*1.e-13;
if params.maskflag
% there is a mask to use
zgrid=nan(ny,nx);
[zgrid(unmasked),flag] = lsqr(A(:,unmasked),rhs,tol,params.maxiter);
else
[zgrid,flag] = lsqr(A,rhs,tol,params.maxiter);
zgrid = reshape(zgrid,ny,nx);
end
% display a warning if convergence problems
switch flag
case 0
% no problems with convergence
case 1
% lsqr iterated MAXIT times but did not converge.
warning('GRIDFIT:solver',['Lsqr performed ', ...
num2str(params.maxiter),' iterations but did not converge.'])
case 3
% lsqr stagnated, successive iterates were the same
warning('GRIDFIT:solver','Lsqr stagnated without apparent convergence.')
case 4
warning('GRIDFIT:solver',['One of the scalar quantities calculated in',...
' LSQR was too small or too large to continue computing.'])
end
end % switch params.solver
end % if params.tilesize...
% only generate xgrid and ygrid if requested.
if nargout>1
[xgrid,ygrid]=meshgrid(xnodes,ynodes);
end
% ============================================
% End of main function - gridfit
% ============================================
% ============================================
% subfunction - parse_pv_pairs
% ============================================
function params=parse_pv_pairs(params,pv_pairs)
% parse_pv_pairs: parses sets of property value pairs, allows defaults
% usage: params=parse_pv_pairs(default_params,pv_pairs)
%
% arguments: (input)
% default_params - structure, with one field for every potential
% property/value pair. Each field will contain the default
% value for that property. If no default is supplied for a
% given property, then that field must be empty.
%
% pv_array - cell array of property/value pairs.
% Case is ignored when comparing properties to the list
% of field names. Also, any unambiguous shortening of a
% field/property name is allowed.
%
% arguments: (output)
% params - parameter struct that reflects any updated property/value
% pairs in the pv_array.
%
% Example usage:
% First, set default values for the parameters. Assume we
% have four parameters that we wish to use optionally in
% the function examplefun.
%
% - 'viscosity', which will have a default value of 1
% - 'volume', which will default to 1
% - 'pie' - which will have default value 3.141592653589793
% - 'description' - a text field, left empty by default
%
% The first argument to examplefun is one which will always be
% supplied.
%
% function examplefun(dummyarg1,varargin)
% params.Viscosity = 1;
% params.Volume = 1;
% params.Pie = 3.141592653589793
%
% params.Description = '';
% params=parse_pv_pairs(params,varargin);
% params
%
% Use examplefun, overriding the defaults for 'pie', 'viscosity'
% and 'description'. The 'volume' parameter is left at its default.
%
% examplefun(rand(10),'vis',10,'pie',3,'Description','Hello world')
%
% params =
% Viscosity: 10
% Volume: 1
% Pie: 3
% Description: 'Hello world'
%
% Note that capitalization was ignored, and the property 'viscosity'
% was truncated as supplied. Also note that the order the pairs were
% supplied was arbitrary.
npv = length(pv_pairs);
n = npv/2;
if n~=floor(n)
error 'Property/value pairs must come in PAIRS.'
end
if n<=0
% just return the defaults
return
end
if ~isstruct(params)
error 'No structure for defaults was supplied'
end
% there was at least one pv pair. process any supplied
propnames = fieldnames(params);
lpropnames = lower(propnames);
for i=1:n
p_i = lower(pv_pairs{2*i-1});
v_i = pv_pairs{2*i};
ind = strmatch(p_i,lpropnames,'exact');
if isempty(ind)
ind = find(strncmp(p_i,lpropnames,length(p_i)));
if isempty(ind)
error(['No matching property found for: ',pv_pairs{2*i-1}])
elseif length(ind)>1
error(['Ambiguous property name: ',pv_pairs{2*i-1}])
end
end
p_i = propnames{ind};
% override the corresponding default in params
params = setfield(params,p_i,v_i); %#ok
end
% ============================================
% subfunction - check_params
% ============================================
function params = check_params(params)
% check the parameters for acceptability
% smoothness == 1 by default
if isempty(params.smoothness)
params.smoothness = 1;
else
if (numel(params.smoothness)>2) || any(params.smoothness<=0)
error 'Smoothness must be scalar (or length 2 vector), real, finite, and positive.'
end
end
% regularizer - must be one of 4 options - the second and
% third are actually synonyms.
valid = {'springs', 'diffusion', 'laplacian', 'gradient'};
if isempty(params.regularizer)
params.regularizer = 'diffusion';
end
ind = find(strncmpi(params.regularizer,valid,length(params.regularizer)));
if (length(ind)==1)
params.regularizer = valid{ind};
else
error(['Invalid regularization method: ',params.regularizer])
end
% interp must be one of:
% 'bilinear', 'nearest', or 'triangle'
% but accept any shortening thereof.
valid = {'bilinear', 'nearest', 'triangle'};
if isempty(params.interp)
params.interp = 'triangle';
end
ind = find(strncmpi(params.interp,valid,length(params.interp)));
if (length(ind)==1)
params.interp = valid{ind};
else
error(['Invalid interpolation method: ',params.interp])
end
% solver must be one of:
% 'backslash', '\', 'symmlq', 'lsqr', or 'normal'
% but accept any shortening thereof.
valid = {'backslash', '\', 'symmlq', 'lsqr', 'normal'};
if isempty(params.solver)
params.solver = '\';
end
ind = find(strncmpi(params.solver,valid,length(params.solver)));
if (length(ind)==1)
params.solver = valid{ind};
else
error(['Invalid solver option: ',params.solver])
end
% extend must be one of:
% 'never', 'warning', 'always'
% but accept any shortening thereof.
valid = {'never', 'warning', 'always'};
if isempty(params.extend)
params.extend = 'warning';
end
ind = find(strncmpi(params.extend,valid,length(params.extend)));
if (length(ind)==1)
params.extend = valid{ind};
else
error(['Invalid extend option: ',params.extend])
end
% tilesize == inf by default
if isempty(params.tilesize)
params.tilesize = inf;
elseif (length(params.tilesize)>1) || (params.tilesize<3)
error 'Tilesize must be scalar and > 0.'
end
% overlap == 0.20 by default
if isempty(params.overlap)
params.overlap = 0.20;
elseif (length(params.overlap)>1) || (params.overlap<0) || (params.overlap>0.5)
error 'Overlap must be scalar and 0 < overlap < 1.'
end
% ============================================
% subfunction - tiled_gridfit
% ============================================
function zgrid=tiled_gridfit(x,y,z,xnodes,ynodes,params)
% tiled_gridfit: a tiled version of gridfit, continuous across tile boundaries
% usage: [zgrid,xgrid,ygrid]=tiled_gridfit(x,y,z,xnodes,ynodes,params)
%
% Tiled_gridfit is used when the total grid is far too large
% to model using a single call to gridfit. While gridfit may take
% only a second or so to build a 100x100 grid, a 2000x2000 grid
% will probably not run at all due to memory problems.
%
% Tiles in the grid with insufficient data (<4 points) will be
% filled with NaNs. Avoid use of too small tiles, especially
% if your data has holes in it that may encompass an entire tile.
%
% A mask may also be applied, in which case tiled_gridfit will
% subdivide the mask into tiles. Note that any boolean mask
% provided is assumed to be the size of the complete grid.
%
% Tiled_gridfit may not be fast on huge grids, but it should run
% as long as you use a reasonable tilesize. 8-)
% Note that we have already verified all parameters in check_params
% Matrix elements in a square tile
tilesize = params.tilesize;
% Size of overlap in terms of matrix elements. Overlaps
% of purely zero cause problems, so force at least two
% elements to overlap.
overlap = max(2,floor(tilesize*params.overlap));
% reset the tilesize for each particular tile to be inf, so
% we will never see a recursive call to tiled_gridfit
Tparams = params;
Tparams.tilesize = inf;
nx = length(xnodes);
ny = length(ynodes);
zgrid = zeros(ny,nx);
% linear ramp for the bilinear interpolation
rampfun = inline('(t-t(1))/(t(end)-t(1))','t');
% loop over each tile in the grid
h = waitbar(0,'Relax and have a cup of JAVA. Its my treat.');
warncount = 0;
xtind = 1:min(nx,tilesize);
while ~isempty(xtind) && (xtind(1)<=nx)
xinterp = ones(1,length(xtind));
if (xtind(1) ~= 1)
xinterp(1:overlap) = rampfun(xnodes(xtind(1:overlap)));
end
if (xtind(end) ~= nx)
xinterp((end-overlap+1):end) = 1-rampfun(xnodes(xtind((end-overlap+1):end)));
end
ytind = 1:min(ny,tilesize);
while ~isempty(ytind) && (ytind(1)<=ny)
% update the waitbar
waitbar((xtind(end)-tilesize)/nx + tilesize*ytind(end)/ny/nx)
yinterp = ones(length(ytind),1);
if (ytind(1) ~= 1)
yinterp(1:overlap) = rampfun(ynodes(ytind(1:overlap)));
end
if (ytind(end) ~= ny)
yinterp((end-overlap+1):end) = 1-rampfun(ynodes(ytind((end-overlap+1):end)));
end
% was a mask supplied?
if ~isempty(params.mask)
submask = params.mask(ytind,xtind);
Tparams.mask = submask;
end
% extract data that lies in this grid tile
k = (x>=xnodes(xtind(1))) & (x<=xnodes(xtind(end))) & ...
(y>=ynodes(ytind(1))) & (y<=ynodes(ytind(end)));
k = find(k);
if length(k)<4
if warncount == 0
warning('GRIDFIT:tiling','A tile was too underpopulated to model. Filled with NaNs.')
end
warncount = warncount + 1;
% fill this part of the grid with NaNs
zgrid(ytind,xtind) = NaN;
else
% build this tile
zgtile = gridfit(x(k),y(k),z(k),xnodes(xtind),ynodes(ytind),Tparams);
% bilinear interpolation (using an outer product)
interp_coef = yinterp*xinterp;
% accumulate the tile into the complete grid
zgrid(ytind,xtind) = zgrid(ytind,xtind) + zgtile.*interp_coef;
end
% step to the next tile in y
if ytind(end)<ny
ytind = ytind + tilesize - overlap;
% are we within overlap elements of the edge of the grid?
if (ytind(end)+max(3,overlap))>=ny
% extend this tile to the edge
ytind = ytind(1):ny;
end
else
ytind = ny+1;
end
end % while loop over y
% step to the next tile in x
if xtind(end)<nx
xtind = xtind + tilesize - overlap;
% are we within overlap elements of the edge of the grid?
if (xtind(end)+max(3,overlap))>=nx
% extend this tile to the edge
xtind = xtind(1):nx;
end
else
xtind = nx+1;
end
end % while loop over x
% close down the waitbar
close(h)
if warncount>0
warning('GRIDFIT:tiling',[num2str(warncount),' tiles were underpopulated & filled with NaNs'])
end
|
github
|
Hadisalman/stoec-master
|
RegularizeData3D.m
|
.m
|
stoec-master/code/Include/RegularizeData3D.m
| 39,576 |
utf_8
|
70e5294ed3d4f8726fe2518bd8b0d6cb
|
function [zgrid,xgrid,ygrid] = RegularizeData3D(x,y,z,xnodes,ynodes,varargin)
% RegularizeData3D: Produces a smooth 3D surface from scattered input data.
%
% RegularizeData3D is a modified version of GridFit from the Matlab File Exchange.
% RegularizeData3D does essentially the same thing, but is an attempt to overcome several
% shortcomings inherent in the design of the legacy code in GridFit.
%
% * GridFit lacks cubic interpolation capabilities.
% Interpolation is necessary to map the scattered input data to locations on the output
% surface. The output surface is most likely nonlinear, so linear interpolation used in
% GridFit is a lousy approximation. Cubic interpolation accounts for surface curvature,
% which is especially beneficial when the output grid is coarse in x and y.
%
% * GridFit's "smoothness" parameter was poorly defined and its methodology may have led to bad output data.
% In RegularizeData3D the smoothness parameter is actually the ratio of smoothness (flatness) to
% fidelity (goodness of fit) and is not affected by the resolution of the output grid.
% Smoothness = 100 gives 100 times as much weight to smoothness (and produces a nearly flat output
% surface)
% Smoothness = 1 gives equal weight to smoothness and fidelity (and results in noticeable smoothing)
% Smoothness = 0.01 gives 100 times as much weight to fitting the surface to the scattered input data (and
% results in very little smoothing)
% Smoothness = 0.001 is good for data with low noise. The input points nearly coincide with the output
% surface.
%
% * GridFit didn't do a good job explaining what math it was doing; it just gave usage examples.
%
% For a detailed explanation of "the math behind the magic" on a 3D dataset, see:
% http://mathformeremortals.wordpress.com/2013/07/22/introduction-to-regularizing-3d-data-part-1-of-2/
%
% and to apply the same principles to a 2D dataset see:
% http://mathformeremortals.wordpress.com/2013/01/29/introduction-to-regularizing-with-2d-data-part-1-of-3/
%
% Both of these links include Excel spreadsheets that break down the calculations step by step
% so that you can see how RegularizeData3D works. There are also very limited (and very slow!) Excel
% spreadsheet functions that do the same thing in 2D or 3D.
%
%
% Aside from the above changes, most of the GridFit code is left intact.
% The original GridFit page is:
% http://www.mathworks.com/matlabcentral/fileexchange/8998-surface-fitting-using-gridfit
% usage #1: zgrid = RegularizeData3D(x, y, z, xnodes, ynodes);
% usage #2: [zgrid, xgrid, ygrid] = RegularizeData3D(x, y, z, xnodes, ynodes);
% usage #3: zgrid = RegularizeData3D(x, y, z, xnodes, ynodes, prop, val, prop, val,...);
%
% Arguments: (input)
% x,y,z - vectors of equal lengths, containing arbitrary scattered data
% The only constraint on x and y is they cannot ALL fall on a
% single line in the x-y plane. Replicate points will be treated
% in a least squares sense.
%
% ANY points containing a NaN are ignored in the estimation
%
% xnodes - vector defining the nodes in the grid in the independent
% variable (x). xnodes need not be equally spaced. xnodes
% must completely span the data. If they do not, then the
% 'extend' property is applied, adjusting the first and last
% nodes to be extended as necessary. See below for a complete
% description of the 'extend' property.
%
% If xnodes is a scalar integer, then it specifies the number
% of equally spaced nodes between the min and max of the data.
%
% ynodes - vector defining the nodes in the grid in the independent
% variable (y). ynodes need not be equally spaced.
%
% If ynodes is a scalar integer, then it specifies the number
% of equally spaced nodes between the min and max of the data.
%
% Also see the extend property.
%
% Additional arguments follow in the form of property/value pairs.
% Valid properties are:
% 'smoothness', 'interp', 'solver', 'maxiter'
% 'extend', 'tilesize', 'overlap'
%
% Any UNAMBIGUOUS shortening (even down to a single letter) is
% valid for property names. All properties have default values,
% chosen (I hope) to give a reasonable result out of the box.
%
% 'smoothness' - scalar or vector of length 2 - the ratio of
% smoothness to fidelity of the output surface. This must be a
% positive real number.
%
% A smoothness of 1 gives equal weight to fidelity (goodness of fit)
% and smoothness of the output surface. This results in noticeable
% smoothing. If your input data x,y,z have little or no noise, use
% 0.01 to give smoothness 1% as much weight as goodness of fit.
% 0.1 applies a little bit of smoothing to the output surface.
%
% If this parameter is a vector of length 2, then it defines
% the relative smoothing to be associated with the x and y
% variables. This allows the user to apply a different amount
% of smoothing in the x dimension compared to the y dimension.
%
% DEFAULT: 0.01
%
%
% 'interp' - character, denotes the interpolation scheme used
% to interpolate the data.
%
% DEFAULT: 'triangle'
%
% 'bicubic' - use bicubic interpolation within the grid
% This is the most accurate because it accounts
% for the fact that the output surface is not flat.
% In some cases it may be slower than the other methods.
%
% 'bilinear' - use bilinear interpolation within the grid
%
% 'triangle' - split each cell in the grid into a triangle,
% then apply linear interpolation inside each triangle
%
% 'nearest' - nearest neighbor interpolation. This will
% rarely be a good choice, but I included it
% as an option for completeness.
%
%
% 'solver' - character flag - denotes the solver used for the
% resulting linear system. Different solvers will have
% different solution times depending upon the specific
% problem to be solved. Up to a certain size grid, the
% direct \ solver will often be speedy, until memory
% swaps causes problems.
%
% What solver should you use? Problems with a significant
% amount of extrapolation should avoid lsqr. \ may be
% best numerically for small smoothnesss parameters and
% high extents of extrapolation.
%
% Large numbers of points will slow down the direct
% \, but when applied to the normal equations, \ can be
% quite fast. Since the equations generated by these
% methods will tend to be well conditioned, the normal
% equations are not a bad choice of method to use. Beware
% when a small smoothing parameter is used, since this will
% make the equations less well conditioned.
%
% DEFAULT: 'normal'
%
% '\' - uses matlab's backslash operator to solve the sparse
% system. 'backslash' is an alternate name.
%
% 'symmlq' - uses matlab's iterative symmlq solver
%
% 'lsqr' - uses matlab's iterative lsqr solver
%
% 'normal' - uses \ to solve the normal equations.
%
%
% 'maxiter' - only applies to iterative solvers - defines the
% maximum number of iterations for an iterative solver
%
% DEFAULT: min(10000,length(xnodes)*length(ynodes))
%
%
% 'extend' - character flag - controls whether the first and last
% nodes in each dimension are allowed to be adjusted to
% bound the data, and whether the user will be warned if
% this was deemed necessary to happen.
%
% DEFAULT: 'warning'
%
% 'warning' - Adjust the first and/or last node in
% x or y if the nodes do not FULLY contain
% the data. Issue a warning message to this
% effect, telling the amount of adjustment
% applied.
%
% 'never' - Issue an error message when the nodes do
% not absolutely contain the data.
%
% 'always' - automatically adjust the first and last
% nodes in each dimension if necessary.
% No warning is given when this option is set.
%
%
% 'tilesize' - grids which are simply too large to solve for
% in one single estimation step can be built as a set
% of tiles. For example, a 1000x1000 grid will require
% the estimation of 1e6 unknowns. This is likely to
% require more memory (and time) than you have available.
% But if your data is dense enough, then you can model
% it locally using smaller tiles of the grid.
%
% My recommendation for a reasonable tilesize is
% roughly 100 to 200. Tiles of this size take only
% a few seconds to solve normally, so the entire grid
% can be modeled in a finite amount of time. The minimum
% tilesize can never be less than 3, although even this
% size tile is so small as to be ridiculous.
%
% If your data is so sparse than some tiles contain
% insufficient data to model, then those tiles will
% be left as NaNs.
%
% DEFAULT: inf
%
%
% 'overlap' - Tiles in a grid have some overlap, so they
% can minimize any problems along the edge of a tile.
% In this overlapped region, the grid is built using a
% bi-linear combination of the overlapping tiles.
%
% The overlap is specified as a fraction of the tile
% size, so an overlap of 0.20 means there will be a 20%
% overlap of successive tiles. I do allow a zero overlap,
% but it must be no more than 1/2.
%
% 0 <= overlap <= 0.5
%
% Overlap is ignored if the tilesize is greater than the
% number of nodes in both directions.
%
% DEFAULT: 0.20
%
%
% Arguments: (output)
% zgrid - (nx,ny) array containing the fitted surface
%
% xgrid, ygrid - as returned by meshgrid(xnodes,ynodes)
%
%
% Speed considerations:
% Remember that gridfit must solve a LARGE system of linear
% equations. There will be as many unknowns as the total
% number of nodes in the final lattice. While these equations
% may be sparse, solving a system of 10000 equations may take
% a second or so. Very large problems may benefit from the
% iterative solvers or from tiling.
%
%
% Example usage:
%
% x = rand(100,1);
% y = rand(100,1);
% z = exp(x+2*y);
% xnodes = 0:.1:1;
% ynodes = 0:.1:1;
%
% g = RegularizeData3D(x,y,z,xnodes,ynodes);
%
% Note: this is equivalent to the following call:
%
% g = RegularizeData3D(x,y,z,xnodes,ynodes, ...
% 'smooth',1, ...
% 'interp','triangle', ...
% 'solver','normal', ...
% 'gradient', ...
% 'extend','warning', ...
% 'tilesize',inf);
%
%
% Rereleased with improvements as RegularizeData3D
% 2014
% - Added bicubic interpolation
% - Fixed a bug that caused smoothness to depend on grid fidelity
% - Removed the "regularizer" setting and documented the calculation process
% Original Version:
% Author: John D'Errico
% e-mail address: [email protected]
% Release: 2.0
% Release date: 5/23/06
% set defaults
% The default smoothness is 0.01. i.e. assume the input data x,y,z
% have little or no noise. This is different from the legacy code,
% which used a default of 1.
params.smoothness = 0.01;
params.interp = 'triangle';
params.solver = 'backslash';
params.maxiter = [];
params.extend = 'warning';
params.tilesize = inf;
params.overlap = 0.20;
params.mask = [];
% was the params struct supplied?
if ~isempty(varargin)
if isstruct(varargin{1})
% params is only supplied if its a call from tiled_gridfit
params = varargin{1};
if length(varargin)>1
% check for any overrides
params = parse_pv_pairs(params,varargin{2:end});
end
else
% check for any overrides of the defaults
params = parse_pv_pairs(params,varargin);
end
end
% check the parameters for acceptability
params = check_params(params);
% ensure all of x,y,z,xnodes,ynodes are column vectors,
% also drop any NaN data
x=x(:);
y=y(:);
z=z(:);
k = isnan(x) | isnan(y) | isnan(z);
if any(k)
x(k)=[];
y(k)=[];
z(k)=[];
end
xmin = min(x);
xmax = max(x);
ymin = min(y);
ymax = max(y);
% did they supply a scalar for the nodes?
if length(xnodes)==1
xnodes = linspace(xmin,xmax,xnodes)';
xnodes(end) = xmax; % make sure it hits the max
end
if length(ynodes)==1
ynodes = linspace(ymin,ymax,ynodes)';
ynodes(end) = ymax; % make sure it hits the max
end
xnodes=xnodes(:);
ynodes=ynodes(:);
dx = diff(xnodes);
dy = diff(ynodes);
nx = length(xnodes);
ny = length(ynodes);
ngrid = nx*ny;
% check to see if any tiling is necessary
if (params.tilesize < max(nx,ny))
% split it into smaller tiles. compute zgrid and ygrid
% at the very end if requested
zgrid = tiled_gridfit(x,y,z,xnodes,ynodes,params);
else
% its a single tile.
% mask must be either an empty array, or a boolean
% aray of the same size as the final grid.
nmask = size(params.mask);
if ~isempty(params.mask) && ((nmask(2)~=nx) || (nmask(1)~=ny))
if ((nmask(2)==ny) || (nmask(1)==nx))
error 'Mask array is probably transposed from proper orientation.'
else
error 'Mask array must be the same size as the final grid.'
end
end
if ~isempty(params.mask)
params.maskflag = 1;
else
params.maskflag = 0;
end
% default for maxiter?
if isempty(params.maxiter)
params.maxiter = min(10000,nx*ny);
end
% check lengths of the data
n = length(x);
if (length(y)~=n) || (length(z)~=n)
error 'Data vectors are incompatible in size.'
end
if n<3
error 'Insufficient data for surface estimation.'
end
% verify the nodes are distinct
if any(diff(xnodes)<=0) || any(diff(ynodes)<=0)
error 'xnodes and ynodes must be monotone increasing'
end
% Are there enough output points to form a surface?
% Bicubic interpolation requires a 4x4 output grid. Other types require a 3x3 output grid.
if strcmp(params.interp, 'bicubic')
MinAxisLength = 4;
else
MinAxisLength = 3;
end
if length(xnodes) < MinAxisLength
error(['The output grid''s x axis must have at least ', num2str(MinAxisLength), ' nodes.']);
end
if length(ynodes) < MinAxisLength
error(['The output grid''s y axis must have at least ', num2str(MinAxisLength), ' nodes.']);
end
clear MinAxisLength;
% do we need to tweak the first or last node in x or y?
if xmin<xnodes(1)
switch params.extend
case 'always'
xnodes(1) = xmin;
case 'warning'
warning('GRIDFIT:extend',['xnodes(1) was decreased by: ',num2str(xnodes(1)-xmin),', new node = ',num2str(xmin)])
xnodes(1) = xmin;
case 'never'
error(['Some x (',num2str(xmin),') falls below xnodes(1) by: ',num2str(xnodes(1)-xmin)])
end
end
if xmax>xnodes(end)
switch params.extend
case 'always'
xnodes(end) = xmax;
case 'warning'
warning('GRIDFIT:extend',['xnodes(end) was increased by: ',num2str(xmax-xnodes(end)),', new node = ',num2str(xmax)])
xnodes(end) = xmax;
case 'never'
error(['Some x (',num2str(xmax),') falls above xnodes(end) by: ',num2str(xmax-xnodes(end))])
end
end
if ymin<ynodes(1)
switch params.extend
case 'always'
ynodes(1) = ymin;
case 'warning'
warning('GRIDFIT:extend',['ynodes(1) was decreased by: ',num2str(ynodes(1)-ymin),', new node = ',num2str(ymin)])
ynodes(1) = ymin;
case 'never'
error(['Some y (',num2str(ymin),') falls below ynodes(1) by: ',num2str(ynodes(1)-ymin)])
end
end
if ymax>ynodes(end)
switch params.extend
case 'always'
ynodes(end) = ymax;
case 'warning'
warning('GRIDFIT:extend',['ynodes(end) was increased by: ',num2str(ymax-ynodes(end)),', new node = ',num2str(ymax)])
ynodes(end) = ymax;
case 'never'
error(['Some y (',num2str(ymax),') falls above ynodes(end) by: ',num2str(ymax-ynodes(end))])
end
end
% determine which cell in the array each point lies in
[~, indx] = histc(x,xnodes);
[~, indy] = histc(y,ynodes);
% any point falling at the last node is taken to be
% inside the last cell in x or y.
k=(indx==nx);
indx(k)=indx(k)-1;
k=(indy==ny);
indy(k)=indy(k)-1;
ind = indy + ny*(indx-1);
% Do we have a mask to apply?
if params.maskflag
% if we do, then we need to ensure that every
% cell with at least one data point also has at
% least all of its corners unmasked.
params.mask(ind) = 1;
params.mask(ind+1) = 1;
params.mask(ind+ny) = 1;
params.mask(ind+ny+1) = 1;
end
% interpolation equations for each point
tx = min(1,max(0,(x - xnodes(indx))./dx(indx)));
ty = min(1,max(0,(y - ynodes(indy))./dy(indy)));
% Future enhancement: add cubic interpolant
switch params.interp
case 'triangle'
% linear interpolation inside each triangle
k = (tx > ty);
L = ones(n,1);
L(k) = ny;
t1 = min(tx,ty);
t2 = max(tx,ty);
A = sparse(repmat((1:n)', 1, 3), [ind, ind + ny + 1, ind + L], [1 - t2, t1, t2 - t1], n, ngrid);
case 'nearest'
% nearest neighbor interpolation in a cell
k = round(1-ty) + round(1-tx)*ny;
A = sparse((1:n)',ind+k,ones(n,1),n,ngrid);
case 'bilinear'
% bilinear interpolation in a cell
A = sparse(repmat((1:n)',1,4),[ind,ind+1,ind+ny,ind+ny+1], ...
[(1-tx).*(1-ty), (1-tx).*ty, tx.*(1-ty), tx.*ty], ...
n,ngrid);
case 'bicubic'
% Legacy code calculated the starting index ind for bilinear interpolation, but for bicubic interpolation we need to be further away by one
% row and one column (but not off the grid). Bicubic interpolation involves a 4x4 grid of coefficients, and we want x,y to be right
% in the middle of that 4x4 grid if possible. Use min and max to ensure we won't exceed matrix dimensions.
% The sparse matrix format has each column of the sparse matrix A assigned to a unique output grid point. We need to determine which column
% numbers are assigned to those 16 grid points.
% What are the first indexes (in x and y) for the points?
XIndexes = min(max(1, indx - 1), nx - 3);
YIndexes = min(max(1, indy - 1), ny - 3);
% These are the first indexes of that 4x4 grid of nodes where we are doing the interpolation.
AllColumns = (YIndexes + (XIndexes - 1) * ny)';
% Add in the next three points. This gives us output nodes in the first row (i.e. along the x direction).
AllColumns = [AllColumns; AllColumns + ny; AllColumns + 2 * ny; AllColumns + 3 * ny];
% Add in the next three rows. This gives us 16 total output points for each input point.
AllColumns = [AllColumns; AllColumns + 1; AllColumns + 2; AllColumns + 3];
% Coefficients are calculated based on:
% http://en.wikipedia.org/wiki/Lagrange_interpolation
% Calculate coefficients for this point based on its coordinates as if we were doing cubic interpolation in x.
% Calculate the first coefficients for x and y.
XCoefficients = (x(:) - xnodes(XIndexes(:) + 1)) .* (x(:) - xnodes(XIndexes(:) + 2)) .* (x(:) - xnodes(XIndexes(:) + 3)) ./ ((xnodes(XIndexes(:)) - xnodes(XIndexes(:) + 1)) .* (xnodes(XIndexes(:)) - xnodes(XIndexes(:) + 2)) .* (xnodes(XIndexes(:)) - xnodes(XIndexes(:) + 3)));
YCoefficients = (y(:) - ynodes(YIndexes(:) + 1)) .* (y(:) - ynodes(YIndexes(:) + 2)) .* (y(:) - ynodes(YIndexes(:) + 3)) ./ ((ynodes(YIndexes(:)) - ynodes(YIndexes(:) + 1)) .* (ynodes(YIndexes(:)) - ynodes(YIndexes(:) + 2)) .* (ynodes(YIndexes(:)) - ynodes(YIndexes(:) + 3)));
% Calculate the second coefficients.
XCoefficients = [XCoefficients, (x(:) - xnodes(XIndexes(:))) .* (x(:) - xnodes(XIndexes(:) + 2)) .* (x(:) - xnodes(XIndexes(:) + 3)) ./ ((xnodes(XIndexes(:) + 1) - xnodes(XIndexes(:))) .* (xnodes(XIndexes(:) + 1) - xnodes(XIndexes(:) + 2)) .* (xnodes(XIndexes(:) + 1) - xnodes(XIndexes(:) + 3)))];
YCoefficients = [YCoefficients, (y(:) - ynodes(YIndexes(:))) .* (y(:) - ynodes(YIndexes(:) + 2)) .* (y(:) - ynodes(YIndexes(:) + 3)) ./ ((ynodes(YIndexes(:) + 1) - ynodes(YIndexes(:))) .* (ynodes(YIndexes(:) + 1) - ynodes(YIndexes(:) + 2)) .* (ynodes(YIndexes(:) + 1) - ynodes(YIndexes(:) + 3)))];
% Calculate the third coefficients.
XCoefficients = [XCoefficients, (x(:) - xnodes(XIndexes(:))) .* (x(:) - xnodes(XIndexes(:) + 1)) .* (x(:) - xnodes(XIndexes(:) + 3)) ./ ((xnodes(XIndexes(:) + 2) - xnodes(XIndexes(:))) .* (xnodes(XIndexes(:) + 2) - xnodes(XIndexes(:) + 1)) .* (xnodes(XIndexes(:) + 2) - xnodes(XIndexes(:) + 3)))];
YCoefficients = [YCoefficients, (y(:) - ynodes(YIndexes(:))) .* (y(:) - ynodes(YIndexes(:) + 1)) .* (y(:) - ynodes(YIndexes(:) + 3)) ./ ((ynodes(YIndexes(:) + 2) - ynodes(YIndexes(:))) .* (ynodes(YIndexes(:) + 2) - ynodes(YIndexes(:) + 1)) .* (ynodes(YIndexes(:) + 2) - ynodes(YIndexes(:) + 3)))];
% Calculate the fourth coefficients.
XCoefficients = [XCoefficients, (x(:) - xnodes(XIndexes(:))) .* (x(:) - xnodes(XIndexes(:) + 1)) .* (x(:) - xnodes(XIndexes(:) + 2)) ./ ((xnodes(XIndexes(:) + 3) - xnodes(XIndexes(:))) .* (xnodes(XIndexes(:) + 3) - xnodes(XIndexes(:) + 1)) .* (xnodes(XIndexes(:) + 3) - xnodes(XIndexes(:) + 2)))];
YCoefficients = [YCoefficients, (y(:) - ynodes(YIndexes(:))) .* (y(:) - ynodes(YIndexes(:) + 1)) .* (y(:) - ynodes(YIndexes(:) + 2)) ./ ((ynodes(YIndexes(:) + 3) - ynodes(YIndexes(:))) .* (ynodes(YIndexes(:) + 3) - ynodes(YIndexes(:) + 1)) .* (ynodes(YIndexes(:) + 3) - ynodes(YIndexes(:) + 2)))];
% Allocate space for all of the data we're about to insert.
AllCoefficients = zeros(16, n);
% There may be a clever way to vectorize this, but then the code would be unreadable and difficult to debug or upgrade.
% The matrix solution process will take far longer than this, so it's not worth the effort to vectorize this.
for i = 1 : n
% Multiply the coefficients to accommodate bicubic interpolation. The resulting matrix is a 4x4 of the interpolation coefficients.
TheseCoefficients = repmat(XCoefficients(i, :)', 1, 4) .* repmat(YCoefficients(i, :), 4, 1);
% Add these coefficients to the list.
AllCoefficients(1 : 16, i) = TheseCoefficients(:);
end
% Each input point has 16 interpolation coefficients (because of the 4x4 grid).
AllRows = repmat(1 : n, 16, 1);
% Now that we have all of the indexes and coefficients, we can create the sparse matrix of equality conditions.
A = sparse(AllRows(:), AllColumns(:), AllCoefficients(:), n, ngrid);
end
rhs = z;
% Do we have relative smoothing parameters?
if numel(params.smoothness) == 1
% Nothing special; this is just a scalar quantity that needs to be the same for x and y directions.
xyRelativeStiffness = [1; 1] * params.smoothness;
else
% What the user asked for
xyRelativeStiffness = params.smoothness(:);
end
% Build a regularizer using the second derivative. This used to be called "gradient" even though it uses a second
% derivative, not a first derivative. This is an important distinction because "gradient" implies a horizontal
% surface, which is not correct. The second derivative favors flatness, especially if you use a large smoothness
% constant. Flat and horizontal are two different things, and in this script we are taking an irregular surface and
% flattening it according to the smoothness constant.
% The second-derivative calculation is documented here:
% http://mathformeremortals.wordpress.com/2013/01/12/a-numerical-second-derivative-from-three-points/
% Minimizes the sum of the squares of the second derivatives (wrt x and y) across the grid
[i,j] = meshgrid(1:nx,2:(ny-1));
ind = j(:) + ny*(i(:)-1);
dy1 = dy(j(:)-1);
dy2 = dy(j(:));
Areg = sparse(repmat(ind,1,3),[ind-1,ind,ind+1], ...
xyRelativeStiffness(2)*[-2./(dy1.*(dy1+dy2)), ...
2./(dy1.*dy2), -2./(dy2.*(dy1+dy2))],ngrid,ngrid);
[i,j] = meshgrid(2:(nx-1),1:ny);
ind = j(:) + ny*(i(:)-1);
dx1 = dx(i(:) - 1);
dx2 = dx(i(:));
Areg = [Areg;sparse(repmat(ind,1,3),[ind-ny,ind,ind+ny], ...
xyRelativeStiffness(1)*[-2./(dx1.*(dx1+dx2)), ...
2./(dx1.*dx2), -2./(dx2.*(dx1+dx2))],ngrid,ngrid)];
nreg = size(Areg, 1);
FidelityEquationCount = size(A, 1);
% Number of the second derivative equations in the matrix
RegularizerEquationCount = nx * (ny - 2) + ny * (nx - 2);
% We are minimizing the sum of squared errors, so adjust the magnitude of the squared errors to make second-derivative
% squared errors match the fidelity squared errors. Then multiply by smoothparam.
NewSmoothnessScale = sqrt(FidelityEquationCount / RegularizerEquationCount);
% Second derivatives scale with z exactly because d^2(K*z) / dx^2 = K * d^2(z) / dx^2.
% That means we've taken care of the z axis.
% The square root of the point/derivative ratio takes care of the grid density.
% We also need to take care of the size of the dataset in x and y.
% The scaling up to this point applies to local variation. Local means within a domain of [0, 1] or [10, 11], etc.
% The smoothing behavior needs to work for datasets that are significantly larger or smaller than that.
% For example, if x and y span [0 10,000], smoothing local to [0, 1] is insufficient to influence the behavior of
% the whole surface. For the same reason there would be a problem applying smoothing for [0, 1] to a small surface
% spanning [0, 0.01]. Multiplying the smoothing constant by SurfaceDomainScale compensates for this, producing the
% expected behavior that a smoothing constant of 1 produces noticeable smoothing (when looking at the entire surface
% profile) and that 1% does not produce noticeable smoothing.
SurfaceDomainScale = (max(max(xnodes)) - min(min(xnodes))) * (max(max(ynodes)) - min(min(ynodes)));
NewSmoothnessScale = NewSmoothnessScale * SurfaceDomainScale;
A = [A; Areg * NewSmoothnessScale];
rhs = [rhs;zeros(nreg,1)];
% do we have a mask to apply?
if params.maskflag
unmasked = find(params.mask);
end
% solve the full system, with regularizer attached
switch params.solver
case {'\' 'backslash'}
if params.maskflag
% there is a mask to use
zgrid=nan(ny,nx);
zgrid(unmasked) = A(:,unmasked)\rhs;
else
% no mask
zgrid = reshape(A\rhs,ny,nx);
end
case 'normal'
% The normal equations, solved with \. Can be faster
% for huge numbers of data points, but reasonably
% sized grids. The regularizer makes A well conditioned
% so the normal equations are not a terribly bad thing
% here.
if params.maskflag
% there is a mask to use
Aunmasked = A(:,unmasked);
zgrid=nan(ny,nx);
zgrid(unmasked) = (Aunmasked'*Aunmasked)\(Aunmasked'*rhs);
else
zgrid = reshape((A'*A)\(A'*rhs),ny,nx);
end
case 'symmlq'
% iterative solver - symmlq - requires a symmetric matrix,
% so use it to solve the normal equations. No preconditioner.
tol = abs(max(z)-min(z))*1.e-13;
if params.maskflag
% there is a mask to use
zgrid=nan(ny,nx);
[zgrid(unmasked),flag] = symmlq(A(:,unmasked)'*A(:,unmasked), ...
A(:,unmasked)'*rhs,tol,params.maxiter);
else
[zgrid,flag] = symmlq(A'*A,A'*rhs,tol,params.maxiter);
zgrid = reshape(zgrid,ny,nx);
end
% display a warning if convergence problems
switch flag
case 0
% no problems with convergence
case 1
% SYMMLQ iterated MAXIT times but did not converge.
warning('GRIDFIT:solver',['Symmlq performed ',num2str(params.maxiter), ...
' iterations but did not converge.'])
case 3
% SYMMLQ stagnated, successive iterates were the same
warning('GRIDFIT:solver','Symmlq stagnated without apparent convergence.')
otherwise
warning('GRIDFIT:solver',['One of the scalar quantities calculated in',...
' symmlq was too small or too large to continue computing.'])
end
case 'lsqr'
% iterative solver - lsqr. No preconditioner here.
tol = abs(max(z)-min(z))*1.e-13;
if params.maskflag
% there is a mask to use
zgrid=nan(ny,nx);
[zgrid(unmasked),flag] = lsqr(A(:,unmasked),rhs,tol,params.maxiter);
else
[zgrid,flag] = lsqr(A,rhs,tol,params.maxiter);
zgrid = reshape(zgrid,ny,nx);
end
% display a warning if convergence problems
switch flag
case 0
% no problems with convergence
case 1
% lsqr iterated MAXIT times but did not converge.
warning('GRIDFIT:solver',['Lsqr performed ', ...
num2str(params.maxiter),' iterations but did not converge.'])
case 3
% lsqr stagnated, successive iterates were the same
warning('GRIDFIT:solver','Lsqr stagnated without apparent convergence.')
case 4
warning('GRIDFIT:solver',['One of the scalar quantities calculated in',...
' LSQR was too small or too large to continue computing.'])
end
end % switch params.solver
end % if params.tilesize...
% only generate xgrid and ygrid if requested.
if nargout>1
[xgrid,ygrid]=meshgrid(xnodes,ynodes);
end
% ============================================
% End of main function - gridfit
% ============================================
% ============================================
% subfunction - parse_pv_pairs
% ============================================
function params=parse_pv_pairs(params,pv_pairs)
% parse_pv_pairs: parses sets of property value pairs, allows defaults
% usage: params=parse_pv_pairs(default_params,pv_pairs)
%
% arguments: (input)
% default_params - structure, with one field for every potential
% property/value pair. Each field will contain the default
% value for that property. If no default is supplied for a
% given property, then that field must be empty.
%
% pv_array - cell array of property/value pairs.
% Case is ignored when comparing properties to the list
% of field names. Also, any unambiguous shortening of a
% field/property name is allowed.
%
% arguments: (output)
% params - parameter struct that reflects any updated property/value
% pairs in the pv_array.
%
% Example usage:
% First, set default values for the parameters. Assume we
% have four parameters that we wish to use optionally in
% the function examplefun.
%
% - 'viscosity', which will have a default value of 1
% - 'volume', which will default to 1
% - 'pie' - which will have default value 3.141592653589793
% - 'description' - a text field, left empty by default
%
% The first argument to examplefun is one which will always be
% supplied.
%
% function examplefun(dummyarg1,varargin)
% params.Viscosity = 1;
% params.Volume = 1;
% params.Pie = 3.141592653589793
%
% params.Description = '';
% params=parse_pv_pairs(params,varargin);
% params
%
% Use examplefun, overriding the defaults for 'pie', 'viscosity'
% and 'description'. The 'volume' parameter is left at its default.
%
% examplefun(rand(10),'vis',10,'pie',3,'Description','Hello world')
%
% params =
% Viscosity: 10
% Volume: 1
% Pie: 3
% Description: 'Hello world'
%
% Note that capitalization was ignored, and the property 'viscosity'
% was truncated as supplied. Also note that the order the pairs were
% supplied was arbitrary.
npv = length(pv_pairs);
n = npv/2;
if n~=floor(n)
error 'Property/value pairs must come in PAIRS.'
end
if n<=0
% just return the defaults
return
end
if ~isstruct(params)
error 'No structure for defaults was supplied'
end
% there was at least one pv pair. process any supplied
propnames = fieldnames(params);
lpropnames = lower(propnames);
for i=1:n
p_i = lower(pv_pairs{2*i-1});
v_i = pv_pairs{2*i};
ind = strmatch(p_i,lpropnames,'exact');
if isempty(ind)
ind = find(strncmp(p_i,lpropnames,length(p_i)));
if isempty(ind)
error(['No matching property found for: ',pv_pairs{2*i-1}])
elseif length(ind)>1
error(['Ambiguous property name: ',pv_pairs{2*i-1}])
end
end
p_i = propnames{ind};
% override the corresponding default in params
params = setfield(params,p_i,v_i); %#ok
end
% ============================================
% subfunction - check_params
% ============================================
function params = check_params(params)
% check the parameters for acceptability
% smoothness == 1 by default
if isempty(params.smoothness)
params.smoothness = 1;
else
if (numel(params.smoothness)>2) || any(params.smoothness<=0)
error 'Smoothness must be scalar (or length 2 vector), real, finite, and positive.'
end
end
% interp must be one of:
% 'bicubic', 'bilinear', 'nearest', or 'triangle'
% but accept any shortening thereof.
valid = {'bicubic', 'bilinear', 'nearest', 'triangle'};
if isempty(params.interp)
params.interp = 'bilinear';
end
ind = find(strncmpi(params.interp,valid,length(params.interp)));
if (length(ind)==1)
params.interp = valid{ind};
else
error(['Invalid interpolation method: ',params.interp])
end
% solver must be one of:
% 'backslash', '\', 'symmlq', 'lsqr', or 'normal'
% but accept any shortening thereof.
valid = {'backslash', '\', 'symmlq', 'lsqr', 'normal'};
if isempty(params.solver)
params.solver = '\';
end
ind = find(strncmpi(params.solver,valid,length(params.solver)));
if (length(ind)==1)
params.solver = valid{ind};
else
error(['Invalid solver option: ',params.solver])
end
% extend must be one of:
% 'never', 'warning', 'always'
% but accept any shortening thereof.
valid = {'never', 'warning', 'always'};
if isempty(params.extend)
params.extend = 'warning';
end
ind = find(strncmpi(params.extend,valid,length(params.extend)));
if (length(ind)==1)
params.extend = valid{ind};
else
error(['Invalid extend option: ',params.extend])
end
% tilesize == inf by default
if isempty(params.tilesize)
params.tilesize = inf;
elseif (length(params.tilesize)>1) || (params.tilesize<3)
error 'Tilesize must be scalar and > 0.'
end
% overlap == 0.20 by default
if isempty(params.overlap)
params.overlap = 0.20;
elseif (length(params.overlap)>1) || (params.overlap<0) || (params.overlap>0.5)
error 'Overlap must be scalar and 0 < overlap < 1.'
end
% ============================================
% subfunction - tiled_gridfit
% ============================================
function zgrid=tiled_gridfit(x,y,z,xnodes,ynodes,params)
% tiled_gridfit: a tiled version of gridfit, continuous across tile boundaries
% usage: [zgrid,xgrid,ygrid]=tiled_gridfit(x,y,z,xnodes,ynodes,params)
%
% Tiled_gridfit is used when the total grid is far too large
% to model using a single call to gridfit. While gridfit may take
% only a second or so to build a 100x100 grid, a 2000x2000 grid
% will probably not run at all due to memory problems.
%
% Tiles in the grid with insufficient data (<4 points) will be
% filled with NaNs. Avoid use of too small tiles, especially
% if your data has holes in it that may encompass an entire tile.
%
% A mask may also be applied, in which case tiled_gridfit will
% subdivide the mask into tiles. Note that any boolean mask
% provided is assumed to be the size of the complete grid.
%
% Tiled_gridfit may not be fast on huge grids, but it should run
% as long as you use a reasonable tilesize. 8-)
% Note that we have already verified all parameters in check_params
% Matrix elements in a square tile
tilesize = params.tilesize;
% Size of overlap in terms of matrix elements. Overlaps
% of purely zero cause problems, so force at least two
% elements to overlap.
overlap = max(2,floor(tilesize*params.overlap));
% reset the tilesize for each particular tile to be inf, so
% we will never see a recursive call to tiled_gridfit
Tparams = params;
Tparams.tilesize = inf;
nx = length(xnodes);
ny = length(ynodes);
zgrid = zeros(ny,nx);
% linear ramp for the bilinear interpolation
rampfun = inline('(t-t(1))/(t(end)-t(1))','t');
% loop over each tile in the grid
h = waitbar(0,'Relax and have a cup of JAVA. Its my treat.');
warncount = 0;
xtind = 1:min(nx,tilesize);
while ~isempty(xtind) && (xtind(1)<=nx)
xinterp = ones(1,length(xtind));
if (xtind(1) ~= 1)
xinterp(1:overlap) = rampfun(xnodes(xtind(1:overlap)));
end
if (xtind(end) ~= nx)
xinterp((end-overlap+1):end) = 1-rampfun(xnodes(xtind((end-overlap+1):end)));
end
ytind = 1:min(ny,tilesize);
while ~isempty(ytind) && (ytind(1)<=ny)
% update the waitbar
waitbar((xtind(end)-tilesize)/nx + tilesize*ytind(end)/ny/nx)
yinterp = ones(length(ytind),1);
if (ytind(1) ~= 1)
yinterp(1:overlap) = rampfun(ynodes(ytind(1:overlap)));
end
if (ytind(end) ~= ny)
yinterp((end-overlap+1):end) = 1-rampfun(ynodes(ytind((end-overlap+1):end)));
end
% was a mask supplied?
if ~isempty(params.mask)
submask = params.mask(ytind,xtind);
Tparams.mask = submask;
end
% extract data that lies in this grid tile
k = (x>=xnodes(xtind(1))) & (x<=xnodes(xtind(end))) & ...
(y>=ynodes(ytind(1))) & (y<=ynodes(ytind(end)));
k = find(k);
if length(k)<4
if warncount == 0
warning('GRIDFIT:tiling','A tile was too underpopulated to model. Filled with NaNs.')
end
warncount = warncount + 1;
% fill this part of the grid with NaNs
zgrid(ytind,xtind) = NaN;
else
% build this tile
zgtile = RegularizeData3D(x(k),y(k),z(k),xnodes(xtind),ynodes(ytind),Tparams);
% bilinear interpolation (using an outer product)
interp_coef = yinterp*xinterp;
% accumulate the tile into the complete grid
zgrid(ytind,xtind) = zgrid(ytind,xtind) + zgtile.*interp_coef;
end
% step to the next tile in y
if ytind(end)<ny
ytind = ytind + tilesize - overlap;
% are we within overlap elements of the edge of the grid?
if (ytind(end)+max(3,overlap))>=ny
% extend this tile to the edge
ytind = ytind(1):ny;
end
else
ytind = ny+1;
end
end % while loop over y
% step to the next tile in x
if xtind(end)<nx
xtind = xtind + tilesize - overlap;
% are we within overlap elements of the edge of the grid?
if (xtind(end)+max(3,overlap))>=nx
% extend this tile to the edge
xtind = xtind(1):nx;
end
else
xtind = nx+1;
end
end % while loop over x
% close down the waitbar
close(h)
if warncount>0
warning('GRIDFIT:tiling',[num2str(warncount),' tiles were underpopulated & filled with NaNs'])
end
|
github
|
Hadisalman/stoec-master
|
cem_Elif.m
|
.m
|
stoec-master/code/Include/gpas-master/cem_Elif.m
| 8,782 |
utf_8
|
06bef7b59249a3e3354d8770c6d0e6c5
|
function [x, c, mu, C] = cem(fun, x0, opts, varargin)
% The cross-entropy method
% @param fun function to be minimized
% @param x0 initial guess
% options:
% @param opts.N: number of samples
% @param opts.rho: quantile (e.g. 0.1)
% @param opts.C: initial covariance
% @param opts.iter: total iterations
% @param opts.v: update coefficients
% @param varagin any other arguments that will be passed to fun
%
% @return x best sample
% @return c best cost
% @return mu distribution mean
% @return C distribution covariance
%
% Author: Marin Kobilarov, [email protected]
d = length(x0);
if ~isfield(opts, 'N')
opts.N = d*20;
end
if ~isfield(opts, 'rho')
opts.rho = 0.1;
end
if ~isfield(opts, 'C')
opts.C = eye(d);
end
if ~isfield(opts, 'iter')
fun = 20;
end
if ~isfield(opts, 'v')
opts.v = 1;
end
if ~isfield(opts, 'sigma')
opts.sigma = 0;
end
if opts.sigma
opts.N = 2*d+1;
end
if ~isfield(opts, 'tilt')
opts.tilt = 0;
end
if ~isfield(opts, 'lb')
opts.lb = [];
end
if ~isfield(opts, 'ub')
opts.ub = [];
end
if opts.tilt
end
N = opts.N;
nf = round(opts.rho*N);
C = opts.C;
v = opts.v;
cs = zeros(N, 1);
xs = zeros(d, N);
x = x0;
c = inf;
mu = x0;
a = 0.001;
k = 0;
b = 2;
l = a*a*(d+k)-d;
Ws = [l/(d+l), repmat(1/(2*(d+l)), 1, 2*d)];
Wc = [l/(d+l) + (1-a*a+b), repmat(1/(2*(d+l)), 1, 2*d)];
for j=1:opts.iter
if opts.sigma
% this is an experimental version of the CE method using sigma-points
A = sqrt(d+l)*chol(C)';
xs = [mu, repmat(mu, 1, d) + A, repmat(mu, 1, d) - A];
xm = zeros(d,1);
for i=1:size(xs,2),
fi = fun(xs(:,i), varargin{:});
if (length(fi) > 1)
cs(i) = sum(fi.*fi);
else
cs(i) = fi;
end
cs(i) = exp(-cs(i));
xm = xm + Ws(i)*cs(i)*xs(:,i);
end
Pm = zeros(d,d);
for i=1:size(xs,2),
dx = xs(:,i) - xm;
Pm = Pm + Wc(i)*cs(i)*dx*dx';
end
csn = sum(cs);
mu = mu/csn;
C = Pm/csn;
x = mu;
c = cs(1);
else
% this is the standard CE method using random sampling
if (~isempty(opts.lb))
n = length(mu);
A=[-eye(n);
eye(n)];
B=[-opts.lb;
opts.ub];
xs = rmvnrnd(mu, C, N, A, B)';
else
xs = mvnrnd(mu, C, N)';
end
for i=1:N,
fi = fun(xs(:,i), varargin{:});
if (length(fi) > 1)
cs(i) = sum(fi.*fi)/2;
else
cs(i) = fi;
end
end
if ~opts.tilt
[cs,is] = sort(cs, 1, 'ascend');
xes = xs(:, is(1:nf));
mu = (1 - v).*mu + v.*mean(xes')';
C = (1 - v).*C + v.*cov(xes');% + diag(opts.rf.*rand(opts.n,1));
if (cs(1) < c)
x = xes(:,1);
c = cs(1);
end
else
if (j==1)
S.ps0 = mvnpdf(xs', mu', C);
end
[cmin, imin] = min(cs);
% b = max(1/cmin, .001);
% b = max(1/(max(cs)-min(cs)), .001);
%good one:
b = 1/mean(cs);
% b = max(1/min(cs), .001);
if 0
b = b*(entropy(mu, C));
S.ps = mvnpdf(xs',mu', C);
S.Jh = mean(cs);
S.Js = cs;
bmin = 0;
bmax = 1;
S.xs = xs;
S.v = v;
S.mu = mu;
S.C = C;
bs = bmin:.001:bmax;
gs = zeros(size(bs));
for l=1:length(bs)
gs(l) = minb3(bs(l), S);
end
plot(bs, gs,'g');
drawnow
gs
[gm,bi]=min(gs);
b=bs(bi)
[b,FVAL,EXITFLAG,OUTPUT] = fminbnd(@(b) minb3(b, S), bmin, bmax)
keyboard
global ws
end
% kl = sum(-log(ws))/N
% b = b*kl;
% b = 1;
ws = exp(-b*cs);
ws = ws/sum(ws);
mu = (1 - v).*mu + v.*(xs*ws);
C = (1 - v).*C + v.*weightedcov(xs', ws);
if (cmin < c)
x = xs(:,imin);
c = cmin;
end
end
end
end
function f = minb(b, S)
b
N = length(S.Js);
ws = exp(-b*S.Js);
eta = sum(ws)/N;
delta = .1;
g = sqrt(log(1/delta)/(2*N));
ws = ws/sum(ws);
mu = (1 - S.v).*S.mu + S.v.*(S.xs*ws);
C = (1 - S.v).*S.C + S.v.*weightedcov(S.xs', ws);
C
vs = 1/eta*ws.*(-log(eta)*ones(N,1) - b*S.Js + log(S.ps) ...
- log(mvnpdf(S.xs', mu', C)));
R = max(vs)-min(vs)
f = sum(vs)/N + R*g;
function f = minb2(b, S)
N = length(S.Js);
ws = exp(-b*S.Js);
eta = sum(ws)/N;
delta = .1;
g = sqrt(log(1/delta)/(2*N));
ws = ws/sum(ws);
mu = (1 - S.v).*S.mu + S.v.*(S.xs*ws);
C = (1 - S.v).*S.C + S.v.*weightedcov(S.xs', ws);
mu
C
Ws = S.ps0./mvnpdf(S.xs', mu', C);
Ws
vs = exp(-2*b*S.Js).*Ws;
R = max(vs);
f = sum(vs)/N + R*g;
function f = minb3(b, S)
N = length(S.Js);
Jmin = min(S.Js)
Jmax = max(S.Js)
ws = exp(-b*S.Js/Jmax);
delta = .5;
g = sqrt(log(1/delta)/(2*N))
mean(ws) - exp(-b*Jmin/Jmax)*g
b*(mean(S.Js)/Jmax - g)
f = log(mean(ws) - exp(-b*Jmin/Jmax)*g) + b*(mean(S.Js)/Jmax - g);
f
f = -f;
function C = weightedcov(Y, w)
% Weighted Covariance Matrix
%
% WEIGHTEDCOV returns a symmetric matrix C of weighted covariances
% calculated from an input T-by-N matrix Y whose rows are
% observations and whose columns are variables and an input T-by-1 vector
% w of weights for the observations. This function may be a valid
% alternative to COV if observations are not all equally relevant
% and need to be weighted according to some theoretical hypothesis or
% knowledge.
%
% C = WEIGHTEDCOV(Y, w) returns a positive semidefinite matrix C, i.e. all its
% eigenvalues are non-negative.
%
% If w = ones(size(Y, 1), 1), no difference exists between
% WEIGHTEDCOV(Y, w) and COV(Y, 1).
%
% REFERENCE: mathematical formulas in matrix notation are available in
% F. Pozzi, T. Di Matteo, T. Aste,
% "Exponential smoothing weighted correlations",
% The European Physical Journal B, Volume 85, Issue 6, 2012.
% DOI:10.1140/epjb/e2012-20697-x.
%
% % ======================================================================
% % EXAMPLE
% % ======================================================================
%
% % GENERATE CORRELATED STOCHASTIC PROCESSES
% T = 100; % number of observations
% N = 500; % number of variables
% Y = randn(T, N); % shocks from standardized normal distribution
% Y = cumsum(Y); % correlated stochastic processes
%
% % CHOOSE EXPONENTIAL WEIGHTS
% alpha = 2 / T;
% w0 = 1 / sum(exp(((1:T) - T) * alpha));
% w = w0 * exp(((1:T) - T) * alpha); % weights: exponential decay
%
% % COMPUTE WEIGHTED COVARIANCE MATRIX
% c = weightedcov(Y, w); % Weighted Covariance Matrix
%
% % ======================================================================
%
% See also CORRCOEF, COV, STD, MEAN.
% Check also WEIGHTEDCORRS (FE 20846) and KENDALLTAU (FE 27361)
%
% % ======================================================================
%
% Author: Francesco Pozzi
% E-mail: [email protected]
% Date: 15 June 2012
%
% % ======================================================================
%
% Check input
ctrl = isvector(w) & isreal(w) & ~any(isnan(w)) & ~any(isinf(w));
if ctrl
w = w(:) / sum(w); % w is column vector
else
error('Check w: it needs be a vector of real positive numbers with no infinite or nan values!')
end
ctrl = isreal(Y) & ~any(isnan(Y)) & ~any(isinf(Y)) & (size(size(Y), 2) == 2);
if ~ctrl
error('Check Y: it needs be a 2D matrix of real numbers with no infinite or nan values!')
end
ctrl = length(w) == size(Y, 1);
if ~ctrl
error('size(Y, 1) has to be equal to length(w)!')
end
[T, N] = size(Y); % T: number of observations; N: number of variables
C = Y - repmat(w' * Y, T, 1); % Remove mean (which is, also, weighted)
C = C' * (C .* repmat(w, 1, N)); % Weighted Covariance Matrix
C = 0.5 * (C + C'); % Must be exactly symmetric
function f = kl(q,p)
f = q.*log(q./p) + (1-q).*log((1-q)./(1-p));
function f = normkl(mu0, S0, mu1, S1)
Si = inv(S1);
f = (trace(Si*S0) + (mu1 - mu0)'*Si*(mu1 - mu0) - log(det(S0)/det(S1)) ...
- length(mu0))/2;
function f = entropy(mu, S)
k=length(mu);
f = k/2*(1+log(2*pi)) + log(det(S))/2;
|
github
|
Hadisalman/stoec-master
|
gp_opt.m
|
.m
|
stoec-master/code/Include/gpas-master/gp_opt.m
| 1,040 |
utf_8
|
73bfd9ba07253327064d9f410c151b93
|
function f = gp_opt(fun, sample, N)
if f < gp.fmin
gp.fmin = f;
gp.xmin = x;
end
gp = gp_add(gp, x, f);
global S
% S.N - number of initial samples
% initial samples
S.xs = feval(sample, S.N0);
%S.xs = [-.2 0 .2 .21 .4];
S.fs = feval(fun, S.xs);
% test points
S.xss = feval(sample, S.Nmax);
S.fss = feval(fun, S.xss);
gp_train;
% optimize hyperparams
%[p,FVAL,EXITFLAG,OUTPUT] = fminsearch(@gp_minhp, [S.l, S.s])
%S.l = p(1);
%S.s = p(2);
if 0
xts = [-2:.01:2];
[S.ms, S.ss] = gp_predict(xts);
vs = sqrt(diag(S.ss));
plot(xts, S.ms + vs, '--', xts, S.ms - vs, '--', xts, S.ms, '-');
hold on
plot(S.xs, S.fs, 'o')
pause(0)
end
fmin = inf;
xmin = [];
for i=1:N
% [S.ms, S.ss] = gp_predict(S.xss(1));
% return
[S.ms, S.ss] = gp_predict(S.xss);
J = S.ms - 1.96*sqrt(diag(S.ss));
[y, i] = min(J);
x = S.xss(:,i);
f = feval(fun, x);
if f < fmin
fmin = f;
xmin = x;
end
fmin
xmin
gp_add(x, f);
end
function f = gp_minhp(p)
global S
S.l = p(1);
S.s = p(2);
gp_train;
f = -S.lp;
|
github
|
Hadisalman/stoec-master
|
gp_test2.m
|
.m
|
stoec-master/code/Include/gpas-master/gp_test2.m
| 4,172 |
utf_8
|
5b42ddc0709d4b8772ea78ee0a05c916
|
function f = gp_test2
% An example of path planning b/n two given states around an
% obstacle and learning the optimal waypoint the system
% should pass through
clear
N0 = 25;
opt.figs(1) = figure;
opt.figs(2) = figure;
opt.figs(3) = figure;
opt.figs(4) = figure;
opt.dr = .2;
opt.xi = [-2.5; -2.5];
opt.xf = [2.5; 2.5];
opt.xr = -2.5:opt.dr:2.5;
opt.yr = -2.5:opt.dr:2.5;
opt.o = [0;0];
opt.r = .8;
opt.xmin = [];
opt.fmin = [];
opt.J = [];
opt.cP = [];
opt.fP = [];
opt.sel = 'pi';
opt.snf = 20;
[X,Y] = meshgrid(opt.xr, opt.yr);
xss = [reshape(X, 1, size(X,1)*size(X,2));
reshape(Y, 1, size(Y,1)*size(Y,2))];
p = randperm(size(xss,2));
% initial data
cxs = xss(:,p(1:N0));
%xss = xss(sort(p(N0+1:end)));
cs = zeros(1,size(cxs,2));
for i=1:size(cxs,2),
cs(i) = con(cxs(:,i),opt);
end
xs = cxs(:,find(cs > 0));
fs = zeros(1,size(xs,2));
for i=1:size(xs,2),
fs(i) = fun(xs(:,i),opt);
end
% cost function gp
fopts.l = 1;
fopts.s = 1;
fopts.sigma = .1;
fgp = gp_init(xs, fs, fopts)
fgp.fun = @fun;
% constraints gp
copts.l = 1;
copts.s = 1;
copts.sigma = .1;
cgp = gp_init(cxs, cs, copts)
cgp.fun = @con;
% test points
%Nmax = 500;
% init opt
[y,ind] = min(fs);
opt.xmin = fgp.xs(:,ind);
opt.fmin = y;
opt.xss = xss;
opt.fgp = fgp;
opt.cgp = cgp;
N = 50;
%plot(S.xss, S.fss, '.b')
%ofig = figure
gp_plot2(opt)
xfig = figure
plot_env(opt)
for i=1:3,
[opt, x, y] = gp_select(opt)
% if (abs(x-cgp.xs)<.005)
% continue;
% end
if ~isempty(cgp)
c = con(x, opt);
opt.cgp = gp_add(opt.cgp, x, c);
if (c < 0)
% figure(ofig)
gp_plot2(opt)
% plot(x,c,'xb')
pause(3)
continue
end
end
f = fun(x,opt);
if f < opt.fmin
opt.fmin = f;
opt.xmin = x;
end
opt.fgp = gp_add(opt.fgp, x, f);
% cgp = cgp_add(cgp, x, c);
display('opt:')
opt.xmin
% figure(ofig)
gp_plot2(opt)
figure(xfig)
plot_env(opt)
print(gcf,'-dpng', 'figures/env.png')
% plot(x,f,'ob')
pause(3)
% S.xmin
% S.fmin
end
%plot(S.xss, S.ms, '.r')
function f = fun(xs, opt)
xi = [-2.5; -2.5];
xf = [2.5; 2.5];
xsa = [xi, xs];
xsb = [xs, xf];
dxs = xsb - xsa;
f = sum(sqrt(sum(dxs.*dxs, 1)));
function xs = sample(N, opt)
xs = 2.5 - 5*rand([2, N]);
function cmin = con(xs, opt)
o = opt.o
r = opt.r;
kin = 0
if ~kin,
xs = [opt.xi, xs, opt.xf];
xs = interp1(linspace(0, 1, size(xs,2)), xs', ...
linspace(0, 1, opt.snf), 'cubic')';
xsa = xs(:,1:end-1);
xsb = xs(:,2:end);
else
xsa = [opt.xi, xs];
xsb = [xs, opt.xf];
end
dxs = xsb - xsa;
cmin = inf;
for i=1:size(xsa,2)
xa = xsa(:,i);
dx = dxs(:,i);
a = dx/norm(dx);
b = o - xa;
d = b'*a;
if d > 0
c = norm(d*a - b) - r;
else
c = norm(xa - o) - r;
end
if c < cmin
cmin = c;
end
end
function f = plot_env(opt)
o = opt.o;
r = opt.r;
a = 0:.1:2*pi;
hold off
%plot(o(1) + cos(a)*r, o(2) + sin(a)*r, '-k', 'LineWidth',3);
[Xs,Ys,Zs] = cylinder2P([r, r], 50, [o;0]', [o;.4]');
%[Xs,Ys,Zs] = sphere;
%Zs = .1*Zs;
%Xs = r*Xs + o(1)*ones(size(Xs));
%Ys = r*Ys + o(2)*ones(size(Ys));
hs = surf(Xs, Ys, Zs);
set(hs,'FaceAlpha',1);
%set(hs,'EdgeColor','none', ...
% 'FaceColor','r', ...
% 'FaceLighting','phong', ...
% 'AmbientStrength',0.3, ...
% 'DiffuseStrength',0.8, ...
% 'SpecularStrength',0.9, ...
% 'SpecularExponent',25, ...
% 'BackFaceLighting','lit');
hold on
if ~isempty(opt.xmin)
xs = [opt.xi, opt.xmin, opt.xf];
xs = interp1(linspace(0, 1, size(xs,2)), xs', ...
linspace(0, 1, opt.snf), 'cubic')';
plot3(opt.xmin(1), opt.xmin(2), 0, '*','MarkerSize', 6, 'LineWidth',5)
plot3(xs(1,:), xs(2,:), zeros(size(xs,2),1), '-g', 'LineWidth',5);
end
for i=1:size(opt.fgp.xs,2)
xs = [opt.xi, opt.fgp.xs(:,i), opt.xf];
xs = interp1(linspace(0, 1, size(xs,2)), xs', ...
linspace(0, 1, opt.snf), 'cubic')';
plot3(opt.fgp.xs(1,i), opt.fgp.xs(2,i), zeros(size(xs,2),1), ...
'o','MarkerSize',5, 'LineWidth',2);
plot3(xs(1,:), xs(2,:), zeros(size(xs,2),1), '--', 'LineWidth',2);
end
axis square
axis equal
view(-20,48)
%view(3)
|
github
|
Hadisalman/stoec-master
|
odom_node.m
|
.m
|
stoec-master/code/Include/gpas-master/odom_node.m
| 1,232 |
utf_8
|
cff6ebe13248643b3777d386676740a3
|
function S = odom_node(S)
% Simulate odometry data ROS node, by waiting for
% commanded path and taking the next pose along the path
%
%
rosshutdown
if isfield(S, 'ROS_MASTER_URI')
setenv('ROS_MASTER_URI', S.ROS_MASTER_URI)
end
if isfield(S, 'ROS_IP')
setenv('ROS_IP', S.ROS_IP)
end
rosinit
% published odometry every at every vehicle simulation step
S.odomPub = rospublisher('/insekf/pose', rostype.nav_msgs_Odometry)
S.odomMsg = rosmessage(S.odomPub)
pause(1)
% subscriber
cmdSub = rossubscriber('/adp_path', rostype.nav_msgs_Path, {@cmdCallback, S})
% start
startPub = rospublisher('/adp_start', rostype.std_msgs_Bool);
startMsg = rosmessage(startPub);
startMsg.Data = 1;
send(startPub, startMsg);
% simulate initial point
S.odomMsg.Pose.Pose.Position.X = 25;
S.odomMsg.Pose.Pose.Position.Y = 25;
S.odomMsg.Pose.Pose.Orientation.Z = 1.1*pi;
send(S.odomPub, S.odomMsg)
while(1)
pause(1)
end
function f = cmdCallback(src, msg, S)
% take the next pose along path
S.odomMsg.Pose.Pose = msg.Poses(1).Pose;
send(S.odomPub, S.odomMsg)
x = [S.odomMsg.Pose.Pose.Position.X;
S.odomMsg.Pose.Pose.Position.Y;
S.odomMsg.Pose.Pose.Position.Z];
disp(['cmdCallback: sent odom=' num2str(x(1)) ',' num2str(x(2))]);
|
github
|
Hadisalman/stoec-master
|
srec.m
|
.m
|
stoec-master/code/Include/gpas-master/srec.m
| 11,940 |
utf_8
|
ec8b6e621cd73fe47ca200a75dc4ce8e
|
function f = srec
%Demonstration of Receding Horizon Adaptive Sampling for
%discovering peak concentration in a 2d scalar field
clear
N0 = 25;
if 0
opt.figs(1) = figure;
opt.figs(2) = figure;
opt.figs(3) = figure;
opt.figs(4) = figure;
else
opt.figs = [];
end
opt.dr = 5;
%opt.xi = [-45; -45; pi/4];
opt.xi = [25; 25; 1.1*pi];
opt.xr = -50:opt.dr:50;
opt.yr = -50:opt.dr:50;
opt.xlb = min(opt.xr);
opt.xub = max(opt.xr);
opt.ylb = min(opt.yr);
opt.yub = max(opt.yr);
opt.xmin = [];
opt.fmin = [];
opt.J = [];
opt.cP = [];
opt.fP = [];
opt.sel = 'pi';
opt.sn = 5;
opt.dt = 3;
opt.tf = 30;
opt.I=[];
%opt.I = double(imread('conc.ppm'))/255;
%opt.I = double(imread('do1.ppm'))/255;
opt.I = 1.5*double(imread('do1.ppm'))/255;
%opt.I =;
%size(I)
%I(250,250,:)
%return
[X,Y] = meshgrid(opt.xr, opt.yr);
% list of grid points
xss = [reshape(X, 1, size(X,1)*size(X,2));
reshape(Y, 1, size(Y,1)*size(Y,2))];
opt.fs = fun(xss,opt);
p = randperm(size(xss,2));
opt.pss = prior(xss, opt);
% initial data
%xs = xss(:,p(1:N0));
%xs = [.2, .1, .2, .1;
% .1, -.3, .3, -.3];
%xs = [.2, .5, .6, .9;
% .3, -.4, .3, -.3];
xs=opt.xi(1:2);
%xs = [1, 1, -1, -1;
% 1, -1, 1, -1];
%xs = repmat(opt.xi(1:2), 1, 5) + .1*randn(2,5);
%xss = xss(sort(p(N0+1:end)));
fs = zeros(1,size(xs,2));
for i=1:size(xs,2),
fs(i) = fun(xs(:,i),opt)
end
% cost function gp
fopts.l = 5;
if ~isempty(opt.I)
fopts.s = .4;
fopts.sigma = .001;
else
fopts.s = 20;
fopts.sigma = .01;
end
fgp = gp_init(xs, fs, fopts)
fgp.fun = @fun;
% test points
%Nmax = 500;
% init opt
[y,ind] = min(fs);
opt.xmin = fgp.xs(:,ind);
opt.fmin = y;
opt.xss = xss;
opt.fgp = fgp;
N = 50;
%plot(S.xss, S.fss, '.b')
%ofig = figure
gp_plot(opt)
%xfig = figure
%plot_env(opt)
% forward velocity lower bound
vlb = .1;
% forward velocity upper bound
vub = 5;
% angular velocity lower bound
wlb = -.5;
% angular velocity upper bound
wub = .5;
%z = zeros(2*opt.sn, 1);
z0 = repmat([3; 0], opt.sn,1);
z=z0;
zlb = repmat([vlb;wlb], opt.sn,1);
zub = repmat([vub;wub], opt.sn,1);
xs = traj(z0,opt);
f = traj_cost(z0,opt)
%[z,fval,exitflag,output] = fmincon(@(z)traj_cost(z,opt), z, [], [],[],[],zlb,zub);
xs = traj(z,opt)
opts.v = .8;
opts.iter = 2;
opts.N = 100;
opts.sigma = 0;
iters = 10;
mu = z;
if ~isempty(opt.I)
C0 = diag(repmat([1;1],opt.sn,1));
else
C0 = diag(repmat([1;.4],opt.sn,1));
end
cs = zeros(iters,1);
opts.C = C0;
opts.lb = zlb;
opts.ub = zub;
% traveled path
xps=opt.xi;
video =0;
mov = 0;
if video,
mov = VideoWriter('as.avi');
open(mov);
% mov = avifile('as.avi');
% mov.Quality = 100;
% mov.fps = 2*iters;
end
j=1;
for k=1:500
%% PLANNING
opts.C = .5*opts.C + .5*C0;
subplot(2,2,1);
Gp= draw_path(traj(z,opt), 0, 'r',2,5);
z = z0;
for i=1:iters
[z, c, mu, C] = cem(@traj_cost, z, opts, opt);
x = mu;
cs(i) = c;
opts.C = C;
xs = traj(z,opt);
set(Gp,'XData', xs(1,:));
set(Gp,'YData', xs(2,:));
drawnow
if video,
saveas(gcf,['as/as' num2str(j,'%03d') '.jpg'])
j=j+1;
% saveas(gca,['se2opt/v' num2str(c) '.eps'],'psc2');
% mov = addframe(mov,getframe(gca));
% writeVideo(mov,getframe);
% print(gcf,'-dpng', 'figures/env.png')
end
end
% "EXECUTE" START OF PATH
x = xs(:,2);
opt.xi = x;
% GET MEASUREMENT AND ADD TO GP
xps = [xps, x];
opt.fgp = gp_add(opt.fgp, x(1:2), fun(x(1:2), opt));
% fun(x(1:2),opt);
hold off
gp_plot(opt)
hold on
subplot(2,2,1)
draw_path(xs(1:2,2:end), 0, 'b',3, 5);
hold on
draw_path(xps(1:2,:), 0, 'g',3, 5);
xlabel('m')
ylabel('m')
drawnow
subplot(2,2,3)
hold off
contour(opt.xr, opt.yr, reshape(opt.pss, length(opt.xr), ...
length(opt.yr)));
%h = contour(opt.xr, opt.yr, reshape(ms, length(opt.xr), ...
% length(opt.yr)));
hold on
draw_path(xs(1:2,2:end), 0, 'b',2, 5);
draw_path(xps(1:2,:), 0, 'g',3, 5);
axis square
axis equal
axis([min(opt.xr),max(opt.xr),min(opt.yr),max(opt.yr)] )
title('Executed (green) and Planned (blue) paths; with prior contours')
xlabel('m')
ylabel('m')
end
if video,
close(mov);
end
return
for i=1:60,
[opt, x, y] = gp_select(opt)
% if (abs(x-cgp.xs)<.005)
% continue;
% end
f = fun(x, opt);
if f < opt.fmin
opt.fmin = f;
opt.xmin = x;
end
opt.fgp = gp_add(opt.fgp, x, f);
% cgp = cgp_add(cgp, x, c);
display('opt:')
opt.xmin
% figure(ofig)
gp_plot2(opt)
figure(xfig)
plot_env(opt)
print(gcf,'-dpng', 'figures/env.png')
% plot(x,f,'ob')
% pause(3)
% S.xmin
% S.fmin
end
%plot(S.xss, S.ms, '.r')
function G = draw_path(xs, z, c, lw, ms)
G=plot3(xs(1,:), xs(2,:), z*ones(size(xs,2),1), [c '-'], ...
'LineWidth', lw, 'MarkerSize', ms);
function f = fun(xs, opt)
if ~isempty(opt.I)
xr = opt.xub-opt.xlb;
yr = opt.yub-opt.ylb;
is = floor((opt.yub - xs(2,:))/yr*size(opt.I,2)) + 1;
js = floor((xs(1,:)-opt.xlb)/xr*size(opt.I,1)) + 1;
is(find(is>size(opt.I,1)))=size(opt.I,2);
js(find(js>size(opt.I,2)))=size(opt.I,2);
is(find(is<1))=1;
js(find(js<1))=1;
for i=1:size(xs,2)
f(i)= opt.I(is(i),js(i),1);
end
return
end
%mvnpdf([0, 0], [0, 0], diag([.05, .1]))
f = 100000*mvnpdf(xs', [0, 0], diag([400, 400]));
f = f + 20000*mvnpdf(xs', [20, 20], diag([50, 100]));
f = f + randn(size(f))*.04;
function f = prior(xs, opt)
%mvnpdf([0, 0], [0, 0], diag([.05, .1]))
if ~isempty(opt.I)
f = mvnpdf(xs', [0, 0], diag([1000, 1000]));
else
f = mvnpdf(xs', [0, 0], diag([1000, 1000]));
end
f = f/max(f);
function xs = sample(N, opt)
xs = 2.5 - 5*rand([2, N]);
function xs = traj(z, opt)
tl = opt.tf/opt.sn;
xs = zeros(3, 1);
xs = opt.xi;
for i=1:opt.sn,
v = z(2*(i-1) + 1);
w = z(2*(i-1) + 2);
th = xs(3,end);
t = opt.dt:opt.dt:tl;
if (abs(w) < 1e-10)
xs = [xs(1,:), xs(1,end) + t*v*cos(th);
xs(2,:), xs(2,end) + t*v*sin(th);
xs(3,:), xs(3,end) + t*0];
else
xs = [xs(1,:), xs(1,end) + v/w*(sin(th + t*w) - sin(th));
xs(2,:), xs(2,end) + v/w*(-cos(th + t*w) + cos(th));
xs(3,:), xs(3,end) + t*w];
end
end
function xs = traj2(z, opt)
dt = opt.tf/opt.sn;
xs = zeros(3, opt.sn+1);
xs(:,1) = opt.xi;
for i=1:opt.sn,
v = z(2*(i-1) + 1);
w = z(2*(i-1) + 2);
th = xs(3,i);
if (abs(w) < 1e-10)
xs(:,i+1) = xs(:,i) + dt*[v*cos(th);
v*sin(th);
0];
else
xs(:,i+1) = xs(:,i) + [v/w*(sin(th + dt*w) - sin(th));
v/w*(-cos(th + dt*w) + cos(th));
dt*w];
end
end
function f = traj_cost(z, opt)
%gp = opt.fgp;
xs = traj(z, opt);
[ms, ss] = gp_predict(opt.fgp, xs(1:2,2:end));
vs = sqrt(diag(ss));
ps = prior(xs(1:2,2:end), opt);
%ps = ones(size(ps));
if ~isempty(opt.I)
f = -sum(ps.*(ms + 1.96*vs));
f = -sum(ms + 1.96*vs);
% f = -sum(ms);
else
% f = -sum(ps.*(ms + 1.96*vs));
%f = sum(ps.*(1.96*vs)) - sum(ps);
f = -sum(vs) - sum(ps);
end
%f = sum(ps.*(ms));
%f = -sum(ps.*vs);
vs = z(1:2:end-1);
ws = z(2:2:end);
dws = ws(2:end)-ws(1:end-1);
%f = f*(1 + .01*ws'*ws);% + .5*dws'*dws);
%f = f + .001*vs'*vs;
%f = mean(ms);
%fs = fun(xs, opt);
%for i=1:size(xs,2)%
% gp = gp_add(gp, xs(:,i),
%end
function f = plot_env(opt)
return
if ~isempty(opt.xmin)
xs = [opt.xi, opt.xmin];
xs = interp1(linspace(0, 1, size(xs,2)), xs', ...
linspace(0, 1, opt.snf), 'cubic')';
plot3(opt.xmin(1), opt.xmin(2), 0, '*','MarkerSize', 2, 'LineWidth',5)
plot3(xs(1,:), xs(2,:), zeros(size(xs,2),1), '-g', 'LineWidth',5);
end
for i=1:size(opt.fgp.xs,2)
% xs = [opt.xi, opt.fgp.xs(:,i), opt.xf];
% xs = interp1(linspace(0, 1, size(xs,2)), xs', ...
% linspace(0, 1, opt.snf), 'cubic')';
plot3(opt.fgp.xs(1,i), opt.fgp.xs(2,i), zeros(size(opt.fgp.xs,2),1), ...
'o','MarkerSize',5, 'LineWidth',2);
% plot3(xs(1,:), xs(2,:), zeros(size(xs,2),1), '--', 'LineWidth',2);
end
axis square
%axis equal
view(-20,48)
%view(3)
function f = gp_plot(opt)
set(0,'DefaultAxesFontName', 'Times New Roman')
set(0,'DefaultAxesFontSize', 15)
set(0,'DefaultTextFontname', 'Times New Roman')
set(0,'DefaultTextFontSize', 15)
if (~isempty(opt.figs))
figure(opt.figs(1));
set(opt.figs(1), 'Position', [100, 100, 800, 600]);
else
sp = subplot(2,2,1);
set(gcf, 'Position', [100, 100, 1400, 800]);
end
[ms, ss] = gp_predict(opt.fgp, opt.xss);
vs = sqrt(diag(ss));
h = surf(opt.xr, opt.yr, reshape(ms, length(opt.xr), length(opt.yr)), ...
'FaceColor','interp','FaceLighting','phong');
hold on
h1 = surf(opt.xr, opt.yr, reshape(ms + 1.96*vs, length(opt.xr), length(opt.yr)), ...
'FaceColor','interp','FaceLighting','phong','EdgeAlpha',.3);
%set(h,'FaceAlpha',0);
h2 = surf(opt.xr, opt.yr, reshape(ms - 1.96*vs, length(opt.xr), length(opt.yr)), ...
'FaceColor','interp','FaceLighting','phong','EdgeAlpha',.3);
%set(h,'FaceAlpha',0);
xlabel('m')
ylabel('m')
alpha(h,.8)
alpha(h1,.3)
alpha(h2,.3)
%xlabel('$x_1$','Interpreter','latex')
%%ylabel('$x_2$','Interpreter','latex')
%zlabel('$\mathbb{E}[J(x)] \pm \beta Var[J(x)]$', 'Interpreter', 'latex')
view(-20,48)
axis tight
%axis equal
title('Guassin Process Model (+-95% conf.)')
drawnow
%print(gcf,'-dpng', 'figures/Jx.png')
%savesp(sp, 'figures/Jx');
%plot(xts, ms + 1.96*vs, '--', xts, ms - 1.96*vs, '--', xts, ms, '-');
%hold on
%plot3(opt.fgp.xs(1,:), opt.fgp.xs(2,:), opt.fgp.fs, 'or');
%title('Probabilistic Model of Trajectory Cost $J(x)$')
if (~isempty(opt.figs))
figure(opt.figs(2));
set(opt.figs(2), 'Position', [100, 100, 800, 600]);
else
sp = subplot(2,2,2);
end
cns = 1;
hold off
if ~isempty(opt.fs)
if cns
h = contour(opt.xr, opt.yr, reshape(opt.fs, length(opt.xr), ...
length(opt.yr)));
hold on
plot(opt.fgp.xs(1,:), opt.fgp.xs(2,:), '-g','LineWidth',2);
else
h = surfc(opt.xr, opt.yr, reshape(opt.fs, length(opt.xr), length(opt.yr)),...
'FaceColor','interp','FaceLighting','phong','EdgeAlpha',.3);
set(h,'FaceAlpha',0.7);
view(-20,48)
end
axis tight
% axis equal
% plot(gp.xss, gp.J, 'b')
hold on
end
title('True Scalar Field')
xlabel('m')
ylabel('m')
if (~isempty(opt.figs))
figure(opt.figs(3));
set(opt.figs(3), 'Position', [100, 100, 800, 600]);
else
sp = subplot(2,2,4);
end
hold off
if cns
h = contour(opt.xr, opt.yr, reshape(ms, length(opt.xr), ...
length(opt.yr)));
hold on
plot(opt.fgp.xs(1,:), opt.fgp.xs(2,:), 'ok-');
else
h = surf(opt.xr, opt.yr, reshape(ms, length(opt.xr), length(opt.yr)), ...
'FaceColor','interp','FaceLighting','phong');
%alpha(h,.5)
set(h,'FaceAlpha',0.5);
% plot(gp.xss, gp.J, 'b')
hold on
plot3(opt.fgp.xs(1,:), opt.fgp.xs(2,:), opt.fgp.fs(:),'*');
view(-20,48)
end
axis tight
%axis equal
xlabel('m')
ylabel('m')
title('Estimated scalar Field (with marked samples)')
%title('States Sampling Distribution')
%xlabel('$x_1$','Interpreter','latex')
%ylabel('$x_2$','Interpreter','latex')
%zlabel('$P(x)$', 'Interpreter', 'latex')
%print(gcf,'-dpng', 'figures/Px.png')
%savesp(sp, 'figures/Px');
if (~isempty(opt.figs))
figure(opt.figs(4));
set(opt.figs(4), 'Position', [100, 100, 800, 600]);
else
% sp = subplot(2,2,3);
end
hold off
if ~isempty(opt.cP)
h = surfc(opt.xr, opt.yr, reshape(opt.cP, length(opt.xr), length(opt.yr)),...
'FaceColor','interp','FaceLighting','phong');
% set(h,'FaceAlpha',0);
view(-20,48)
axis tight
%axis equal
hold on
end
%title('Constraint Satisfaction Probability')
%zlabel('$P(g(x)\geq 0)$', 'Interpreter', 'latex')
%xlabel('$x_1$', 'Interpreter', 'latex')
%ylabel('$x_2$', 'Interpreter', 'latex')
%print(gcf,'-dpng', 'figures/Pg.png')
%savesp(sp, 'figures/Pf');
|
github
|
Hadisalman/stoec-master
|
gp_optparams.m
|
.m
|
stoec-master/code/Include/gpas-master/gp_optparams.m
| 251 |
utf_8
|
cca5be5e042c465e7871e16bce99a82b
|
function gp = gp_optparams(gp);
p = [gp.l, gp.s];
[p,FVAL,EXITFLAG,OaUTPUT] = fminsearch(@(p) gp_minhp(p, gp), p);
gp.l = p(1);
gp.s = p(2);
gp = gp_train(gp);
function f = gp_minhp(p, gp)
gp.l = p(1);
gp.s = p(2);
gp = gp_train(gp);
f = -gp.lp;
|
github
|
Hadisalman/stoec-master
|
env_node.m
|
.m
|
stoec-master/code/Include/gpas-master/env_node.m
| 1,439 |
utf_8
|
31e37716cd1aa05b64e54bfc13264e42
|
function S = env_node(S)
% Simulate environmental data ROS node
% Will send back data after receiving odom
% or could just broadcast when new data is available
%
% @param S.envFile environment image file
% scale
% xlb, xub bounds
% sigma meas noise
%
rosshutdown
if isfield(S, 'ROS_MASTER_URI')
setenv('ROS_MASTER_URI', S.ROS_MASTER_URI)
end
if isfield(S, 'ROS_IP')
setenv('ROS_IP', S.ROS_IP)
end
if ~isfield(S, 'envFile')
S.envFile = 'data/do1.ppm';
end
if ~isfield(S, 'xlb')
S.xlb = [-50;-50];
end
if ~isfield(S, 'xub')
S.xub = [50;50];
end
if ~isfield(S, 'scale')
S.scale = 1.5;
end
if ~isfield(S, 'sigma')
S.sigma = 0;
end
rosinit
% scalar field over 2d domain loaded from a file
S.I = S.scale*double(imread(S.envFile))/255;
% environmental sensor data (use Temperature for now)
S.envPub = rospublisher('/env', rostype.sensor_msgs_Temperature)
S.envMsg = rosmessage(S.envPub)
% subscriber
odomSub = rossubscriber('/insekf/pose', rostype.nav_msgs_Odometry, {@odomCallback, S}, 'BufferSize', 100)
disp('waiting for odoms...')
while(1)
pause(1)
end
function f = odomCallback(src, msg, S)
x = [msg.Pose.Pose.Position.X;
msg.Pose.Pose.Position.Y];
% get reading and publish it
S.envMsg.Temperature_ = env_scalar2d(x, S);
send(S.envPub, S.envMsg);
disp(['odomCallback: sent data=' num2str(S.envMsg.Temperature_)...
' at p=(' num2str(x(1)) ',' num2str(x(2)) ')']);
|
github
|
Hadisalman/stoec-master
|
gp_init.m
|
.m
|
stoec-master/code/Include/gpas-master/gp_init.m
| 498 |
utf_8
|
3db97c58bea8c7ae61ac0dcebc3988cf
|
function gp = gp_init(xs, fs, opts)
% Initialize a GP over f(x) using an initial dataset (xs, fs)
%
% Required options
% opts.l
% opts.s
gp = [];
gp.l = opts.l;
gp.s = opts.s;
gp.sigma = opts.sigma;
gp.xs = xs;
gp.fs = fs;
gp = gp_train(gp);
% optimize hyperparams
%p = [gp.l, gp.s];
%
%[p,FVAL,EXITFLAG,OaUTPUT] = fminsearch(@(p) gp_minhp(p, gp), p);
%
%gp.l = p(1);
%gp.s = p(2);
%gp = gp_train(gp);
function f = gp_minhp(p, gp)
gp.l = p(1);
gp.s = p(2);
gp = gp_train(gp);
f = -gp.lp;
|
github
|
Hadisalman/stoec-master
|
gpas_node.m
|
.m
|
stoec-master/code/Include/gpas-master/gpas_node.m
| 14,050 |
utf_8
|
f85451a29d338c7511a21d52d494c4cd
|
function f = gpas_node(opt)
% Adaptive Sampling for discovering peak concentration in a 2d scalar field
%
% Author: Marin Kobilarov, marin(at)jhu.edu
% Options:
% workspace lower bound
if ~isfield(opt, 'xlb')
opt.xlb = [-50;-50];
end
% workspace upper bound
if ~isfield(opt, 'xub')
opt.xub = [50;50];
end
% grid cells along each dimension
if ~isfield(opt, 'ng')
opt.ng = [30;30];
end
% trajectory parameters
if ~isfield(opt, 'sn')
opt.sn = 5;
end
% time-step
if ~isfield(opt, 'dt')
opt.dt = 3;
end
% time horizon (seconds)
if ~isfield(opt, 'tf')
opt.tf = 30;
end
% forward velocity lower bound
if ~isfield(opt, 'vlb')
opt.vlb = .1;
end
% forward velocity upper bound
if ~isfield(opt, 'vub')
opt.vub = 5;
end
% angular velocity lower bound
if ~isfield(opt, 'wlb')
opt.wlb = -.5;
end
% angular velocity upper bound
if ~isfield(opt, 'wub')
opt.wub = .5;
end
% Cross-entropy parameters
% outer CE iterations (only useful if we want to display/save each CE iteration)
if ~isfield(opt, 'iters')
opt.iters = 2;
end
if ~isfield(opt, 'ce')
opt.ce = [];
end
% #of samples
if ~isfield(opt.ce, 'N')
opt.ce.N = 100;
end
% smoothing parameter
if ~isfield(opt.ce, 'v')
opt.ce.v = .8;
end
% CE iterations per optimization
if ~isfield(opt.ce, 'iter')
opt.ce.iter = 10;
end
% use the sigma-point CE
if ~isfield(opt.ce, 'sigma')
opt.ce.sigma = 0;
end
% initial covariance
if ~isfield(opt.ce, 'C0')
opt.ce.C0 = diag(repmat([1;1],opt.sn,1));
end
% initial mean (straight line)
if ~isfield(opt.ce, 'z0')
opt.ce.z0 = repmat([1; 0], opt.sn,1);
end
% GP parameters
if ~isfield(opt, 'gp')
opt.gp = [];
end
% length-scale
if ~isfield(opt.gp, 'l')
opt.gp.l = 5;
end
% maximum variance
if ~isfield(opt.gp, 's')
opt.gp.s = 0.4;
end
% output noise
if ~isfield(opt.gp, 'sigma')
opt.gp.sigma = 0.001;
end
% environment parameters
if ~isfield(opt, 'mapFile')
opt.map = [];
end
if isfield(opt, 'envFile')
if ~isfield(opt, 'scale')
opt.scale = 1.5;
end
opt.I = opt.scale*double(imread(opt.envFile))/255;
else
opt.I = [];
end
% how many time stages to run
if ~isfield(opt, 'stages')
opt.stages = 500;
end
% obstacle map
if isfield(opt, 'mapFile')
opt.map = double(imread(opt.mapFile))/255;
else
opt.map = [];
end
% obstacle map
if ~isfield(opt, 'devBias')
opt.devBias = .001;
end
% use one or separate figures?
if 0
opt.figs(1) = figure;
opt.figs(2) = figure;
opt.figs(3) = figure;
opt.figs(4) = figure;
else
opt.figs = [];
end
% meshgrid for display
opt.xr = linspace(opt.xlb(1), opt.xub(1), opt.ng(1))';
opt.yr = linspace(opt.xlb(2), opt.xub(2), opt.ng(2))';
opt.xopt = [];
opt.fopt = [];
opt.J = [];
opt.sel = 'pi';
[X,Y] = meshgrid(opt.xr, opt.yr);
% list of grid points
xss = [reshape(X, 1, size(X,1)*size(X,2));
reshape(Y, 1, size(Y,1)*size(Y,2))];
%opt.xi = [-45; -45; pi/4];
%opt.xi = [25; 25; 1.1*pi]; % for DO
% sequence of measured (unprocessed) states and current state
global odomData envData startCmd
startCmd = [];
odomData = [];
envData.xs = [];
envData.fs = [];
% setup ROS node
rosshutdown
if isfield(opt, 'ROS_MASTER_URI')
setenv('ROS_MASTER_URI', opt.ROS_MASTER_URI)
end
if isfield(opt, 'ROS_IP')
setenv('ROS_IP', opt.ROS_IP)
end
rosinit
odomSub = rossubscriber('/insekf/pose', rostype.nav_msgs_Odometry, ...
@odomCallback)
% wait for valid odom data
while isempty(odomData)
pause(.01);
end
envSub = rossubscriber('/env', rostype.sensor_msgs_Temperature, ...
@envCallback)
% wait for valid env data
while isempty(envData.xs)
pause(.01);
end
startSub = rossubscriber('/adp_start', rostype.std_msgs_Bool, ...
@startCallback)
% wait for start command
while isempty(startCmd)
pause(1);
end
cmdPub = rospublisher('/adp_path', rostype.nav_msgs_Path)
cmdMsg = rosmessage(cmdPub)
cmdPub_rviz = rospublisher('/adp_path_rviz', rostype.geometry_msgs_PoseStamped)
cmdMsg_rviz = rosmessage(cmdPub_rviz)
% if this is simulated (i.e. from a file) then display the true
if ~isempty(opt.I)
opt.fs = env_scalar2d(xss,opt);
p = randperm(size(xss,2));
opt.pss = prior(xss, opt);
end
opt.xi = odomData(:,end);
xps = opt.xi;
% init current trajectory and measurements to start data
% init GP
fgp = gp_init(envData.xs(1:2,:), envData.fs, opt.gp);
%fgp.fun = @fun;
% init opt
[y,ind] = min(envData.fs);
% empty env data
envData.xs = [];
envData.fs = [];
opt.xopt = fgp.xs(:,ind);
opt.fopt = y;
opt.xss = xss;
opt.fgp = fgp;
%plot(opt.xss, opt.fss, '.b')
%ofig = figure
gp_plot(opt)
%xfig = figure
%plot_env(opt)
z=opt.ce.z0;
mu = z;
zlb = repmat([opt.vlb; opt.wlb], opt.sn,1);
zub = repmat([opt.vub; opt.wub], opt.sn,1);
xs = traj(z, opt)
opt.z = z;
c = traj_cost(z, opt)
%[z,fval,exitflag,output] = fmincon(@(z)traj_cost(z,opt), z, [], [],[],[],zlb,zub);
xs = traj(z, opt);
opt.ce.z = z;
opt.ce.C = opt.ce.C0;
opt.ce.lb = zlb;
opt.ce.ub = zub;
% traveled path
%xps = opt.xi;
video =0;
mov = 0;
if video,
mov = VideoWriter('as.avi');
open(mov);
% mov = avifile('as.avi');
% mov.Quality = 100;
% mov.fps = 2*iters;
end
j=1; % image index
% time-series
ts = 0;
ys = y;
cs = c;
for k=1:opt.stages
% wait for start command
while isempty(startCmd)
pause(1);
end
%% PLANNING
opt.ce.C = .5*opt.ce.C + .5*opt.ce.C0;
subplot(2,3,1);
Gp = draw_path(traj(z, opt), 0, 'r', 2,5);
z = opt.ce.z0;
for i=1:opt.iters
opt.ce.z = z;
[z, c, mu, C] = cem(@traj_cost, z, opt.ce, opt);
opt.ce.C = C;
xs = traj(z,opt);
set(Gp,'XData', xs(1,:));
set(Gp,'YData', xs(2,:));
drawnow
if video,
saveas(gcf,['as/as' num2str(j,'%03d') '.jpg'])
j=j+1;
% saveas(gca,['se2opt/v' num2str(c) '.eps'],'psc2');
% mov = addframe(mov,getframe(gca));
% writeVideo(mov,getframe);
% print(gcf,'-dpng', 'figures/env.png')
end
end
% "EXECUTE" START OF PATH
% broadcast all the points in the planned path
for i_p=2:size(xs,2) %start from the second point, as first point is current location.
xd = xs(:,i_p);
m = rosmessage(rostype.geometry_msgs_PoseStamped);
m.Pose.Position.X = xd(1);
m.Pose.Position.Y = xd(2);
m.Pose.Orientation.Z = xd(3);
% send command
cmdMsg.Poses(i_p-1) = m;
end
send(cmdPub, cmdMsg);
%publish another message for rviz visualization
cmdMsg_rviz.Pose.Position.X = xd(1);
cmdMsg_rviz.Pose.Position.Y = xd(2);
cmdMsg_rviz.Pose.Orientation.Z = xd(3);
cmdMsg_rviz.Header.FrameId = 'map';
send(cmdPub_rviz,cmdMsg_rviz);
while(1)
% wait for env data
while isempty(envData.xs)
pause(.1)
end
if norm(opt.xi(1:2)-odomData(1:2)) > 1
break
end
pause(.1)
end
ts = [ts, ts(end) + opt.dt];
ys = [ys, envData.fs(end)];
cs = [cs, c];
% the latest measurement
opt.xi = odomData;
% process accumulated measurements
opt.fgp = gp_add(opt.fgp, envData.xs(1:2,:), envData.fs);
envData.xs = [];
envData.fs = [];
xps = [xps, opt.xi];
hold off
gp_plot(opt)
hold on
subplot(2,3,1)
draw_path(xs(1:2,2:end), 0, 'b',3, 5);
hold on
draw_path(xps(1:2,:), 0, 'g',3, 5);
xlabel('m')
ylabel('m')
drawnow
subplot(2,3,4)
hold off
contour(opt.xr, opt.yr, reshape(opt.pss, length(opt.xr), length(opt.yr)));
%h = contour(opt.xr, opt.yr, reshape(ms, length(opt.xr), ...
% length(opt.yr)));
hold on
draw_path(xs(1:2,2:end), 0, 'b',2, 5);
draw_path(xps(1:2,:), 0, 'g',3, 5);
axis square
axis equal
axis([min(opt.xr),max(opt.xr),min(opt.yr),max(opt.yr)] )
title('Executed (g) and Planned (b) paths')
xlabel('m')
ylabel('m')
subplot(2,3,3)
hold off
plot(ts, ys)
xlabel('s')
title('Env Data')
subplot(2,3,6)
hold off
plot(ts, cs)
xlabel('s')
title('Trajectory Cost')
end
if video,
close(mov);
end
%plot(opt.xss, opt.ms, '.r')
function f = odomCallback(src, msg)
global odomData
odomData = [msg.Pose.Pose.Position.X;
msg.Pose.Pose.Position.Y;
msg.Pose.Pose.Orientation.Z];
disp(['odomCallback: p=' num2str(odomData(1)) ',' num2str(odomData(2))])
function f = envCallback(src, msg)
global envData odomData
fm = msg.Temperature_;
disp(['envCallback: envData=' num2str(fm) ])
% use current odom
if isempty(odomData)
disp('[W] envCallback: empty odomData!')
return
end
envData.xs = [envData.xs, odomData];
envData.fs = [envData.fs, fm];
function f = startCallback(src, msg)
global startCmd
if msg.Data
startCmd = 1;
disp('Adaptive Sampling Enabled');
else
startCmd = [];
disp('Adaptive Sampling Disabled');
end
function G = draw_path(xs, z, c, lw, ms)
G=plot3(xs(1,:), xs(2,:), z*ones(size(xs,2),1), [c '-'], ...
'LineWidth', lw, 'MarkerSize', ms);
function f = prior(xs, opt)
%mvnpdf([0, 0], [0, 0], diag([.05, .1]))
if ~isempty(opt.I)
f = mvnpdf(xs', [0, 0], diag([1000, 1000]));
else
f = mvnpdf(xs', [0, 0], diag([1000, 1000]));
end
f = f/max(f);
function xs = traj(z, opt)
tl = opt.tf/opt.sn;
xs = zeros(3, 1);
xs = opt.xi;
for i=1:opt.sn,
v = z(2*(i-1) + 1);
w = z(2*(i-1) + 2);
th = xs(3,end);
t = opt.dt:opt.dt:tl;
if (abs(w) < 1e-10)
xs = [xs(1,:), xs(1,end) + t*v*cos(th);
xs(2,:), xs(2,end) + t*v*sin(th);
xs(3,:), xs(3,end) + t*0];
else
xs = [xs(1,:), xs(1,end) + v/w*(sin(th + t*w) - sin(th));
xs(2,:), xs(2,end) + v/w*(-cos(th + t*w) + cos(th));
xs(3,:), xs(3,end) + t*w];
end
end
function f = traj_cost(z, opt)
xs = traj(z, opt);
% check for bounds
for i=1:2
if sum(find(xs(i,:) < opt.xlb(i))) || sum(find(xs(i,:) > opt.xub(i)))
f = 1000;
return
end
end
% check for obstacles
if ~isempty(opt.map)
xr = opt.xub(1)-opt.xlb(1);
yr = opt.xub(2)-opt.xlb(2);
is = floor((opt.xub(2) - xs(2,:))/yr*size(opt.I,2)) + 1;
js = floor((xs(1,:)-opt.xlb(1))/xr*size(opt.I,1)) + 1;
is(find(is>size(opt.I,1)))=size(opt.I,2);
js(find(js>size(opt.I,2)))=size(opt.I,2);
is(find(is<1))=1;
js(find(js<1))=1;
for i=1:size(xs,2)
if opt.map(is(i),js(i),1) > .5
f = 1000;
return
end
end
end
[ms, ss] = gp_predict(opt.fgp, xs(1:2,2:end));
vs = sqrt(diag(ss));
%ps = prior(xs(1:2,2:end), opt);
%ps = ones(size(ps));
f = -sum(ms + 1.96*vs);
f = f + opt.devBias*norm(opt.z-z);
%f = sum(ps.*(ms));
%f = -sum(ps.*vs);
vs = z(1:2:end-1);
ws = z(2:2:end);
dws = ws(2:end)-ws(1:end-1);
%f = f*(1 + .01*ws'*ws);% + .5*dws'*dws);
%f = f + .001*vs'*vs;
%f = mean(ms);
%fs = fun(xs, opt);
%for i=1:size(xs,2)%
% gp = gp_add(gp, xs(:,i),
%end
function f = gp_plot(opt)
set(0,'DefaultAxesFontName', 'Times New Roman')
set(0,'DefaultAxesFontSize', 15)
set(0,'DefaultTextFontname', 'Times New Roman')
set(0,'DefaultTextFontSize', 15)
if (~isempty(opt.figs))
figure(opt.figs(1));
set(opt.figs(1), 'Position', [100, 100, 800, 600]);
else
sp = subplot(2,3,1);
set(gcf, 'Position', [100, 100, 1400, 800]);
end
[ms, ss] = gp_predict(opt.fgp, opt.xss);
vs = sqrt(diag(ss));
h = surf(opt.xr, opt.yr, reshape(ms, length(opt.xr), length(opt.yr)), ...
'FaceColor','interp','FaceLighting','phong');
hold on
h1 = surf(opt.xr, opt.yr, reshape(ms + 1.96*vs, length(opt.xr), length(opt.yr)), ...
'FaceColor','interp','FaceLighting','phong','EdgeAlpha',.3);
%set(h,'FaceAlpha',0);
h2 = surf(opt.xr, opt.yr, reshape(ms - 1.96*vs, length(opt.xr), length(opt.yr)), ...
'FaceColor','interp','FaceLighting','phong','EdgeAlpha',.3);
%set(h,'FaceAlpha',0);
xlabel('m')
ylabel('m')
alpha(h,.8)
alpha(h1,.3)
alpha(h2,.3)
%xlabel('$x_1$','Interpreter','latex')
%%ylabel('$x_2$','Interpreter','latex')
%zlabel('$\mathbb{E}[J(x)] \pm \beta Var[J(x)]$', 'Interpreter', 'latex')
view(-20,48)
axis tight
%axis equal
title('Guassin Process Model (+-95% conf.)')
drawnow
%print(gcf,'-dpng', 'figures/Jx.png')
%savesp(sp, 'figures/Jx');
%plot(xts, ms + 1.96*vs, '--', xts, ms - 1.96*vs, '--', xts, ms, '-');
%hold on
%plot3(opt.fgp.xs(1,:), opt.fgp.xs(2,:), opt.fgp.fs, 'or');
%title('Probabilistic Model of Trajectory Cost $J(x)$')
if (~isempty(opt.figs))
figure(opt.figs(2));
set(opt.figs(2), 'Position', [100, 100, 800, 600]);
else
sp = subplot(2,3,2);
end
cns = 1;
hold off
if ~isempty(opt.fs)
if cns
h = contour(opt.xr, opt.yr, reshape(opt.fs, length(opt.xr), ...
length(opt.yr)));
hold on
colorbar;
plot(opt.fgp.xs(1,:), opt.fgp.xs(2,:), '-g','LineWidth',2);
else
h = surfc(opt.xr, opt.yr, reshape(opt.fs, length(opt.xr), length(opt.yr)),...
'FaceColor','interp','FaceLighting','phong','EdgeAlpha',.3);
set(h,'FaceAlpha',0.7);
view(-20,48)
end
axis tight
axis equal
% plot(gp.xss, gp.J, 'b')
hold on
end
title('True Scalar Field')
xlabel('m')
ylabel('m')
if (~isempty(opt.figs))
figure(opt.figs(3));
set(opt.figs(3), 'Position', [100, 100, 800, 600]);
else
sp = subplot(2,3,5);
end
hold off
if cns
h = contour(opt.xr, opt.yr, reshape(ms, length(opt.xr), ...
length(opt.yr)));
hold on
colorbar;
plot(opt.fgp.xs(1,:), opt.fgp.xs(2,:), 'ok-');
else
h = surf(opt.xr, opt.yr, reshape(ms, length(opt.xr), length(opt.yr)), ...
'FaceColor','interp','FaceLighting','phong');
%alpha(h,.5)
set(h,'FaceAlpha',0.5);
% plot(gp.xss, gp.J, 'b')
hold on
plot3(opt.fgp.xs(1,:), opt.fgp.xs(2,:), opt.fgp.fs(:),'*');
view(-20,48)
end
axis tight
axis equal
xlabel('m')
ylabel('m')
title('Estimated Field')
%title('States Sampling Distribution')
%xlabel('$x_1$','Interpreter','latex')
%ylabel('$x_2$','Interpreter','latex')
%zlabel('$P(x)$', 'Interpreter', 'latex')
%print(gcf,'-dpng', 'figures/Px.png')
%savesp(sp, 'figures/Px');
if (~isempty(opt.figs))
figure(opt.figs(4));
set(opt.figs(4), 'Position', [100, 100, 800, 600]);
else
% sp = subplot(2,2,3);
end
|
github
|
Hadisalman/stoec-master
|
cem.m
|
.m
|
stoec-master/code/Include/gpas-master/cem.m
| 8,782 |
utf_8
|
06bef7b59249a3e3354d8770c6d0e6c5
|
function [x, c, mu, C] = cem(fun, x0, opts, varargin)
% The cross-entropy method
% @param fun function to be minimized
% @param x0 initial guess
% options:
% @param opts.N: number of samples
% @param opts.rho: quantile (e.g. 0.1)
% @param opts.C: initial covariance
% @param opts.iter: total iterations
% @param opts.v: update coefficients
% @param varagin any other arguments that will be passed to fun
%
% @return x best sample
% @return c best cost
% @return mu distribution mean
% @return C distribution covariance
%
% Author: Marin Kobilarov, [email protected]
d = length(x0);
if ~isfield(opts, 'N')
opts.N = d*20;
end
if ~isfield(opts, 'rho')
opts.rho = 0.1;
end
if ~isfield(opts, 'C')
opts.C = eye(d);
end
if ~isfield(opts, 'iter')
fun = 20;
end
if ~isfield(opts, 'v')
opts.v = 1;
end
if ~isfield(opts, 'sigma')
opts.sigma = 0;
end
if opts.sigma
opts.N = 2*d+1;
end
if ~isfield(opts, 'tilt')
opts.tilt = 0;
end
if ~isfield(opts, 'lb')
opts.lb = [];
end
if ~isfield(opts, 'ub')
opts.ub = [];
end
if opts.tilt
end
N = opts.N;
nf = round(opts.rho*N);
C = opts.C;
v = opts.v;
cs = zeros(N, 1);
xs = zeros(d, N);
x = x0;
c = inf;
mu = x0;
a = 0.001;
k = 0;
b = 2;
l = a*a*(d+k)-d;
Ws = [l/(d+l), repmat(1/(2*(d+l)), 1, 2*d)];
Wc = [l/(d+l) + (1-a*a+b), repmat(1/(2*(d+l)), 1, 2*d)];
for j=1:opts.iter
if opts.sigma
% this is an experimental version of the CE method using sigma-points
A = sqrt(d+l)*chol(C)';
xs = [mu, repmat(mu, 1, d) + A, repmat(mu, 1, d) - A];
xm = zeros(d,1);
for i=1:size(xs,2),
fi = fun(xs(:,i), varargin{:});
if (length(fi) > 1)
cs(i) = sum(fi.*fi);
else
cs(i) = fi;
end
cs(i) = exp(-cs(i));
xm = xm + Ws(i)*cs(i)*xs(:,i);
end
Pm = zeros(d,d);
for i=1:size(xs,2),
dx = xs(:,i) - xm;
Pm = Pm + Wc(i)*cs(i)*dx*dx';
end
csn = sum(cs);
mu = mu/csn;
C = Pm/csn;
x = mu;
c = cs(1);
else
% this is the standard CE method using random sampling
if (~isempty(opts.lb))
n = length(mu);
A=[-eye(n);
eye(n)];
B=[-opts.lb;
opts.ub];
xs = rmvnrnd(mu, C, N, A, B)';
else
xs = mvnrnd(mu, C, N)';
end
for i=1:N,
fi = fun(xs(:,i), varargin{:});
if (length(fi) > 1)
cs(i) = sum(fi.*fi)/2;
else
cs(i) = fi;
end
end
if ~opts.tilt
[cs,is] = sort(cs, 1, 'ascend');
xes = xs(:, is(1:nf));
mu = (1 - v).*mu + v.*mean(xes')';
C = (1 - v).*C + v.*cov(xes');% + diag(opts.rf.*rand(opts.n,1));
if (cs(1) < c)
x = xes(:,1);
c = cs(1);
end
else
if (j==1)
S.ps0 = mvnpdf(xs', mu', C);
end
[cmin, imin] = min(cs);
% b = max(1/cmin, .001);
% b = max(1/(max(cs)-min(cs)), .001);
%good one:
b = 1/mean(cs);
% b = max(1/min(cs), .001);
if 0
b = b*(entropy(mu, C));
S.ps = mvnpdf(xs',mu', C);
S.Jh = mean(cs);
S.Js = cs;
bmin = 0;
bmax = 1;
S.xs = xs;
S.v = v;
S.mu = mu;
S.C = C;
bs = bmin:.001:bmax;
gs = zeros(size(bs));
for l=1:length(bs)
gs(l) = minb3(bs(l), S);
end
plot(bs, gs,'g');
drawnow
gs
[gm,bi]=min(gs);
b=bs(bi)
[b,FVAL,EXITFLAG,OUTPUT] = fminbnd(@(b) minb3(b, S), bmin, bmax)
keyboard
global ws
end
% kl = sum(-log(ws))/N
% b = b*kl;
% b = 1;
ws = exp(-b*cs);
ws = ws/sum(ws);
mu = (1 - v).*mu + v.*(xs*ws);
C = (1 - v).*C + v.*weightedcov(xs', ws);
if (cmin < c)
x = xs(:,imin);
c = cmin;
end
end
end
end
function f = minb(b, S)
b
N = length(S.Js);
ws = exp(-b*S.Js);
eta = sum(ws)/N;
delta = .1;
g = sqrt(log(1/delta)/(2*N));
ws = ws/sum(ws);
mu = (1 - S.v).*S.mu + S.v.*(S.xs*ws);
C = (1 - S.v).*S.C + S.v.*weightedcov(S.xs', ws);
C
vs = 1/eta*ws.*(-log(eta)*ones(N,1) - b*S.Js + log(S.ps) ...
- log(mvnpdf(S.xs', mu', C)));
R = max(vs)-min(vs)
f = sum(vs)/N + R*g;
function f = minb2(b, S)
N = length(S.Js);
ws = exp(-b*S.Js);
eta = sum(ws)/N;
delta = .1;
g = sqrt(log(1/delta)/(2*N));
ws = ws/sum(ws);
mu = (1 - S.v).*S.mu + S.v.*(S.xs*ws);
C = (1 - S.v).*S.C + S.v.*weightedcov(S.xs', ws);
mu
C
Ws = S.ps0./mvnpdf(S.xs', mu', C);
Ws
vs = exp(-2*b*S.Js).*Ws;
R = max(vs);
f = sum(vs)/N + R*g;
function f = minb3(b, S)
N = length(S.Js);
Jmin = min(S.Js)
Jmax = max(S.Js)
ws = exp(-b*S.Js/Jmax);
delta = .5;
g = sqrt(log(1/delta)/(2*N))
mean(ws) - exp(-b*Jmin/Jmax)*g
b*(mean(S.Js)/Jmax - g)
f = log(mean(ws) - exp(-b*Jmin/Jmax)*g) + b*(mean(S.Js)/Jmax - g);
f
f = -f;
function C = weightedcov(Y, w)
% Weighted Covariance Matrix
%
% WEIGHTEDCOV returns a symmetric matrix C of weighted covariances
% calculated from an input T-by-N matrix Y whose rows are
% observations and whose columns are variables and an input T-by-1 vector
% w of weights for the observations. This function may be a valid
% alternative to COV if observations are not all equally relevant
% and need to be weighted according to some theoretical hypothesis or
% knowledge.
%
% C = WEIGHTEDCOV(Y, w) returns a positive semidefinite matrix C, i.e. all its
% eigenvalues are non-negative.
%
% If w = ones(size(Y, 1), 1), no difference exists between
% WEIGHTEDCOV(Y, w) and COV(Y, 1).
%
% REFERENCE: mathematical formulas in matrix notation are available in
% F. Pozzi, T. Di Matteo, T. Aste,
% "Exponential smoothing weighted correlations",
% The European Physical Journal B, Volume 85, Issue 6, 2012.
% DOI:10.1140/epjb/e2012-20697-x.
%
% % ======================================================================
% % EXAMPLE
% % ======================================================================
%
% % GENERATE CORRELATED STOCHASTIC PROCESSES
% T = 100; % number of observations
% N = 500; % number of variables
% Y = randn(T, N); % shocks from standardized normal distribution
% Y = cumsum(Y); % correlated stochastic processes
%
% % CHOOSE EXPONENTIAL WEIGHTS
% alpha = 2 / T;
% w0 = 1 / sum(exp(((1:T) - T) * alpha));
% w = w0 * exp(((1:T) - T) * alpha); % weights: exponential decay
%
% % COMPUTE WEIGHTED COVARIANCE MATRIX
% c = weightedcov(Y, w); % Weighted Covariance Matrix
%
% % ======================================================================
%
% See also CORRCOEF, COV, STD, MEAN.
% Check also WEIGHTEDCORRS (FE 20846) and KENDALLTAU (FE 27361)
%
% % ======================================================================
%
% Author: Francesco Pozzi
% E-mail: [email protected]
% Date: 15 June 2012
%
% % ======================================================================
%
% Check input
ctrl = isvector(w) & isreal(w) & ~any(isnan(w)) & ~any(isinf(w));
if ctrl
w = w(:) / sum(w); % w is column vector
else
error('Check w: it needs be a vector of real positive numbers with no infinite or nan values!')
end
ctrl = isreal(Y) & ~any(isnan(Y)) & ~any(isinf(Y)) & (size(size(Y), 2) == 2);
if ~ctrl
error('Check Y: it needs be a 2D matrix of real numbers with no infinite or nan values!')
end
ctrl = length(w) == size(Y, 1);
if ~ctrl
error('size(Y, 1) has to be equal to length(w)!')
end
[T, N] = size(Y); % T: number of observations; N: number of variables
C = Y - repmat(w' * Y, T, 1); % Remove mean (which is, also, weighted)
C = C' * (C .* repmat(w, 1, N)); % Weighted Covariance Matrix
C = 0.5 * (C + C'); % Must be exactly symmetric
function f = kl(q,p)
f = q.*log(q./p) + (1-q).*log((1-q)./(1-p));
function f = normkl(mu0, S0, mu1, S1)
Si = inv(S1);
f = (trace(Si*S0) + (mu1 - mu0)'*Si*(mu1 - mu0) - log(det(S0)/det(S1)) ...
- length(mu0))/2;
function f = entropy(mu, S)
k=length(mu);
f = k/2*(1+log(2*pi)) + log(det(S))/2;
|
github
|
Hadisalman/stoec-master
|
gp_test3.m
|
.m
|
stoec-master/code/Include/gpas-master/gp_test3.m
| 3,828 |
utf_8
|
ed5a82390730af6a1554eb97d60094cf
|
function f = gp_test3
clear
N0 = 500;
Ns = 5000;
opt.Ns = Ns;
opt.xi = [-2.5; -2.5];
opt.xf = [2.5; 2.5];
opt.xr = -2.5:.1:2.5;
opt.yr = -2.5:.1:2.5;
%%%%%%%%%
% 5 g%
% %
% 12 4 %
% 3 %
%s %
%%%%%%%%%
opt.os = [-1.2, -.8, -.25, 1.3, 0.1;
0, -.3, -1, -.6, 1.8];
opt.r = [.4, .5, .4, .9, .9];
opt.xmin = [];
opt.fmin = [];
opt.J = [];
opt.cP = [];
opt.fP = [];
opt.sel = 'pi';
opt.sn = 2;
opt.snf = 10;
xs0 = stline(opt.xi, opt.xf, opt.sn);
opt.mu = reshape(xs0(:,2:end-1), 2*opt.sn, 1);
opt.Sigma = 2*eye(2*opt.sn);
[X,Y] = meshgrid(opt.xr, opt.yr);
xss = [reshape(X, 1, size(X,1)*size(X,2));
reshape(Y, 1, size(Y,1)*size(Y,2))];
xss = sample(opt, Ns);
p = randperm(size(xss,2));
% initial data
cxs = xss(:,p(1:N0));
%xss = xss(sort(p(N0+1:end)));
cs = zeros(1,size(cxs,2));
for i=1:size(cxs,2),
cs(i) = con(cxs(:,i),opt);
end
xs = cxs(:,find(cs > 0));
fs = zeros(1,size(xs,2));
for i=1:size(xs,2),
fs(i) = fun(xs(:,i),opt);
end
opt.N0f = size(xs,2);
% cost function gp
fopts.l = 1;
fopts.s = 1;
fopts.sigma = .1;
fgp = gp_init(xs, fs, fopts)
fgp.fun = @fun;
% constraints gp
copts.l = 1;
copts.s = 1;
copts.sigma = .1;
cgp = gp_init(cxs, cs, copts)
cgp.fun = @con;
% test points
%Nmax = 500;
% init opt
[y,ind] = min(fs);
opt.xmin = fgp.xs(:,ind);
opt.fmin = y;
opt.xss = xss;
opt.fgp = fgp;
opt.cgp = cgp;
N = 50;
%plot(S.xss, S.fss, '.b')
ofig = figure
gp_plot3(opt)
xfig = figure
plot_env(opt)
%return
for i=1:10,
opt = gp_fit(opt);
tic
[opt, x, y] = gp_select(opt);
disp('select')
toc
% if (abs(x-cgp.xs)<.005)
% continue;
% end
if ~isempty(cgp)
c = con(x, opt);
tic
opt.cgp = gp_add(opt.cgp, x, c);
disp('cgp add')
toc
if (c < 0)
disp('added con')
continue
end
end
disp('added fun')
f = fun(x,opt);
if f < opt.fmin
opt.fmin = f;
opt.xmin = x;
end
tic
opt.fgp = gp_add(opt.fgp, x, f);
disp('fgp add')
toc
% cgp = cgp_add(cgp, x, c);
display('opt:')
opt.xmin
% figure(ofig)
% gp_plot3(opt)
figure(xfig)
plot_env(opt);
% plot(x,f,'ob')
% S.xmin
% S.fmin
end
%plot(S.xss, S.ms, '.r')
function f = fun(xs, opt)
xs = reshape(xs, 2,length(xs)/2);
xsa = [opt.xi, xs];
xsb = [xs, opt.xf];
dxs = xsb - xsa;
f = sum(sqrt(sum(dxs.*dxs, 1)));
function xs = sample(opt,N)
xs = mvnrnd(opt.mu, opt.Sigma, N)';
function cmin = con(xs, opt)
cmin = inf;
xs = reshape(xs, 2,length(xs)/2);
xsa = [opt.xi, xs];
xsb = [xs, opt.xf];
dxs = xsb - xsa;
for i=1:size(opt.os,2)
o = opt.os(:,i);
r = opt.r(i);
for i=1:size(dxs,2)
xa = xsa(:,i);
dx = dxs(:,i);
a = dx/norm(dx);
b = o - xa;
d = b'*a;
if d > 0
c = norm(d*a - b) - r;
else
c = norm(xa - o) - r;
end
if c < cmin
cmin = c;
end
end
end
function f = plot_env(opt)
a = 0:2*pi/20:2*pi;
hold off
for i=1:size(opt.os,2)
o = opt.os(:,i);
r = opt.r(i);
plot(o(1) + cos(a)*r, o(2) + sin(a)*r, '-k', 'LineWidth',3);
hold on
if ~isempty(opt.xmin)
xs = [opt.xi, reshape(opt.xmin, 2,length(opt.xmin)/2), opt.xf];
plot(xs(1,:), xs(2,:), '-*g', 'LineWidth',4);
end
end
for i=1:size(opt.fgp.xs,2)
ps = opt.fgp.xs(:,i);
xs = [opt.xi, reshape(ps, 2,length(ps)/2), opt.xf];
if (i<=opt.N0f)
plot(xs(1,:), xs(2,:), '--o', 'LineWidth',1);
else
plot(xs(1,:), xs(2,:), '-xb', 'LineWidth',2);
end
end
axis equal
%axis([-2.5 2.5 -2.5 2.5])
drawnow
function xs = stline(xi, xf, sn)
n = length(xi);
xs = zeros(n, sn + 2);
for i=1:n
xs(i,:) = linspace(xi(i), xf(i), sn+2);
end
function xs = si_traj(ps, S)
xs = [S.xi, reshape(ps, 2, S.sn), S.xf];
xs = interp1(linspace(0, 1, size(xs,2)), xs', ...
linspace(0, 1, S.snf), 'cubic')';
|
github
|
Hadisalman/stoec-master
|
likBeta.m
|
.m
|
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/lik/likBeta.m
| 4,830 |
utf_8
|
8e503690924874d07a77dc48bc238db1
|
function [varargout] = likBeta(link, hyp, y, mu, s2, inf, i)
% likBeta - Beta likelihood function for interval data y from [0,1].
% The expression for the likelihood is
% likBeta(f) = 1/Z * y^(mu*phi-1) * (1-y)^((1-mu)*phi-1) with
% mean=mu and variance=mu*(1-mu)/(1+phi) where mu = g(f) is the Beta intensity,
% f is a Gaussian process, y is the interval data and
% Z = Gamma(phi)/Gamma(phi*mu)/Gamma(phi*(1-mu)).
% Hence, we have
% llik(f) = log(likBeta(f)) = -lam*(y-mu)^2/(2*mu^2*y) - log(Zy).
%
% We provide two inverse link functions 'logit' and 'expexp':
% g(f) = 1/(1+exp(-f)) and g(f) = exp(-exp(-f))).
% The link functions are located at util/glm_invlink_*.m.
%
% Note that for neither link function the likelihood lik(f) is log concave.
%
% The hyperparameters are:
%
% hyp = [ log(phi) ]
%
% Several modes are provided, for computing likelihoods, derivatives and moments
% respectively, see likFunctions.m for the details. In general, care is taken
% to avoid numerical issues when the arguments are extreme.
%
% See also LIKFUNCTIONS.M.
%
% Copyright (c) by Hannes Nickisch, 2014-03-04.
if nargin<4, varargout = {'1'}; return; end % report number of hyperparameters
phi = exp(hyp);
if nargin<6 % prediction mode if inf is not present
if numel(y)==0, y = zeros(size(mu)); end
s2zero = 1; if nargin>4, if norm(s2)>0, s2zero = 0; end, end % s2==0 ?
if s2zero % log probability
lg = g(mu,link); elg = exp(lg); v = phi*elg; w = phi-v;
a0 = gammaln(w)-gammaln(phi);
lp = (v-1).*log(y) + (w-1).*log(1-y) - gammaln(v) - a0;
else
lp = likBeta(link, hyp, y, mu, s2, 'infEP');
end
ymu = {}; ys2 = {};
if nargout>1 % compute y moments by quadrature
n = max([length(y),length(mu),length(s2)]); on = ones(n,1);
N = 20; [t,w] = gauher(N); oN = ones(1,N); lw = ones(n,1)*log(w');
mu = mu(:).*on; sig = sqrt(s2(:)).*on; % vectors only
lg = g(sig*t'+mu*oN,link);
ymu = exp(logsumexp2(lg+lw)); % first moment using Gaussian-Hermite quad
if nargout>2
elg = exp(lg);
yv = elg.*(1-elg)/(1+phi); % second y moment from Beta distribution
ys2 = (yv+(elg-ymu*oN).^2)*w;
end
end
varargout = {lp,ymu,ys2};
else
switch inf
case 'infLaplace'
[lg,dlg,d2lg,d3lg] = g(mu,link); elg = exp(lg); v = phi*elg; w = phi-v;
if nargin<7 % no derivative mode
a0 = gammaln(phi-v)-gammaln(phi);
lp = (v-1).*log(y) + (w-1).*log(1-y) - gammaln(v) - a0;
dlp = {}; d2lp = {}; d3lp = {}; % return arguments
if nargout>1 % dlp, derivative of log likelihood
a1 = v.*(log(y)-log(1-y) + psi(0,w)-psi(0,v));
dlp = dlg.*a1;
if nargout>2 % d2lp, 2nd derivative of log likelihood
a2 = v.^2.*(psi(1,w)+psi(1,v)); z = dlg.^2+d2lg;
d2lp = z.*a1 - dlg.^2.*a2;
if nargout>3 % d3lp, 3rd derivative of log likelihood
a3 = v.^3.*(psi(2,w)-psi(2,v));
d3lp = (dlg.*z+2*dlg.*d2lg+d3lg).*a1 - 3*dlg.*z.*a2 + dlg.^3.*a3;
end
end
end
varargout = {lp,dlp,d2lp,d3lp};
else % derivative mode
% deriv. of log lik w.r.t. phi
lp_dhyp = v.*log(y)+w.*log(1-y)-v.*psi(0,v)-w.*psi(0,w)+phi*psi(0,phi);
a1 = v.*(log(y)-log(1-y) + psi(0,w)-psi(0,v));
da1 = a1 + v.*(w.*psi(1,w)-v.*psi(1,v));
dlp_dhyp = dlg.*da1; % first derivative
a2 = v.^2.*(psi(1,w)+psi(1,v)); z = dlg.^2+d2lg;
da2 = v.^2.*(w.*psi(2,w)+v.*psi(2,v)) + 2*a2;
d2lp_dhyp = z.*da1 - dlg.^2.*da2; % second derivative
varargout = {lp_dhyp,dlp_dhyp,d2lp_dhyp};
end
case 'infEP'
if nargin<7 % no derivative mode
% Since we are not aware of an analytical expression of the integral,
% we use quadrature.
varargout = cell(1,nargout);
[varargout{:}] = lik_epquad({@likBeta,link},hyp,y,mu,s2);
else % derivative mode
varargout = {[]}; % deriv. wrt hyp.lik
end
case 'infVB'
error('infVB not supported')
end
end
% compute the log intensity using the inverse link function
function varargout = g(f,link)
varargout = cell(nargout, 1); % allocate the right number of output arguments
if strcmp(link,'expexp')
[varargout{:}] = glm_invlink_expexp(f);
else
[varargout{:}] = glm_invlink_logit(f);
end
|
github
|
Hadisalman/stoec-master
|
likT.m
|
.m
|
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/lik/likT.m
| 4,776 |
utf_8
|
6463e0fed8f6484854dd3dd212db5202
|
function [varargout] = likT(hyp, y, mu, s2, inf, i)
% likT - Student's t likelihood function for regression.
% The expression for the likelihood is
% likT(t) = Z * ( 1 + (t-y)^2/(nu*sn^2) ).^(-(nu+1)/2),
% where Z = gamma((nu+1)/2) / (gamma(nu/2)*sqrt(nu*pi)*sn)
% and y is the mean (for nu>1) and nu*sn^2/(nu-2) is the variance (for nu>2).
%
% The hyperparameters are:
%
% hyp = [ log(nu-1)
% log(sn) ]
%
% Note that the parametrisation guarantees nu>1, thus the mean always exists.
%
% Several modes are provided, for computing likelihoods, derivatives and moments
% respectively, see likFunctions.m for the details. In general, care is taken
% to avoid numerical issues when the arguments are extreme.
%
% Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2013-09-02.
%
% See also LIKFUNCTIONS.M.
if nargin<3, varargout = {'2'}; return; end % report number of hyperparameters
numin = 1; % minimum value of nu
nu = exp(hyp(1))+numin; sn2 = exp(2*hyp(2)); % extract hyperparameters
lZ = gammaln(nu/2+1/2) - gammaln(nu/2) - log(nu*pi*sn2)/2;
if nargin<5 % prediction mode if inf is not present
if numel(y)==0, y = zeros(size(mu)); end
s2zero = 1; if nargin>3, if norm(s2)>0, s2zero = 0; end, end % s2==0 ?
if s2zero % log probability evaluation
lp = lZ - (nu+1)*log( 1+(y-mu).^2./(nu.*sn2) )/2; s2 = 0;
else % prediction
lp = likT(hyp, y, mu, s2, 'infEP');
end
ymu = {}; ys2 = {};
if nargout>1
ymu = mu; % first y moment; for nu<=1 this is the mode
if nargout>2
if nu<=2
ys2 = Inf(size(mu)); % variance does not always exist
else
ys2 = (s2 + nu*sn2/(nu-2)).*ones(size(mu)); % second y moment
end
end
end
varargout = {lp,ymu,ys2};
else
switch inf
case 'infLaplace'
r = y-mu; r2 = r.*r;
if nargin<6 % no derivative mode
dlp = {}; d2lp = {}; d3lp = {};
lp = lZ - (nu+1)*log( 1+r2./(nu.*sn2) )/2;
if nargout>1
a = r2+nu*sn2;
dlp = (nu+1)*r./a; % dlp, derivative of log likelihood
if nargout>2 % d2lp, 2nd derivative of log likelihood
d2lp = (nu+1)*(r2-nu*sn2)./a.^2;
if nargout>3 % d3lp, 3rd derivative of log likelihood
d3lp = (nu+1)*2*r.*(r2-3*nu*sn2)./a.^3;
end
end
end
varargout = {lp,dlp,d2lp,d3lp};
else % derivative mode
a = r2+nu*sn2; a2 = a.*a; a3 = a2.*a;
if i==1 % derivative w.r.t. nu
lp_dhyp = nu*( psi(nu/2+1/2)-psi(nu/2) )/2 - 1/2 ...
-nu*log(1+r2/(nu*sn2))/2 +(nu/2+1/2)*r2./(nu*sn2+r2);
lp_dhyp = (1-numin/nu)*lp_dhyp; % correct for lower bound on nu
dlp_dhyp = nu*r.*( a - sn2*(nu+1) )./a2;
dlp_dhyp = (1-numin/nu)*dlp_dhyp; % correct for lower bound on nu
d2lp_dhyp = nu*( r2.*(r2-3*sn2*(1+nu)) + nu*sn2^2 )./a3;
d2lp_dhyp = (1-numin/nu)*d2lp_dhyp; % correct for lower bound on nu
else % derivative w.r.t. sn
lp_dhyp = (nu+1)*r2./a - 1;
dlp_dhyp = -(nu+1)*2*nu*sn2*r./a2;
d2lp_dhyp = (nu+1)*2*nu*sn2*(a-4*r2)./a3;
end
varargout = {lp_dhyp,dlp_dhyp,d2lp_dhyp};
end
case 'infEP'
if nargout>1
error('infEP not supported since likT is not log-concave')
end
n = max([length(y),length(mu),length(s2)]); on = ones(n,1);
y = y(:).*on; mu = mu(:).*on; sig = sqrt(s2(:)).*on; % vectors only
% since we are not aware of an analytical expression of the integral,
% we use Gaussian-Hermite quadrature
N = 20; [t,w] = gauher(N); oN = ones(1,N);
lZ = likT(hyp, y*oN, sig*t'+mu*oN, []);
lZ = log_expA_x(lZ,w); % log( exp(lZ)*w )
varargout = {lZ};
case 'infVB'
% variational lower site bound
% t(s) \propto (1+(s-y)^2/(nu*s2))^(-nu/2+1/2)
% the bound has the form: (b+z/ga)*f - f.^2/(2*ga) - h(ga)/2
n = numel(s2); b = zeros(n,1); y = y.*ones(n,1); z = y;
varargout = {b,z};
end
end
% computes y = log( exp(A)*x ) in a numerically safe way by subtracting the
% maximal value in each row to avoid cancelation after taking the exp
function y = log_expA_x(A,x)
N = size(A,2); maxA = max(A,[],2); % number of columns, max over columns
y = log(exp(A-maxA*ones(1,N))*x) + maxA; % exp(A) = exp(A-max(A))*exp(max(A))
|
github
|
Hadisalman/stoec-master
|
likLaplace.m
|
.m
|
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/lik/likLaplace.m
| 6,922 |
iso_8859_13
|
9673b9c57508bdbfd0dc917f10944f80
|
function [varargout] = likLaplace(hyp, y, mu, s2, inf, i)
% likLaplace - Laplacian likelihood function for regression.
% The expression for the likelihood is
% likLaplace(t) = exp(-|t-y|/b)/(2*b) with b = sn/sqrt(2),
% where y is the mean and sn^2 is the variance.
%
% The hyperparameters are:
%
% hyp = [ log(sn) ]
%
% Several modes are provided, for computing likelihoods, derivatives and moments
% respectively, see likFunctions.m for the details. In general, care is taken
% to avoid numerical issues when the arguments are extreme.
%
% Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2013-10-16.
%
% See also LIKFUNCTIONS.M.
if nargin<3, varargout = {'1'}; return; end % report number of hyperparameters
sn = exp(hyp); b = sn/sqrt(2);
if nargin<5 % prediction mode if inf is not present
if numel(y)==0, y = zeros(size(mu)); end
s2zero = 1; if nargin>3, if norm(s2)>0, s2zero = 0; end, end % s2==0 ?
if s2zero % log probability evaluation
lp = -abs(y-mu)./b -log(2*b); s2 = 0;
else % prediction
lp = likLaplace(hyp, y, mu, s2, 'infEP');
end
ymu = {}; ys2 = {};
if nargout>1
ymu = mu; % first y moment
if nargout>2
ys2 = s2 + sn.^2; % second y moment
end
end
varargout = {lp,ymu,ys2};
else % inference mode
switch inf
case 'infLaplace'
if nargin<6 % no derivative mode
if numel(y)==0, y=0; end
ymmu = y-mu; dlp = {}; d2lp = {}; d3lp = {};
lp = -abs(ymmu)/b -log(2*b);
if nargout>1
dlp = sign(ymmu)/b; % dlp, derivative of log likelihood
if nargout>2 % d2lp, 2nd derivative of log likelihood
d2lp = zeros(size(ymmu));
if nargout>3 % d3lp, 3rd derivative of log likelihood
d3lp = zeros(size(ymmu));
end
end
end
varargout = {lp,dlp,d2lp,d3lp};
else % derivative mode
lp_dhyp = abs(y-mu)/b - 1; % derivative of log likelihood w.r.t. hypers
dlp_dhyp = sign(mu-y)/b; % first derivative,
d2lp_dhyp = zeros(size(mu)); % and also of the second mu derivative
varargout = {lp_dhyp,dlp_dhyp,d2lp_dhyp};
end
case 'infEP'
n = max([numel(y),numel(mu),numel(s2),numel(sn)]); on = ones(n,1);
y = y(:).*on; mu = mu(:).*on; s2 = s2(:).*on; sn = sn(:).*on; % vectors only
fac = 1e3; % factor between the widths of the two distributions ...
% ... from when one considered a delta peak, we use 3 orders of magnitude
idlik = fac*sn<sqrt(s2); % Likelihood is a delta peak
idgau = fac*sqrt(s2)<sn; % Gaussian is a delta peak
id = ~idgau & ~idlik; % interesting case in between
if nargin<6 % no derivative mode
lZ = zeros(n,1); dlZ = lZ; d2lZ = lZ; % allocate memory
if any(idlik)
[lZ(idlik),dlZ(idlik),d2lZ(idlik)] = ...
likGauss(log(s2(idlik))/2, mu(idlik), y(idlik));
end
if any(idgau)
[lZ(idgau),dlZ(idgau),d2lZ(idgau)] = ...
likLaplace(log(sn(idgau)), mu(idgau), y(idgau));
end
if any(id)
% substitution to obtain unit variance, zero mean Laplacian
tmu = (mu(id)-y(id))./sn(id); tvar = s2(id)./sn(id).^2;
% an implementation based on logphi(t) = log(normcdf(t))
zp = (tmu+sqrt(2)*tvar)./sqrt(tvar);
zm = (tmu-sqrt(2)*tvar)./sqrt(tvar);
ap = logphi(-zp)+sqrt(2)*tmu;
am = logphi( zm)-sqrt(2)*tmu;
lZ(id) = logsumexp2([ap,am]) + tvar - log(sn(id)*sqrt(2));
if nargout>1
lqp = -zp.^2/2 - log(2*pi)/2 - logphi(-zp); % log( N(z)/Phi(z) )
lqm = -zm.^2/2 - log(2*pi)/2 - logphi( zm);
dap = -exp(lqp-log(s2(id))/2) + sqrt(2)./sn(id);
dam = exp(lqm-log(s2(id))/2) - sqrt(2)./sn(id);
% ( exp(ap).*dap + exp(am).*dam )./( exp(ap) + exp(am) )
dlZ(id) = expABz_expAx([ap,am],[1;1],[dap,dam],[1;1]);
if nargout>2
a = sqrt(8)./sn(id)./sqrt(s2(id));
bp = 2./sn(id).^2 - (a - zp./s2(id)).*exp(lqp);
bm = 2./sn(id).^2 - (a + zm./s2(id)).*exp(lqm);
% d2lZ(id) = ( exp(ap).*bp + exp(am).*bm )./( exp(ap) + exp(am) )...
% - dlZ(id).^2;
d2lZ(id) = expABz_expAx([ap,am],[1;1],[bp,bm],[1;1]) - dlZ(id).^2;
end
end
end
varargout = {lZ,dlZ,d2lZ};
else % derivative mode
dlZhyp = zeros(n,1);
if any(idlik)
dlZhyp(idlik) = 0;
end
if any(idgau)
dlZhyp(idgau) = ...
likLaplace(log(sn(idgau)), mu(idgau), y(idgau), 'infLaplace', 1);
end
if any(id)
% substitution to obtain unit variance, zero mean Laplacian
tmu = (mu(id)-y(id))./sn(id); tvar = s2(id)./sn(id).^2;
zp = (tvar+tmu/sqrt(2))./sqrt(tvar); vp = tvar+sqrt(2)*tmu;
zm = (tvar-tmu/sqrt(2))./sqrt(tvar); vm = tvar-sqrt(2)*tmu;
dzp = (-s2(id)./sn(id)+tmu.*sn(id)/sqrt(2)) ./ sqrt(s2(id));
dvp = -2*tvar - sqrt(2)*tmu;
dzm = (-s2(id)./sn(id)-tmu.*sn(id)/sqrt(2)) ./ sqrt(s2(id));
dvm = -2*tvar + sqrt(2)*tmu;
lezp = logerfc(zp); % ap = exp(vp).*ezp
lezm = logerfc(zm); % am = exp(vm).*ezm
vmax = max([vp+lezp,vm+lezm],[],2); % subtract max to avoid numerical pb
ep = exp(vp+lezp-vmax);
em = exp(vm+lezm-vmax);
dap = ep.*(dvp - 2/sqrt(pi)*exp(-zp.^2-lezp).*dzp);
dam = em.*(dvm - 2/sqrt(pi)*exp(-zm.^2-lezm).*dzm);
dlZhyp(id) = (dap+dam)./(ep+em) - 1;
end
varargout = {dlZhyp}; % deriv. wrt hypers
end
case 'infVB'
% variational lower site bound
% t(s) = exp(-sqrt(2)|y-s|/sn) / sqrt(2*sn²)
% the bound has the form: (b+z/ga)*f - f.^2/(2*ga) - h(ga)/2
n = numel(s2); b = zeros(n,1); y = y.*ones(n,1); z = y;
varargout = {b,z};
end
end
% logerfc(z) = log(1-erf(z))
function lc = logerfc(z)
lc = logphi(-z*sqrt(2)) + log(2);
function y = expABz_expAx(A,x,B,z)
N = size(A,2); maxA = max(A,[],2); % number of columns, max over columns
A = A-maxA*ones(1,N); % subtract maximum value
y = ( (exp(A).*B)*z ) ./ ( exp(A)*x );
|
github
|
Hadisalman/stoec-master
|
likGaussWarp.m
|
.m
|
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/lik/likGaussWarp.m
| 9,118 |
utf_8
|
baca6bc6eb9f081dff2f85d7a4eb8318
|
function [varargout] = likGaussWarp(warp, hyp, y, mu, varargin)
% likGaussWarp - Warped Gaussian likelihood for regression.
% The expression for the likelihood is
% likGaussWarp( y | t ) = likGauss( g(y) | t ) * g'(y),
% where likGauss is the Gaussian likelihood and g is the warping function.
%
% The hyperparameters are:
%
% hyp = [ theta_1
% theta_2
% ..
% theta_ng
% log(sn) ]
%
% Here, sn is the standard deviation of the underlying Gaussian and theta_i for
% i=1..ng are the ng hyperparameters of the warping function g.
%
% At the moment, likGaussWarp offers 3 different warping functions:
% id yields g(y) = y => likGaussWarp = likGauss
% poly<m> e.g. 'poly1' yields g(y) = y => likGaussWarp = likGauss
% 'poly3' yields g(y) = y + c1*sy*ay^2 + c2*sy*ay^3
% where sy = sign(y), ay = abs(y), cj = exp(theta_j)
% tanh<m> e.g. 'tanh0' yields g(y) = y => likGaussWarp = likGauss
% 'tanh2' yields g(y) = y + a1*tanh(b1*(y+c1)) + a2*tanh(b2*(y+c2))
% where aj = exp(theta_j), bj = exp(theta_j+m), bj = theta_j+2*m
%
% The code is based on the exposition in the paper Warped Gaussian Processes,
% NIPS, 2003 by Edward Snelson, Carl Rasmussen and Zoubin Ghahramani.
%
% Several modes are provided, for computing likelihoods, derivatives and moments
% respectively, see likFunctions.m for the details. In general, care is taken
% to avoid numerical issues when the arguments are extreme.
%
% Copyright (c) by Hannes Nickisch, 2013-10-24.
%
% See also LIKFUNCTIONS.M.
lik = {@likGauss}; % in principle any likelihood function can be warped but only
% for homoscedastic likelihoods, in particular Gaussian has feasible integrals
if numel(warp)==0, warp = 'id'; end % set default warping function
ng = g(warp); % number of hyperparameters for the warping function
nhyp = ['(',num2str(ng),'+',feval(lik{:}),')']; % number of hyperparameters
if nargin<4, varargout = {nhyp}; return, end % report number of parameters
nhyp = eval(nhyp);
if nhyp>length(hyp), error('not enough hyperparameters'), end
[gy,lgpy] = g(warp,y,hyp(1:ng)); % evaluate warping function
i = 0; if nargin>6, i = varargin{3}; varargin{3} = varargin{3}-ng; end
varargout = cell(nargout,1); % allocate memory for output arguments
if i==0 || ng<i % only evaluate the required parts
[varargout{:}] = feval(lik{:},hyp(ng+1:end),gy,mu,varargin{:}); % eval lik
end
if nargin<6 % prediction mode if inf is not present
if numel(y)==0, y = zeros(size(mu)); end
s2zero = 1; % s2==0 ?
if nargin>4, s2 = varargin{1}; if norm(s2)>0, s2zero = 0; end, end
if s2zero % log probability
lp = likGaussWarp(warp, hyp, y, mu, [], 'infLaplace'); s2 = 0*mu;
else
lp = likGaussWarp(warp, hyp, y, mu, s2, 'infEP'); % prediction
end
if nargout>0, varargout{1} = lp; end % works for any lik
% the predictive moments are very hard to compute for lik not being likGauss
if nargout>1
ymu = mu; % first g(y) moment
sn2 = exp(2*hyp(ng+1)); % Gaussian noise variance
ys2 = s2 + sn2; % second g(y) moment
% ymuM = ig(warp,ymu,hyp(1:ng)); % median
% yupp = ig(warp,ymu+2*sqrt(ys2),hyp(1:ng)); % 95% confidence interval
% ylow = ig(warp,ymu-2*sqrt(ys2),hyp(1:ng));
% ys2C = (yupp-ylow).^2/16;
N = 20; [t,w] = gauher(N); oN = ones(1,N); % Gaussian-Hermite quadrature
Z = sqrt(ys2(:))*t'+ymu(:)*oN;
Y = ig(warp,Z,hyp(1:ng));
ymu = Y*w; ys2 = (Y-ymu*oN).^2*w; % first and second y moment
varargout{2} = reshape(ymu,size(mu));
if nargout>2
varargout{3} = ys2;
end
end
else
inf = varargin{2}; % obtain input variables
switch inf
case {'infLaplace','infEP'} % they have the same structure
if nargin<7 % no derivative mode
if nargout>0, varargout{1} = varargout{1} + lgpy; end
else % derivative mode
if i<=ng % derivatives w.r.t. warping function parameters
n = max([numel(y),numel(mu)]);
for j=2:nargout, varargout{j} = zeros(n,1); end
[dgy,dlgpy] = g(warp,y,hyp(1:ng),i); % warping function derivative
out = cell(nargout+1,1); % allocate memory
[out{:}] = likGaussWarp(warp, hyp, y, mu, varargin{1:2}); % query lik
% works only for homoscedastic likelihoods where y and mu can be swapped
if nargout>0, varargout{1} = dlgpy - out{2}.*dgy; end % apply chain rule
if nargout>1, varargout{2} = - out{3}.*dgy; end
if nargout>2, varargout{3} = - out{4}.*dgy; end
end
end
case 'infVB' % output does not depend on mu and following parameters
end
end
% marshalling of parameters and available warping functions
function varargout = g(warp,varargin)
varargout = cell(nargout, 1); % allocate the right number of output arguments
if strcmp(warp,'id') % indentity warping likGaussWarp = likGauss
if nargin<2
if nargout>0, varargout{1} = 0; end
elseif nargin<4
if nargout>0, varargout{1} = varargin{1}; end
if nargout>1, varargout{2} = 0*varargin{1}; end
end
elseif numel(strfind(warp,'poly'))>0
m = str2double(warp(5:end));
if nargin<2 && nargout>0, varargout{1} = m-1; return, end
[varargout{:}] = g_poly(varargin{:});
elseif numel(strfind(warp,'tanh'))>0
m = str2double(warp(5:end));
if nargin<2 && nargout>0, varargout{1} = 3*m; return, end
[varargout{:}] = g_tanh(varargin{:});
end
% invert g(y) = z <=> ig(z) = y via bisection search + Newton iterations
function [y,n,d] = ig(warp,z,hyp)
y = z; gy = g(warp,z,hyp)-z; dz = max(abs(z(:))); % lower bound search ylow
while any(0<gy(:)), y(0<gy) = y(0<gy)-dz; gy = g(warp,y,hyp)-z; end, ylow = y;
y = z; gy = g(warp,z,hyp)-z; dz = max(abs(z(:))); % upper bound search yupp
while any(0>gy(:)), y(0>gy) = y(0>gy)+dz; gy = g(warp,y,hyp)-z; end, yupp = y;
for n=1:12 % bisection search ylow<=y<=yupp
d = max(abs(gy(:))); if d<sqrt(eps), break, end
y = (ylow+yupp)/2; gy = g(warp,y,hyp)-z;
ylow(gy<0) = y(gy<0); yupp(gy>0) = y(gy>0);
end
for n=1:12 % Newton iterations
[gy,lgpy] = g(warp,y,hyp); gpy = exp(lgpy);
y = y - (gy-z)./gpy;
y(y<ylow) = ylow(y<ylow); y(y>yupp) = yupp(y>yupp); % keep brackets
d = max( abs(gy(:)-z(:)) );
if d<sqrt(eps), break, end
end
if n==10 || d>sqrt(eps), fprintf('Not converged: res=%1.4e\n',d), end
% poly warping function g(y) and log of the derivative log(g'(y))>0
% or derivatives of the latter w.r.t. ith hyperparameter
function [gy,lgpy] = g_poly(y,hyp,i)
m = numel(hyp)+1;
c = exp(hyp);
if nargin==2 % function values
gy = y; gpy = 1; ay = abs(y);
for j=2:m
gy = gy + c(j-1)*ay.^j;
gpy = gpy + c(j-1)*j*ay.^(j-1);
end
gy = sign(y).*gy;
lgpy = log(gpy);
else % derivatives
gpy = 1; ay = abs(y);
for j=2:m
gpy = gpy + c(j-1)*j*ay.^(j-1);
end
gy = c(i)*ay.^j;
lgpy = c(i)*j*ay.^(j-1)./gpy;
end
% tanh warping function g(y) and log of the derivative log(g'(y))>0
% or derivatives of the latter w.r.t. ith hyperparameter
function [gy,lgpy] = g_tanh(y,hyp,i)
m = numel(hyp)/3;
a = exp(hyp(1:m)); b = exp(hyp(m+(1:m))); c = hyp(2*m+(1:m));
if nargin==2 % function values
gy = y; gpy = 1;
for j=1:m
ai = a(j); bi = b(j); ci = c(j); ti = tanh(bi*(y+ci)); dti = 1-ti.^2;
gy = gy + ai *ti;
gpy = gpy + ai*bi*dti;
end
lgpy = log(gpy);
else % derivatives
gpy = 1;
for j=1:m
ai = a(j); bi = b(j); ci = c(j); ti = tanh(bi*(y+ci)); dti = 1-ti.^2;
gpy = gpy + ai*bi*dti;
end
if i<=m
j = i;
ai = a(j); bi = b(j); ci = c(j); ti = tanh(bi*(y+ci)); dti = 1-ti.^2;
gy = ai*ti;
lgpy = ai*bi*dti./gpy;
elseif i<=2*m
j = i-m;
ai = a(j); bi = b(j); ci = c(j); ti = tanh(bi*(y+ci)); dti = 1-ti.^2;
gy = ai*bi*dti.*(y+ci);
d2ti = -2*ti.*dti;
lgpy = ai*bi*(dti+bi*d2ti.*(y+ci))./gpy;
else
j = i-2*m;
ai = a(j); bi = b(j); ci = c(j); ti = tanh(bi*(y+ci)); dti = 1-ti.^2;
gy = ai*bi*dti;
d2ti = -2*ti.*dti;
lgpy = ai*bi^2*d2ti./gpy;
end
end
|
github
|
Hadisalman/stoec-master
|
likWeibull.m
|
.m
|
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/lik/likWeibull.m
| 4,548 |
utf_8
|
5134b34b56b016f15d716469fb93c583
|
function [varargout] = likWeibull(link, hyp, y, mu, s2, inf, i)
% likWeibull - Weibull likelihood function for strictly positive data y. The
% expression for the likelihood is
% likWeibull(f) = g1*ka/mu * (g1*y/mu)^(ka-1) * exp(-(g1*y/mu)^ka) with
% gj = gamma(1+j/ka), mean=mu and variance=mu^2*(g2/g1^2-1) where mu = g(f) is
% the Weibull intensity, f is a Gaussian process, y is the positive data.
% Hence, we have llik(f) = log(likWeibull(f)) =
% log(g1*ka/mu) + (ka-1)*log(g1*y/mu) - (g1*y/mu)^ka.
%
% We provide two inverse link functions 'exp' and 'logistic':
% g(f) = exp(f) and g(f) = log(1+exp(f))).
% The link functions are located at util/glm_invlink_*.m.
%
% Note that for neither link function the likelihood lik(f) is log concave.
%
% The hyperparameters are:
%
% hyp = [ log(ka) ]
%
% Several modes are provided, for computing likelihoods, derivatives and moments
% respectively, see likFunctions.m for the details. In general, care is taken
% to avoid numerical issues when the arguments are extreme.
%
% See also LIKFUNCTIONS.M.
%
% Copyright (c) by Hannes Nickisch, 2013-10-30.
if nargin<4, varargout = {'1'}; return; end % report number of hyperparameters
ka = exp(hyp);
lg1 = gammaln(1+1/ka); g1 = exp(lg1); dlg1 = -psi(1+1/ka)/ka;
if nargin<6 % prediction mode if inf is not present
if numel(y)==0, y = zeros(size(mu)); end
s2zero = 1; if nargin>4, if norm(s2)>0, s2zero = 0; end, end % s2==0 ?
if s2zero % log probability
lg = g(mu,link);
lp = lg1 + log(ka) + (ka-1)*(lg1+log(y)) - ka*lg - exp(ka*(lg1+log(y)-lg));
else
lp = likWeibull(link, hyp, y, mu, s2, 'infEP');
end
ymu = {}; ys2 = {};
if nargout>1 % compute y moments by quadrature
n = max([length(y),length(mu),length(s2)]); on = ones(n,1);
N = 20; [t,w] = gauher(N); oN = ones(1,N); lw = ones(n,1)*log(w');
mu = mu(:).*on; sig = sqrt(s2(:)).*on; % vectors only
lg = g(sig*t'+mu*oN,link);
ymu = exp(logsumexp2(lg+lw)); % first moment using Gaussian-Hermite quad
if nargout>2
elg = exp(lg); g2 = gamma(1+2/ka);
yv = elg.^2*(g2/g1^2-1); % second y moment from Weibull distribution
ys2 = (yv+(elg-ymu*oN).^2)*w;
end
end
varargout = {lp,ymu,ys2};
else
switch inf
case 'infLaplace'
[lg,dlg,d2lg,d3lg] = g(mu,link); elg = exp(-ka*lg);
if nargin<7 % no derivative mode
lp = lg1 + log(ka) + (ka-1)*(lg1+log(y)) -ka*lg - exp(ka*(lg1+log(y)-lg));
dlp = {}; d2lp = {}; d3lp = {}; % return arguments
if nargout>1
dlp = -ka*dlg + ka*(g1*y).^ka .* elg.*dlg; % dlp, deriv of log lik
if nargout>2 % d2lp, 2nd derivative of log likelihood
d2lp = -ka*d2lg + ka*(g1*y).^ka .* ( -ka*elg.*dlg.^2 + elg.*d2lg );
if nargout>3 % d3lp, 3rd derivative of log likelihood
a = ka^2*dlg.^3 -3*ka*dlg.*d2lg + d3lg;
d3lp = - ka*d3lg + ka*(g1*y).^ka .* a .*elg;
end
end
end
varargout = {lp,dlp,d2lp,d3lp};
else % derivative mode
v = ka*(lg1+log(y)-lg); ev = exp(v); % derivative of log lik w.r.t. ka
w = v+ka*dlg1; dw = -ka*dlg; d2w = -ka*d2lg;
lp_dhyp = 1 + w - ev.*w;
dlp_dhyp = dw.*(1-ev.*(1+w)); % first derivative
d2lp_dhyp = d2w.*(1-ev.*(1+w)) - dw.^2.*(ev.*(2+w)); % and also second
varargout = {lp_dhyp,dlp_dhyp,d2lp_dhyp};
end
case 'infEP'
if nargin<7 % no derivative mode
% Since we are not aware of an analytical expression of the integral,
% we use quadrature.
varargout = cell(1,nargout);
[varargout{:}] = lik_epquad({@likWeibull,link},hyp,y,mu,s2);
else % derivative mode
varargout = {[]}; % deriv. wrt hyp.lik
end
case 'infVB'
error('infVB not supported')
end
end
% compute the log intensity using the inverse link function
function varargout = g(f,link)
varargout = cell(nargout, 1); % allocate the right number of output arguments
if strcmp(link,'exp')
[varargout{:}] = glm_invlink_exp(f);
else
[varargout{:}] = glm_invlink_logistic(f);
end
|
github
|
Hadisalman/stoec-master
|
likGamma.m
|
.m
|
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/lik/likGamma.m
| 4,573 |
utf_8
|
30195b20deb79baed3429087b58977a8
|
function [varargout] = likGamma(link, hyp, y, mu, s2, inf, i)
% likGamma - Gamma likelihood function for strictly positive data y. The
% expression for the likelihood is
% likGamma(f) = al^al*y^(al-1)/gamma(al) * exp(-y*al/mu) / mu^al with
% mean=mu and variance=mu^2/al where mu = g(f) is the Gamma intensity, f is a
% Gaussian process, y is the strictly positive data. Hence, we have -- with
% log(Zy) = log(gamma(al)) - al*log(al) + (1-al)*log(y)
% llik(f) = log(likGamma(f)) = -al*( log(g(f)) + y/g(f) ) - log(Zy).
% The larger one chooses al, the stronger the likelihood resembles a Gaussian
% since skewness = 2/sqrt(al) and kurtosis = 6/al.
%
% We provide two inverse link functions 'exp' and 'logistic':
% g(f) = exp(f) and g(f) = log(1+exp(f))).
% The link functions are located at util/glm_invlink_*.m.
%
% Note that for neither link function the likelihood lik(f) is log concave.
%
% The hyperparameters are:
%
% hyp = [ log(al) ]
%
% Several modes are provided, for computing likelihoods, derivatives and moments
% respectively, see likFunctions.m for the details. In general, care is taken
% to avoid numerical issues when the arguments are extreme.
%
% See also LIKFUNCTIONS.M.
%
% Copyright (c) by Hannes Nickisch, 2013-10-16.
if nargin<4, varargout = {'1'}; return; end % report number of hyperparameters
al = exp(hyp);
if nargin<6 % prediction mode if inf is not present
if numel(y)==0, y = zeros(size(mu)); end
s2zero = 1; if nargin>4, if norm(s2)>0, s2zero = 0; end, end % s2==0 ?
if s2zero % log probability
lg = g(mu,link);
lZy = gammaln(al) - al*log(al) + (1-al)*log(y); % normalisation constant
lp = -al*(lg+y./exp(lg)) - lZy;
else
lp = likGamma(link, hyp, y, mu, s2, 'infEP');
end
ymu = {}; ys2 = {};
if nargout>1 % compute y moments by quadrature
n = max([length(y),length(mu),length(s2)]); on = ones(n,1);
N = 20; [t,w] = gauher(N); oN = ones(1,N); lw = ones(n,1)*log(w');
mu = mu(:).*on; sig = sqrt(s2(:)).*on; % vectors only
lg = g(sig*t'+mu*oN,link);
ymu = exp(logsumexp2(lg+lw)); % first moment using Gaussian-Hermite quad
if nargout>2
elg = exp(lg);
yv = elg.^2/al; % second y moment from Gamma distribution
ys2 = (yv+(elg-ymu*oN).^2)*w;
end
end
varargout = {lp,ymu,ys2};
else
switch inf
case 'infLaplace'
[lg,dlg,d2lg,d3lg] = g(mu,link); elg = exp(lg);
if nargin<7 % no derivative mode
lZy = gammaln(al) - al*log(al) + (1-al)*log(y); % normalisation constant
lp = -al*(lg+y./elg) - lZy;
dlp = {}; d2lp = {}; d3lp = {}; % return arguments
if nargout>1
dlp = -al*dlg.*(1-y./elg); % dlp, derivative of log likelihood
if nargout>2 % d2lp, 2nd derivative of log likelihood
d2lp = -al*d2lg.*(1-y./elg) - al*dlg.*dlg.*y./elg;
if nargout>3 % d3lp, 3rd derivative of log likelihood
d3lp = -al*d3lg.*(1-y./elg) + al*dlg.*(dlg.*dlg-3*d2lg).*y./elg;
end
end
end
varargout = {lp,dlp,d2lp,d3lp};
else % derivative mode
dlZy = al*psi(0,al) - al*(log(al) + 1 + log(y));
lp_dhyp = -al*(lg+y./elg) - dlZy; % derivative of log likelihood w.r.t. al
dlp_dhyp = -al*dlg.*(1-y./elg); % first derivative
d2lp_dhyp = -al*d2lg.*(1-y./elg) - al*dlg.*dlg.*y./elg; % and also second
varargout = {lp_dhyp,dlp_dhyp,d2lp_dhyp};
end
case 'infEP'
if nargin<7 % no derivative mode
% Since we are not aware of an analytical expression of the integral,
% we use quadrature.
varargout = cell(1,nargout);
[varargout{:}] = lik_epquad({@likGamma,link},hyp,y,mu,s2);
else % derivative mode
varargout = {[]}; % deriv. wrt hyp.lik
end
case 'infVB'
error('infVB not supported')
end
end
% compute the log intensity using the inverse link function
function varargout = g(f,link)
varargout = cell(nargout, 1); % allocate the right number of output arguments
if strcmp(link,'exp')
[varargout{:}] = glm_invlink_exp(f);
else
[varargout{:}] = glm_invlink_logistic(f);
end
|
github
|
Hadisalman/stoec-master
|
likInvGauss.m
|
.m
|
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/lik/likInvGauss.m
| 4,679 |
utf_8
|
1bffc204bfdee3ee427008906bce81ad
|
function [varargout] = likInvGauss(link, hyp, y, mu, s2, inf, i)
% likInvGauss - Inverse Gaussian likelihood function for strictly positive data
% y. The expression for the likelihood is
% likInvGauss(f) = sqrt(lam/(2*pi*y^3))*exp(-lam*(mu-y)^2/(2*mu^2*y)) with
% mean=mu and variance=mu^3/lam where mu = g(f) is the Inverse Gaussian
% intensity, f is a Gaussian process, y is the strictly positive data.
% Hence, we have -- with log(Zy) = -(log(lam)-log(2*pi*y^3))/2
% llik(f) = log(likInvGauss(f)) = -lam*(y-mu)^2/(2*mu^2*y) - log(Zy).
% The larger one chooses lam, the stronger the likelihood resembles a Gaussian
% since skewness = 3*sqrt(mu/lam) and kurtosis = 15*mu/lam.
%
% We provide two inverse link functions 'exp' and 'logistic':
% g(f) = exp(f) and g(f) = log(1+exp(f))).
% The link functions are located at util/glm_invlink_*.m.
%
% Note that for neither link function the likelihood lik(f) is log concave.
%
% The hyperparameters are:
%
% hyp = [ log(lam) ]
%
% Several modes are provided, for computing likelihoods, derivatives and moments
% respectively, see likFunctions.m for the details. In general, care is taken
% to avoid numerical issues when the arguments are extreme.
%
% See also LIKFUNCTIONS.M.
%
% Copyright (c) by Hannes Nickisch, 2013-10-16.
if nargin<4, varargout = {'1'}; return; end % report number of hyperparameters
lam = exp(hyp);
if nargin<6 % prediction mode if inf is not present
if numel(y)==0, y = zeros(size(mu)); end
s2zero = 1; if nargin>4, if norm(s2)>0, s2zero = 0; end, end % s2==0 ?
if s2zero % log probability
lg = g(mu,link); elg = exp(lg);
lZy = -(log(lam)-log(2*pi*y.^3))/2; % normalisation constant
lp = -lam*(y./elg-1).^2 ./(2*y) - lZy;
else
lp = likInvGauss(link, hyp, y, mu, s2, 'infEP');
end
ymu = {}; ys2 = {};
if nargout>1 % compute y moments by quadrature
n = max([length(y),length(mu),length(s2)]); on = ones(n,1);
N = 20; [t,w] = gauher(N); oN = ones(1,N); lw = ones(n,1)*log(w');
mu = mu(:).*on; sig = sqrt(s2(:)).*on; % vectors only
lg = g(sig*t'+mu*oN,link);
ymu = exp(logsumexp2(lg+lw)); % first moment using Gaussian-Hermite quad
if nargout>2
elg = exp(lg);
yv = elg.^3/lam; % second y moment from inverse Gaussian distribution
ys2 = (yv+(elg-ymu*oN).^2)*w;
end
end
varargout = {lp,ymu,ys2};
else
switch inf
case 'infLaplace'
[lg,dlg,d2lg,d3lg] = g(mu,link); elg = exp(lg);
if nargin<7 % no derivative mode
lZy = -(log(lam)-log(2*pi*y.^3))/2; % normalisation constant
lp = -lam*(y./elg-1).^2 ./(2*y) - lZy;
dlp = {}; d2lp = {}; d3lp = {}; % return arguments
if nargout>1
dlp = lam*(y./elg-1).*dlg./elg; % dlp, derivative of log likelihood
if nargout>2 % d2lp, 2nd derivative of log likelihood
d2lp = lam*( (y./elg-1).*(d2lg-dlg.^2) - y.*dlg.^2./elg )./elg;
if nargout>3 % d3lp, 3rd derivative of log likelihood
d3lp = lam*( (y./elg-1) .* (4*dlg.^3-6*dlg.*d2lg+d3lg) ...
+ (3*dlg.^3 - 3*dlg.*d2lg) )./ elg;
end
end
end
varargout = {lp,dlp,d2lp,d3lp};
else % derivative mode
lp_dhyp = 1/2-lam*(y./elg-1).^2 ./(2*y); % deriv. of log lik w.r.t. lam
dlp_dhyp = lam*(y./elg-1).*dlg./elg; % first derivative
d2lp_dhyp = lam*( (y./elg-1).*(d2lg-dlg.^2) - y.*dlg.^2./elg )./elg; % 2nd
varargout = {lp_dhyp,dlp_dhyp,d2lp_dhyp};
end
case 'infEP'
if nargin<7 % no derivative mode
% Since we are not aware of an analytical expression of the integral,
% we use quadrature.
varargout = cell(1,nargout);
[varargout{:}] = lik_epquad({@likInvGauss,link},hyp,y,mu,s2);
else % derivative mode
varargout = {[]}; % deriv. wrt hyp.lik
end
case 'infVB'
error('infVB not supported')
end
end
% compute the log intensity using the inverse link function
function varargout = g(f,link)
varargout = cell(nargout, 1); % allocate the right number of output arguments
if strcmp(link,'exp')
[varargout{:}] = glm_invlink_exp(f);
else
[varargout{:}] = glm_invlink_logistic(f);
end
|
github
|
Hadisalman/stoec-master
|
likPoisson.m
|
.m
|
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/lik/likPoisson.m
| 4,178 |
utf_8
|
9bdb4f7a4905445839d4697149efc827
|
function [varargout] = likPoisson(link, hyp, y, mu, s2, inf, i)
% likPoisson - Poisson likelihood function for count data y. The expression for
% the likelihood is
% likPoisson(f) = mu^y * exp(-mu) / y! with mean=variance=mu
% where mu = g(f) is the Poisson intensity, f is a
% Gaussian process, y is the non-negative integer count data and
% y! = gamma(y+1) its factorial. Hence, we have -- with Zy = gamma(y+1) = y! --
% llik(f) = log(likPoisson(f)) = log(g(f))*y - g(f) - log(Zy).
% The larger the intensity mu, the stronger the likelihood resembles a Gaussian
% since skewness = 1/sqrt(mu) and kurtosis = 1/mu.
%
% We provide two inverse link functions 'exp' and 'logistic':
% For g(f) = exp(f), we have lik(f) = exp(f*y-exp(f)) / Zy.
% For g(f) = log(1+exp(f))), we have lik(f) = log^y(1+exp(f)))(1+exp(f)) / Zy.
% The link functions are located at util/glm_invlink_*.m.
%
% Note that for both intensities g(f) the likelihood lik(f) is log concave.
%
% Several modes are provided, for computing likelihoods, derivatives and moments
% respectively, see likFunctions.m for the details. In general, care is taken
% to avoid numerical issues when the arguments are extreme.
%
% See also LIKFUNCTIONS.M.
%
% Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2013-10-16.
if nargin<4, varargout = {'0'}; return; end % report number of hyperparameters
if nargin<6 % prediction mode if inf is not present
if numel(y)==0, y = zeros(size(mu)); end
s2zero = 1; if nargin>4, if norm(s2)>0, s2zero = 0; end, end % s2==0 ?
if s2zero % log probability
lg = g(mu,link);
lp = lg.*y - exp(lg) - gammaln(y+1);
else
lp = likPoisson(link, hyp, y, mu, s2, 'infEP');
end
ymu = {}; ys2 = {};
if nargout>1 % compute y moments by quadrature
n = max([length(y),length(mu),length(s2)]); on = ones(n,1);
N = 20; [t,w] = gauher(N); oN = ones(1,N); lw = ones(n,1)*log(w');
mu = mu(:).*on; sig = sqrt(s2(:)).*on; % vectors only
lg = g(sig*t'+mu*oN,link);
ymu = exp(logsumexp2(lg+lw)); % first moment using Gaussian-Hermite quad
if nargout>2
elg = exp(lg);
yv = elg; % second y moment from Poisson distribution
ys2 = (yv+(elg-ymu*oN).^2)*w;
end
end
varargout = {lp,ymu,ys2};
else
switch inf
case 'infLaplace'
if nargin<7 % no derivative mode
[lg,dlg,d2lg,d3lg] = g(mu,link); elg = exp(lg);
lp = lg.*y - elg - gammaln(y+1);
dlp = {}; d2lp = {}; d3lp = {}; % return arguments
if nargout>1
dlp = dlg.*(y-elg); % dlp, derivative of log likelihood
if nargout>2 % d2lp, 2nd derivative of log likelihood
d2lp = d2lg.*(y-elg) - dlg.*dlg.*elg;
if nargout>3 % d3lp, 3rd derivative of log likelihood
d3lp = d3lg.*(y-elg) - dlg.*(dlg.*dlg+3*d2lg).*elg;
end
end
end
varargout = {lp,dlp,d2lp,d3lp};
else % derivative mode
varargout = {[],[],[]}; % derivative w.r.t. hypers
end
case 'infEP'
if nargin<7 % no derivative mode
% Since we are not aware of an analytical expression of the integral,
% hence we use quadrature.
varargout = cell(1,nargout);
[varargout{:}] = lik_epquad({@likPoisson,link},hyp,y,mu,s2);
else % derivative mode
varargout = {[]}; % deriv. wrt hyp.lik
end
case 'infVB'
error('infVB not supported')
end
end
% compute the log intensity using the inverse link function
function varargout = g(f,link)
varargout = cell(nargout, 1); % allocate the right number of output arguments
if strcmp(link,'exp')
[varargout{:}] = glm_invlink_exp(f);
else
[varargout{:}] = glm_invlink_logistic(f);
end
|
github
|
Hadisalman/stoec-master
|
likLogistic.m
|
.m
|
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/lik/likLogistic.m
| 6,137 |
utf_8
|
0227c40f8798f8f47d1f32e9dfd6e946
|
function [varargout] = likLogistic(hyp, y, mu, s2, inf, i)
% likLogistic - logistic function for binary classification or logit regression.
% The expression for the likelihood is
% likLogistic(t) = 1./(1+exp(-t)).
%
% Several modes are provided, for computing likelihoods, derivatives and moments
% respectively, see likFunctions.m for the details. In general, care is taken
% to avoid numerical issues when the arguments are extreme. The moments
% \int f^k likLogistic(y,f) N(f|mu,var) df are calculated via a cumulative
% Gaussian scale mixture approximation.
%
% Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2013-09-02.
%
% See also LIKFUNCTIONS.M.
if nargin<3, varargout = {'0'}; return; end % report number of hyperparameters
if nargin>1, y = sign(y); y(y==0) = 1; else y = 1; end % allow only +/- 1 values
if numel(y)==0, y = 1; end
if nargin<5 % prediction mode if inf is not present
y = y.*ones(size(mu)); % make y a vector
s2zero = 1; if nargin>3, if norm(s2)>0, s2zero = 0; end, end % s2==0 ?
if s2zero % log probability evaluation
yf = y.*mu; % product latents and labels
lp = yf; ok = -35<yf; lp(ok) = -log(1+exp(-yf(ok))); % log of likelihood
else % prediction
lp = likLogistic(hyp, y, mu, s2, 'infEP');
end
ymu = {}; ys2 = {};
if nargout>1
p = exp(lp);
ymu = 2*p-1; % first y moment
if nargout>2
ys2 = 4*p.*(1-p); % second y moment
end
end
varargout = {lp,ymu,ys2};
else % inference mode
switch inf
case 'infLaplace'
if nargin<6 % no derivative mode
f = mu; yf = y.*f; s = -yf; % product latents and labels
dlp = {}; d2lp = {}; d3lp = {}; % return arguments
ps = max(0,s);
lp = -(ps+log(exp(-ps)+exp(s-ps))); % lp = -(log(1+exp(s)))
if nargout>1 % first derivatives
s = min(0,f);
p = exp(s)./(exp(s)+exp(s-f)); % p = 1./(1+exp(-f))
dlp = (y+1)/2-p; % derivative of log likelihood
if nargout>2 % 2nd derivative of log likelihood
d2lp = -exp(2*s-f)./(exp(s)+exp(s-f)).^2;
if nargout>3 % 3rd derivative of log likelihood
d3lp = 2*d2lp.*(0.5-p);
end
end
end
varargout = {lp,dlp,d2lp,d3lp};
else % derivative mode
varargout = {[],[],[]}; % derivative w.r.t. hypers
end
case 'infEP'
if nargin<6 % no derivative mode
y = y.*ones(size(mu)); % make y a vector
% likLogistic(t) \approx 1/2 + \sum_{i=1}^5 (c_i/2) erf(lam_i/sqrt(2)t)
lam = sqrt(2)*[0.44 0.41 0.40 0.39 0.36]; % approx coeffs lam_i and c_i
c = [1.146480988574439e+02; -1.508871030070582e+03; 2.676085036831241e+03;
-1.356294962039222e+03; 7.543285642111850e+01 ];
[lZc,dlZc,d2lZc] = likErf([], y*ones(1,5), mu*lam, s2*(lam.^2), inf);
lZ = log_expA_x(lZc,c); % A=lZc, B=dlZc, d=c.*lam', lZ=log(exp(A)*c)
dlZ = expABz_expAx(lZc, c, dlZc, c.*lam'); % ((exp(A).*B)*d)./(exp(A)*c)
% d2lZ = ((exp(A).*Z)*e)./(exp(A)*c) - dlZ.^2 where e = c.*(lam.^2)'
d2lZ = expABz_expAx(lZc, c, dlZc.^2+d2lZc, c.*(lam.^2)') - dlZ.^2;
% The scale mixture approximation does not capture the correct asymptotic
% behavior; we have linear decay instead of quadratic decay as suggested
% by the scale mixture approximation. By observing that for large values
% of -f*y ln(p(y|f)) for likLogistic is linear in f with slope y, we are
% able to analytically integrate the tail region.
val = abs(mu)-196/200*s2-4; % empirically determined bound at val==0
lam = 1./(1+exp(-10*val)); % interpolation weights
lZtail = min(s2/2-abs(mu),-0.1); % apply the same to p(y|f) = 1 - p(-y|f)
dlZtail = -sign(mu); d2lZtail = zeros(size(mu));
id = y.*mu>0; lZtail(id) = log(1-exp(lZtail(id))); % label and mean agree
dlZtail(id) = 0;
lZ = (1-lam).* lZ + lam.* lZtail; % interpolate between scale ..
dlZ = (1-lam).* dlZ + lam.* dlZtail; % .. mixture and ..
d2lZ = (1-lam).*d2lZ + lam.*d2lZtail; % .. tail approximation
varargout = {lZ,dlZ,d2lZ};
else % derivative mode
varargout = {[]}; % deriv. wrt hyp.lik
end
case 'infVB'
% variational lower site bound
% using -log(1+exp(-s)) = s/2 -log( 2*cosh(s/2) );
% the bound has the form: (b+z/ga)*f - f.^2/(2*ga) - h(ga)/2
n = numel(s2); b = (y/2).*ones(n,1); z = zeros(size(b));
varargout = {b,z};
end
end
% computes y = log( exp(A)*x ) in a numerically safe way by subtracting the
% maximal value in each row to avoid cancelation after taking the exp
function y = log_expA_x(A,x)
N = size(A,2); maxA = max(A,[],2); % number of columns, max over columns
y = log(exp(A-maxA*ones(1,N))*x) + maxA; % exp(A) = exp(A-max(A))*exp(max(A))
% computes y = ( (exp(A).*B)*z ) ./ ( exp(A)*x ) in a numerically safe way
% The function is not general in the sense that it yields correct values for
% all types of inputs. We assume that the values are close together.
function y = expABz_expAx(A,x,B,z)
N = size(A,2); maxA = max(A,[],2); % number of columns, max over columns
A = A-maxA*ones(1,N); % subtract maximum value
y = ( (exp(A).*B)*z ) ./ ( exp(A)*x );
|
github
|
Hadisalman/stoec-master
|
likSech2.m
|
.m
|
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/lik/likSech2.m
| 8,514 |
utf_8
|
25a639e43b4bcdc60d8fd113ded18611
|
function [varargout] = likSech2(hyp, y, mu, s2, inf, i)
% likSech2 - sech-square likelihood function for regression. Often, the sech-
% square distribution is also referred to as the logistic distribution not to be
% confused with the logistic function for classification. The expression for the
% likelihood is
% likSech2(t) = Z / cosh(tau*(y-t))^2 where
% tau = pi/(2*sqrt(3)*sn) and Z = tau/2
% and y is the mean and sn^2 is the variance.
%
% hyp = [ log(sn) ]
%
% Several modes are provided, for computing likelihoods, derivatives and moments
% respectively, see likFunctions.m for the details. In general, care is taken
% to avoid numerical issues when the arguments are extreme. The moments
% \int f^k likSech2(y,f) N(f|mu,var) df are calculated via a Gaussian
% scale mixture approximation.
%
% Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2013-09-02.
%
% See also LIKFUNCTIONS.M, LIKLOGISTIC.M.
if nargin<3, varargout = {'1'}; return; end % report number of hyperparameters
sn = exp(hyp); tau = pi/(2*sqrt(3)*sn);
lZ = log(pi) - log(sn) - log(4*sqrt(3));
if nargin<5 % prediction mode if inf is not present
if numel(y)==0, y = zeros(size(mu)); end
s2zero = 1; if nargin>3, if norm(s2)>0, s2zero = 0; end, end % s2==0 ?
if s2zero % log probability evaluation
lp = lZ - 2*logcosh(tau*(y-mu)); s2 = 0;
else % prediction
lp = likSech2(hyp, y, mu, s2, 'infEP');
end
ymu = {}; ys2 = {};
if nargout>1
ymu = mu; % first y moment
if nargout>2
ys2 = s2 + sn.^2; % second y moment
end
end
varargout = {lp,ymu,ys2};
else % inference mode
switch inf
case 'infLaplace'
r = y-mu; [g,dg,d2g,d3g] = logcosh(tau.*r); % precompute derivatives
if nargin<6 % no derivative mode
dlp = {}; d2lp = {}; d3lp = {};
lp = lZ - 2*g;
if nargout>1 % first derivatives
dlp = 2*tau.*dg;
if nargout>2 % 2nd derivative of log likelihood
d2lp = -2*tau.^2.*d2g;
if nargout>3 % 3rd derivative of log likelihood
d3lp = 2*tau.^3.*d3g;
end
end
end
varargout = {lp,dlp,d2lp,d3lp};
else % derivative mode
lp_dhyp = 2*tau.*r.*dg - 1; % derivative w.r.t. sn
dlp_dhyp = -2*tau.*(dg+tau.*r.*d2g);
d2lp_dhyp = 2*tau.^2.*(2*d2g + tau.*r.*d3g);
varargout = {lp_dhyp,dlp_dhyp,d2lp_dhyp};
end
case 'infEP'
n = max([length(y),length(mu),length(s2),length(sn)]); on = ones(n,1);
y = y.*on; mu = mu.*on; s2 = s2.*on; sn = sn.*on; % vectors only
fac = 1e3; % factor between the widths of the two distributions ...
% ... from when one considered a delta peak, we use 3 orders of magnitude
idlik = fac*sn<sqrt(s2); % Likelihood is a delta peak
idgau = fac*sqrt(s2)<sn; % Gaussian is a delta peak
id = ~idgau & ~idlik; % interesting case in between
% likLogistic(t) \approx 1/2 + \sum_{i=1}^5 (c_i/2) erf(lam_i/sqrt(2)t)
% likSech2(t|y,sn) \approx \sum_{i=1}^5 c_i likGauss(t|y,sn*rho_i)
lam = sqrt(2)*[0.44 0.41 0.40 0.39 0.36]; % approx coeffs lam_i, c_i, rho_i
c = [1.146480988574439e+02; -1.508871030070582e+03; 2.676085036831241e+03;
-1.356294962039222e+03; 7.543285642111850e+01 ];
rho = sqrt(3)./(pi*lam); o5 = ones(1,5);
if nargin<6 % no derivative mode
lZ = zeros(n,1); dlZ = lZ; d2lZ = lZ; % allocate memory
if any(idlik)
[lZ(idlik),dlZ(idlik),d2lZ(idlik)] = ...
likGauss(log(s2(idlik))/2, mu(idlik), y(idlik));
end
if any(idgau)
[lZ(idgau),dlZ(idgau),d2lZ(idgau)] = ...
likSech2(log(sn(idgau)), mu(idgau), y(idgau));
end
if any(id)
[lZc,dlZc,d2lZc] = likGauss(log(sn(id)*rho), ...
y(id)*o5, mu(id)*o5, s2(id)*o5, inf);
lZ(id) = log_expA_x(lZc,c); % A=lZc, B=dlZc, lZ=log(exp(A)*c)
dlZ(id) = expABz_expAx(lZc, c, dlZc, c); % ((exp(A).*B)*c)./(exp(A)*c)
% d2lZ(id) = ((exp(A).*Z)*c)./(exp(A)*c) - dlZ.^2
d2lZ(id) = expABz_expAx(lZc, c, dlZc.^2+d2lZc, c) - dlZ(id).^2;
% the tail asymptotics of likSech2 is the same as for likLaplace
% which is not covered by the scale mixture approximation, so for
% extreme values, we approximate likSech2 by a rescaled likLaplace
tmu = (mu-y)./sn; tvar = s2./sn.^2; crit = 0.596*(abs(tmu)-5.38)-tvar;
idl = -1<crit & id; % if 0<crit, Laplace is better
if any(idl) % close to zero, we use a smooth ..
lam = 1./(1+exp(-15*crit(idl))); % .. interpolation with weights lam
thyp = log(sqrt(6)*sn(idl)/pi);
[lZl,dlZl,d2lZl] = likLaplace(thyp, y(idl), mu(idl), s2(idl), inf);
lZ(idl) = (1-lam).*lZ(idl) + lam.*lZl;
dlZ(idl) = (1-lam).*dlZ(idl) + lam.*dlZl;
d2lZ(idl) = (1-lam).*d2lZ(idl) + lam.*d2lZl;
end
end
varargout = {lZ,dlZ,d2lZ};
else % derivative mode
dlZhyp = zeros(n,1);
if any(idlik)
dlZhyp(idlik) = 0;
end
if any(idgau)
dlZhyp(idgau) = ...
likSech2(log(sn(idgau)), mu(idgau), y(idgau), 'infLaplace', 1);
end
if any(id)
lZc = likGauss(log(sn(id)*rho),y(id)*o5,mu(id)*o5,s2(id)*o5,inf);
dlZhypc = likGauss(log(sn(id)*rho),y(id)*o5,mu(id)*o5,s2(id)*o5,inf,1);
% dlZhyp = ((exp(lZc).*dlZhypc)*c)./(exp(lZc)*c)
dlZhyp(id) = expABz_expAx(lZc, c, dlZhypc, c);
% the tail asymptotics of likSech2 is the same as for likLaplace
% which is not covered by the scale mixture approximation, so for
% extreme values, we approximate likLogistic by a rescaled likLaplace
tmu = (mu-y)./sn; tvar = s2./sn.^2; crit = 0.596*(abs(tmu)-5.38)-tvar;
idl = -1<crit & id; % if 0<crit, Laplace is better
if any(idl) % close to zero, we use a smooth ..
lam = 1./(1+exp(-15*crit(idl))); % .. interpolation with weights lam
thyp = log(sqrt(6)*sn(idl)/pi);
dlZhypl = likLaplace(thyp, y(idl), mu(idl), s2(idl), inf, i);
dlZhyp(idl) = (1-lam).*dlZhyp(idl) + lam.*dlZhypl;
end
end
varargout = {dlZhyp}; % derivative w.r.t. hypers
end
case 'infVB'
% variational lower site bound
% using -log( 2*cosh(s/2) );
% the bound has the form: (b+z/ga)*f - f.^2/(2*ga) - h(ga)/2
n = numel(s2); b = zeros(n,1); y = y.*ones(n,1); z = y;
varargout = {b,z};
end
end
% numerically safe version of log(cosh(x)) = log(exp(x)+exp(-x))-log(2)
function [f,df,d2f,d3f] = logcosh(x)
a = exp(-2*abs(x)); % always between 0 and 1 and therefore safe to evaluate
f = abs(x) + log(1+a) - log(2);
df = sign(x).*( 1 - 2*a./(1+a) );
d2f = 4*a./(1+a).^2;
d3f = -8*sign(x).*a.*(1-a)./(1+a).^3;
% computes y = log( exp(A)*x ) in a numerically safe way by subtracting the
% maximal value in each row to avoid cancelation after taking the exp
function y = log_expA_x(A,x)
N = size(A,2); maxA = max(A,[],2); % number of columns, max over columns
y = log(exp(A-maxA*ones(1,N))*x) + maxA; % exp(A) = exp(A-max(A))*exp(max(A))
% computes y = ( (exp(A).*B)*z ) ./ ( exp(A)*x ) in a numerically safe way
% The function is not general in the sense that it yields correct values for
% all types of inputs. We assume that the values are close together.
function y = expABz_expAx(A,x,B,z)
N = size(A,2); maxA = max(A,[],2); % number of columns, max over columns
A = A-maxA*ones(1,N); % subtract maximum value
y = ( (exp(A).*B)*z ) ./ ( exp(A)*x );
|
github
|
Hadisalman/stoec-master
|
likGumbel.m
|
.m
|
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/lik/likGumbel.m
| 3,976 |
utf_8
|
e181712e58f8360c4d43c5c354d8431a
|
function [varargout] = likGumbel(sign, hyp, y, mu, s2, inf, i)
% likGumbel - Gumbel likelihood function for extremal value regression.
% The expression for the likelihood is
% likGumbel(t) = exp(-z-exp(-z))/be, z = ga+s*(y-t)/be, be = sn*sqrt(6)/pi
% where s={+1,-1} is a sign switching between left and right skewed, ga is the
% Euler-Mascheroni constant, y is the mean, sn^2 is the variance.
% The skewness and kurtosis of likGumbel are 1.14*s and 2.4, respectively.
%
% The hyperparameters are:
%
% hyp = [ log(sn) ]
%
% Several modes are provided, for computing likelihoods, derivatives and moments
% respectively, see likFunctions.m for the details. In general, care is taken
% to avoid numerical issues when the arguments are extreme.
%
% Copyright (c) by Hannes Nickisch, 2013-11-01.
%
% See also LIKFUNCTIONS.M.
if nargin<4, varargout = {'1'}; return; end % report number of hyperparameters
if sign=='-', s = -1; else s = 1; end % extract sign of skewness
sn2 = exp(2*hyp); % extract hyperparameters
ga = 0.5772156649; % Euler-Mascheroni constant
be = sqrt(6*sn2)/pi;
lZ = -log(be);
if nargin<6 % prediction mode if inf is not present
if numel(y)==0, y = zeros(size(mu)); end
s2zero = 1; if nargin>4, if norm(s2)>0, s2zero = 0; end, end % s2==0 ?
if s2zero % log probability evaluation
lp = likGumbel(sign, hyp, y, mu, [], 'infLaplace'); s2 = 0;
else % prediction
lp = likGumbel(sign, hyp, y, mu, s2, 'infEP');
end
ymu = {}; ys2 = {};
if nargout>1
ymu = mu; % first y moment
if nargout>2
ys2 = s2 + sn2; % second y moment
end
end
varargout = {lp,ymu,ys2};
else
switch inf
case 'infLaplace'
z = ga+s*(y-mu)/be; emz = exp(-z);
if nargin<7 % no derivative mode
dlp = {}; d2lp = {}; d3lp = {};
lp = lZ -z -emz;
if nargout>1
dz = -s/be; % dz/dmu
dlp = dz*(emz-1); % dlp, derivative of log likelihood
if nargout>2 % d2lp, 2nd derivative of log likelihood
d2lp = -dz^2*emz;
if nargout>3 % d3lp, 3rd derivative of log likelihood
d3lp = dz^3*emz;
end
end
end
varargout = {lp,dlp,d2lp,d3lp};
else % derivative w.r.t. log(sn)
dz = -s/be; % dz/dmu
dzs = -s*(y-mu)/be; % dz/dlog(sn)
lp_dhyp = dzs.*(emz-1) -1;
dlp_dhyp = dz*(1-emz.*(1+dzs));
d2lp_dhyp = dz^2*emz.*(2+dzs);
varargout = {lp_dhyp,dlp_dhyp,d2lp_dhyp};
end
case 'infEP'
if nargout>1
error('infEP not supported since likT is not log-concave')
end
n = max([length(y),length(mu),length(s2)]); on = ones(n,1);
y = y(:).*on; mu = mu(:).*on; sig = sqrt(s2(:)).*on; % vectors only
% since we are not aware of an analytical expression of the integral,
% we use Gaussian-Hermite quadrature
N = 20; [t,w] = gauher(N); oN = ones(1,N);
lZ = likGumbel(sign, hyp, y*oN, sig*t'+mu*oN, []);
lZ = log_expA_x(lZ,w); % log( exp(lZ)*w )
varargout = {lZ};
case 'infVB'
error('infVB not supported')
end
end
% computes y = log( exp(A)*x ) in a numerically safe way by subtracting the
% maximal value in each row to avoid cancelation after taking the exp
function y = log_expA_x(A,x)
N = size(A,2); maxA = max(A,[],2); % number of columns, max over columns
y = log(exp(A-maxA*ones(1,N))*x) + maxA; % exp(A) = exp(A-max(A))*exp(max(A))
|
github
|
Hadisalman/stoec-master
|
priorSmoothBox1.m
|
.m
|
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/prior/priorSmoothBox1.m
| 1,617 |
utf_8
|
df60218e999e45adf5f4204501f3c42f
|
function [lp,dlp] = priorSmoothBox1(a,b,eta,x)
% Univariate smoothed box prior distribution with linear decay in the log domain
% and infinite support over the whole real axis.
% Compute log-likelihood and its derivative or draw a random sample.
% The prior distribution is parameterized as:
%
% p(x) = sigmoid(eta*(x-a))*(1-sigmoid(eta*(x-b))),
% where sigmoid(z) = 1/(1+exp(-z))
%
% a(1x1) is the lower bound parameter, b(1x1) is the upper bound parameter,
% eta(1x1)>0 is the slope parameter and x(1xN) contains query hyperparameters
% for prior evaluation. Larger values of eta make the distribution more
% box-like.
%
% /------------\
% / \
% -------- | | --------> x
% a b
%
% For more help on design of priors, try "help priorDistributions".
%
% Copyright (c) by Jose Vallet and Hannes Nickisch, 2014-09-08.
%
% See also PRIORDISTRIBUTIONS.M.
if nargin<3, error('a, b and eta parameters need to be provided'), end
if b<=a, error('b must be greater than a.'), end
if ~(isscalar(a)&&isscalar(b)&&isscalar(eta))
error('a, b and eta parameters need to be scalar values')
end
if nargin<4 % inverse sampling
u = exp((b-a)*eta*rand());
lp = log((u-1)/(exp(-eta*a)-u*exp(-eta*b)))/eta;
return
end
[lpa,dlpa] = logr(eta*(x-a)); [lpb,dlpb] = logr(-eta*(x-b));
lp = lpa + lpb - log(b-a) + log(1-exp((a-b)*eta));
dlp = eta*(dlpa - dlpb);
% r(z) = 1/(1+exp(-z)), log(r(z)) = -log(1+exp(-z))
function [lr,dlr] = logr(z)
lr = z; ok = -35<z; lr(ok) = -log(1+exp(-z(ok)));
dlr = 1./(1+exp(z));
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.