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
|
sunhongfu/scripts-master
|
Gsparse.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/Gsparse.m
| 7,162 |
utf_8
|
313f033569655fb4925e3490b7ae7f5a
|
function ob = Gsparse(arg1, varargin)
%function ob = Gsparse(file.wtf | sparse | cell, options)
%
% Construct Gsparse object, either from a sparse matrix itself,
% or from the arguments that would be passed to matlab's sparse() command,
% or from an Aspire binary .wtf file.
%
% The purpose of this object is to overcome some annoying limitations of
% matlab's sparse() function and sparse datatype. In particular, this function
% allows single precision arguments (that are converted silently to doubles,
% as long as matlab continues to insist on that) instead of the useless
% error message provided by our good friends at Mathworks. And you can do
% multiplication of a Gsparse object times a non-double-precision vector
% (which is silently upgraded to doubles), which Matlab does not support.
%
% More substantively, this object also supports the "multidimensional"
% constructs needed in imaging problems. (support mask, subsets, etc.)
%
% This just uses an ordinary Matlab sparse matrix for the core!
% See Gsparse_test.m for example usage.
%
% You create an system object by calling:
% G = Gsparse(file)
% and then you can use it thereafter by typing commands like
% y = G * x.
%
% in
% arg1 char | cell | sparse sparse matrix (usual case)
% or cell array of sparse() arguments
% or filename of an aspire .wtf
% options
% mask [idim] logical support mask
% idim [1,ndim_in] input dimensions: nx,ny,nz etc.
% odim [1,ndim_out] output dimensions: nb,na etc.
% chat verbosity
%
% out
% ob [nd,np] nd = prod(odim), np = sum(mask(:))
% so it is already "masked"
%
% Copyright 2005-6-16, Jeff Fessler, The University of Michigan
if nargin == 1 & streq(arg1, 'test'), Gsparse_test, return, end
if nargin < 1, help(mfilename), error(mfilename), end
% defaults
arg.mask = [];
arg.idim = [];
arg.odim = [];
arg.chat = 0;
arg.blocks = {}; % place to store blocks of G for subset algorithms
arg = vararg_pair(arg, varargin);
if ~isempty(arg.mask) && ~islogical(arg.mask)
error 'mask must be logical'
end
%
% cell array of arguments to sparse()
%
if iscell(arg1)
if length(arg1) >= 3 % i, j, s ...
arg1{3} = double(arg1{3}); % trick: double values for s
end
arg1 = sparse(arg1{:});
end
%
% if input is an Aspire .wtf file
%
if ischar(arg1)
arg.file = arg1;
if ~isempty(arg.idim) | ~isempty(arg.odim)
error 'idim / odim should not be given for .wtf'
end
[arg.G arg.idim(1) arg.idim(2) arg.odim(1) arg.odim(2)] = ...
wtfmex('load', arg.file);
% default mask from .wtf
if isempty(arg.mask)
tmp = full(sum(arg.G) > 0);
arg.mask = reshape(tmp, arg.idim);
end
arg.G = arg.G(:,arg.mask(:));
%
% if input is a sparse matrix
%
elseif issparse(arg1)
arg.G = arg1;
if isempty(arg.idim)
if ~isempty(arg.mask)
arg.idim = size(arg.mask);
else
warning 'idim not given for sparse matrix!'
arg.idim = [size(arg.G,2) 1];
end
end
if isempty(arg.mask)
arg.mask = true(arg.idim); % default mask is all
elseif length(arg.idim) ~= ndims(arg.mask) | ...
any(arg.idim ~= size(arg.mask))
disp(arg), error 'bad mask size'
end
if isempty(arg.odim)
warning 'odim not given for sparse matrix!'
arg.odim = [size(arg.G,1) 1];
elseif prod(arg.odim) ~= size(arg.G,1)
error 'bad row dimension'
end
if sum(arg.mask(:)) ~= size(arg.G,2)
if size(arg.G,2) == numel(arg.mask)
arg.G = arg.G(:, arg.mask(:)); % trick: compact size
else
disp(arg), error 'bad G size'
end
end
else
error 'input must be cell or filename or sparse matrix'
end
%
% build Fatrix object
%
arg.nd = prod(arg.odim);
arg.np = sum(arg.mask(:));
ob = Fatrix([arg.nd arg.np], arg, 'caller', mfilename, ...
'forw', @Gsparse_forw, 'back', @Gsparse_back, ...
'block_setup', @Gsparse_block_setup, ...
'mtimes_block', @Gsparse_mtimes_block, ...
'abs', @Gsparse_abs, 'power', @Gsparse_power);
%
% Gsparse_forw(): y = G * x
%
function y = Gsparse_forw(arg, x)
% if needed, convert array to concise column
flag_array = 0;
if size(x,1) ~= arg.np
flag_array = 1;
x = reshape(x, numel(arg.mask), []); % [*N,*L]
x = x(arg.mask(:),:); % [np, *L]
end
if isa(x, 'double')
y = arg.G * x; % [nd, *L]
else
y = arg.G * double(x); % [nd, *L]
if ~issparse(y)
y = single(y);
end
end
if flag_array
y = reshaper(y, arg.odim); % [(M),*L]
end
%
% Gsparse_back(): x = G' * y
%
function x = Gsparse_back(arg, y)
flag_array = 0;
if size(y,1) ~= arg.nd
flag_array = 1;
y = reshape(y, arg.nd, []); % [nd,*L]
end
if isa(y, 'double')
x = (y' * arg.G)'; % [np,*L] trick: runs faster this way!
else
x = (double(y)' * arg.G)'; % [np,*L]
if ~issparse(x)
x = single(x);
end
end
if flag_array
x = embed(x, arg.mask); % [(N),*L]
end
%
% Gsparse_abs()
%
function ob = Gsparse_abs(ob)
ob.arg.G = abs(ob.arg.G);
%
% Gsparse_block_setup()
% Pre-construct blocks of sparse matrix so that it need not be done
% for every block access. Doubles memory.
%
function ob = Gsparse_block_setup(ob)
nb = prod(ob.arg.odim(1:end-1));
na = ob.arg.odim(end);
ob.arg.blocks = cell(ob.nblock,1);
for iblock=1:ob.nblock
ia = iblock:ob.nblock:na;
ii = outer_sum(1:nb, (ia-1)*nb);
ii = ii(:);
t = ob.arg.G(ii,:); % fix: sparse, but nzmax is too large!
[i j s] = find(t);
if iblock == 1 & length(s) ~= nzmax(t)
% persistent warned
warning 'stupid matlab sparse too big'
end
t = sparse(i, j, s, length(ii), size(ob.arg.G, 2));
ob.arg.blocks{iblock} = t;
end
%
% Gsparse_mtimes_block()
% note: this is not incredibly efficient, but it is mostly for testing anyway.
%
function y = Gsparse_mtimes_block(arg, is_transpose, x, istart, nblock)
if is_transpose
y = Gsparse_mtimes_back(arg, x, istart, nblock);
else
y = Gsparse_mtimes_forw(arg, x, istart, nblock);
end
% old slow way
%nb = prod(arg.odim(1:end-1));
%ii = outer_sum(1:nb, (ia-1)*nb);
% trick: just reuse almost everything in arg
%arg.G = arg.G(ii(:),:);
%
% Gsparse_mtimes_forw()
%
function y = Gsparse_mtimes_forw(arg, x, istart, nblock);
ia = istart:nblock:arg.odim(end); % subset over last dim
% if needed, convert array to concise column
flag_array = 0;
if size(x,1) ~= arg.np
flag_array = 1;
x = reshape(x, numel(arg.mask), []); % [*N,*L]
x = x(arg.mask(:),:); % [np,*L]
end
if isa(x, 'double')
y = arg.blocks{istart} * x; % [nd, *L]
else
y = arg.blocks{istart} * double(x); % [nd, *L]
y = single(full(y));
end
if flag_array
y = reshaper(y, [arg.odim(1:end-1) length(ia)]);
end
%
% Gsparse_mtimes_back()
%
function x = Gsparse_mtimes_back(arg, y, istart, nblock);
ia = istart:nblock:arg.odim(end); % subset over last dim
nd1 = arg.nd * length(ia) / arg.odim(end);
flag_array = 0;
if size(y,1) ~= nd1
flag_array = 1;
y = reshape(y, nd1, []); % [nd1,*L]
end
if isa(y, 'double')
x = full(y' * arg.blocks{istart})'; % [np,*L] trick: runs faster
else
x = full(double(y)' * arg.blocks{istart})'; % [np,*L]
x = single(x);
end
if flag_array
x = embed(x, arg.mask); % [(N),*L]
end
%
% Gsparse_power()
%
function ob = Gsparse_power(ob, sup)
ob.arg.G = ob.arg.G .^ sup;
% fix: this is inefficient to be working with both G and its blocks
if ~isempty(ob.nblock)
for ii=1:ob.nblock
ob.arg.blocks{ii} = ob.arg.blocks{ii} .^ sup;
end
end
|
github
|
sunhongfu/scripts-master
|
ifft_sym.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/ifft_sym.m
| 1,181 |
utf_8
|
01ebf2f01e0379ebb2d3ae4792f996f7
|
function y = ifft_sym(varargin)
%function y = ifft_sym(varargin)
% matlab 7.0 introduced a 'symmetric' option to ifft to handle
% spectra that are (circularly) hermitian symmetric (real signal).
% this glue routine is to provide backward compatibility for matlab 6.5.
% Caution: v7 ifft with 'symmetric' just uses the first half of the spectrum
% along whichever dimension is requested. Here, for pre v7, I just take
% the real part. The difference is neglible in the cases where this
% routine is expected to be used, where the spectrum should be exactly
% symmetric but has slight asymmetry due to numerical precision.
% If the spectrum is severely asymmetric, then "real(ifft())" and
% ifft(..., 'symmetric') will differ substantially. (But one should
% not call this routine in such cases.)
if ~nargin, help(mfilename), error(mfilename), end
if nargin == 1 && streq(varargin{1}, 'test'), ifft_sym_test, return, end
if is_pre_v7
y = ifft(varargin{:});
y = reale(y, 1e-11, 'prompt');
else
y = ifft(varargin{:}, 'symmetric');
end
function y = ifft_sym_test
del = 10^5*eps;
format compact
x1 = [4 2+0i*del 8 2-1i*del]
y1 = ifft(x1)
y2 = ifft_sym(x1)
x2 = fft(y2)
y1 - y2
|
github
|
sunhongfu/scripts-master
|
jf_protected_names.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/jf_protected_names.m
| 2,298 |
utf_8
|
9430f87fc9730771e794a957c0e20697
|
function pn = jf_protected_names
%|function pn = jf_protected_names
%|
%| A serious drawback of the matlab language is that it lacks
%| a protected or local namespace. Every m-file that is in the path
%| is available to all functions (except those in "private" subdirectories).
%| Users who have their own m-files that happen to have the same names as
%| any of the routines in a toolbox like this one will have problems.
%|
%| To try to overcome this limitation, I created this function in late 2009
%| to serve as a repository of simple functions.
%| To use any of these functions, one types something like
%| pn = jf_protected_names;
%| and then one can call the functions using
%| out = pn.fun(arg1, arg2, ...);
%|
%| Copyright 2009-11-21, Jeff Fessler, University of Michigan
pn = strum(struct, { ...
'struct_recurse', @jf_struct_recurse, '()';
'color_order', @jf_color_order, '()';
'diary', @jf_diary, '(file)';
'has_hct2', @jf_has_hct2, '()';
'hct_arg', @jf_hct_arg, '(cg, ig)';
'ind2sub', @jf_ind2sub, '(siz, ind)';
'mid3', @jf_mid3, '(im_3d, [dim])';
'normcdf', @jf_normcdf, '(x, mu, sigma)';
'prctile', @jf_prctile, '(x, p, [dim])';
'case', @jf_case, '(x, v0, v1, ...)';
'test', @jf_test, '()';
});
end % jf_protected_names()
% jf_case()
% its purpose is to act like the '?' operator in C
% jf_case(x, 'value if x is 0', 'value if x is 1', ...)
function out = jf_case(st, x, varargin)
if x+1 > numel(varargin)
fail('x=%d but num=%d', x, numel(varargin))
end
out = varargin{x+1};
end % jf_case()
% jf_diary()
% this version prompts if file exists!
function jf_diary(st, file)
if streq(file, 'off')
diary('off');
return
end
if exist(file, 'file')
fail 'file exists'
else
printm('starting diary for "%s"', file)
diary(file);
end
end % jf_diary()
% jf_ind2sub()
% version with a single matrix output, one dimension per column
function subs = jf_ind2sub(st, Nd, ind)
ind = ind(:);
subs = zeros(numel(ind), numel(Nd));
switch numel(Nd)
case 2
[subs(:,1) subs(:,2)] = ind2sub(Nd, ind);
case 3
[subs(:,1) subs(:,2) subs(:,3)] = ind2sub(Nd, ind);
case 4
[subs(:,1) subs(:,2) subs(:,3) subs(:,4)] = ind2sub(Nd, ind);
otherwise
fail 'not done'
end
end % jf_ind2sub()
% jf_test()
function jf_test(st, varargin)
jf_equal(st.case(1, 2, 3), 3)
end % jf_test()
|
github
|
sunhongfu/scripts-master
|
os_run.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/os_run.m
| 496 |
utf_8
|
b86b9948f9e383a3f5f8d047d0ec9ae0
|
function out = os_run(str)
%|function out = os_run(str)
%| call OS (unix only of course), check for error, optionally return output
if nargin < 1, help(mfilename), error(mfilename), end
if streq(str, 'test'), os_run_test, return, end
[s out1] = unix(str);
if s
fail('unix call failed:\n%s', str)
end
if nargout
out = out1;
end
function os_run_test
printm 'os_run test'
if ~isunix
warn 'os_run works only on unix'
return
end
out = os_run('echo 1+2 | bc');
jf_equal(out, sprintf('3\n'))
|
github
|
sunhongfu/scripts-master
|
interp1_jump.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/interp1_jump.m
| 2,280 |
utf_8
|
b183193c9190a72ea28565ea8def6dba
|
function yi = interp1_jump(xj, yj, xi, varargin)
%function yi = interp1_jump(xj, yj, xi, {arguments for interp1})
% Generalization of matlab's "interp1" to allow xj with repeated values,
% for interpolation of a function that has "jumps" (discontinuities),
% such as is caused by k-edges for mass attenuation coefficients.
% If the first option is 'monodown' then the function is expected to
% be monotone decreasing except for certain jumps that may not correspond
% to xj's with equal values.
% The (remaining) options are passed to 'interp1'.
% Copyright 2004-5-2, Jeff Fessler, The University of Michigan
if nargin == 1 && streq(xj, 'test'), interp1_jump_test, return, end
if nargin < 3, help(mfilename), error(mfilename), end
if length(xj) ~= length(yj), error 'xj and yj have different lengths', end
jjump = find(diff(xj) == 0);
if length(varargin) && streq(varargin{1}, 'monodown')
varargin = {varargin{2:end}};
yjump = find(diff(yj) > 0);
jjump = unique([jjump; yjump]);
end
npiece = 1 + length(jjump);
if npiece == 1
yi = interp1(xj, yj, xi, varargin{:});
return
end
yi = zeros(size(xi));
done = zeros(size(xi));
for ip=1:npiece
if ip == 1
jlist = [1:jjump(1)];
elseif ip == npiece
jlist = [(1+jjump(npiece-1)):length(xj)];
else
jlist = [(1+jjump(ip-1)):jjump(ip)];
end
x = xj(jlist);
y = yj(jlist);
if ip == 1
ilist = find(xi <= max(x));
elseif ip == npiece
ilist = find(min(x) <= xi);
else
ilist = find(min(x) <= xi & xi <= max(x));
end
if isempty(ilist), continue, end
if length(x) > 1
yi(ilist) = interp1(x, y, xi(ilist), varargin{:});
done(ilist) = 1;
elseif length(x) == 1
if any(x == xi(ilist))
yi(ilist) = y(x == xi(ilist));
else
warning 'bug?'
keyboard
end
end
end
% for anything left over, use linear interpolation
if any(~done)
[xj jj] = unique(xj);
yi(~done) = interp1(xj, yj(jj), xi(~done), 'linear');
end
function interp1_jump_test
x = [0 0.5 1 1 2 3 3 4 5];
%x = [0 0.5 1 1.1 2 3 3.1 4 5];
y = [1 0 0 1 1 2 1 2 2];
t = linspace(-0.5,0.5+max(x),1001);
f = interp1_jump(x, y, t, 'cubic', 'extrap');
if im
clf, subplot(211)
plot(x, y, 'o', t, f, '-')
end
x = [0:5];
y = [4 2 1 2 1 0];
f = interp1_jump(x, y, t, 'monodown', 'cubic', 'extrap');
if im
subplot(212)
plot(x, y, 'o', t, f, '-')
end
|
github
|
sunhongfu/scripts-master
|
jf_histn.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/jf_histn.m
| 2,106 |
utf_8
|
8a5e6756705f9e4c239f592b17967eed
|
function [hist center] = jf_histn(data, varargin)
%|function [hist center] = jf_histn(data, varargin)
%|
%| Fast histogram of multidimensional data for equally-spaced bins.
%| todo: use accumarray?
%|
%| in
%| data [N M] data values to be binned (M-dimensional)
%|
%| option
%| 'min' [M] minimum bin values for each dimension (left side)
%| 'max' [M] maximum bin values for each dimension (right side)
%| 'nbin' [M] # of bins for each dimension (default: 100)
%|
%| out
%| hist [[ncent]] histogram values: sum(hist(:)) = N
%| center {ncent} cell array of bin centers for each dimension
%|
%| Copyright 2010-07-31, Jeff Fessler, University of Michigan
if nargin == 1 && streq(data, 'test'), jf_histn_test, return, end
if nargin < 1, help(mfilename), error(mfilename), end
arg.min = [];
arg.max = [];
arg.nbin = [];
arg.chat = 0;
arg = vararg_pair(arg, varargin);
M = size(data,2);
if isempty(arg.nbin)
arg.nbin = 100;
end
if numel(arg.nbin) == 1
arg.nbin = arg.nbin * ones(M,1);
end
for id=1:M
tmp = data(:,id);
if isempty(arg.min)
xmin = min(tmp);
else
xmin = arg.min(id);
end
if isempty(arg.max)
xmax = max(tmp);
else
xmax = arg.max(id);
end
if xmin == xmax
if xmin == 0
xmin = -0.5;
xmax = +0.5;
else
xmin = 0.5 * xmin;
xmax = 1.5 * xmin;
end
end
K = arg.nbin(id);
tmp = (tmp - xmin) / (xmax - xmin); % [0,1]
tmp(tmp < 0) = 0;
tmp(tmp > 1) = 1;
tmp = 1 + tmp * (K-1); % [1 K]
data(:,id) = round(tmp);
if K == 1
center{id} = (xmin + xmax) / 2;
else
center{id} = linspace(xmin, xmax, K);
end
end
[hist hcent] = hist_bin_int(data);
for id=1:M
tmp = hcent{id};
K = arg.nbin(id);
if min(tmp) ~= 1 || max(tmp) ~= K
minmax(tmp)
fail 'todo'
end
end
% test routine
function jf_histn_test
randn('state', 0)
n = 1000;
sig = 5;
rho = 0.6; % correlated gaussian
Cov = sig * [1 rho; rho 1];
tmp = sqrtm(Cov)
data = randn(n, 2) * sqrtm(Cov);
nbin = [30 30]
[hist cent] = jf_histn(data, 'nbin', nbin);
[xs ys] = deal(cent{:});
if im
im plc 1 2
im(1, xs, ys, hist)
axis equal
im subplot 2
plot(data(:,1), data(:,2), '.')
axis equal
end
|
github
|
sunhongfu/scripts-master
|
jf_assert.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/jf_assert.m
| 871 |
utf_8
|
444b53c5605424b42508cd26fa0da635
|
function jf_assert(varargin)
%function jf_assert(command)
% verify that the command (evaluated within caller) returns true.
% if not, print error message.
if nargin < 1, help(mfilename), error(mfilename), end
if nargin == 1 && streq(varargin{1}, 'test'), jf_assert_test, return, end
arg = [varargin{:}]; % handle cases with spaces like 'jf_assert x == y'
[name line] = caller_name;
if isempty(name)
str = '';
else
str = sprintf(' at %d in "%s"', line, name);
end
try
tmp = evalin('caller', arg);
catch
error(['%s was unable to evaluate "%s"' str], mfilename, arg)
end
% note: use isequal, not issame!
if isscalar(tmp) && islogical(tmp)
if ~tmp
fail(['jf_assert of "%s" was untrue' str], arg)
% dbup
% dbstack
% keyboard
end
else
tmp
whos
error(['jf_assert of "%s" did not return logical scalar' str], arg)
end
function jf_assert_test
jf_assert 7 == 7
|
github
|
sunhongfu/scripts-master
|
gaussian_kernel.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/gaussian_kernel.m
| 760 |
utf_8
|
119655fccf91567673b1e3739af2b637
|
function kern = gaussian_kernel(fwhm, nk_half)
%function kern = gaussian_kernel(fwhm, nk_half)
% samples of a gaussian kernel at [-nk_half:nk_half]
% with given FWHM in pixels
% uses integral over each sample bin so that sum is very close to unity
%
% Copyright 2001-9-18, Jeff Fessler, The University of Michigan
if nargin < 1, help(mfilename), return, end
if streq(fwhm, 'test'), gaussian_kernel_test, return, end
if nargin < 2, nk_half = 2 * ceil(fwhm); end
if fwhm == 0
kern = zeros(nk_half*2+1, 1);
kern(nk_half+1) = 1;
else
sig = fwhm / sqrt(log(256));
x = [-nk_half:nk_half]';
pn = jf_protected_names;
kern = pn.normcdf(x+1/2, 0, sig) - pn.normcdf(x-1/2, 0, sig);
end
function gaussian_kernel_test
kern = gaussian_kernel(3);
plot(kern, '-o')
|
github
|
sunhongfu/scripts-master
|
fwhm_match.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/fwhm_match.m
| 1,878 |
utf_8
|
8ae6568a77739be15c5ac4afea48b4d8
|
function [fwhm_best, costs, im_best] = ...
fwhm_match(true_image, blurred_image, fwhms)
%|function [fwhm_best, costs, im_best] = ...
%| fwhm_match(true_image, blurred_image, fwhms)
%|
%| given a blurred_image of a true_image, find the FHWM of a Gaussian kernel
%| that, when convolved to the true_image, yields the smoothed image
%| that best matches blurred_image.
%|
%| the set of FWHM values given in the array fwhms is tried.
%|
%| Copyright 2001-8-30, Jeff Fessler, University of Michigan
if nargin == 1 && streq(true_image, 'test'), fwhm_match_test, return, end
if nargin < 2, help(mfilename), error(' '), end
if nargin < 3
fwhms = 0:0.5:4;
end
costs = zeros(size(fwhms));
cost_min = Inf;
for ii=1:length(fwhms)
fwhm = fwhms(ii);
kern = gaussian_kernel(fwhm);
psf = kern * kern';
tmp = conv2(true_image, psf, 'same');
costs(ii) = norm(tmp(:) - blurred_image(:)) / norm(true_image(:));
if costs(ii) < cost_min
im_best = tmp;
end
end
[dummy ibest] = min(costs);
if ibest == 1 | ibest == length(fwhms)
warning 'need wider range of fwhms'
end
fwhm_best = fwhms(ibest);
% fwhm_match_test
function fwhm_match_test
% pyramidal PSF to stress the approach
psf1 = [0:5 4:-1:0]; psf1 = psf1 / sum(psf1); psf = psf1' * psf1;
true_image = zeros(128); true_image(64:96,64:96) = 1;
blurred_image = conv2(true_image, psf, 'same');
im plc 2 2
im(1, true_image, 'True Image')
im(2, blurred_image, 'Blurred Image')
fwhms = [2:0.25:8];
[fwhm_best, costs] = fwhm_match(true_image, blurred_image, fwhms);
np = length(psf); ip = -(np-1)/2:(np-1)/2;
kern = gaussian_kernel(fwhm_best);
nk = length(kern); ik = -(nk-1)/2:(nk-1)/2;
if im
im subplot 3
plot(fwhms, costs, 'c-o', fwhm_best, min(costs), 'yx')
xlabel FWHM, ylabel Cost, title 'Cost vs FWHM'
im subplot 4
plot(ip, psf1, '-o', ik, kern(:), '-+')
xlabel pixel, title 'PSF profile: actual and Gaussian fit'
end
|
github
|
sunhongfu/scripts-master
|
fractional_delay.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/fractional_delay.m
| 2,438 |
utf_8
|
09fad587ef6cfbb84e8a06617919b92f
|
function y = fractional_delay(x, delay)
%function y = fractional_delay(x, delay)
%
% given N samples x[n] of a real, periodic, band-limited signal x(t),
% compute sinc interpolated samples of delayed signal y(t) = x(t - delay)
% each column of x can be shifted by a different amount if delay is a vector.
% in
% x [N,L]
% delay [L]
% out
% y [N,L]
%
% see laakso:96:stu for more ideas.
%
% Copyright 2003-11-1, Jeff Fessler, The University of Michigan
% Extend to allow x to have multiple columns, 2003-11-2, Yingying Zhang.
if nargin < 1, help(mfilename), disp('Need Inputs'), error(mfilename), end
if streq(x, 'test'), fractional_delay_test, return, end
if size(x,2) ~= length(delay)
error 'Need size(x) = [N,L]; length(delay) = L'
end
dims = size(x);
N = dims(1);
L = dims(2);
if length(dims) > 2, error 'x must be 1d or 2d', end
X = fft(x); % fft of each column
% it is important to choose the k indices appropriately!
if rem(N,2) % odd
k = [-(N-1)/2:(N-1)/2]';
else
k = [-N/2:(N/2-1)]';
end
c = exp(-1i * 2*pi/N * k * delay(:)'); % [N,L] outer product
if ~rem(N,2) % even
mid = 1;
c(mid,:) = real(c(mid,:)); % this is the other key trick!
end
c = ifftshift1(c); % ifftshift differs from fftshift for odd N!
Y = X .* c;
y = ifft(Y);
%
% 1D ifftshift for each column
%
function c = ifftshift1(c)
[N,L] = size(c);
if L == 1
c = ifftshift(c); % ifftshift differs from fftshift for odd N!
else % multiple input signals
if ~rem(N,2) % even
c = c([N/2+1:end 1:N/2],:);
else % odd
c = c([(N-1)/2+1:end 1:(N-1)/2],:);
end
end
%
% self test
%
function fractional_delay_test
Nlist = [5 6];
im clf, pl=240;
for ii=1:2
N = Nlist(ii);
n = [0:(N-1)]';
xt = inline('sinc_periodic(t, N)', 't', 'N');
x = xt(n, N);
xx = [x x];
delay = [3.7; -2.2];
y = fractional_delay(xx, delay);
t = linspace(0,2*N,401);
yt1 = xt(t-delay(1),N);
yt2 = xt(t-delay(2),N);
if im
subplot(pl+0+ii), plot(t, xt(t,N), '-', n, xx(:,1), 'o')
axis([0 2*N -0.4 1.1]), title(sprintf('N=%d 1st input', N))
subplot(pl+2+ii), plot(t, xt(t,N), '-', n, xx(:,2), 'o')
axis([0 2*N -0.4 1.1]), title(sprintf('N=%d 2nd input', N))
subplot(pl+4+ii)
plot(t, yt1, '-', n, real(y(:,1)), 's', n, imag(y(:,1)), '.')
axis([0 2*N -0.4 1.1]), title(sprintf('delay=%g 1st input',delay(1)))
subplot(pl+6+ii)
plot(t, yt2, '-', n, real(y(:,2)), 's', n, imag(y(:,2)), '.')
axis([0 2*N -0.4 1.1]), title(sprintf('delay=%g 2nd input',delay(2)))
end
end
|
github
|
sunhongfu/scripts-master
|
pad_into_center.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/pad_into_center.m
| 1,210 |
utf_8
|
ab74a76cd16f351c6d2e6238fc95017e
|
function xpad = pad_into_center(x, npad)
%function xpad = pad_into_center(x, npad)
% Zero pad an input signal x symmetrically around "0" (image center).
% Useful for DFT/FFT of PSF.
% todo: replace with matlab's padarray.m
% Originally by A. Yendiki, modified by Jeff Fessler, 2005-7-26.
if nargin < 1, help(mfilename), error(mfilename), end
if nargin == 1 && streq(x, 'test'), pad_into_center_test, return, end
if length(npad) == 1
if min(size(x)) == 1 % 1d. kludge: wrong if size(x) = [nx,1,nz]
if size(x,1) == 1
npad = [1 npad];
else
npad = [npad 1];
end
else % n-dimensional; pad all dimensions the same amount
npad = repmat(npad, [1 ndims(x)]);
end
end
ndim = ndims(x);
if ndim ~= length(npad)
error 'Incorrect number of dimensions'
end
args = cell(ndim,1);
for id = 1:ndim
nold = size(x,id);
nnew = npad(id);
if nold > nnew
error(sprintf('Padding[%d]=%d too small cf %d', id, nnew, nold))
end
args{id} = [1:nold] + ceil((nnew - nold)/2);
end
xpad = zeros(npad);
xpad(args{:}) = x;
function pad_into_center_test
pad_into_center([1 2 1], [7])
pad_into_center([1 2 1]', [7])'
pad_into_center([1 2 1], [7 3])
pad_into_center([1 2 1]', [7 3])
pad_into_center(ones(3), [5 7])
|
github
|
sunhongfu/scripts-master
|
downsample2.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/downsample2.m
| 796 |
utf_8
|
45fe4dcbfeb45d32d39d0bc20299a641
|
function y = downsample2(x, m, varargin)
%|function y = downsample2(x, m, varargin)
%| downsample by averaging by integer factors
%| m can be a scalar (same factor for both dimensions)
%| or a 2-vector
%| in
%| x [nx ny]
%| option
%| 'warn' 0|1 warn if non-integer factor. default: 1
%| out
%| y [nx/m ny/m]
if nargin == 1 & streq(x, 'test'), downsample2_test, return, end
if nargin < 2, help(mfilename), error(mfilename), end
arg.warn = 1;
arg = vararg_pair(arg, varargin);
fun = @(x, d) downsample1(x, d, 'warn', arg.warn);
y = fun(x, m(1));
y = fun(y', m(end))';
function downsample2_test
x = reshape(1:24, [4 6]);
y = downsample2(x, 2);
jf_equal(y, [3.5 11.5 19.5; 5.5 13.5 21.5])
if 1 % big test
x = zeros(2^12);
cpu etic
y = downsample2(x, 2);
cpu etoc 'downsample2 time:'
end
|
github
|
sunhongfu/scripts-master
|
reshaper.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/reshaper.m
| 890 |
utf_8
|
b1851d49886b11b9ca0b1a4651a16a51
|
function y = reshaper(x, dim)
%|function y = reshaper(x, dim)
%|
%| reshape function that is more flexible, allowing for "multiples".
%| example: reshape(rand(2*3*5,7), [2 3 5]) will become [2 3 5 7]
%|
%| in
%| x [*dim (Ld)]
%| dim short row or column
%| if dim is '2d' then y is 2d with first n-1 dims collapsed
%|
%| out
%| y [dim (Ld)]
%|
%| Copyright 2004-8-22, Jeff Fessler, University of Michigan
if nargin == 1 & streq(x, 'test'), reshaper_test, return, end
if nargin < 2, help(mfilename), error(mfilename), end
dim_i = size(x);
if ischar(dim) && streq(dim, '2d')
y = reshape(x, prod(dim_i(1:end-1)), dim_i(end));
return
end
dim_e = dim_i(2:end); % extra dimensions (this could be made fancier)
dim_o = [dim dim_e];
y = reshape(x, dim_o);
% self test
function reshaper_test
x = reshape(1:2*3*5*7, 2*3*5, 7);
dim = [2 3 5];
y = reshaper(x, dim);
jf_equal(size(y), [dim 7])
|
github
|
sunhongfu/scripts-master
|
fld_write.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/fld_write.m
| 5,854 |
utf_8
|
a537cbf0ff76de352fe949e0e946577d
|
function fld_write(file, data, varargin)
%|function fld_write(file, data, [options])
%| write data into AVS format .fld file
%| see ASPIRE user's guide (or AVS online documentation) for file format.
%|
%| todo: generalize to include 'extent' options and default
%|
%| options
%| 'check' 0|1 1: report error if file exists (default: 0)
%| 'dir' char directory name to prepend file name
%| 'type' char e.g., 'short_be'. default is 'xdr_float'
%| 'head' strings comment information for file header
%| 'raw' 0|1 1: put raw data in name.raw, header in name.fld
%| where file = name.fld
%| 'endian' str 'ieee-le' or 'ieee-be' for little/big endian
%|
%| Copyright 2003-5-13, Jeff Fessler, University of Michigan
%| options (obsolete way)
%| '-check' report error if file already exists
%| '-nocheck' overwrite file even if it already exists
%| 'header' [strings] comment information for file header
%| datatype e.g., 'short_be'. default is 'xdr_float'
if nargin == 1 & streq(file, 'test'), fld_write_test, return, end
if nargin < 2, help(mfilename), error(mfilename), end
if length(varargin)
arg1 = varargin{1};
if streq(arg1, '-check') || streq(arg1, '-nocheck') ...
|| streq(arg1, 'header') || streq(arg1, 'byte')
warn 'old style syntax; please upgrade!'
fld_write_old(file, data, varargin{:});
elseif streq(arg1, 'new')
fail 'the ''new'' option no longer needed - remove!'
else
fld_write_new(file, data, varargin{:});
end
else
fld_write_new(file, data);
end
%
% fld_write_new()
%
function fld_write_new(file, data, varargin)
arg.check = 0;
arg.raw = 0;
arg.type = '';
arg.head = '';
arg.dir = '';
arg.endian = 'ieee-be';
arg = vararg_pair(arg, varargin);
if isempty(arg.type)
if streq(arg.endian, 'ieee-be')
arg.type = 'xdr_float';
elseif streq(arg.endian, 'ieee-le')
arg.type = 'float_le';
else
error 'bug'
end
end
% try to check that endian and data type match
if streq(arg.type, 'xdr_', 4) && streq(arg.endian, 'ieee-le')
warn('for xdr_ data types, endian should be ieee-be')
arg.endian = 'ieee-be';
end
if any(strfind(arg.type, '_le')) && streq(arg.endian, 'ieee-be')
warn('for _le data types, endian should be ieee-le')
arg.endian = 'ieee-le';
end
if any(strfind(arg.type, '_be')) && streq(arg.endian, 'ieee-le')
warn('for _be data types, endian should be ieee-be')
arg.endian = 'ieee-be';
end
if ~isempty(arg.dir)
file = [arg.dir filesep file];
printm('file = "%s"', file)
end
fld_write_do(file, data, arg.check, arg.type, arg.endian, arg.head, arg.raw);
%
% fld_write_old()
%
function fld_write_old(file, data, varargin);
% defaults
check1st = 0;
datatype = 'xdr_float'; % default
endian = 'ieee-be';
header = '';
while length(varargin)
arg1 = varargin{1};
varargin = {varargin{2:end}};
if streq(arg1, '-check')
check1st = 1;
elseif streq(arg1, '-nocheck')
check1st = 0;
elseif streq(arg1, 'header')
header = varargin{1};
varargin = {varargin{2:end}};
else
datatype = arg1;
end
end
fld_write_do(file, data, check1st, datatype, endian, header, 0);
%
% fld_write_do()
%
function fld_write_do(file, data, check1st, datatype, endian, header, raw)
% check if file already exists
loop = check1st & exist(file, 'file');
while (loop)
t = sprintf('file "%s" exists. overwrite? [y|n|d]: ', file);
t = input(t, 's');
if streq(t, 'd')
t = fld_read(file);
printf('max %% diff = %g', max_percent_diff(t, data))
continue
end
if streq(t, 'y')
break
else
return
end
end
if raw
fileraw = file; fileraw(end+[-2:0]) = 'raw';
loop = check1st && exist(fileraw);
while (loop)
t = sprintf('file "%s" exists. overwrite? [y|(n)]: ', fileraw);
t = input(t, 's');
if streq(t, 'y')
break
else
return
end
end
end
% data type
if 1
switch datatype
case {'byte', 'uint8'}
datatype = 'byte';
format = 'uint8';
case {'short_be', 'short_sun', 'int16'}
datatype = 'short_be';
format = 'int16';
case 'float'
format = 'float';
endian = 'native'; % not portable
case {'float_le', 'float'}
format = 'float';
case {'float_be', 'xdr_float'}
datatype = 'xdr_float';
format = 'float32';
otherwise
error(['datatype ' datatype ' not implemented yet'])
end
end
% open avs file for writing
fid = fopen(file, 'w', endian);
if fid == -1, fail('cannot open %s', file), end
if raw
fraw = fopen(fileraw, 'w', endian);
else
fraw = fid;
end
% write header
ndim = ndims(data);
fprintf(fid, '# created by %s\n', mfilename);
if ~isempty(header)
for ii=1:nrow(header)
fprintf(fid, '# %s\n', header(ii,:));
end
end
fprintf(fid, 'ndim=%d\n', ndim);
%fprintf(fid, 'nspace=%d\n', ndim);
for ii=1:ndim
fprintf(fid, 'dim%d=%d\n', ii, size(data,ii));
end
fprintf(fid, 'data=%s\n', datatype);
fprintf(fid, 'veclen=1\n');
fprintf(fid, 'field=uniform\n');
if raw
fprintf(fid, 'variable 1 file=%s filetype=binary\n', fileraw);
else
fprintf(fid, '\f\f'); % two form feeds: char(12)
end
%
% finally, write the binary data
%
count = fwrite(fraw, data, format);
if count ~= numel(data)
disp([count size(data)])
fail('file count=%d vs data=%d', count, prod(dims))
end
if fclose(fid), error 'fclose error?', end
if raw
if fclose(fraw), error 'fclose error?', end
end
function fld_write_test1(file, data, varargin)
fld_write(file, data, varargin{:})
tmp = fld_read(file);
if any(tmp ~= data), keyboard, error 'test failed', end
delete(file)
function fld_write_test
file = [test_dir 'tmp.fld'];
data = [5:8; 1:4];
%fld_write(file, data)
%fld_write(file, data, 'new', 'check', 1, 'endian', 'ieee-le')
if 1 % test raw/header
fld_write_test1(file, data, 'check', 1, 'endian', 'ieee-le', 'raw', 1)
delete([test_dir 'tmp.raw'])
end
formats = {'float_be', 'float_le', 'float', 'xdr_float'};
for ii=1:length(formats)
format = formats{ii};
pr format
fld_write_test1(file, data, 'check', 1, 'endian', 'ieee-le', ...
'type', format)
end
printm 'passed'
|
github
|
sunhongfu/scripts-master
|
unpadn.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/unpadn.m
| 818 |
utf_8
|
efcd912abfb2bb3205ef2bc3c72ff01c
|
function out = unpadn(mat, newdim)
%|function out = unpadn(mat, newdim)
%| pad old to newdim, preserving 'center point'
if nargin == 1 && streq(mat, 'test'), unpadn_test, return, end
if nargin < 2, error(mfilename), help(mfilename), end
olddim = size(mat);
if any(newdim > olddim), error('must be smaller'), end
idx = cell(1, length(newdim));
for ii=1:length(newdim)
pad = olddim(ii) - newdim(ii);
if ~rem(pad,2) % even
offset = pad/2;
else
if rem(olddim(ii),2) % odd
offset = floor(pad/2);
else
offset = ceil(pad/2);
end
end
idx{ii} = [1:newdim(ii)] + offset;
end
out = mat(idx{:});
function unpadn_test
jf_equal(unpadn([0 1 2 1 0], [1 3]), [1 2 1])
jf_equal(unpadn([0 1 2 1 0], [1 4]), [0 1 2 1])
jf_equal(unpadn([0 1 2 1], [1 3]), [1 2 1])
jf_equal(unpadn([0 0 1 2 1 0], [1 4]), [0 1 2 1])
|
github
|
sunhongfu/scripts-master
|
isvar.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/isvar.m
| 1,105 |
utf_8
|
e6f2c6aa9ef51279a672904d75970008
|
%|function tf = isvar(name)
%|
%| determine if "name" is a variable in the caller's workspace.
%|
%| if argument is of the form 'name.field' or 'name.field1.field2' etc.
%| then this uses isfield(st, 'field') recursively as needed
%|
%| Copyright 2000-01-01, Jeff Fessler, University of Michigan
%| modified 2010-04-21 to use 'exist' and 'isfield'
function tf = isvar(name, field)
if nargin < 1, help(mfilename), error(mfilename), end
dots = strfind(name, '.'); % look for any field references
if isempty(dots)
base = name;
else
base = name(1:dots(1)-1);
tail = name((dots(1)+1):end);
end
str = sprintf('exist(''%s'', ''var'');', base);
tf = evalin('caller', str);
while tf && length(dots)
if length(dots) == 1
str = sprintf('isfield(%s, ''%s'');', base, tail);
tf = tf & evalin('caller', str);
return
else
dots = dots(2:end) - dots(1);
next = tail(1:dots(1)-1);
str = sprintf('isfield(%s, ''%s'');', base, next);
tf = tf & evalin('caller', str);
base = [base '.' next];
tail = tail((dots(1)+1):end);
end
end
%tf = true;
%evalin('caller', [name ';'], 'tf=false;') % old way
|
github
|
sunhongfu/scripts-master
|
dft_sym_check.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/dft_sym_check.m
| 1,124 |
utf_8
|
2232513db8d14465e04adc59ed9f646e
|
function dft_sym_check(xk, varargin)
%function dft_sym_check(xk)
% see if array xk (usually containing DFT coefficients)
% obeys the conjugate symmetry conditions expected
% for its (inverse) DFT to be real.
if nargin == 1 && streq(xk, 'test'), dft_sym_check_test, return, end
if nargin < 1, help(mfilename), error(mfilename), end
arg.tol = 1e-6;
if ndims(xk) == 2
dft_sym_check2(xk, arg.tol)
else
error 'only 2d done'
end
function dft_sym_check2(xk, tol)
[nx ny] = size(xk);
iix = 0:nx-1;
iiy = 0:ny-1;
[ix iy] = ndgrid(iix, iiy);
i1 = 1 + ix + iy * nx;
i2 = 1 + mod(nx-ix,nx) + mod(ny-iy,ny) * nx;
err = abs(xk(i1) - conj(xk(i2)));
err = err / max(max(abs(xk(:))), eps);
bad = find(err(:) > tol);
if length(bad)
printm('#bad = %d, worst = %g%%', length(bad), max(err(:))*100)
nn = min(5, length(bad));
for ii=1:nn
kk = bad(ii);
printm('ix,iy=(%d,%d) err=%g%%', ix(kk), iy(kk), err(kk)*100)
end
im(iix, iiy, err), cbar
else
printm('ok, worst = %g%%', max(err(:))*100)
end
function dft_sym_check_test
rand('state', 0)
xk = fft2(rand(14,23));
dft_sym_check(xk)
xk(35) = 1.1 * xk(5);
dft_sym_check(xk)
|
github
|
sunhongfu/scripts-master
|
dsingle.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/dsingle.m
| 320 |
utf_8
|
131f14ecc3813385227fdb653e79b58b
|
function [varargout] = dsingle(varargin)
%function y = dsingle(x)
% truncate a (possibly) double precision value to single precision,
% then convert back to "double" using double6:
% y = double6(single(x));
for ii=1:nargin
varargout{ii} = dsingle1(varargin{ii});
end
function y = dsingle1(x)
y = double6(single(x));
|
github
|
sunhongfu/scripts-master
|
jf_equal.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/jf_equal.m
| 1,871 |
utf_8
|
53cbc8605bbf1ab3fb4ec2641bc8bf9b
|
function jf_equal(a, b, varargin)
%|function jf_equal(a, b, varargin)
%|
%| verify that the two arguments are equal.
%| if not, print error message.
%| See also: equivs
%| note: to compare two (e.g. Fatrix) objects, use jf_equal(struct(a), struct(b))
%| option
%| 'warn' 0|1 if 0 (default) then fail; if 1 just warn instead
%|
%| Copyright 2007, Jeff Fessler, University of Michigan
if nargin < 1, help(mfilename), error(mfilename), end
if nargin == 1 && streq(a, 'test'), jf_equal_test, return, end
if isequal(a, b), return, end
arg.warn = 0;
arg = vararg_pair(arg, varargin);
if arg.warn
fun = @warn;
else
fun = @fail;
end
[name line] = caller_name;
if isempty(name)
str = '';
else
str = sprintf('%s %d', name, line);
end
if streq(class(a), 'char') && streq(class(b), 'char')
if streq(a, b), return, end
aname = inputname(1);
bname = inputname(2);
fun([str ': "%s" (%s) and "%s" (%s) unequal'], aname, a, bname, b)
if arg.warn, return, end
end
if streq(class(a), 'strum')
a = struct(a);
end
if streq(class(b), 'strum')
b = struct(b);
end
if isstruct(a) && isstruct(b)
jf_compare_struct(a, b)
else
minmax(a)
minmax(b)
if ~isequal(size(a), size(b))
printm(['size(%s) = %s'], inputname(1), mat2str(size(a)))
printm(['size(%s) = %s'], inputname(2), mat2str(size(b)))
error 'dimension mismatch'
end
max_percent_diff(a, b)
end
aname = inputname(1);
bname = inputname(2);
fun([str ': "%s" and "%s" unequal'], aname, bname)
function jf_compare_struct(s1, s2)
%[a perm] = orderfields(a);
try
s2 = orderfields(s2, s1);
catch
warn 'different fields'
return
end
names = fieldnames(s1);
for ii=1:length(names)
name = names{ii};
f1 = getfield(s1, name);
f2 = getfield(s2, name);
try
jf_equal(f1, f2)
catch
warn('field %s differs', name)
end
end
function jf_equal_test
a = 7;
b = 7;
c = 8;
jf_equal(a,b)
jf_equal(a,7)
%jf_equal(a,c)
|
github
|
sunhongfu/scripts-master
|
hist_equal.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/hist_equal.m
| 2,496 |
utf_8
|
0d27bae082772372de17cf66a6f14d6b
|
function [nk, center] = hist_equal(data, ncent, varargin)
%|function [nk, center] = hist_equal(data, ncent, varargin)
%|
%| fast histogram of multidimensional data into equally-spaced bins
%| todo: accumarray?
%|
%| in
%| data [N M] data values to be binned (M-dimensional)
%| ncent [1 M] # of centroids for each dimension
%| option
%| 'ifsame' char what to do if all data same along some dimension
%| 'orig' use original ncent values (default)
%| '1bin' ignore ncent value and use 1 bin
%| out
%| nk [[ncent]] histogram values: sum(nk(:)) = N
%| center {ncent} cell array of bin centers for each dimension
%|
%| Copyright 2004-7-5, Jeff Fessler, University of Michigan
if nargin == 1 & streq(data, 'test'), hist_equal_test, return, end
if nargin < 2, help(mfilename), error(mfilename), end
arg.ifsame = 'orig'; % default
arg.fudge = 1.001;
arg.dmin = [];
arg.dmax = [];
arg = vararg_pair(arg, varargin);
[N M] = size(data);
if M ~= length(ncent), error 'bad dimensions', end
list = zeros(N,M);
for id=1:M
nc = ncent(id);
if ~isempty(arg.dmin)
dmin = arg.dmin(id);
else
dmin = min(data(:,id));
end
if ~isempty(arg.dmax)
dmax = arg.dmax(id);
else
dmax = max(data(:,id));
end
if dmin == dmax
switch arg.ifsame
case 'orig'
center{id} = dmin + [0:(nc-1)]';
list(:,id) = 1;
case '1bin'
ncent(id) = 1;
center{id} = dmin;
list(:,id) = 1;
otherwise
fail('option ifzero="%s" unknown', arg.ifzero)
end
else
dmin = dmin * arg.fudge;
dmax = dmax / arg.fudge;
center{id} = col(linspace(dmin, dmax, nc));
ddif = center{id}(2) - center{id}(1);
ii = 1 + floor((data(:,id) - dmin) / ddif);
ii = min(ii, nc);
ii = max(ii, 1);
list(:,id) = ii;
end
end
% the sparse trick below does the following incrementing:
% for ii=1:N, nk(list(ii)) += 1, end
s = cumprod(ncent);
s = [1 s(1:end-1)];
list = 1 + (list-1) * s(:);
s = sparse([1:N]', list, ones(N,1), N, prod(ncent));
nk = full(sum(s));
nk = reshape(nk, ncent);
%
% self test
%
function hist_equal_test
randn('state', 0)
r1 = 10 * randn(10^3,1);
r2 = 40 + 10 * randn(10^3,1);
i1 = 5 * randn(10^3,1);
i2 = 7 + 3 * randn(10^3,1);
x = [[r1; r2], 1+[i1; i2]];
[nk cents] = hist_equal(x, [18 15], 'ifsame', '1bin');
if im
clf, subplot(121), plot(x(:,1), x(:,2), '.')
c1 = cents{1};
c2 = cents{2};
% axis([minmax(creal); minmax(cimag)])
im(122, c1, c2, nk), axis normal
[c1 c2] = ndgrid(c1, c2);
subplot(121)
hold on
plot(c1, c2, 'g.')
hold off
xlabel 'real', ylabel 'imag'
end
|
github
|
sunhongfu/scripts-master
|
fwhm1.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/fwhm1.m
| 1,785 |
utf_8
|
521eddf7df2e4bf7dd77c7f89f15d48e
|
function [fw, hr, hl] = fwhm1(psfs, varargin)
%|function [fw, hr, hl] = fwhm1(psfs, options)
%| compute fwhm of point-spread function centered at pixel imid
%| and half-right width and half-left width (fw = hr + hl)
%| in
%| psfs [np nc] column psf(s)
%| option
%| imid [1] which pixel is the middle (default: peak)
%| chat 0|1 if 1, then plot
%| dx [1] pixel size (default: 1)
%| out
%| fw [nc] fwhm of each psf column
if ~nargin, help(mfilename), error(mfilename), end
if streq(psfs, 'test'), fwhm1_test, return, end
arg.chat = 0;
arg.dx = 1;
arg.imid = [];
arg = vararg_pair(arg, varargin);
psfs = squeeze(psfs); % in case [1 1 np]
[np nc] = size(psfs);
if (np == 1) % single row
psfs = psfs';
[np nc] = size(psfs);
end
warned = false;
for ic = 1:nc
psf = psfs(:,ic);
if isempty(arg.imid)
imid = imax(psf);
else
imid = arg.imid;
end
% normalize
psf = psf / psf(imid);
if ~warned & (1 ~= max(psf))
warn 'peak not at center'
warned = true;
end
% right
ir = sum(cumprod(double6(psf((imid+1):np) >= 0.5)));
if (imid + ir == np)
hr(ic,1) = ir;
else
high = psf(imid + ir);
low = psf(imid + ir + 1);
hr(ic,1) = ir + (high - 1/2) / (high-low);
end
% left
il = sum(cumprod(double6(psf((imid-1):-1:1) >= 0.5)));
if (il == imid-1)
hl(ic,1) = il;
else
high = psf(imid - il);
low = psf(imid - il - 1);
hl(ic,1) = il + (high - 1/2) / (high-low);
end
end
hr = hr * arg.dx;
hl = hl * arg.dx;
fw = hr + hl;
if arg.chat && im
plot(([1:np]-imid)*arg.dx, psf, '-o', ...
[-hl hr], [0.5 0.5], '-')
xlabel 'x', ylabel 'psf(x)'
title(sprintf('fwhm=%g', fw))
end
%
% fwhm1_test
%
function fwhm1_test
dx = 3;
nx = 100;
xx = [-nx/2:nx/2-1]' * dx;
fx = 30;
sx = fx / sqrt(log(256));
psf = exp(-((xx/sx).^2)/2);
fw = fwhm1(psf, 'dx', dx, 'chat', 1);
|
github
|
sunhongfu/scripts-master
|
ndgrid_jf.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/ndgrid_jf.m
| 1,825 |
utf_8
|
81141c55ae5b933826ba00a65b23fcc3
|
function out = ndgrid_jf(otype, varargin)
%function out = ndgrid_jf('cell', varargin)
%function out = ndgrid_jf('mat', varargin)
%| version of ndgrid where output is cell array (default) or large matrix
%| think:
%| [out{1} ... out{M}] = ndgrid_cell(in{1}, ..., in{M});
%| also supported is ndgrid_jf('mat'|'cell', {in1, in2, ...})
%|
%| fix: is there a simple way to do this with nargout?
%| Copyright 2007, Jeff Fessler, University of Michigan
if nargin == 1 && streq(otype, 'test'), ndgrid_jf_test, return, end
if nargin < 2, help(mfilename), error(mfilename), end
switch otype
case 'cell'
is_cell = 1;
case 'mat'
is_cell = 0;
otherwise
error 'unknown output type'
end
% handle a convenient special case (this avoids strum.arg{:})
if length(varargin) == 1 && iscell(varargin{1})
out = ndgrid_jf(otype, varargin{1}{:});
return
end
if length(varargin) == 1
if is_cell
out = {varargin{1}};
else
out = varargin{1}(:);
end
return
end
nn = length(varargin);
for ii=nn:-1:1
varargin{ii} = full(varargin{ii});
siz(ii) = numel(varargin{ii});
end
out = cell(1,nn);
for ii=1:nn
x = varargin{ii}(:);
s = siz; s(ii) = []; % remove i-th dimension
x = reshape(x(:,ones(1,prod(s))), [length(x) s]); % expand x
out{ii} = permute(x, [2:ii 1 ii+1:nn]); % permute to i'th dimension
end
if ~is_cell
out = stackup(out{:});
end
%
% ndgrid_jf_test
%
function ndgrid_jf_test
x = 1:2;
y = 1:3;
z = 1:4;
out = ndgrid_jf('cell', x, y, z);
[xx yy zz] = ndgrid(x, y, z);
if ~isequal(xx, out{1}) || ~isequal(yy, out{2}) || ~isequal(zz, out{3})
error 'bug'
end
out = ndgrid_jf('mat', x, y, z);
if ~isequal(xx, out(:,:,:,1)) ...
|| ~isequal(yy, out(:,:,:,2)) ...
|| ~isequal(zz, out(:,:,:,3))
error 'bug'
end
out2 = ndgrid_jf('mat', {x, y, z});
jf_equal(out, out2)
out = ndgrid_jf('cell', x);
out = ndgrid_jf('mat', x);
|
github
|
sunhongfu/scripts-master
|
kde_pmf_width.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/kde_pmf_width.m
| 1,573 |
utf_8
|
6c684711031188408ae21134004afd70
|
function dx = kde_pmf_width(x, varargin)
%|function dx = kde_pmf_width(x, varargin)
%|
%| Determine bin width for kde_pmf1,2
%|
%| in
%| x [N 1] iid realizations of random variable pairs (x,y)
%|
%| option
%| 'type' 'silverman' to choose dx based on rule-of-thumb
%| using inter-quartile range (p48 of 1986 book)
%| 'chat' 0|1 print out intermediate values? (default: 0)
%|
%| out
%| dx [1 1] bin width
%|
%| Default is for a quadratic spline kernel supported on (-3/2,3/2).
%|
%| Copyright 2010-07-31, Jeff Fessler, University of Michigan
arg.type = 'silverman';
arg.kernel = 'bspline2';
arg.chat = 0;
arg = vararg_pair(arg, varargin);
if nargin < 1, help(mfilename), error(mfilename), end
if streq(x, 'test'), kde_pmf_width_test, return, end
if ~streq(arg.kernel, 'bspline2')
fail('only bspline2 done')
end
switch arg.type
case 'silverman'
dx = kde_pmf_width_silverman(x(:), arg.chat);
otherwise
fail('not done')
end
% kde_pmf_width_silverman()
function dx = kde_pmf_width_silverman(x, chat)
N = numel(x);
pn = jf_protected_names;
sig = std(x);
iqr = diff(pn.prctile(x, [25 75])); % inter-quartile range
if sig == 0
warn 'sig = 0 so dx = 0'
dx = 0;
return
end
if iqr == 0
warn 'iqr = 0, so ignoring iqr'
iqr = inf;
end
hx = 0.9 * min(sig, iqr/1.34) / N^(1/5); % rule of thumb for gaussian
dx = hx * sqrt(log(256)) / (3 - sqrt(3)); % convert to bspline2 width
if chat > 1
pr sig
pr iqr
end
if chat
pr dx
end
% test routine
function kde_pmf_width_test
randn('state', 0)
n = 300;
sig = 5;
x = sig * randn(n, 1);
dx = kde_pmf_width(x, 'chat', 2);
|
github
|
sunhongfu/scripts-master
|
arg_get.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/arg_get.m
| 953 |
utf_8
|
0e42582c06b61201a8a9468a8afcce32
|
function [arg, ii] = arg_get(list, what, default)
%function [arg, ii] = arg_get(list, what, default)
% extract an argument (e.g., nx or pixel_size, etc.)
% from a list (vertically concatenated strings)
% e.g., as generated by arg_pair() or strvcat()
% the *first* match is used.
% Copyright 2005, Jeff Fessler, The University of Michigan
if nargin < 1, help(mfilename), error(mfilename), end
if nargin == 1 && streq(list, 'test'), arg_get_test, return, end
list(list == ' ') = ' '; % replace tabs with spaces
what = [what ' '];
for ii=1:size(list,1)
if streq(list(ii,:), what, length(what))
arg = list(ii,(1+length(what)):end);
return
end
end
if isvar('default') & ~isempty(default)
if isnumeric(default)
arg = sprintf('%d', default);
else
arg = default;
end
ii = 0;
else
fail('cannot find "%s"', what)
end
function arg_get_test
tmp = strvcat('na 9', 'nb 8', 'nxyz 7');
tmp = arg_get(tmp, 'na');
tmp = str2num(tmp);
jf_equal(tmp, 9)
|
github
|
sunhongfu/scripts-master
|
filtmat.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/filtmat.m
| 3,758 |
utf_8
|
4f6ac3e0ab4e6785b3698d7b1b702542
|
function [mat, nexp] = filtmat(arg0, arg1, arg2, arg3, arg4)
%function mat = filtmat('1d', kernx, nx)
% 1d nonperiodic
%function mat = filtmat({'1d' 'per'}, kernx, nx)
% 1d periodic
%function mat = filtmat('2d,mul,sep', kernx, kerny, [nx ny])
% 2d multiplicatively separable nonperiodic
%function mat = filtmat('3d,mul,sep', kernx, kerny, kernz, [nx ny nz])
% 3d multiplicatively separable nonperiodic
% kernel(x,y,z) = kernx(x) * kerny(y) * kernz(z)
%function [mat, nexp] = filtmat({'3d,mul,sep' 'expand'}, kernx, kerny, kernz, [nx ny nz])
% 3d multiplicatively separable nonperiodic, expanded
%function mat = filtmat('1d,causal', kernx, nx)
% 1d causal filter, ala convmtx
%
% Form matrix to do 3d linear filtering - odd kernel length.
% expanding is like what happens in 'conv' - output is longer
if ~nargin, help filtmat, error arg, end
flag_expand = any(strcmp(arg0, 'expand'));
if nargin == 3 & strcmp(arg0, '1d,causal')
mat = filtmat1causal(arg1, arg2);
return
elseif nargin == 3 & any(strcmp(arg0, '1d'))
if any(strcmp(arg0, 'per'))
mat = filtmat1per(arg1, arg2);
else
mat = filtmat1(arg1, arg2, flag_expand);
end
return
elseif nargin == 4 & any(strcmp(arg0, '2d,mul,sep'))
mat = filtmat('3d,mul,sep', arg1, arg2, 1, [arg3 1]);
return
elseif nargin == 5 & any(strcmp(arg0, '3d,mul,sep'))
k.x = arg1;
k.y = arg2;
k.z = arg3;
n.x = arg4(1);
n.y = arg4(2);
n.z = arg4(3);
else
nargin, help filtmat, error arg
end
if flag_expand
[p.x, o.x] = filtmat1(k.x, n.x, flag_expand);
[p.y, o.y] = filtmat1(k.y, n.y, flag_expand);
[p.z, o.z] = filtmat1(k.z, n.z, 0); % no z expansion
p.x = kron(speye(n.y*n.z), p.x);
p.y = kron(speye(n.z), kron(p.y, speye(o.x)));
p.z = kron(p.z, speye(o.x*o.y));
if 0
n.xyz = n.x * n.y * n.z;
t = (o.y-n.y)/2 * o.x;
p.x = [sparse(t,n.xyz); p.x; sparse(t,n.xyz)];
t = zeros(o.x,o.y);
t([1:n.x]+(o.x-n.y)/2-1,:) = 1;
tt = sparse(o.x*o.y, n.x*n.y);
tt(find(t(:)),:) = p.y;
p.y = tt;
p.z = sparse(1,1);
if n.z ~= 1, error notdone, end
end
else
p.x = filtmat1(k.x, n.x, flag_expand);
p.y = filtmat1(k.y, n.y, flag_expand);
p.z = filtmat1(k.z, n.z, flag_expand);
p.x = kron(speye(n.y*n.z), p.x);
p.y = kron(speye(n.z), kron(p.y, speye(n.x)));
p.z = kron(p.z, speye(n.x*n.y));
o = n;
end
% mat = p.x + p.y + p.z;
if flag_expand, warning('fix: expand may not work for multiplicative?'), end
mat = p.z * p.y * p.x;
nexp = [o.x o.y o.z];
function mat = filtmat1causal(kern, n)
nk = length(kern);
if nk < n, error n, end
if n ~= nk, error 'not done', end
t = kern(:,ones(1,n));
t = [t; zeros(nk,nk)];
t = t(:);
t((end-nk+1):end) = [];
mat = reshape(t, 2*nk-1,nk);
mat = mat(1:nk,:);
function [mat, nexp] = filtmat1(kern, n, flag_expand)
% 1d matrix that does linear filtering - odd kernel length.
% flag_expand means output has more entries than input (n+nk-1)
nk = length(kern);
ic = (nk+1)/2; % center index
if round(ic) ~= ic, error('odd kernel only'), end
if flag_expand
n = n + nk-1;
end
nexp = n;
mat = diag(ones(n,1)*kern(ic));
for iv=1:(ic-1)
mat = mat + diag(ones(n-iv,1) * kern(ic-iv), -iv) ...
+ diag(ones(n-iv,1) * kern(ic+iv), iv);
end
if flag_expand
mat = mat(:,ic:(end-ic+1));
end
mat = sparse(mat);
function mat = filtmat1per(kern, nn)
% 1d matrix that does periodic linear filtering. odd or even kernel ok.
nk = length(kern);
ic = (nk+1)/2;
mat = spdiag(ones(nn,1)*kern(ic));
for kk=1:(ic-1)
mat = mat ...
+ diag(ones(nn-kk,1) * kern(ic-kk), -kk) ...
+ diag(ones(kk ,1) * kern(ic-kk), nn-kk);
end
for kk=1:floor(nk/2)
mat = mat ...
+ diag(ones(nn-kk,1) * kern(ic+kk), kk) ...
+ diag(ones(kk ,1) * kern(ic+kk), kk-nn);
end
mat = sparse(mat);
|
github
|
sunhongfu/scripts-master
|
remove_spaces.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/remove_spaces.m
| 793 |
utf_8
|
44dcf5c3a35ebc4ce3ddd6e590aab8a4
|
function arg = remove_spaces(arg)
%|function arg = remove_spaces(arg)
%| replace extra spaces at ends of matrix string array with zeros.
%| also add extra '0' at end to be sure to null terminate string
%| Copyright May 2000, Jeff Fessler, University of Michigan
if nargin < 1, help(mfilename), error(mfilename), end
if streq(arg, 'test'), remove_spaces_test, clear arg, return, end
for ii=1:size(arg,1)
jj = size(arg,2);
while (arg(ii,jj) == ' ')
arg(ii,jj) = 0;
jj = jj - 1;
if jj < 1
warn('bug in %s', mfilename)
keyboard
end
end
end
arg(:,end+1) = 0;
arg(arg(:,1) == 10, :) = []; % remove blank lines too
function remove_spaces_test
str = strvcat('a', 'bb ', 'c c ');
out = remove_spaces(str);
tmp = char([97 0 0 0 0; 98 98 0 0 0; 99 32 99 0 0]);
jf_equal(out, tmp)
|
github
|
sunhongfu/scripts-master
|
interp1_lagrange.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/interp1_lagrange.m
| 1,111 |
utf_8
|
2245c39a0a1bf94677de8caef3c0efe7
|
function y = interp1_lagrange(xi, yi, x)
%function y = interp1_lagrange(xi, yi, x)
% Lagrange (1D) interpolation: polynomial of order length(xi)
% in: xi [n,1], yi [n,1], x [m,1]
% if yi is empty, then "y" is the m,n interpolation matrix
% Copyright 2003-5-13 Jeff Fessler The University of Michigan
if nargin < 3, interp1_lagrange_test, help(mfilename), return, end
n = length(xi);
%num = outer_sum(x, -xi); % [m,n]
den = outer_sum(xi, -xi);
den = den + (1 - den) .* eye(n); % i \neq j
den = prod(den,2);
out = outer_sum(x, -xi); % [m,n]
if isempty(yi)
y = zeros(length(x), n);
for ii=1:n
t = out;
t(:,ii) = []; % [m,n-1]
y(:,ii) = prod(t,2) / den(ii);
end
else
yi = yi(:) ./ den; % [n,1]
y = zeros(size(x));
for ii=1:n
t = out;
t(:,ii) = []; % [m,n-1]
y = y + yi(ii) * prod(t, 2);
end
end
function interp1_lagrange_test
xi = [1 3 4 7]';
%xi = [-2:2]';
yi = [6 2 5 1]';
%yi = xi == 0;
x = linspace(0,8,101)';
%x = linspace(-2,2,101)';
y1 = interp1_lagrange(xi, yi, x);
y2 = interp1_lagrange(xi, [], x);
if im
plot(xi, yi, 'o', x, y1, 'y-', x, y2, ':', x, y2*yi, 'c.')
end
|
github
|
sunhongfu/scripts-master
|
arg_pair.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/arg_pair.m
| 1,517 |
utf_8
|
5efeebd0651d931efc4ac151090edec1
|
function arg = arg_pair(varargin)
%|function arg = arg_pair(varargin)
%|
%| construct AsciiArg pairs from input arguments
%| for building arguments akin to .dsc file
%| example: arg = arg_pair('system', 2, 'nx', 128, ...)
%|
%| Copyright May 2000, Jeff Fessler, University of Michigan
if nargin == 1 & streq(varargin{1}, 'test'), arg_pair_test, return, end
if nargin == 1 & isstruct(varargin{1})
arg = arg_pair_struct(varargin{1});
return
end
if nargin < 2, help(mfilename), error(mfilename), end
% see if first argument is already a char array; if so, then augment it.
arg = varargin{1};
if ischar(arg) && size(arg,1) > 1
varargin = {varargin{2:end}};
else
arg = [];
end
if rem(length(varargin),2), error 'even # of arguments required', end
for ii=1:2:length(varargin)
a = varargin{ii};
b = varargin{ii+1};
if ~ischar(a), error a, end
if ischar(b)
arg = strvcat(arg, [a ' ' b]);
elseif isscalar(b)
arg = strvcat(arg, sprintf('%s %g', a, b));
else
pr size(b)
fail('nonscalar argument class "%s"', class(b))
end
end
arg = remove_spaces(arg);
%
% arg_pair_struct()
%
function arg = arg_pair_struct(st)
names = fieldnames(st);
arg = [];
for ii=1:length(names)
a = names{ii};
b = st.(a);
if ischar(b)
arg = strvcat(arg, [a ' ' b]);
else
arg = strvcat(arg, sprintf('%s %g', a, b));
end
end
arg = remove_spaces(arg);
function arg_pair_test
a1 = arg_pair('a1', 1, 'a2', 'v2');
a2 = arg_pair(a1, 'liii', 3.3);
a0 = remove_spaces(strvcat('a1 1', 'a2 v2', 'liii 3.3'));
jf_equal(a0, a2)
|
github
|
sunhongfu/scripts-master
|
upsample_rep.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/upsample_rep.m
| 629 |
utf_8
|
3db6e5ee1beac6a80b0a8880a17d5c3d
|
function y = upsample_rep(x, m)
%function y = upsample_rep(x, m)
% upsample a 2D image a factor of m by simple replication
if nargin == 1 && streq(x, 'test'), upsample_rep_test, return, end
if nargin < 1, help(mfilename), error(mfilename), end
if nargin < 2, m = [2 2]; end
y = upsample1_rep(x, m(1));
y = upsample1_rep(y', m(end))';
% 1d upsampling of each column
function y = upsample1_rep(x, m)
[n1 n2] = size(x);
y = zeros(m*n1,n2);
for ii=1:m
y(ii+m*[0:n1-1],:) = x;
end
function upsample_rep_test
x = reshape(1:24, [4 6]);
y = upsample_rep(x, 2);
for i1=1:2
for i2=1:2
jf_equal(x, y(i1:2:end,i2:2:end))
end
end
|
github
|
sunhongfu/scripts-master
|
max_percent_diff.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/max_percent_diff.m
| 1,971 |
utf_8
|
0b4ab863976402c87de0914aa0e5a0a0
|
function d = max_percent_diff(s1, s2, varargin)
%|function d = max_percent_diff(s1, s2, [options])
%|
%| compute the "maximum percent difference" between two signals: s1, s2
%| options
%| 1 use both arguments as the normalizer
%| string print this
%|
%| Copyright 2000-9-16, Jeff Fessler, University of Michigan
if nargin == 1 && streq(s1, 'test'), max_percent_diff_test, return, end
if nargin < 2, help(mfilename), error(mfilename), end
base = '';
if ischar(s1)
t1 = s1;
s1 = evalin('caller', t1);
base = [caller_name ': '];
else
t1 = inputname(1);
end
if ischar(s2)
t2 = s2;
s2 = evalin('caller', t2);
else
t2 = inputname(2);
end
use_both = 0;
doprint = (nargout == 0);
while (length(varargin))
arg1 = varargin{1};
if isnumeric(varargin{1})
use_both = 1;
varargin = {varargin{2:end}};
continue
end
if ischar(arg1)
doprint = 1;
base = [arg1 ': '];
varargin = {varargin{2:end}};
continue
end
end
% first check that we have comparable signals!
if ~isequal(size(s1), size(s2))
printm(['size(%s) = %s'], inputname(1), mat2str(size(s1)))
printm(['size(%s) = %s'], inputname(2), mat2str(size(s2)))
error 'dimension mismatch'
end
if any(isnan(s1(:)))
warn([mfilename ': NaN values in %s in %s!?'], t1, caller_name)
end
if any(isnan(s2(:)))
warn([mfilename ': NaN values in %s in %s!?'], t2, caller_name)
end
s1 = doubles(s1);
s2 = doubles(s2);
if use_both
denom = max(abs([s1(:); s2(:)]));
if ~denom
d = 0;
else
d = max(abs(s1(:)-s2(:))) / denom;
end
else
denom = max(abs(s1(:)));
if ~denom
denom = max(abs(s2(:)));
end
if ~denom
d = 0;
else
d = max(abs(s1(:)-s2(:))) / denom;
end
end
d = full(d) * 100;
if doprint
printf([base 'max_percent_diff(%s, %s) = %g%%'], t1, t2, d)
if ~nargout
clear d
end
end
%
% max_percent_diff_test
%
function max_percent_diff_test
v1 = [0 1000];
v2 = [0 1001];
max_percent_diff([0 1000], [1 1000])
max_percent_diff(v1, v2, 'numeric')
max_percent_diff '[0 1000]' '[1 1000]'
|
github
|
sunhongfu/scripts-master
|
bspline_1d_coef.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/bspline_1d_coef.m
| 5,143 |
utf_8
|
68fc2ba254910a9aed75f78d9a852b84
|
function coef = bspline_1d_coef(fn, varargin)
%|function coef = bspline_1d_coef(fn, varargin)
%|
%| Given f[n], uniformly spaced samples of a 1D signal f(t),
%| compute the bspline coefficients so that the following model interpolates:
%| f(t) = \sum_{k=0}^{N-1} coef[k] b(t - k)
%|
%| in
%| fn [N,(L)] 1d signal(s) of length N (columns)
%| option
%| order default: 3
%| ending end / boundary conditions: mirror / periodic / zero
%| out
%| coef [N,(L)] bspline coefficients, for use in bspline_1d_interp()
%|
%| Caution: the 'zero' end conditions do not quite interpolate the edge samples.
%| That would require returning more coefficients than signal samples, which is
%| not worth the trouble since 'mirror' and 'periodic' are more common.
%|
%| Copyright 2005-12-7, Jeff Fessler, University of Michigan
if nargin < 1, help(mfilename), error(mfilename), end
if streq(fn, 'test'), bspline_1d_coef_test, return, end
arg.order = 3;
arg.ending = 'periodic';
arg.n0 = 10; % boundary conditions, more than enough for single precision.
arg.mex = 1; % default is to try mex version
arg = vararg_pair(arg, varargin);
if arg.mex
ii = strvcat('mirror', 'periodic', 'zero');
ii = strmatch(arg.ending, ii, 'exact');
if length(ii) ~= 1, error 'unknown end conditions', end
try
coef = jf_mex('bspline,coef,1d', single(fn), ...
int32(arg.order), int32(ii));
return
catch
printm 'Warn: mex version failed; reverting to matlab version'
end
end
dims = size(fn);
N = dims(1);
fn = reshapee(fn, N, []); % [N,*L]
if arg.order == 1
coef = fn;
elseif arg.order == 3
coef = bspline3_1d_coef(fn, arg.n0, arg.ending);
else
error 'order not done'
end
coef = reshape(coef, dims); % [N,(L)]
%
% 1d cubic bspline, various end conditions
% fn and coef are [N,L]
%
function coef = bspline3_1d_coef(fn, n0, ending)
p = -2 + sqrt(3); % pole location
N = size(fn,1);
fn = 6 * fn;
coef = zeros(size(fn));
n0 = min(n0, N);
ps = p .^ [1:n0];
% initial condition for forward
if streq(ending, 'mirror')
coef(1,:) = ps/p * fn(1:n0,:);
elseif streq(ending, 'periodic')
coef(1,:) = fn(1,:) + fliplr(ps) * fn([(N-n0+1):N],:);
elseif streq(ending, 'zero')
coef(1,:) = fn(1,:);
else
error 'unknown end conditions'
end
% causal iir filter
for n=2:N
coef(n,:) = fn(n,:) + p * coef(n-1,:);
end
% initial condition for anti-causal
if streq(ending, 'mirror')
% coef(N,:) = -fliplr(ps) * coef([(N-n0+1):N],:); % my way, not good
coef(N,:) = -p/(1-p^2) * ( coef(N,:) + p * coef(N-1,:) ); % unser way
elseif streq(ending, 'periodic')
coef(N,:) = -p * coef(N,:) - p * ps * coef(1:n0,:);
else % zero
coef(N,:) = -p * coef(N,:);
end
% anti-causal iir filter
for n=N-1:-1:1
coef(n,:) = p * ( coef(n+1,:) - coef(n,:) );
end
%
% fft approach, for validating periodic and mirror cases
%
function coef = bspline3_1d_coef_fft(fn, ending)
N = size(fn,1);
if streq(ending, 'mirror')
hn = zeros(2*N-2,1);
hn([1 2 2*N-2]) = [4 1 1]'/6;
coef = ifft(fft([fn; flipud(fn(2:N-1,:))]) ./ ...
repmat(fft(hn), [1 ncol(fn)]));
coef = reale(coef(1:N,:));
elseif streq(ending, 'periodic')
hn = zeros(N,1);
hn([1 2 N]) = [4 1 1]'/6;
coef = ifft(fft(fn) ./ repmat(fft(hn), [1 ncol(fn)]));
coef = reale(coef);
elseif streq(ending, 'zero')
coef = zeros(size(fn)); % fake
end
%
% exact matrix approach based on cbanal.m from kybic, for validating
%
function coef = bspline3_1d_coef_exact(y, ending)
N = size(y,1);
A = zeros(N,N);
if N == 1
coef = 1.5 * y; % 6/4
return
end
if streq(ending, 'mirror')
coef = bspline3_1d_coef_exact([y; flipud(y(2:N-1,:))], 'periodic');
coef = coef(1:N,:);
return
end
A(1,1:2) = [4 1]/6;
A(N,N-1:N) = [1 4]/6;
if streq(ending, 'mirror')
A(1,2) = 2/6;
A(N,N-1) = 2/6;
elseif streq(ending, 'periodic')
A(1,N) = 1/6;
A(N,1) = 1/6;
end
for i=2:N-1,
A(i,i-1:i+1) = [1 4 1]/6;
end
coef = A \ y;
%
% test periodic case by comparing to fft and to matrix "exact" method
%
function bspline_1d_coef_test
N = 2^5;
%fn = zeros(N,1); fn(3) = 1;
fn = eye(N);
orders = [1 3];
endings = {'mirror', 'periodic', 'zero'};
for io=1:length(orders)
order = orders(io);
for ie=1:length(endings)
ending = endings{ie};
printm([ending ' ' num2str(order)])
arg = {'order', order, 'ending', ending};
if 1 % check mex version
% cpu etic
coef = bspline_1d_coef(fn, arg{:}, 'mex', 0);
% cpu etoc 'matlab'
% cpu etic
cmex = bspline_1d_coef(fn, arg{:}, 'mex', 1);
% cpu etoc 'mex'
max_percent_diff(coef, cmex)
im clf, im pl 1 3
im(1, coef)
im(2, cmex)
im(3, cmex-coef)
end
if has_mex_jf % check adjoint
A = bspline_1d_coef(eye(N), arg{:}, 'mex', 1);
B = jf_mex('bspline,coef,adj,1d', single(eye(N)), ...
int32(order), int32(ie));
if max(col(abs(A-B'))) > 1e-5, error 'adjoint', end
end
if order ~= 3, continue, end
cfft = bspline3_1d_coef_fft(fn, ending);
exact = bspline3_1d_coef_exact(fn, ending);
max_percent_diff(exact, cfft)
max_percent_diff(exact, coef)
im clf, im pl 2 3
im(1, fn, 'f[n]'), cbar
im(4, exact, 'exact'), cbar
im(2, coef, 'coef'), cbar
im(5, coef-exact, 'error'), cbar
im(3, cfft, 'coef fft'), cbar
im(6, cfft-exact, 'error'), cbar
end
end
|
github
|
sunhongfu/scripts-master
|
downsample1.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/downsample1.m
| 1,242 |
utf_8
|
cde1ae93622ba9447977d20910d44b6d
|
function y = downsample1(x, down, varargin)
%|function y = downsample1(x, down, varargin)
%| downsample by factor m along first dimension by averaging
%|
%| in
%| x [n1 (Nd)]
%| down integer downsampling factor
%| option
%| 'warn' 0|1 warn if noninteger multiple (default: 1)
%| out
%| y [n1/down (Nd)]
%|
%| Copyright 2009-6-4, Jeff Fessler, University of Michigan
if nargin == 1 & streq(x, 'test'), downsample1_test, return, end
if nargin < 2, help(mfilename), error(mfilename), end
arg.warn = 1;
arg = vararg_pair(arg, varargin);
dim = size(x);
x = reshape(x, dim(1), prod(dim(2:end))); % [n1 *Nd]
m1 = floor(dim(1) / down);
if m1 * down < dim(1)
if arg.warn
warn('truncating input size %d to %d', dim(1), m1 * down)
end
x = x(1:(m1*down),:);
end
y = reshapee(x, down, []);
y = mean(y, 1);
y = reshape(y, [m1 dim(2:end)]);
if 0
% old way with loop
n1 = floor(size(x,1) / m);
n2 = size(x,2);
y = zeros(n1,n2);
for ii=0:m-1
y = y + x(ii+[1:m:m*n1],:);
ticker(mfilename, ii+1,m)
end
y = y / m;
end
function downsample1_test
x = reshape(2:2:48, [4 6]);
y = downsample1(x, 2);
jf_equal(y, reshape(3:4:47, [2 6]))
if 0 % big test
x = zeros(2^12);
cpu etic
y = downsample1(x, 2);
cpu etoc 'downsample1 time:'
end
|
github
|
sunhongfu/scripts-master
|
fwhm2.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/fwhm2.m
| 3,918 |
utf_8
|
de4664218f9f1cae8bb7f5cd25d64465
|
function [fw, angle, rad] = fwhm2(psf, varargin)
%|function [fw, angle, rad] = fwhm2(psf, [options])
%|
%| compute 2d fwhm of point-spread function using contourc()
%|
%| in
%| psf [nx ny] 2D psf image
%|
%| option
%| 'dx' pixel size (default 1)
%| 'dy' pixel size (default dx)
%| 'level' default 0.5 (for "half" maximum)
%| 'type' 'max' uses location of maximum (default)
%| 'centroid' takes 2D centroid around that max
%| 'user' uses user-defined center
%| 'center' [cx cy] user-defined
%| 'chat'
%|
%| out
%| fw FWHM
%|
%| Copyright 2003-11-29, Jeff Fessler, University of Michigan
%| 2010-04-01 repaired bad bug in 'centroid' version that was former default
if nargin < 1, help(mfilename), error(mfilename), end
if streq(psf, 'test'), fwhm2_test, return, end
arg.dx = 1;
arg.dy = [];
arg.chat = (nargout == 0);
arg.level = 0.5;
arg.type = 'max';
arg.center = []; % for user-specified peak
%if nargin > 1 && isnumeric(varargin{1}) % old style: dx, chat
% arg.dx = varargin{1}; varargin = {varargin{2:end}};
% if length(varargin) > 1
% arg.chat = varargin{2}; varargin = {varargin{2:end}};
% end
%end
arg = vararg_pair(arg, varargin);
if isempty(arg.dy), arg.dy = arg.dx; end
if ~isreal(psf), warn 'unsure what happens for complex psf!', end
if min(size(psf)) < 11
psf = padn(psf, max(size(psf), 23));
end
[nx ny] = size(psf);
ii = imax(psf, 2); % image maximum
cx = ii(1);
cy = ii(2);
switch arg.type
case 'max'
% done
case 'user'
if length(arg.center) ~= 2, error 'center should be [cx cy]', end
cx = arg.center(1);
cy = arg.center(2);
case 'centroid' % find center estimate by local centroid
ix = [-5:5]';
iy = [-5:5]';
[iix iiy] = ndgrid(ix, iy);
t = psf(cx + iix, cy + iiy);
if arg.chat
im(ix, iy, t)
end
ox = sum(t(:) .* iix(:)) / sum(t(:));
oy = sum(t(:) .* iiy(:)) / sum(t(:));
cx = cx + ox;
cy = cy + oy;
if ox ~= 0 || oy ~= 0
printm('centroid offset %g %g', ox, oy)
end
otherwise
fail('bad type %s', arg.type)
end
if any(isnan(psf)), error 'psf contains nan', end
if min(psf(:)) > 1/2 * max(psf(:))
warn 'psf does not decrease below max/2; could extrapolate?'
fw = inf;
return
end
psf = double(psf); % stupid matlab
cc = contourc(psf, [1e30 arg.level * max(psf(:))]);
if isempty(cc), error 'empty contour? check minimum!', end
cc = cc(:,2:length(cc))';
cc = cc(:,[2 1]); % swap row,col or x,y
% check center pixel found
if arg.chat && im
im plc 1 2
im(1, psf)
hold on
plot(cc(:,1), cc(:,2), '+')
plot(cx, cy, 'rx')
titlef('length(cc)=%d', length(cc))
hold off
end
xx = arg.dx * (cc(:,1) - cx); % physical coordinates
yy = arg.dy * (cc(:,2) - cy);
rsamp = sqrt(xx.^2 + yy.^2);
tsamp = atan2(yy,xx);
tsamp = rad2deg(tsamp);
[tsamp order] = sort(tsamp); % trick: monotone
rsamp = rsamp(order);
if abs(tsamp(end) - 180) < eps % -180 should match 180
tsamp = [-180; tsamp];
rsamp = [rsamp(end); rsamp];
end
angle = [0:180]'; % interpolate to equally spaced angles
% todo: replace with something better than linear interpolation
% todo: and make it handle 360 wrap around better?
r1 = interp1x(tsamp, rsamp, angle);
r2 = interp1x(tsamp, rsamp, angle-180);
rad = r1 + r2;
fw = mean(rad); % should the "average" be done s.t. for an ellipse contour
% we get the avg of the two major axes?
if arg.chat && im
% plot(tsamp, rsamp, 'o', angle, r1, '-', angle-180, r2, '-'), prompot
im subplot 2
plot(angle, rad, '-o', tsamp, 2*rsamp, 'yx')
xlabel 'Angle \phi [degrees]'
ylabel 'FWHM(\phi)'
axisx(0,180), xtick([0 90 180])
titlef('overall fwhm=%g', fw)
zoom on
end
% fwhm2_test
function fwhm2_test
dx = 3;
dy = 2;
nx = 100;
ny = 80;
x = [-nx/2:nx/2-1]' * dx;
y = [-ny/2:ny/2-1]' * dy;
fx = 30;
fy = 16;
sx = fx / sqrt(log(256));
sy = fy / sqrt(log(256));
[xx yy] = ndgrid(x,y);
psf = exp(-((xx/sx).^2 + (yy/sy).^2)/2);
if im
im pl 1 2
im(1, x, y, psf, 'psf'), axis equal, axis image
end
[fw ang rad] = fwhm2(psf, 'dx', dx, 'dy', dy, 'chat', 1);
|
github
|
sunhongfu/scripts-master
|
poisson.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/poisson.m
| 1,180 |
utf_8
|
0265d6eb478b5a47dc8d273d2c07d330
|
function data = poisson(xm, seed, varargin)
%|function data = poisson(xm, seed, [options])
%|
%| option
%| 'factor' see poisson2.m
%|
%| Generate Poisson random vector with mean xm.
%| For small, use poisson1.m
%| For large, use poisson2.m
%| see num. rec. C, P. 222
%|
%| Copyright 1997-4-29, Jeff Fessler, University of Michigan
if nargin < 1, help(mfilename), error(mfilename), end
if nargin == 1 & streq(xm, 'test'), poisson_test, return, end
if ~isvar('seed')
seed = [];
end
arg.factor = 0.85;
arg = vararg_pair(arg, varargin);
data = xm;
xm = xm(:);
small = xm < 12;
data( small) = poisson1(xm( small), seed);
data(~small) = poisson2(xm(~small), 'seed', seed, 'factor', arg.factor);
%
% poisson_test()
% run a timing race against matlab's poissrnd
%
function poisson_test
n = 2^8;
t = reshape(linspace(1, 1000, n^2), n, n);
cpu etic
poisson(t);
cpu etoc 'fessler poisson time'
if exist('poissrnd') == 2
cpu etic
poissrnd(t);
cpu etoc 'matlab poissrnd time'
else
warn 'matlab poissrnd unavailable'
end
if 0 % look for bad values?
poisson(10^6 * ones(n,n));
poisson(1e-6 * ones(n,n));
poisson(linspace(11,13,2^10+1));
poisson(linspace(12700,91800,n^3));
end
|
github
|
sunhongfu/scripts-master
|
nrms.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/nrms.m
| 1,109 |
utf_8
|
042ba79752bcb9662b4db291ca79144b
|
function n = nrms(x, xtrue, arg)
%|function n = nrms(x, xtrue, arg)
%| normalized rms error
%| in
%| x [[Nd] Nrep] multiple x's for one xtrue
%| xtrue [[Nd]]
%| arg use '2' to do along 2nd dim for same size
%| out
%| scalar
%| vector if x and xtrue have same size and arg = 2
if nargin == 1 && streq(x, 'test'), nrms_test, return, end
if nargin < 2, help(mfilename), error(mfilename), end
if nargin == 3 && arg == 2
if any(size(x) ~= size(xtrue))
error 'need same size'
end
n = mean(abs(xtrue - x).^2);
return
end
xtrue = double(xtrue(:));
np = length(xtrue);
nrep = numel(x) / np;
x = reshape(x, np, nrep);
x = double(x);
n = abs(x - xtrue(:,ones(1,nrep)));
xnorm = norm(xtrue);
enorm = sqrt(sum(n.^2)');
if xnorm
n = enorm / xnorm;
elseif ~enorm
n = 0; % 0/0 = 0
else
n = inf;
end
doprint = nargout < 1;
base = '';
if doprint
fprintf('%snrms(%s,%s) =', base, inputname(1), inputname(2))
for ii=1:length(n)
fprintf(' %g%%', n(ii) * 100)
end
fprintf('\n')
if ~nargout
clear n
end
end
function nrms_test
x = ones(5,1);
y = 1.1*ones(5,1);
z = 1.2*ones(5,1);
nrms(y,x)
nrms([y z], x)
|
github
|
sunhongfu/scripts-master
|
fld_read.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/fld_read.m
| 12,334 |
utf_8
|
4d7e7ee0934f826d43db5b5fe965f388
|
function [data, coord, dims] = fld_read(file, varargin)
%|function [data, coord, dims] = fld_read(file, options)
%| Read data from AVS format .fld file.
%|
%| options
%| 'raw' 0|1 1: return raw data class (default), 0: return doubles
%| 'slice' int specify which slice to read from 3D file. (0 ... nz-1)
%| 'chat' 0|1 enable verbosity
%| 'dim_only' 0|1 returns dims. data and coord are equal to [].
%| 'coord' 0|1 returns coordinates too (default: 0)
%| 'coord_format' default: 'n'; see fopen() for machine format options
%| (needed for some UM .fld files with 'vaxd' coordinates)
%| out
%| data stores the element values.
%| coord vector that contains the coordinate values in the order
%| X axis, Y axis, Z axis, ...
%| dims vector that specifies the length of each dimension.
%|
%| see ASPIRE user's guide for documentation
%|
%| Copyright 2003-5-13, Jeff Fessler & Rongping Zeng, University of Michigan
if nargin == 1 & streq(file, 'test'), fld_write('test'), return, end
if nargin < 1, help(mfilename), error(mfilename), end
% defaults
arg.slice = [];
arg.raw = true;
arg.chat = false;
arg.dim_only = false;
arg.coord = false;
arg.coord_format = 'n'; % default 'native
arg = vararg_pair(arg, varargin);
fid = fopen(file, 'r');
if fid == -1, fail('cannot open %s', file), end
formfeed = char(12); % form feed
newline = sprintf('\n');
is_external_file = false;
% read header until we find the end of file or the 1st form feed
header = '';
while (1)
[inchar count] = fread(fid, 1, '*char'); % read one character
% end of file means external file (or error)
if count ~= 1
if ~isempty(strfind(header, 'file='))
is_external_file = true;
break % end of header file!
else
disp(header)
error 'end of file before form feeds?'
end
end
% form feed means embedded file
if inchar == formfeed
[inchar count] = fread(fid, 1, '*char');
if count ~= 1, error 'end of file before 2nd form feed?', end
if inchar ~= formfeed, error 'not two form feeds?', end
if (arg.chat)
printm('embedded data file')
end
break
end
% otherwise append this character to header string
header = [header inchar];
end, clear inchar formfeed count newline
header = string_to_array(header); % convert to array
if (arg.chat)
disp(header)
end
% parse header to determine data dimensions and type
ndim = arg_get(header, 'ndim');
dims = zeros(1,ndim);
for ii=1:ndim
dims(ii) = arg_get(header, sprintf('dim%d', ii));
end
fieldtype = arg_get(header, 'field', '%s');
datatype = arg_get(header, 'data', '%s');
if arg_get(header, 'veclen') ~= 1, error 'only veclen=1 done', end
if arg.chat
printm('ndim=%d', ndim)
printm('dim%d=%d ', [1:ndim; dims])
end
% process dim_only option
if arg.dim_only
data = [];
coord = [];
fclose(fid);
return
end
% external file (binary data in another file)
% fix: external ASCII files to be implemented
skip = 0;
if is_external_file
fclose(fid);
extfile = arg_get(header, 'file', '%s');
filetype = arg_get(header, 'filetype', '%s');
if arg.chat, printm('Current file = "%s", External file = "%s", type="%s"', ...
file, extfile, filetype), end
if ~isempty(strfind(col(header')', 'skip='))
skip = arg_get(col(header')', 'skip');
end
if ~streq(filetype, 'multi')
if ~exist(extfile, 'file')
fdir = file;
slash = strfind(fdir, '/');
if isempty(slash)
fail('cannot find external file %s', extfile)
end
fdir = fdir(1:slash(end));
extfile = [fdir extfile]; % add directory
if ~exist(extfile, 'file')
fail('no external ref file %s', extfile)
end
end
else
num_of_files = str2num(extfile);
fdir = file;
slash = strfind(fdir, '/');
if isempty(slash)
fail('cannot find external file %s', extfile)
end
fdir = fdir(1:slash(end));
end
else
filetype = '';
extfile = '';
end
% finally, read the binary data
[format endian bytes] = datatype_fld_to_mat(datatype);
if streq(filetype, 'multi') % multi file reading
if arg.coord, fail 'coord not implemented for multi files', end
coord = [];
data = fld_read_multi(file, fid, arg, ...
dims, datatype, fieldtype, fdir, header, ...
is_external_file, extfile, format, endian, bytes, skip);
else % single file reading
[data, coord] = fld_read_single(file, fid, arg, ...
dims, datatype, fieldtype, ...
is_external_file, extfile, format, endian, bytes, skip);
fclose(fid);
end
%
% fld_read_single()
%
function [data, coord] = fld_read_single(file, fid, arg, ...
dims, datatype, fieldtype, ...
is_external_file, extfile, format, endian, bytes, skip)
% reopen file to same position, with appropriate endian too.
if is_external_file
if isempty(endian)
fid = fopen(extfile, 'r');
else
fid = fopen(extfile, 'r', endian);
end
if fid == -1, fail('cannot open external %s', extfile), end
else
position = ftell(fid);
if fclose(fid) ~= 0, warning fclose, end
if isempty(endian)
fid = fopen(file, 'r');
else
fid = fopen(file, 'r', endian);
end;
if fid == -1, fail('cannot re-open %s', file), end
if fseek(fid, position, 'bof') ~= 0, error fseek, end
end
if skip
if fseek(fid, skip, 'cof') ~= 0, error fseek, end
end
% if a single slice to be read, then skip to it
if ~isempty(arg.slice)
if length(dims) ~= 3
if arg.slice == 0 || arg.slice == -1
dims(3) = 1;
arg.slice = 0;
else
error 'slice only good for 3d files', end
end
if (arg.slice < 0), arg.slice = arg.slice + dims(3); end % trick for negative slice
if (arg.slice < 0 | arg.slice >= dims(3)), error 'bad slice', end
offset = bytes * arg.slice * dims(1) * dims(2);
if fseek(fid, offset, 'cof') ~= 0, error fseek, end
rdims = dims(1:2);
else
rdims = dims;
end
% read binary data (converting to double) and reshape appropriately
% to avoid converting to double, we would need to preface format with a '*',
% per fread documentation.
if arg.raw
format = ['*' format];
end
[data count] = fread(fid, prod(rdims), format);
if count ~= prod(rdims)
pr rdims
fid
fail('file count=%d vs data=%d', count, prod(rdims))
end
if length(rdims) > 1
data = reshape(data, rdims);
end
% reopen file to the same position, but to specified machine format
% to read in coordinates.
% UM RadOnc .fld files sometimes use 'vaxd' format for coordinates,
% which are no longer supported by matlab, so they may not work.
if arg.coord
position = ftell(fid);
fclose(fid);
if streq(datatype, 'xdr_short')
fid = fopen(file, 'r', 'ieee-be');
else
fread_coord = @(file,n,type) fread(file,n,type);
try
fid = fopen(file, 'r', arg.coord_format);
catch
if ~streq(arg.coord_format, 'vaxd')
fail('fopen(%s) with format "%s" failed', ...
file, arg.coord_format)
end
if exist('freadVAXD') ~= 2
fail(['need to get "freadVAXD from ', ...
' http://www.mathworks.com/matlabcentral/fileexchange/22675'])
end
fid = fopen(file, 'r', 'ieee-le'); % trick
fread_coord = @(f,n,type) freadVAXD(f,n,type); % trick
end
end
fseek(fid, position, 'bof');
switch fieldtype
case 'uniform'
% printm('Number of coordinate values is 0')
coord = [];
case 'rectilinear'
cor_num = sum(dims);
% trick: so single-slice works:
fseek(fid, -(cor_num*4+1), 'eof');
[coord count] = fread_coord(fid, inf, 'float');
if count ~= cor_num
error('error in reading coordinate values')
end
otherwise
fail('fieldtype "%s" not implemented yet!', fieldtype)
end
else
coord = [];
end
%
% fld_read_multi()
% multiple file reading ([email protected])
% reusing code from single external file/same file reading above
%
% first implemented for the case when separate slices are saved
% as different binary files.
%
% todo: implement skip
% todo: implement vaxd
%
function data = fld_read_multi(file, fid, arg, ...
dims, datatype, fieldtype, fdir, header, ...
is_external_file, extfile, format, endian, bytes, skip)
if ~is_external_file
error 'file=num_of_files usage missing when filetype=multi is used'
end
if skip
error 'skip not yet implemented for filetype=multi.'
end
extfile_list = '';
% if a line of fld file does not contain a '='
% then we use that line as one of the filenames
for ii=1:size(header,1)
temp = header(ii,:);
if isempty(strfind(temp,'='))
extfile_list = strvcat(extfile_list,temp);
end
end
if arg.chat
printm('current dir = %s', fdir)
printm 'file list:-'
printm '=============================================================='
extfile_list
printm '=============================================================='
end
% setup format per fread documentation
if arg.raw
format = ['*' format];
end
% if a single slice to be read, then read that particular slice file
if ~isempty(arg.slice)
if length(dims) ~= 3
if arg.slice == 0 || arg.slice == -1
dims(3) = 1;
arg.slice = 0;
else
error 'slice only good for 3d files', end
end
if (arg.slice < 0), arg.slice = arg.slice + dims(3); end % trick for negative slice
if (arg.slice < 0 | arg.slice >= dims(3)), error 'bad slice', end
extfile_slice = deblank([fdir extfile_list(arg.slice,:)]);
fid = fopen(extfile_slice, 'r', endian);
if fid == -1, fail('cannot open external %s', extfile_slice), end
rdims = dims(1:2);
% read in and reshape the data
[data count] = fread(fid, prod(rdims), format);
if count ~= prod(rdims)
disp(rdims)
fid
fail('file count=%d vs data=%d', count, prod(rdims))
end
fclose(fid);
else
rdims = dims;
rdims_slice = dims(1:2);
data = [];
count = 0;
ticker reset
nfile = size(extfile_list,1);
for ii=1:nfile % read in each file
ticker(mfilename, ii, nfile)
extfile_slice = deblank([fdir extfile_list(ii,:)]);
fid = fopen(extfile_slice, 'r', endian);
if fid == -1, fail('cannot open external %s', extfile_slice), end
[data_new count_new] = fread(fid, prod(rdims_slice), format);
data = [data; data_new];
count = count + count_new;
fclose(fid);
end
if count ~= prod(rdims)
fail('file count=%d vs data=%d', count, prod(rdims))
end
if length(rdims) > 1
data = reshape(data, rdims);
end
end
%
% string_to_array()
% convert long string with embedded newlines into string array
%
function header = string_to_array(header_lines)
newline = sprintf('\n');
% ensure there is a newline at end, since dumb editors can forget...
if header_lines(end) ~= newline
header_lines = [header_lines newline];
end
ends = strfind(header_lines, newline);
if length(ends) <= 0
error 'no newlines?'
end
header = header_lines(1:(ends(1)-1));
for ll = 2:length(ends)
line = header_lines((ends(ll-1)+1):(ends(ll)-1));
header = strvcat(header, line);
end
% strip comments (lines that begin with #)
header(header(:,1) == '#',:) = [];
%
% arg_get()
% parse an argument from header, of the name=value form
%
function arg = arg_get(head, name, type)
if ~isvar('type')
type = '%d';
end
for ll = 1:nrow(head)
line = head(ll,:);
start = strfind(line, [name '=']);
if ~isempty(start)
if length(start) > 1, error 'bug: multiples?', end
line = line((start+length(name)+1):end);
[arg, count, err] = sscanf(line, type, 1);
if ~isempty(err)
error(err)
end
return
end
end
fail('could not find %s in header', name)
%
% datatype_fld_to_mat()
% determine matlab format from .fld header datatype
%
function [format, endian, bytes] = datatype_fld_to_mat(datatype)
switch datatype
case 'byte'
format = 'uint8';
endian = 'ieee-be'; % irrelevant
bytes = 1;
case 'short'
format = 'short';
endian = ''; % native short - not portable
bytes = 2;
case {'short_be', 'short_sun', 'xdr_short'}
format = 'int16';
endian = 'ieee-be';
bytes = 2;
case 'short_le'
format = 'int16';
endian = 'ieee-le';
bytes = 2;
case 'int'
format = 'int';
endian = ''; % native int - not portable
bytes = 4;
case 'int_le'
format = 'int32';
endian = 'ieee-le';
bytes = 4;
case {'int_be', 'xdr_int'}
format = 'int32';
endian = 'ieee-be';
bytes = 4;
case 'float'
format = 'float';
endian = ''; % native float - not portable
bytes = 4;
case 'float_le'
format = 'float32';
endian = 'ieee-le';
bytes = 4;
case {'float_be', 'xdr_float'}
format = 'float32';
endian = 'ieee-be';
bytes = 4;
case 'double'
format = 'double';
endian = ''; % native double - not portable
bytes = 8;
case 'double_le'
format = 'double';
endian = 'ieee-le';
bytes = 8;
case {'double_be', 'xdr_double'}
format = 'float64';
endian = 'ieee-be';
bytes = 8;
otherwise
error(['format "' datatype '" not yet implemented. ask jeff!'])
end
|
github
|
sunhongfu/scripts-master
|
outer_sum.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/outer_sum.m
| 1,339 |
utf_8
|
6fcbf93474fbbffdf7eb645159d64f36
|
function ss = outer_sum(xx,yy)
%function ss = outer_sum(xx,yy)
% compute an "outer sum" x + y'
% that is analogous to the "outer product" x * y'
% in
% xx [nx,1]
% yy [1,ny]
% more generally: xx [(dim)] + yy [L,1] -> xx [(dim) LL]
% out
% ss [nx,ny] ss(i,j) = xx(i) + yy(j)
% Copyright 2001, Jeff Fessler, The University of Michigan
if ~nargin, help(mfilename), error(mfilename), end
if streq(xx, 'test'), outer_sum_test, return, end
% for 1D vectors, allow rows or cols for backward compatibility
if ndims(xx) == 2 && min(size(xx)) == 1 && ndims(yy) == 2 && min(size(yy)) == 1
nx = length(xx);
ny = length(yy);
xx = repmat(xx(:), [1 ny]);
yy = repmat(yy(:)', [nx 1]);
ss = xx + yy;
return
end
%if size(xx,1) == 1
% warn 'xx is a row vector? are you sure?'
%end
% otherwise, xx is not a vector, but yy must be
xdim = size(xx);
ydim = size(yy);
if ndims(yy) ~= 2 || min(size(yy)) ~= 1
error 'yy must be a vector'
end
sdim = [xdim length(yy)];
xo = repmat(xx, [ones(1, length(xdim)) length(yy)]); % [xdim] -> [xdim ny]
yo = repmat(yy(:), [1 xdim]); yo = permute(yo, [2 3 1]);
% yo = repmat(yy(:)', [xdim 1 1]); % not sure how to make this work.
ss = xo + yo;
function outer_sum_test
%xx = [1:4];
%yy = [0:10:50];
%pr outer_sum(xx,yy)
pr outer_sum([1:4], [0:10:50])
xx = outer_sum([1:4], [0:10:50]);
pr outer_sum(xx, [100 200])
|
github
|
sunhongfu/scripts-master
|
hist_bin_int.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/hist_bin_int.m
| 3,687 |
utf_8
|
2d4d4e6439eba6ef169ea21443b06188
|
function [nk center] = hist_bin_int(data, varargin)
%|function [nk center] = hist_bin_int(data, varargin)
%|
%| fast histogram of multidimensional data into equally-spaced bins
%| todo: time this vs accumarray
%|
%| in
%| data [N M] data values to be binned (M-dimensional)
%| must be integer valued >= 1
%|
%| option
%| show 1|0 if no nargout, then display/print (default 1)
%|
%| out
%| nk [[ncent]] histogram values: sum(nk(:)) = N
%| center {ncent} cell array of bin centers for each dimension
%|
%| Copyright 2010-05-16, Jeff Fessler, University of Michigan
if nargin == 1 && streq(data, 'test'), hist_bin_int_test, return, end
if nargin < 1, help(mfilename), error(mfilename), end
arg.show = 1;
arg.how = 'accumarray'; % found to be faster than 'histc' option
arg = vararg_pair(arg, varargin);
M = size(data,2);
ncent = nan(1,M);
center = cell(M,1);
if any(data(:) ~= int32(data(:)))
fail 'not int'
end
data = int32(data); % 2010-08-13 to avoid overflow with int16
switch arg.how
case 'accumarray'
for id=1:M
tmp = data(:,id);
dmin = min(tmp);
dmax = max(tmp);
data(:,id) = tmp - dmin + 1;
center{id} = dmin:dmax;
ncent(id) = length(center{id});
end
nk = accumarray(data, ones(size(data,1),1));
case 'histc'
tmp = data(:,1);
dmin = min(tmp);
dmax = max(tmp);
list = tmp - dmin;
center{1} = dmin:dmax;
ncent(1) = numel(center{1});
nprod = ncent(1);
for id=2:M
tmp = data(:,id);
dmin = min(tmp);
dmax = max(tmp);
center{id} = dmin:dmax;
list = list + (tmp - dmin) * nprod;
ncent(id) = length(center{id});
nprod = nprod * ncent(id);
end
if nprod > 2^30-1, fail 'int32 too small', end
nk = histc(list, 0:(nprod-1)); % note: specifies left "edges"
nk = reshape(nk, [ncent 1]);
case 'sparse' % obsolete
for id=1:M
tmp = data(:,id);
dmin = min(tmp);
dmax = max(tmp);
data(:,id) = tmp - dmin;
center{id} = dmin:dmax;
ncent(id) = length(center{id});
end
% the sparse trick below does the following incrementing:
% for ii=1:N, nk(list(ii)) += 1, end
s = cumprod(ncent);
s = [1 s(1:end-1)];
list = 1 + double(data) * s(:); % need double to avoid overflow
N = size(data,1);
s = sparse((1:N)', list, ones(N,1), N, prod(ncent));
nk = full(sum(s));
nk = reshape(nk, [ncent 1]);
otherwise
fail('how=%s not done', arg.how)
end
if ~nargout && arg.show && M <= 2
if length(nk) < 10
for ik=1:length(nk)
printf('hist[%g]=%d', center{1}(ik), nk(ik))
end
else
if M == 1
plot(center{1}, nk)
elseif M == 2
im(center{1}, center{2}, nk)
end
end
clear center nk
end
%
% self test
%
function hist_bin_int_test
data = [2 4; 1 2; 2 4];
nk = hist_bin_int(data);
ideal = zeros(2,3);
m1 = min(data(:,1)) - 1;
m2 = min(data(:,2)) - 1;
ideal(2-m1,4-m2) = 2;
ideal(1-m1,2-m2) = 1;
jf_equal(nk, ideal)
data = [3 3 2 5]';
[nk center] = hist_bin_int(data);
jf_equal(nk, [1 2 0 1]')
jf_equal(center{1}, [2 3 4 5])
% look at joint gaussian distribution
randn('state', 0)
n = 2^19;
sig = 5;
rho = 0.7; % correlated gaussian
Cov = sig * [1 rho; rho 1];
tmp = sqrtm(Cov);
data = randn(n, 2) * sqrtm(Cov);
data = round(3 * (data + 8));
types = {'accumarray', 'histc', 'sparse'};
for it=1:numel(types)
hist_bin_int(data, 'how', types{it}); % warm up
cpu etic
[tmp cent] = hist_bin_int(data, 'how', types{it});
cpu('etoc', types{it})
if it == 1
nk = tmp;
else
jf_equal(tmp, nk)
end
end
if im
im plc 1 2
im(1, cent{1}, cent{2}, nk)
axis equal
im subplot 2
plot(data(:,1), data(:,2), '.')
axis equal
end
% check marginals
if 1
pj = nk/sum(nk(:));
p1 = sum(pj, 2);
p2 = sum(pj, 1)';
n1 = hist_bin_int(data(:,1)) / n;
n2 = hist_bin_int(data(:,2)) / n;
equivs(n1, p1)
equivs(n2, p2)
end
|
github
|
sunhongfu/scripts-master
|
stackpick.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/stackpick.m
| 1,177 |
utf_8
|
94edbe3b375bee1198ac10df6439e535
|
function y = stackpick(x, ii)
%|function y = stackpick(x, ii)
%| pick one (or more) of the last "slices" of a multi-dimensional array
%| think x(:,:,...,:,ii)
%| This is useful in conjunction with stackup().
%| Copyright 2005-6-18, Jeff Fessler, University of Michiga
if nargin == 1 && streq(x, 'test'), stackpick_test, return, end
if nargin < 2, help(mfilename), error(mfilename), end
s = size(x);
if any(ii < 1) || any(ii > s(end))
pr ii
fail('bad index! last dimension is %d', s(end))
end
%if length(s) == 2 && s(2) == 1 % [M,1] case; ambiguous but treat as [M]
% if ii > 1, fail('[%d,1] input with ii=%d', size(x,1), ii), end
% y = x;
% warn 'ambiguous, resolving as if 1D'
% todo: add an option not to warn?
%else
x = reshapee(x, [], s(end));
y = x(:,ii);
y = reshape(y, [s(1:end-1) length(ii)]);
%end
% stackpick_test
function stackpick_test
x = reshape(1:(5*3*4), [5 3 4]);
y = stackpick(x, 2);
jf_equal(y, x(:,:,2))
% 1d
jf_equal(stackpick([1:9], 2), 2) % [1,M]
jf_equal(stackpick([1:9]', 1), [1:9]') % [M,1]
% 2d
x = reshape(1:(4*3), [4 3]);
y = stackpick(x, 2);
jf_equal(y, [5:8]')
% multiple index
y = stackpick(x, [1 3]);
jf_equal(y, [[1:4]' [9:12]'])
|
github
|
sunhongfu/scripts-master
|
bspline_1d_interp.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/bspline_1d_interp.m
| 3,926 |
utf_8
|
0450bc0a6193efe6e03381d744ef3104
|
function ft = bspline_1d_interp(fn, ti, varargin)
%|function ft = bspline_1d_interp(fn, ti, varargin)
%|
%| given f[n], the "unit spaced" samples of a continuous signal f(t),
%| perform b-spline interpolation at sample locations t_i using the model:
%| f(t) = \sum_{k=0}^{N-1} coef_k b(t - k)
%| where the coefficients are computed internally using bspline_1d_coef.m
%|
%| in
%| fn [N (L)] 1d signal(s) samples
%| ti [M 1] or [M (L)] desired sample points (unitless)
%| option
%| order default: 3
%| ending end / boundary conditions: mirror / periodic / zero
%| mex 0 to disable mex (default: 1)
%| ob 1 to create Fatrix object (default: 0)
%| out
%| ft [M (L)] f(t_i) interpolated signal values
%|
%| Copyright 2005-12-7, Jeff Fessler, University of Michigan
if nargin == 1 && streq(fn, 'test'), bspline_1d_interp_test, return, end
if nargin < 2, help(mfilename), error(mfilename), end
arg.order = 3;
arg.ending = 'periodic';
arg.mex = 1; % default is to try mex
arg.ob = false; % 1 to create Fatrix
arg = vararg_pair(arg, varargin);
arg.ti = ti;
arg.N = size(fn,1);
ii = strvcat('mirror', 'periodic', 'zero');
arg.ie = strmatch(arg.ending, ii, 'exact');
if length(arg.ie) ~= 1, error 'unknown end conditions', end
if arg.ob
ft = bspline_1d_interp_ob(arg);
return
end
ft = bspline_1d_interp_arg(arg, fn);
%
% bspline_1d_interp_ob()
%
function ob = bspline_1d_interp_ob(arg)
if size(arg.ti,2) == 1
dim = [length(arg.ti) arg.N];
else
dim = [numel(arg.ti) arg.N*size(arg.ti,2)];
end
ob = Fatrix(dim, arg, 'caller', 'bspline_1d_interp', ...
'forw', @bspline_1d_interp_arg, 'back', @bspline_1d_interp_adj);
%
% bspline_1d_interp_adj()
%
function fn = bspline_1d_interp_adj(arg, ft)
fn = jf_mex('bspline,interp,adj,1d', ...
single(ft), single(arg.ti), int32(arg.N), ...
int32(arg.order), int32(arg.ie));
%
% bspline_1d_interp_arg()
%
function ft = bspline_1d_interp_arg(arg, fn)
if arg.mex
try
ft = jf_mex('bspline,interp,1d', single(fn), single(arg.ti), ...
int32(arg.order), int32(arg.ie));
return
catch
printm 'mex failed; revert to matlab'
end
end
ck = bspline_1d_coef(fn, 'order', arg.order, 'ending', arg.ending);
ft = bspline_1d_synth(ck, arg.ti, 'order', arg.order, 'ending', arg.ending);
%
% test
%
function bspline_1d_interp_test
N = 12;
ff = inline('t+1', 't');
ff = inline('1+cos(2*pi*t/6)', 't');
n = [0:N-1]';
fn = ff(n);
ti = linspace(-4,N+4,41*(N+8)+1)';
ft = ff(ti);
if 0 % test multi
ti = [ti flipud(ti)];
fn = [fn 2+flipud(fn)];
end
%fn = single(fn);
%ti = single(ti);
orders = [1 3];
endings = {'mirror', 'periodic', 'zero'};
fx = cell(2,3);
fm = cell(2,3);
for io = 1:length(orders)
order = orders(io);
for ie = 1:length(endings)
ending = endings{ie};
arg = {'order', order, 'ending', ending};
fx{io,ie} = bspline_1d_interp(fn, ti, arg{:}, 'mex', 1);
fm{io,ie} = bspline_1d_interp(fn, ti, arg{:}, 'mex', 0);
max_percent_diff(fx{io,ie}, fm{io,ie})
if 0 & io==1 & ie==1
plot(n, fn, 'ro', ti, ft, 'y-', ...
ti, fx{io,ie}, 'g', ti, fm{io,ie}, 'c')
keyboard
end
if has_mex_jf % test adjoint
A = bspline_1d_interp(single(eye(N)), ti, arg{:});
B = jf_mex('bspline,interp,adj,1d', ...
single(eye(length(ti))), ...
single(ti), int32(N), int32(order), int32(ie));
if max(col(abs(A-B'))) > 1e-5, error 'adjoint', end
A = bspline_1d_interp(ones(N,1), ti, arg{:}, 'ob', 1);
B = A' * eye(length(ti));
A = A * eye(N);
if max(col(abs(A-B'))) > 1e-5, error 'adjoint', end
end
end
end
if im
subplot(211)
plot(n, fn, 'ro', ti, ft, 'b-', ...
ti, fm{1,1}, 'm-.', ...
ti, fm{1,2}, 'y--', ...
ti, fm{1,3}, 'g--')
legend('sample', 'f(t)', '1m', '1p', '1z', 'location', 'south')
subplot(212)
plot(n, fn, 'ro', ti, ft, 'b-', ...
ti, fm{2,1}, 'm-.', ...
ti, fm{2,2}, 'y--', ...
ti, fm{2,3}, 'g--')
legend('sample', 'f(t)', '3m', '3p', '3z', 'location', 'south')
end
%max_percent_diff(ft, fm{2,2})
|
github
|
sunhongfu/scripts-master
|
ticker.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/ticker.m
| 3,188 |
utf_8
|
d37224bdcbb9b5731efdb04eb3ef9d42
|
function ticker(varargin)
%|function ticker(varargin)
%|
%| This utility is used in functions that might take a long time
%| to provide a status update so the user knows it is working.
%| "ticker print" to make output print to command window (default)
%| "ticker waitbar" to display using waitbar
%| ticker(waittime) to set time between updates to "waittime"
%| the default is 1 seconds
%| ticker(mfilename, i, n) to report at ith of n iterations
%| trick: i can be 2 elements (iteration, subset) and nn can be (#iter, #subset)
%|
%| Copyright 2003-11-29, Jeff Fessler, University of Michigan
persistent Ticker % stores state
if isempty(Ticker)
Ticker = ticker_default;
end
% query state
if ~nargin
printf('Ticker.how=%s Ticker.wait=%g Ticker.who="%s"', ...
Ticker.how, Ticker.wait, Ticker.who)
return
end
% set mode from command line
if nargin == 1
arg = varargin{1};
if ischar(arg)
if streq(arg, 'help')
help(mfilename)
elseif streq(arg, 'form')
Ticker.form = arg;
elseif streq(arg, 'reset')
Ticker = ticker_default;
elseif streq(arg, 'test')
ticker_test
else
Ticker.how = arg;
end
else
Ticker.wait = arg; % time
end
return
end
% set who and mode (or give help)
if nargin == 2
if ~ischar(varargin{1})
error 'first arg must be mfilename'
end
if isempty(Ticker.who)
Ticker.who = varargin{1};
else
return % some other mfile has control!
end
if ischar(varargin{2})
Ticker.how = varargin{2};
else
Ticker.wait = varargin{2};
end
return
end
% within a loop
if nargin == 3
ww = varargin{1};
ii = varargin{2};
nn = varargin{3};
if isempty(Ticker.who)
Ticker.who = ww;
end
if ~streq(ww, Ticker.who, length(Ticker.who))
% fix: what about nested uses of ticker?
% printf(['ticker who mismatch? ' Ticker.who ' ' ww])
return
end
if streq(Ticker.how, 'waitbar')
if isempty(Ticker.h)
Ticker.h = waitbar(ii(1)/nn(1));
else
waitbar(ii(1)/nn(1), Ticker.h)
end
if ii(1)==nn(1)
close(Ticker.h)
Ticker = ticker_default;
end
elseif streq(Ticker.how, 'print')
if isempty(Ticker.t0)
Ticker.t0 = clock;
end
if ii(1) > 0
t1 = clock;
te = etime(t1, Ticker.t0);
if te >= Ticker.wait
Ticker.t0 = t1;
switch Ticker.form
case 'hour'
% form = sprintf('%d:%2d:%2d', t1(4:6));
% form = datestr(t1-Ticker.t0, 'HH:MM:SS');
te = etime(t1, Ticker.tinit);
form = sprintf('%.1f', te/60);
otherwise
form = '';
end
if length(nn) == 1
printf('%s: %d of %d %s', ww, ii, nn, form)
else
printf('%s: %d,%d of %d,%d %s', ...
ww, ii(1), ii(2), nn(1), nn(2), form)
end
end
end
if ii(1) == nn(1) % reset
Ticker = ticker_default;
end
else
error('unknown Ticker mode %s', Ticker.how)
end
end
function t = ticker_default
t.who = ''; % which mfile controls
t.how = 'print'; % how to display
t.h = []; % waitbar handle
t.t0 = []; % start of recent elapsed time
t.tinit = clock; % start of total elapsed time
t.wait = 1; % (seconds) how often to update
t.form = 'hour'; % format for displaying time
% self test
function t = ticker_test
ticker reset
nloop=100;
for ii=1:nloop
ticker(mfilename, ii, nloop)
pause(0.1)
end
|
github
|
sunhongfu/scripts-master
|
downsample3.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/downsample3.m
| 1,725 |
utf_8
|
3c07f350e6c231aa9b3ba83589194f0a
|
function y = downsample3(x, m)
%|function y = downsample3(x, m)
%| downsample by averaging by integer factors
%| m can be a scalar (same factor for both dimensions)
%| or a 3-vector
%| in
%| x [nx ny nz]
%| m [1] or [1 3]
%| out
%| y [nx/m ny/m nz/m]
%| function modified to 3D space by: Taka Masuda
if nargin == 1 & streq(x, 'test'), downsample3_test, return, end
if nargin < 2, help(mfilename), error(mfilename), end
if ndims(x) == 2
warn('2d case')
y = downsample2(x, m);
return
end
if ndims(x) ~= 3
fail('not 3d')
end
if length(m) == 1
m = m * ones(ndims(x),1);
end
if length(m) ~= ndims(x), error 'bad m', end
% downsample along each dimension
y = downsample1(x, m(1));
y = downsample1(permute(y, [2 1 3]), m(2));
y = downsample1(permute(y, [3 2 1]), m(3)); % [3 1 2] order
y = permute(y, [2 3 1]);
%
% 1d down sampling of each column
%
function y = downsample1hide(x, m)
'ok'
if m == 1, y = x; return; end
n1 = floor(size(x,1) / m);
n2 = size(x,2);
n3 = size(x,3);
y = zeros(n1,n2,n3);
for ii=0:m-1
y = y + x(ii+[1:m:m*n1],:,:);
ticker(mfilename, ii+1, m)
end
y = y / m;
%
% downsample3_test
%
function downsample3_test
x = [6 5 2];
x = reshape(2*[1:prod(x)], x);
down = 2;
y = downsample3(x, down);
if down == 1
jf_equal(y, x)
else
jf_equal(y, [39 63; 43 67; 47 71])
end
if has_aspire
filex = [test_dir filesep 'testx.fld'];
filey = [test_dir filesep 'testy.fld'];
fld_write(filex, x)
delete(filey)
com = ['op sample3 mean ' filey ' ' filex ' %d %d %d'];
com = sprintf(com, down, down, down);
os_run(com)
z = fld_read(filey);
if ~isequal(y, z), error 'aspire/matlab mismatch', end
end
if 0 % big
x = zeros(2.^[7 8 9]);
cpu etic
y = downsample3(x, 2);
cpu etoc 'downsample3 time:'
end
|
github
|
sunhongfu/scripts-master
|
embed.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/embed.m
| 2,247 |
utf_8
|
6120e062d8c154359dfcf977a07ce6eb
|
function ff = embed(x, mask, varargin)
%|function ff = embed(x, mask, varargin)
%| embed x in nonzero elements of (logical) mask
%| in
%| x [np (L)] the "nonzero" pixels (lexicographically stacked)
%| mask [(Nd)] logical array, np = sum(mask)
%| option
%| '*dim' {0|1} 0: [(N) (L)] (default); 1: return [(N) *L]
%| out
%| ff [(Nd) (L)] viewable image(s)
%| if input is sparse, output is full double
%|
%| See also: masker
%|
%| Copyright 2000-9-16, Jeff Fessler, University of Michigan
if nargin == 1 && streq(x, 'test'), embed_test, return, end
if nargin < 2, help(mfilename), error(mfilename), end
if isempty(mask) % trick: handle empty mask quickly, ignoring '*dim'
ff = x;
return
end
arg.prod_dim = 0;
arg = vararg_pair(arg, varargin, 'subs', {'*dim', 'prod_dim'});
if ~islogical(mask), error 'mask must be logical', end
dimx = size(x);
cl = class(x);
if issparse(x)
cl = 'double';
end
pL = prod(dimx(2:end));
if islogical(x)
% cl = 'double';
ff = false([numel(mask) pL]); % [np *L]
else
ff = zeros([numel(mask) pL], cl); % [np *L]
end
%if is_pre_v7
% ff = zeros([numel(mask) pL]); % [np *L]
%else
% ff = zeros([numel(mask) pL], cl); % [np *L]
%end
if pL > 1
ff(mask(:),:) = reshapee(x, [], pL);
else
ff(mask(:),1) = x;
end
if ~arg.prod_dim
if ndims(mask) == 2 && size(mask,2) == 1 % 1d cases, 2008-12-14
% trick: omit '1' in 2nd dimension for 1d cases:
ff = reshape(ff, [size(mask,1) dimx(2:end)]); % [(Nd) (L)]
else
ff = reshape(ff, [size(mask) dimx(2:end)]); % [(Nd) (L)]
end
end
function embed_test
ig = image_geom('nx', 512, 'ny', 500, 'dx', 1);
ig.mask = ig.circ > 0;
ig.mask = conv2(double(ig.mask), ones(2), 'same') > 0;
x = [1:sum(ig.mask(:))]';
cpu etic
f1 = embed(x, ig.mask);
cpu etoc 'time for one'
f2 = embed([x x], ig.mask);
cpu etoc 'time for two'
jf_equal(f1, f2(:,:,2))
x = repmat(x, [1 2 3]);
f3 = embed(x, ig.mask);
jf_equal(f1, f3(:,:,2))
x = ig.unitv;
x = x(ig.mask);
f4 = ig.embed(x);
x = sparse(double(x));
% f5 = ig.embed(x); % no! trick in image_geom.m for sparse x
f5 = embed(x, ig.mask);
jf_equal(f4, f5)
% test 1d case
mask = logical([0 1 1 1 0]');
x = [1 2 3]';
jf_equal(embed(x,mask), [0 1 2 3 0]')
x = [1 2 3]' * [1 1]; % [np 2]
jf_equal(embed(x,mask), [0 1 2 3 0]'*[1 1])
|
github
|
sunhongfu/scripts-master
|
lloyd_max_hist.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/lloyd_max_hist.m
| 4,365 |
utf_8
|
7c6c53b0980357b7e0752258250dbca4
|
function centers = lloyd_max_hist(data, centers, MM, tol, max_iter, chat)
%|function centers = lloyd_max_hist(data, centers, MM, tol, max_iter, chat)
%|
%| "improved" version of the lloyd-max algorithm for scalar quantizer design
%| that saves computation by histogramming the data first.
%| Before using this, try using highrate_centers() first!
%|
%| in
%| data [N 1] training data
%| centers [K 1] initial guess of centroids (codebook)
%| MM # of histogram bins: K < M < N
%| out
%| centers [K 1] final centroids
%|
%| Copyright 2004-7-1, Jeff Fessler, University of Michigan
if nargin == 1 & streq(data, 'test'), lloyd_max_hist_test, return, end
if nargin < 2, help(mfilename), error(mfilename), end
if nargin < 3, MM = 0; end
if nargin < 4, tol = 1e-3; end
if nargin < 5, max_iter = 40; end
if nargin < 6, chat = 0; end
data = data(:);
Norig = length(data);
if MM
if ~isreal(data)
if length(MM) == 1
MM = [MM MM];
end
[wt data] = hist_equal([real(data) imag(data)], MM);
[dr di] = ndgrid(data(:,1), data(:,2));
data = dr + 1i * di;
else
[wt data] = hist(data, MM);
end
data = data(:);
wt = wt(:);
% eliminate data bins with 0 wt
data = data(wt ~= 0);
wt = wt(wt ~= 0);
else
wt = ones(size(data));
end
K = length(centers);
if length(unique(centers)) ~= K
error 'initial centers are not unique'
end
redundant = 0;
if K > length(data)
if K > Norig
warning(sprintf('#centroids %d > #data %d!?', K, Norig))
else
printf('Warn: #centroids %d > #unique(data) %d.', K, length(data))
end
redundant = 1;
end
tol = tol * max(abs(data));
iter = 1;
change = inf;
while iter <= max_iter & change > tol
if ~redundant && (length(unique(centers)) ~= K)
warning 'centers became not unique'
end
index = quant1_index(data, centers);
old = centers;
for kk=1:K
ik = index == kk;
if sum(ik)
if ~sum(wt(ik))
warning 'bug?'
keyboard
end
centers(kk) = sum(data(ik) .* wt(ik)) ./ sum(wt(ik));
else
centers(kk) = NaN;
end
end
% assign any unused centers to the data point(s) furthest from centroids
if redundant
centers(isnan(centers)) = 0;
else
printf('warn %s: fixing unused center', mfilename)
while any(isnan(centers))
cgood = col(centers(~isnan(centers)));
index = quant1_index(data, cgood);
dhat = cgood(index);
iworst = imax(abs(data - dhat));
knan = find(isnan(centers));
centers(knan(1)) = data(iworst);
end
end
% disp([iter centers])
change = max(abs(centers - old));
iter = iter + 1;
end
if iter == max_iter + 1
warning 'max %d iterations reached'
end
if chat
printf('%s: %d iterations', mfilename, iter)
end
% quant1_index()
% find index of nearest centroid.
% this version works even for complex data / centroids
%
function index = quant1_index(x, centers)
[dummy index] = min(abs(outer_sum(x, -centers)), [], 2);
%breaks = (centers(2:end) + centers(1:end-1)) / 2;
%index0 = 1 + sum(outer_sum(x, -breaks) > 0, 2);
%minmax(index-index0)
% quant1_rms()
% rms error between data and its quantized version (complex ok)
%
function rms = quant1_rms(x, centers)
index = quant1_index(x, centers);
rms = sqrt(mean(abs(x(:) - col(centers(index))).^2));
% lloyd_max_hist_test
% self test: compare this approach to matlab's lloyds routine
function lloyd_max_hist_test
randn('state', 0)
x = [10*randn(10^4,1); 50 + 15*randn(10^4,1)];
%x = [10*rand(10^4,1); 50 + 15*rand(10^4,1)];
L = 5;
%c0 = 10*linspace(-1,1,L);
pn = jf_protected_names;
c0 = pn.prctile(x, 100*([1:L]-0.5)/L);
[nx cx] = hist(x, 100);
ch = highrate_centers(x, L);
if exist('lloyds') == 2
tic
[p1 c1] = lloyds(x, c0);
t1 = toc;
else
p1 = nan(L,1);
c1 = nan(L,1);
t1 = nan;
end
tic
c2 = lloyd_max_hist(x, c0, 50);
t2 = toc;
o = ones(L,1);
if im
plot(cx, nx, '-', c0, 80*o, 'yo', ch, 60*o, 'yx', ...
c1, 40*o, 'ys', c2, 20*o, 'y^')
legend('hist', 'c0', 'highrate', 'lloyds', 'hist')
end
tic
c3 = lloyd_max_hist(x, c0);
t3 = toc;
if exist('quantiz') == 2
[dum1 dum2 distor] = quantiz(x, p1, c1);
else
distor = nan;
end
rms0 = quant1_rms(x, c0);
rms1 = quant1_rms(x, c1);
rms2 = quant1_rms(x, c2);
rms3 = quant1_rms(x, c3);
rmsh = quant1_rms(x, ch);
printf('lloyds matlab time=%g rms=%g distor=%g', t1, rms1, sqrt(distor))
printf('lloyd_max_hist time=%g rms=%g', t2, rms2)
printf('lloyd_max (no hist) time=%g rms=%g', t3, rms3)
printf('rms0=%g rmsh=%g', rms0, rmsh)
disp([c0; c1; c2; c3])
|
github
|
sunhongfu/scripts-master
|
num2list.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/num2list.m
| 390 |
utf_8
|
0076ebb4ee93b833462e21640099a15d
|
function varargout = num2list(x)
%function varargout = num2list(x)
%
% convert a numeric vector input into a comma separated list of output values
% DOES NOT WORK!
if nargin < 1, num2list_test, help(mfilename), error(mfilename), end
%nargout
%nargout = numel(x)
%varargout = cell(size(x));
for ii=1:numel(x)
varargout{ii} = x(ii);
end
function num2list_test
zeros(num2list([2 3 4 5]))
|
github
|
sunhongfu/scripts-master
|
cpu.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/cpu.m
| 1,462 |
utf_8
|
9c3b3cf49d0fa8f7180049a943c9356b
|
function out = cpu(arg, varargin)
%|function out = cpu(arg, varargin)
%|
%| cpu etic
%| cpu etoc printarg
%| tic/toc elapsed time
%|
%| cpu etic
%| cpu tic
%| cpu toc
%| cpu toc printarg
%| work like tic/toc except they use cpu time instead of wall time.
%|
%| also:
%| If printarg begins with a ':' then caller_name preceeds when printing
%|
if nargin < 1, help(mfilename), error(mfilename), end
if streq(arg, 'test'), cpu_test, return, end
% todo: add default behaviour
persistent t
if ~isvar('t') || isempty(t)
t.tic = [];
t.clock = [];
end
if streq(arg, 'tic')
t.tic = cputime;
if length(varargin), error 'tic takes no option', end
return
elseif streq(arg, 'etic')
t.clock = clock;
if length(varargin), error 'tic takes no option', end
return
end
if streq(arg, 'toc')
if isempty(t.tic)
error 'must initialize cpu with tic first'
end
out = cputime - t.tic;
elseif streq(arg, 'etoc')
if isempty(t.clock)
error 'must initialize cpu with etic first'
end
out = etime(clock, t.clock);
else
error 'bad argument'
end
if length(varargin) == 1
arg = varargin{1};
if ischar(arg)
if arg(1) == ':'
name = caller_name;
printf('%s%s %g', name, arg, out)
else
printf('%s %g', arg, out)
end
end
if ~nargout
clear out
end
elseif length(varargin) > 1
error 'too many arguments'
end
function cpu_test
cpu tic
cpu('toc');
cpu toc cpu_test:toc
cpu etic
cpu('etoc');
cpu etoc cpu_test:etoc
out = cpu('etoc', 'cpu_test:out');
|
github
|
sunhongfu/scripts-master
|
kde_pmf1.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/kde_pmf1.m
| 4,806 |
utf_8
|
014fb3c9ec686832ebae267a27b3f9e7
|
function [pmf xs] = kde_pmf1(x, varargin)
%|function [pmf xs] = kde_pmf1(x, varargin)
%|
%| Compute an empirical probability mass function (PMF) using interpolation
%| that is similar to a kernel density estimate.
%| This routine is useful for making PMFs (interpolated / smoothed) histograms
%| for computing entropy and other similarity metrics for image registration.
%|
%| in
%| x [N 1] iid realizations of a random variable
%|
%| option
%| 'dx' bin spacing (default: 1)
%| use 'silverman' to choose dx based on rule-of-thumb
%| using inter-quartile range (p48 of 1986 book)
%| 'chat' 0|1 print out intermediate values? (default: 0)
%|
%| out
%| pmf [K 1] nonnegative and sum to 1
%| xs [K 1] sample locations, differing by dx
%|
%| Code assumes kernel support is (-width/2, width/2).
%| Default is a quadratic spline supported on (-3/2,3/2).
%|
%| Copyright 2010-7-4, Jeff Fessler, University of Michigan
arg.dx = 1;
arg.kernel = @kde_pmf1_bspline2;
arg.width = 3; % kernel width, must match kernel!
arg.loop = 'pmf';
arg.nhist = 100;
arg.chat = 0;
arg = vararg_pair(arg, varargin);
if nargin < 1, help(mfilename), error(mfilename), end
if streq(x, 'test'), kde_pmf1_test, return, end
x = x(:);
[pmf xs] = kde_pmf1_do(x, arg.dx, arg.kernel, arg.width, arg.loop, arg.chat);
if ~nargout && im % plot it if no output requested
clf, subplot(211)
[his xh] = hist(x, arg.nhist);
ax = [min(min(xh), min(xs)) max(max(xh), max(xs))];
bar(xh, his/numel(x)), title 'histogram'
axisx(ax)
subplot(212)
bar(xs, pmf), title 'KDE PMF'
axisx(ax)
colormap('default')
clear pmf xs
end
% kde_pmf1_do()
function [pmf xs] = kde_pmf1_do(x, dx, kernel, width, loop, chat)
if kernel(-width/2) ~= 0 || kernel(width/2) ~= 0
fail 'kernel must be zero at +/- width/2 (and beyond)'
end
N = numel(x);
% eqn (3.31) on p 48 of Silverman 1986, which is for gaussian.
% here converted to match the FWHM for quadratic bspline
if streq(dx, 'silverman')
dx = kde_pmf_width(x, 'chat', chat);
end
kmin = floor(min(x)/dx - width/2) + 1;
kmax = ceil(max(x)/dx + width/2) - 1; % kmin <= k <= kmax
K = kmax - kmin + 1;
switch loop
case 'none' % no loop, but O(NK)
kk = kmin:kmax;
pmf = sum(kernel(outer_sum(x/dx, -kk)), 1)';
case 'data' % loop over data N
pmf = zeros(K,1);
for nn=1:N
xn = x(nn);
k1 = floor(xn/dx - width/2) + 1;
k2 = ceil(xn/dx + width/2) - 1;
kk = (k1:k2)';
pmf(kk-kmin+1) = pmf(kk-kmin+1) + kernel(xn/dx - kk);
end
case 'pmf' % loop over PMF bins K
pmf = zeros(K,1);
for ik=1:K
kk = kmin + ik - 1;
xmin = ((kk - width/2)) * dx;
xmax = ((kk + width/2)) * dx;
good = xmin < x & x < xmax;
pmf(ik) = sum(kernel(x(good)/dx - kk));
end
case 'kernel' % loop over kernel width
fail 'does not work because multiple identical k values per'
pmf = zeros(K+0,1);
k1 = floor(x/dx - width/2) + 1;
for ll=0:ceil(width)-1
kk = k1 + ll;
pmf(kk-kmin+1) = pmf(kk-kmin+1) + kernel(x/dx - kk);
end
% if any(pmf(K+1:end)), keyboard, end
% pmf = pmf(1:K);
otherwise
fail('unknown loop type "%s"', loop)
end
xs = (kmin:kmax)' * dx;
pmf = pmf / N;
% quadratic B-spline
% kde_pmf1_bspline2()
function y = kde_pmf1_bspline2(x)
y = (3/4 - x.^2) .* (abs(x) < 1/2) + ...
(abs(x) - 3/2).^2 / 2 .* (1/2 <= abs(x) & abs(x) < 1.5);
% test routine
function kde_pmf1_test
randn('state', 0)
n = 300;
sig = 5;
x = sig * randn(n, 1);
if 1 % check bspline2
t = linspace(-2,2,101);
dt = t(2) - t(1);
b2 = kde_pmf1_bspline2(t);
gauss = @(x,s) 1/sqrt(2*pi*s^2) * exp(-x.^2 / 2 / s^2);
if im
clf, subplot(211)
fwhm = 3 - sqrt(3); % FWHM of bspline2, about 1.28
s = fwhm / sqrt(log(256)); % sig of gauss with matching FWHM
gauss0 = @(x) gauss(x,s)/gauss(0,s)*3/4; % scaled
plot(t, b2, '-', t, gauss0(t), '--', ...
fwhm/2, gauss0(fwhm/2), 'o')
legend('b2', 'gauss', 'FWHM/2')
subplot(212)
plot(t, diffc(b2) / dt)
prompt
end
end
dx = 1.8;
[pmf xs] = kde_pmf1(x, 'dx', dx);
[pmf xs] = kde_pmf1(x, 'dx', 'silverman', 'chat', 1);
if 1 % check other loop methods
loop_list = {'none', 'pmf', 'data'}; % 'kernel'
for ii=1:numel(loop_list)
[pmfn xsn] = kde_pmf1(x, 'dx', 'silverman', ...
'loop', loop_list{ii});
equivs(pmf, pmfn)
jf_equal(xs, xsn)
end
end
equivs(sum(pmf), 1)
h = (1 + log(2*pi*sig^2)) / 2; % differential entropy for gaussian
pr h
Hf = @(p) sum(-p(p>0) .* log(p(p>0)));
H = Hf(pmf);
pr H
pr H + dx * log(dx)
if im
im clf, pl = @(t) subplot(130 + t);
pl(1)
[his xh] = hist(x, 20);
plot(xh, his/n, '.-')
pl(2)
plot(xs, pmf, '.-')
dx = linspace(0.2, 2.8, 31);
nd = numel(dx);
for id=1:nd
pmf = kde_pmf1(x, 'dx', dx(id));
Hv(id) = Hf(pmf); % H for several dx values
end
pl(3)
plot(dx([1 end]), [h h], '-', ...
dx, Hv, 'o', ...
dx, Hv + log(dx), '+') % H + log(dx) approximately is h
legend('h', 'H', 'H + log(dx)')
end
|
github
|
sunhongfu/scripts-master
|
poly_string.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/poly_string.m
| 1,452 |
utf_8
|
5efc7525a6d221ad41a8e377311fd06c
|
function [str, d1, d2] = poly_string(order, varargin)
%function [str, d1, d2] = poly_string(order, [options])
% make a string with all the terms in a 2d polynomial
% up to given order, e.g. [1+0*x x y ...]
% also return partial derivatives w.r.t. x and y
% in
% order
% options
% maxdegree maximum of sum of degrees (default: 2*order)
% dc set to 1 to include dc (constant) term (default: 1)
% out
% str use: feval(str, x, y) to evaluate polynomial
% d1,d2 likewise, for 1st partial derivatives thereof
%
% Copyright 2005-6-18, Jeff Fessler, The University of Michigan
if nargin < 1, help(mfilename), error(mfilename), end
if nargin == 1 && streq(order, 'test'), poly_string_test, return, end
arg.maxdegree = [];
arg.dc = true;
arg = vararg_pair(arg, varargin);
if isempty(arg.maxdegree), arg.maxdegree = 2 * order; end
str = '';
d1 = '';
d2 = '';
for i2=0:order
for i1=0:order
if i1+i2 == 0 && ~arg.dc
continue
end
if i1 + i2 > arg.maxdegree
continue
end
str = [str sprintf(' (x.^%d).*(y.^%d)', i1, i2)];
if i1 == 0
s1 = '0*x';
else
s1 = sprintf('%d*x.^%d', i1, i1-1);
end
if i2 == 0
s2 = '0*y';
else
s2 = sprintf('%d*y.^%d', i2, i2-1);
end
d1 = [d1 sprintf(' (%s).*(y.^%d)', s1, i2)];
d2 = [d2 sprintf(' (x.^%d).*(%s)', i1, s2)];
end
end
str = ['[ ' str ' ]'];
%
% poly_string_test
%
function poly_string_test
[str d1 d2] = poly_string(1, 'dc', 0)
[str d1 d2] = poly_string(2, 'maxdegree', 3)
|
github
|
sunhongfu/scripts-master
|
run_mfile_local.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/run_mfile_local.m
| 1,861 |
utf_8
|
10ab734b28bb404cd05ded222b52fe5a
|
function run_mfile_local(arg, varargin)
%|function run_mfile_local(arg)
%| run an mfile in a local environment so that workspace variables
%| are untouched. useful for tests.
%| arg can be a cell with many mfiles to run
%| options
%| 'draw' 1|0 1 to draw after each test (default: 0)
%| 'pause' 1|0 1 to pause after each test (default: 0)
%| 'abort' 1|0 1 to abort if any test fails (default: 0)
%| Copyright 2005-6-21, Jeff Fessler, University of Michigan
if nargin < 1, help(mfilename), error(mfilename), end
opt.draw = false;
opt.pause = false;
opt.abort = false;
opt = vararg_pair(opt, varargin);
% track which tests open a figure even though they should not if im disabled
check_fig = ~figure_opened && ~im;
bad_fig = {};
test_bad = {};
test_good = {};
if iscell(arg)
for ii=1:length(arg)
printf('\n\nTesting: %s\n\n', arg{ii})
try
run_mfile_local(arg{ii})
test_good{end+1} = arg{ii};
catch
test_bad{end+1} = arg{ii};
if opt.abort
fail('test "%s" failed', arg{ii})
end
end
if opt.draw, drawnow, end
if opt.pause, printm 'pausing', pause, end
drawnow;
if check_fig && figure_opened
bad_fig{end+1} = arg{ii};
close all
end
end
if length(test_good)
printm('in "%s" the following test(s) passed:', caller_name)
disp(char(test_good))
end
if length(bad_fig)
warn('in %s: the following test(s) had figure issues:', caller_name)
disp(char(bad_fig))
end
if length(test_bad)
warn('in "%s" the following test(s) failed:', caller_name)
disp(char(test_bad))
error 'the above tests failed'
else
printm('in "%s" all %d tests passed!', caller_name, length(arg))
end
else
eval(arg)
end
% try to determine if any figure window is opened
function out = figure_opened
if isfreemat
out = true; % freemat will not tell, so assume yes
else
out = ~isempty(get(0, 'children')); % matlab knows
end
|
github
|
sunhongfu/scripts-master
|
minmax.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/minmax.m
| 2,324 |
utf_8
|
1b60715426dbb9ffeb27f85aa09fff8a
|
function r = minmax(x, varargin)
%function r = minmax(x, dim)
% Return mininum and maximum of values of input x.
% Default is to examine the entire array.
% Specify a dimension dim otherwise.
% If dim is a string, print...
% Copyright 2003, Jeff Fessler, University of Michigan
if nargin < 1, help(mfilename), error(mfilename), end
dim = [];
if length(varargin) && isnumeric(varargin{1})
dim = varargin{1};
varargin = {varargin{2:end}};
end
str = '';
if length(varargin)
if ischar(varargin{1})
str = varargin{1};
else
error 'bug'
end
end
if iscell(x)
r = [];
for ii = 1:length(x)
if ~isempty(dim)
r = [r, minmax(x{ii}, dim)];
else
r = [r, minmax(x{ii})];
end
end
elseif isstruct(x)
if nargout == 0
printm 'minmax of struct fields:'
minmax_struct(x, inputname(1))
return
else
r = [];
names = fieldnames(x);
for ii = 1:length(names)
r = [r; minmax(x.(names{ii}))];
end
end
elseif ~isempty(dim)
r = [min(x, [], dim); max(x, [], dim)];
else
r = [min(x(:)); max(x(:))];
end
if issparse(r)
r = full(r);
end
if nargout == 0
if isempty(str) & ~isempty(inputname(1))
[cname line] = caller_name;
cname = sprintf('%s %d', cname, line);
str = [cname ': ' inputname(1) ':'];
end
if ncol(r) == 1
if any(isnan(x(:)))
nanstr = sprintf(' %d NaN!', sum(isnan(x(:))));
else
nanstr = '';
end
if isempty(str)
printm('min=%g max=%g %s', r(1), r(2), nanstr)
else
printf('%s min=%g max=%g %s', str, r(1), r(2), nanstr)
end
else % todo: check nan's in structure?
for ii=1:ncol(r)
if isempty(str)
printm('%d min=%g max=%g', ii, r(1,ii), r(2,ii))
else
printf('%s %d min=%g max=%g', str, ii, r(1,ii), r(2,ii))
end
end
end
clear r
end
%
% minmax_struct(st, prefix)
% show min/max of all elements of a structure, descending recursively.
%
function minmax_struct(st, prefix)
prefix = [prefix '.'];
names = fieldnames(st);
for ii=1:length(names)
name = names{ii};
t = st.(name);
if isempty(t), continue, end
if islogical(t) | isnumeric(t)
if numel(t) == 1
printf(' %s = %d', [prefix name], t)
else
printf(' %s %g %g', [prefix name], min(t(:)), max(t(:)))
end
elseif isstruct(t)
minmax_struct(t, [prefix name]);
elseif ischar(t)
printf([prefix name ' = "' t '"'])
else
printf('%s ?', [prefix name])
end
end
|
github
|
sunhongfu/scripts-master
|
masker.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/masker.m
| 884 |
utf_8
|
de844e9fcd7044d558d79c5644951dc9
|
function y = masker(x, mask)
%|function y = masker(x, mask)
%| extract from x the nonzero elements within (logical) mask
%| in
%| x [(Nd) (L)] image(s)
%| mask [(Nd)] logical array, np = sum(mask)
%| out
%| y [np (L)] concise columns
%|
%| See also: embed
%|
%| Copyright 2004-9-28, Jeff Fessler, University of Michigan
if nargin == 1 && streq(x, 'test'), masker_test, return, end
if nargin < 2, help(mfilename), error(mfilename), end
if ~islogical(mask), error 'mask must be logical', end
xdim = size(mask);
L = size(x); L = L(1+ndims(mask):end);
x = reshape(x, [numel(mask) prod(L)]); % [*Nd,*L]
y = x(mask(:),:); % [np, *L]
y = reshape(y, [size(y,1) L]); % [np,(L)]
function masker_test
ig = image_geom('nx', 40, 'ny', 50, 'dx', 1);
ig.mask = ig.circ > 0;
x1 = ones([ig.nx ig.ny 3 2]);
y1 = masker(x1, ig.mask);
x2 = ig.embed(y1);
y2 = masker(x2, ig.mask);
jf_equal(y1, y2)
|
github
|
sunhongfu/scripts-master
|
truncate_precision.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/truncate_precision.m
| 924 |
utf_8
|
0f0d50a4e0af0fded1105d0ee262b6d8
|
function y = truncate_precision(x, digits, varargin)
%|function y = truncate_precision(x, digits, [option])
%|
%| truncate x to "digits" signficant digits of precision
%| option
%| 'type' floor (default) | round | ceil
%|
%| Copyright 2008-11-05, Jeff Fessler, University of Michigan
if nargin == 1 && streq(x, 'test'), truncate_precision_test, return, end
if nargin < 2, help(mfilename), error(mfilename), end
arg.type = 'floor';
arg = vararg_pair(arg, varargin);
sgn = sign(x);
x = abs(x);
pow = log10(x);
pow = floor(pow);
x = x ./ 10.^pow;
x = x .* 10.^(digits-1);
switch arg.type
case 'floor'
x = floor(x);
case 'ceil'
x = ceil(x);
case 'round'
x = round(x);
otherwise
fail('bad type %s', arg.type)
end
x = x ./ 10.^(digits-1);
y = x .* 10.^pow;
y(sgn == 0) = 0;
y = y .* sgn;
function truncate_precision_test
y = truncate_precision([1234 0.1234 5 0 -1299], [3 2 2 2 2]);
jf_equal(y, [1230 0.12 5 0 -1200])
|
github
|
sunhongfu/scripts-master
|
jf.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/jf.m
| 4,286 |
utf_8
|
4e7f9a86f93ffea5dbd3ef927829d18a
|
function out = jf(varargin)
%|function out = jf(varargin)
%| various personalization routines
%| 'mv var_old var_new'
%| 'ncore' # of cores this machine has
%| add optional 2nd argument to over-ride, e.g., jf('ncore', 4)
%| 'whos'
%| 'clf'
%| 'nobar' preclude toolbar and menubar from figures to render faster!
%| 'nomex' remove mex files from path
%| 'isum' 1 if UM, 0 else
%| 'path'
%| 'off'
%| 'on'
%| 'plc' set up subplot with clf first
%| {'pl', 'pl-tight'} set up subplot, don't clear first
%| 'sub'
%| 'title_no_tex'
%| 'test'
if ~nargin, help(mfilename), error(mfilename), end
%
% handle states
%
persistent state
if ~isvar('state') || isempty(state)
state = jf_reset;
end
switch varargin{1}
case 'mv' % rename a variable, unix style
% todo: make sure not renaming a field of a structure!
if ~isempty(findstr(varargin{2}, '.')) ...
|| ~isempty(findstr(varargin{2}, '.'))
fail('struct field renames not implemented yet, but could be')
end
tmp = [varargin{3} ' = ' varargin{2} ';'];
evalin('base', tmp);
tmp = ['clear ' varargin{2} ';'];
evalin('base', tmp);
case 'ncore'
persistent ncore
if length(varargin) == 2
ncore = varargin{2};
if ischar(ncore) % for this syntax: jf ncore 8
if streq(ncore, 'reset')
ncore = [];
ncore = jf('ncore');
else
ncore = str2num(ncore);
end
end
end
if isvar('ncore') && ~isempty(ncore)
out = ncore; % return previously determined value
return
end
try
tmp = os_run('sysctl hw.ncpu');
out = sscanf(tmp, 'hw.ncpu: %d');
ncore = out;
return
catch
persistent warned1
if ~isvar('warned1') || isempty(warned1)
warned1 = 1;
warn 'sysctl did not work'
end
end
try
maxNumCompThreads('automatic');
out = maxNumCompThreads;
ncore = out;
return
catch
persistent warned2
if ~isvar('warned2') || isempty(warned2)
warned2 = 1;
warn 'maxNumCompThreads failed; reverting to 1 thread'
end
out = 1;
ncore = out;
return
end
case 'whos'
st = evalin('caller', 'whos');
byte = {st.bytes};
byte = cell2mat(byte);
byte = sum(byte);
printm('total bytes = %d = %g Gb', byte, byte/1024^3)
case 'clf'
if state.display, clf, end
case 'isum'
out = exist('dd_ge2_mex') == 3;
case 'nobar'
set(0, 'DefaultFigureToolbar', 'none')
set(0, 'DefaultFigureMenubar', 'none')
case 'notoolbox' % remove all matlab extra toolboxed from path for testing
jf_rm_toolbox
case 'nomex'
tmp = path;
tmp = strsplit(tmp, pathsep);
for ii=1:length(tmp)
if ~isempty(strfind(tmp{ii}, 'mex/v7'))
printm('removing from path: "%s"', tmp{ii})
rmpath(tmp{ii})
end
end
printm('done removing mex dirs from path')
case 'path'
path_jf
case 'off'
state.display = false;
case 'on'
state.display = true;
case 'plc' % set up subplot with clf first
jf clf
jf('pl', varargin{2:end});
case {'pl', 'pl-tight'} % set up subplot, don't clear first
if nargin == 3
state.sub_m = ensure_num(varargin{2});
state.sub_n = ensure_num(varargin{3});
elseif nargin == 1
state.sub_m = [];
state.sub_n = [];
else
error 'bad pl usage'
end
state.pl_tight = streq(varargin{1}, 'pl-tight');
case 'sub'
arg = ensure_num(varargin{2});
if arg > 99 % reset
state.sub_m = [];
state.sub_n = [];
end
if isempty(state.sub_m)
if arg >= 111
subplot(arg)
else
printm('ignoring subplot %d', arg)
end
else
jf_subplot(state, arg)
end
case 'test'
jf_test
case 'title_no_tex'
set(get(gca, 'title'), 'interpreter', 'none')
otherwise
fail('unknown arg %s', varargin{1})
end
% split long string using
function out = strsplit(in, sep)
in = [in sep]; % add : at end
isep = strfind(in, sep);
for ii=1:(length(isep)-1)
out{ii} = in((1+isep(ii)):(isep(ii+1)-1));
end
%
% jf_subplot()
%
function jf_subplot(state, num)
if state.display
if state.pl_tight
num = num - 1;
x = 1 / state.sub_n;
y = 1 / state.sub_m;
ny = floor(num / state.sub_n);
nx = num - ny * state.sub_n;
ny = state.sub_m - ny - 1;
subplot('position', [nx*x ny*y x y])
else
subplot(state.sub_m, state.sub_n, num)
end
end
function x = ensure_num(x)
if ischar(x), x = str2num(x); end
%
% jf_state()
%
function state = jf_reset
state.sub_m = []; % for subplot
state.sub_n = [];
state.pl_tight = false;
state.display = true;
function jf_test
jf plc 2 3
jf sub 1, plot(rand(3))
|
github
|
sunhongfu/scripts-master
|
vararg_pair.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/vararg_pair.m
| 6,046 |
utf_8
|
6b4318d95d5b5332f4aaf0ed91d43a86
|
function [opt, extra] = vararg_pair(opt, varargs, varargin)
%function [opt, extra] = vararg_pair(opt, varargs, [options])
% Process name / value pairs, replacing the "default" field values
% of the opt structure with the user-specified values.
% This allows flexible argument order and "named arguments" somewhat like IDL.
% This newer version allows option names to differ from the field names.
% If two output arguments are given, then any "extra" name value pairs
% that are not associated with the fields in structure opt will be
% returned as name/value pairs in the "extra" output.
%
% in
% opt struct opt.name1 opt.name2 etc., containing default values
% varargs {'name1', 'value1', ... } as a cell array
% options
% 'subs' Nx2 cell {'arg_name1', 'struct_name1'; ...}
% short argument name followed by longer structure name
% 'allow_new' 0|1 allow new structure elements? (default: 0)
% out
% opt opt.(name) = value
% extra {'name_i', 'value_i', ...} all "unused" pairs
%
% Copyright 2005-6-18, Jeff Fessler, The University of Michigan
if nargin < 1, help(mfilename), error(mfilename), end
if nargin == 1 && streq(opt, 'test'), vararg_pair_test, clear, return, end
base = [caller_name ' arg: ']; % for printing
if isempty(varargs) && numel(varargin) == 0
extra = {};
return
end
local.subs = {};
local.allow_new = 0;
local = vararg_pair_do(local, varargin, {}, 0, 0);
allow_extra = nargout > 1;
[opt extra] = vararg_pair_do(opt, varargs, local.subs, local.allow_new, ...
allow_extra, base);
% Structure elements of opt with value "NaN" are checked as being required.
% NO, this just adds overhead. Removed 2007-2-9.
% vararg_pair_check(opt);
%
% vararg_pair_do()
%
function [opt, extra] = ...
vararg_pair_do(opt, varargs, subs, allow_new, allow_extra, base)
if allow_extra && allow_new
error 'only one of "new" or "extra" is sensible for vararg_pair'
end
npair = floor(length(varargs) / 2);
if 2*npair ~= length(varargs), fail('need names and values in pairs'), end
args = varargs(1:2:end);
vals = varargs(2:2:end);
if ~isempty(subs)
if size(subs,2) ~= 2, fail('subs must be Nx2'), end
% subs1 = strvcat(subs(:,1));
subs1 = char(subs(:,1)); % strmatch doc says fastest for char array!
subs2 = subs(:,2);
% todo: apply 'subs' all at once here?
end
extra = {};
for ii=1:npair
arg = args{ii};
val = vals{ii};
if ~ischar(arg)
fail('unknown option of class %s', class(arg))
end
if ~isempty(subs)
arg = vararg_pair_sub(arg, subs1, subs2);
end
[opt ex] = vararg_pair_put(opt, arg, val, allow_new, allow_extra);
if allow_extra && ~isempty(ex)
extra = [extra(:); ex(:)]'; % faster than {extra{:}, ex{:}};
end
if isfield(opt, 'chat') && opt.chat && isempty(ex)
show_pair(arg, val, base)
end
end
%
% vararg_pair_sub()
% substitute option name for field name, if a Nx2 cell array is provided.
%
function arg = vararg_pair_sub(arg, subs1, subs2)
ii = strmatch(arg, subs1, 'exact');
if isempty(ii)
return
elseif length(ii) == 1
arg = subs2{ii};
else
printm([subs1(ii) ' ' subs2{ii}])
error 'double match? only one substitution allowed'
end
%
% vararg_pair_put()
% opt.(arg) = value
% with extra effort to handle opt.(arg1.arg2) = value
% because matlab does not handle that case by itself, except via subsagn
%
function [opt, extra] = vararg_pair_put(opt, arg, value, allow_new, allow_extra)
extra = {};
if isfield(opt, arg) % simple case of name / value pair
opt.(arg) = value;
return
end
idot = strfind(arg, '.');
if isempty(idot)
if allow_new
opt.(arg) = value;
return
elseif allow_extra
extra = {arg, value};
return
else
fail('unknown option name "%s"', arg)
end
end
% tricky case of a.b.c
if length(idot) > 1, error 'a.b.c.d not done', end
arg1 = arg([1:(idot-1)]);
arg2 = arg([(idot+1):end]);
if ~isfield(opt, arg1)
fail('unknown option1 name "%s"', arg1)
end
if ~isfield(opt.(arg1), arg2)
fail('unknown option2 name %s', arg2)
end
s = struct('type', {'.', '.'}, 'subs', ...
{ arg([1:(idot-1)]), arg([(idot+1):end]) });
try
opt = subsasgn(opt, s, value);
catch
printf(lasterr)
fail('subsasgn? unknown option name %s', arg)
end
%
% vararg_pair_check()
% check that the user supplied the required arguments,
% which are signified by 'nan' values.
%
function vararg_pair_check(opt)
names = fieldnames(opt);
ok = 1;
for ii=1:length(names)
t = opt.(names{ii});
if isnumeric(t) && any(isnan(t(:)))
printf('Required option "%s" missing', names{ii});
ok = 0;
end
end
if ~ok, error 'missing required "option(s)"', end
%
% show_pair()
%
function show_pair(name, value, base)
pri = @(varargin) printf([base varargin{1}], varargin{2:end});
if isnumeric(value) | islogical(value)
if max(size(value)) == 1 % only print scalars
if ~streq(name, 'chat')
pri('%s = %g', name, value)
end
else % otherwise print sum (e.g., for mask)
pri('sum(%s) = %g', name, sum(value(:)))
end
elseif ischar(value)
pri('%s = %s', name, value)
elseif isa(value, 'cell')
pri('%s {cell}', name)
elseif isa(value, 'function_handle')
pri('%s = @%s', name, func2str(value))
elseif isstruct(value) % show first structure element, if string
fields = fieldnames(value);
% name = getfield(arg, fields{1});
name1 = value.(fields{1});
if ischar(name1)
pri('%s.%s = %s', name, fields{1}, name1)
end
else
warn('display type "%s" not implemented', class(value))
end
%
% test routine
%
function vararg_pair_test
args = {'a', 1, 'b', 2, 'c.d', 3, 'g', 9, 'l', 5, 'll', 6};%, 'c.f', 4};
opt.a = 0;
opt.b = 0;
opt.f = 0;
opt.long1 = 0;
opt.long2 = 0;
%opt.g = nan;
opt.c.d = 0;
opt.c.e = 0;
sub = {'g', 'f'; 'l', 'long1'; 'll', 'long2'};
opt = vararg_pair(opt, args, 'subs', sub);
jf_equal(opt.a, 1)
jf_equal(opt.b, 2)
jf_equal(opt.c.d, 3)
jf_equal(opt.c.e, 0)
jf_equal(opt.f, 9)
jf_equal(opt.long1, 5)
jf_equal(opt.long2, 6)
opt = vararg_pair(opt, {'z', 'new'}, 'allow_new', 1);
if ~isequal(opt.z, 'new'), fail('bug'), end
try % typo in name should yield error
opt = vararg_pair(opt, {'verify_bad_test!', 'new'}, 'allow_new', 0)
catch
return
end
error 'should not get here'
|
github
|
sunhongfu/scripts-master
|
reshapee.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/reshapee.m
| 1,254 |
utf_8
|
74240ee060a675b89895e56891c7460d
|
function y = reshapee(x, varargin)
%|function y = reshapee(x, varargin)
%|
%| reshape function that allows possibly one null argument, and all
%| other arguments can be vectors, unlike matlab that requires scalars.
%| example: reshape(rand(2*3*5,7), [2 3], [], 7) will become [2 3 5 7]
%|
%| in
%| x [(*dim)]
%| varargin dimensions
%|
%| out
%| y [dim]
%|
%| Copyright 2004-8-22, Jeff Fessler, University of Michigan
if nargin == 1 & streq(x, 'test'), reshapee_test, return, end
if nargin < 2, help(mfilename), error(mfilename), end
dim_i = size(x);
ndim = 0;
edim = [];
dim_o = [];
for ii=1:length(varargin)
arg = varargin{ii};
ndim = ndim + length(arg);
if isempty(arg)
if ~isempty(edim)
fail 'only one empty dim allowed'
end
edim = 1+length(dim_o);
dim_o = [dim_o, 1]; % trick: place holder
else
dim_o = [dim_o, arg];
end
end
if ~isempty(edim) % fill in empty dim if present
if prod(dim_o) <= 0, fail('nonpositive dims?'), end
dim_o(edim) = prod(dim_i) / prod(dim_o);
if round(dim_o(edim)) ~= dim_o(edim)
pr dim_i
pr dim_o
fail('bad dim')
end
end
y = reshape(x, dim_o);
% self test
function reshapee_test
dim = [2 3 5 7];
x = 1:prod(dim);
y = reshapee(x, dim(1:2), [], dim(4));
z = reshape(x, dim);
jf_equal(y,z)
|
github
|
sunhongfu/scripts-master
|
sinc_periodic.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/sinc_periodic.m
| 1,401 |
utf_8
|
6ded04b3754f67a5d4372c05ed651386
|
function x = sinc_periodic(t, K)
%|function x = sinc_periodic(t, K)
%| periodic sinc function, obtained by replicates of a sinc:
%| x(t) = \sum_l sinc(t - l K) = ... = sin(pi*t) / tan(pi*t/K) / K for K even.
%| This function is bandlimited and its samples are an impulse train.
%| It is closely related to the Dirichlet function diric() for odd K,
%| but it differs for even K.
%| Copyright 2003-11-2, Jeff Fessler, University of Michigan
if nargin < 1, help(mfilename), error(mfilename), end
if streq(t, 'test'), sinc_periodic_test, return, end
if ~rem(K,2) % even
d = tan(pi*t/K);
j = abs(d) > 1e-12;
x = ones(size(t));
t = t(j);
d = d(j);
x(j) = sin(pi*t) ./ d / K;
else
x = nufft_diric(t, K, K, 1);
% xo = diric(2*pi*t/K,K); % would require matlab's signal toolbox
% max_percent_diff(xo, x)
end
%
% self test
%
function sinc_periodic_test
Klist = [4 5];
im clf, pl=220;
for kk=1:2
K = Klist(kk);
n = [0:(4*K)]';
t = linspace(0,4*K,401)';
x = @(t,K) sinc_periodic(t, K);
% y = @(t,K) diric(2*pi*t/K,K); % would require matlab's signal toolbox
y = @(t,K) nufft_diric(t,K,K,1);
if im
subplot(pl+kk+0)
plot(t, x(t,K), '-', n, x(n,K), 'o')
titlef('Sinc-Periodic K=%d', K)
axis([0 4*K -1 1]), xtick([0:4]*K), grid
subplot(pl+kk+2)
plot(t, y(t,K), '-', n, y(n,K), 'o')
titlef('Dirichlet K=%d', K)
axis([0 4*K -1 1]), xtick([0:4]*K), grid
ylabelf('K=%d', K)
end
end
|
github
|
sunhongfu/scripts-master
|
poisson2.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/poisson2.m
| 1,772 |
utf_8
|
3b7335e80615537c281d420af6cce9fa
|
function data = poisson2(xm, varargin)
%|function data = poisson2(xm, [options])
%|
%| in
%| 'xm' float
%|
%| option
%| 'seed' int seed for 'rand'
%| 'factor' double a value < 1 for rejection method
%|
%| Generate Poisson random column vector with mean xm.
%| Uses rejection method - good for large values of xm.
%| See "Numerical Recipes in C", P. 222.
if nargin < 1, help(mfilename), error(mfilename), end
if streq(xm, 'test'), poisson2_test, return, end
arg.seed = [];
%arg.factor = 0.9; % from num rec
arg.factor = 0.85; % seems to work better, but maybe not always
arg = vararg_pair(arg, varargin);
if ~isempty(arg.seed)
rand('state', arg.seed)
end
if isa(xm, 'double')
data = zeros(size(xm), 'double');
else
data = zeros(size(xm), 'single');
end
if any(xm < 0), error 'negative poisson means?', end
data(xm > 0) = poisson2_positive(col(xm(xm > 0)), arg.factor);
%
% poisson2_positive()
%
function data = poisson2_positive(xm, factor)
sx = sqrt(2.0 * xm);
lx = log(xm);
gx = xm .* lx - gammaln(1 + xm);
data = zeros(size(xm));
id = [1:length(xm)]'; % indicates which data left to do
while any(id)
Tss = sx(id);
Tll = lx(id);
Tgg = gx(id);
Txx = xm(id);
yy = zeros(size(id));
em = zeros(size(id));
ib = true(size(id));
while ib
yy(ib) = tan(pi * rand(size(ib)));
em(ib) = Tss(ib) .* yy(ib) + Txx(ib);
ib = find(em < 0);
end
em = floor(em);
tt = factor * (1+yy.*yy) .* exp(em .* Tll - gammaln(em+1) - Tgg);
if any(tt > 1)
pr xm(tt > 1)
pr max(tt)
fail(['sorry: factor %g is too large!\n please rerun using' ...
' a smaller value for the ''factor'' option'], factor)
end
ig = rand(size(id)) < tt;
data(id(ig(:))) = em(ig);
id = id(~ig(:));
end
function poisson2_test
xm = linspace(21, 70, 201)';
poisson2(xm);
|
github
|
sunhongfu/scripts-master
|
min_cos_quad.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/min_cos_quad.m
| 3,173 |
utf_8
|
096e10676fa8af29d31a265aa6d3c2dc
|
function t = min_cos_quad(m, p, b, c, niter)
%|function t = min_cos_quad(m, p, b, c, niter)
%|
%| find the minimizer of the sinusoid + quadratic form:
%| f(t) = m * (1-cos(t-p)) + b*t + c/2 t^2
%|
%| This is useful for certain phase-related optimization transfer problems.
%|
%| Copyright 2003-11-9, Jeff Fessler, University of Michigan
if nargin < 4
if nargin == 1 & streq(m, 'test')
min_cos_quad_test, return
elseif nargin == 1 & streq(m, 'fig')
min_cos_quad_fig, return
else
help(mfilename), error(mfilename)
end
end
if any(c < 0), error 'need c > 0', end
if any(m < 0), error 'need m >= 0', end
t = zeros(size(m));
% analytical solution where m=0
i0 = m == 0;
t(i0) = -b(i0) ./ c(i0);
p0 = p(~i0);
a = -p0 - b(~i0) ./ c(~i0);
k = c(~i0) ./ m(~i0);
u = zero_sin_line(-p0, k, a, niter);
t(~i0) = u + p0;
% zero_sin_line()
% find zeros of sin(u) + k * (u - a)
function u = zero_sin_line(u, k, a, niter)
amid = round(a/(2*pi)) * 2*pi; % midpoint of nearest [-pi,pi] + n*2*pi
% for any initial points not within proper interval,
% set initial guess to that interval's midpoint
ibad = u < amid - pi | u > amid + pi;
u(ibad) = amid(ibad);
for ii=1:niter
% s = mod(t+pi,2*pi) - pi; % [-pi,pi]
% curv = nufft_sinc(s/pi);
% denom = m .* curv + c;
% t = t - (m .* sin(t-p) + b + c.*t) ./ denom;
% s = mod(t+pi,2*pi) - pi; % [-pi,pi]
% curv = nufft_sinc(s/pi);
% denom = curv + k;
denom = 1 + k;
u = u - (sin(u) + k.*(u-a)) ./ denom;
end
% min_cos_quad_test
% self test
function min_cos_quad_test
mlist = 1;
plist = 3.8;
blist = 0.1;
clist = 0.2;
[mm pp bb cc] = ndgrid(mlist, plist, blist, clist);
im clf, pl=100 + 10*numel(mm);
t = linspace(-3*pi,3*pi,501);
%f = inline('a * (1-cos(x)) + c/2 * (x-b).^2', 'x', 'a', 'b', 'c');
f = inline('m * (1-cos(t-p)) + b*t + c/2 * t.^2', ...
't', 'm', 'p', 'b', 'c');
for ip=1:numel(mm)
m = mm(ip);
p = pp(ip);
b = bb(ip);
c = cc(ip);
if im
subplot(pl+ip)
plot(t, f(t,m,p,b,c), 'y-', 0, f(0,m,p,b,c), 'go')
xlabel 't', ylabel 'surrogate(t)'
title 'm [1-cos(t-p)] + b t + c/2 t^2'
axis([minmax(t)' 0 9])
xaxis_pi '-3*p -p 0 p 3*p'
end
for ii=1:4
x = min_cos_quad(m, p, b, c, ii);
if im
hold on, plot(x, f(x,m,p,b,c), 'co'), hold off
end
end
if im
hold on, plot(x, f(x,m,p,b,c), 'r.'), hold off
end
% savefig c 'fig_cos_quad'
end
%
% figure to show minima
%
function min_cos_quad_fig
alist = [pi/4 3*pi/4 -pi/2]+0*pi;
klist = [0.1 0.2 0.2];
clf, pl=330;
t = linspace(-2*pi,2*pi,301);
xtick = [-2:2]*pi;
d1 = inline('a * (1-cos(x)) + c/2 * (x-b).^2', 'x', 'a', 'b', 'c');
for ii=1:3
a = alist(ii);
k = klist(ii);
subplot(pl+ii)
plot(t, -cos(t)+k/2*(t-a).^2, '-')
axisx(minmax(t))
set(gca, 'xtick', xtick)
set(gca, 'xticklabel', {'-2\pi', '-\pi', '0', '\pi', '2\pi'})
subplot(pl+ii+3)
plot(t, -sin(t), '--', t, k*(t-a), '--')
axis([minmax(t)' -2 2])
set(gca, 'xtick', xtick)
set(gca, 'xticklabel', {'-2\pi', '-\pi', '0', '\pi', '2\pi'})
if ii==3, legend('-sin(t)', 'k(t-a)',2), end
subplot(pl+ii+6)
plot(t, cos(t)+k, '-', t, 0*t, ':')
axisx(minmax(t))
set(gca, 'xtick', xtick)
set(gca, 'xticklabel', {'-2\pi', '-\pi', '0', '\pi', '2\pi'})
% todo \tex{}
end
|
github
|
sunhongfu/scripts-master
|
kde_pmf2.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/kde_pmf2.m
| 6,301 |
utf_8
|
2d56a911549ea0f282371a9122e09d0f
|
function [pmf xs ys] = kde_pmf2(x, y, varargin)
%|function [pmf xs ys] = kde_pmf2(x, y, varargin)
%|
%| Compute a 2D empirical joint probability mass function (PMF)
%| using interpolation that is similar to a kernel density estimate.
%| This joint PMF (interpolated / smoothed histogram) is useful for
%| computing joint entropy and other similarity metrics for image registration.
%|
%| in
%| x [N 1]
%| y [N 1] iid realizations of random variable pairs (x,y)
%|
%| option
%| 'dx' bin spacing (default: 1)
%| use 'silverman' to choose dx based on rule-of-thumb
%| using inter-quartile range (p48 of 1986 book)
%| 'dy' bin spacing (default: dx)
%| 'loop' method; default is to try 'mex' if available, else 'pmf'
%| 'chat' 0|1 print out intermediate values? (default: 0)
%|
%| out
%| pmf [Kx Ky] nonnegative and sum to 1
%| xs [Kx 1] sample locations, differing by dx
%| ys [Ky 1] sample locations, differing by dy
%|
%| Code assumes kernel support is (-width/2, width/2).
%| Default is a quadratic spline supported on (-3/2,3/2).
%|
%| Copyright 2010-07-31, Jeff Fessler, University of Michigan
if nargin == 1 && streq(x, 'test'), kde_pmf2_test, return, end
if nargin < 2, help(mfilename), error(mfilename), end
arg.dx = 1;
arg.dy = []; % dx below
arg.kernel = @kde_pmf2_bspline2;
arg.widthx = 3; % kernel width, must match kernel!
arg.widthy = []; % widthx below
arg.loop = ''; % see below
arg.chat = 0;
arg = vararg_pair(arg, varargin);
if isempty(arg.loop)
if has_mex_jf
arg.loop = 'mex';
else
arg.loop = 'pmf';
end
end
if isempty(arg.dy)
arg.dy = arg.dx;
end
if isempty(arg.widthy)
arg.widthy = arg.widthx;
end
x = x(:);
y = y(:);
% eqn (3.31) on p 48 of Silverman 1986, which is for gaussian.
% here converted to match the FWHM for quadratic bspline
if streq(arg.dx, 'silverman')
arg.dx = kde_pmf_width(x, 'chat', arg.chat);
end
if streq(arg.dy, 'silverman')
arg.dy = kde_pmf_width(y, 'chat', arg.chat);
end
if streq(arg.loop, 'mex')
if ~isequal(arg.kernel, @kde_pmf2_bspline2) ...
|| arg.widthx ~= 3 || arg.widthy ~= 3
fail 'mex only supports bspline2 with width=3'
end
[pmf xs ys] = jf_mex('kde,b2', single([x y]), single([arg.dx arg.dy]));
else
[pmf xs ys] = kde_pmf2_do(x, y, ...
arg.dx, arg.dy, arg.widthx, arg.widthy, ...
arg.kernel, arg.kernel, arg.loop, arg.chat);
end
if ~nargout & im
im clf, im pl 1 2
[his cen] = jf_histn([x(:) y(:)]);
im(1, cen{1}, cen{2}, his, 'histogram')
im(2, xs, ys, pmf, 'pmf')
clear pmf
end
% kde_pmf2_do()
function [pmf xs ys] = kde_pmf2_do(x, y, dx, dy, wx, wy, kernx, kerny, ...
loop, chat)
if kernx(-wx/2) ~= 0 || kernx(wx/2) ~= 0
fail 'kernel must be zero at +/- width/2 (and beyond)'
end
if kerny(-wy/2) ~= 0 || kerny(wy/2) ~= 0
fail 'kernel must be zero at +/- width/2 (and beyond)'
end
N = numel(x);
if N ~= numel(y), fail('x and y must be same size'), end
kmin = floor(min(x)/dx - wx/2) + 1;
kmax = ceil(max(x)/dx + wx/2) - 1; % kmin <= k <= kmax
Kx = kmax - kmin + 1;
xs = (kmin:kmax)' * dx;
x = x - dx * (kmin-1); % wlog, shift so that kmin=1 (for matlab)
%if chat, pr [kmin kmax], end
kmin = floor(min(y)/dy - wy/2) + 1;
kmax = ceil(max(y)/dy + wy/2) - 1; % kmin <= k <= kmax
Ky = kmax - kmin + 1;
ys = (kmin:kmax)' * dy;
y = y - dy * (kmin-1); % wlog, shift so that kmin=1 (for matlab)
%if chat, pr [kmin kmax], end
clear kmin kmax
switch loop
case 'none' % no loop, but O(NK) and huge memory use!
kx = 1:Kx;
ky = 1:Ky;
tmp1 = kernx(outer_sum(x/dx, -kx)); % [N Kx]
tmp2 = kerny(outer_sum(y/dy, -ky)); % [N Ky]
pmf = tmp1' * tmp2; % [Kx Ky]
case 'data' % loop over data N
pmf = zeros(Kx,Ky);
for nn=1:N
xn = x(nn);
yn = y(nn);
k1 = floor(xn/dx - wx/2) + 1;
k2 = ceil(xn/dx + wx/2) - 1;
kx = (k1:k2)';
k1 = floor(yn/dy - wy/2) + 1;
k2 = ceil(yn/dy + wy/2) - 1;
ky = (k1:k2);
pmf(kx,ky) = pmf(kx,ky) + ...
kernx(xn/dx - kx) * kerny(yn/dy - ky); % outer prod
end
case 'pmf' % loop over PMF bins K
pmf = zeros(Kx,1);
for ky=1:Ky
for kx=1:Kx
xmin = ((kx - wx/2)) * dx;
xmax = ((kx + wx/2)) * dx;
good = xmin < x & x < xmax;
ymin = ((ky - wy/2)) * dy;
ymax = ((ky + wy/2)) * dy;
good = (ymin < y & y < ymax) & good;
tmp = kernx(x(good)/dx - kx) .* kerny(y(good)/dy - ky);
pmf(kx,ky) = sum(tmp);
end
end
otherwise
fail('unknown loop type "%s"', loop)
end
pmf = pmf / N;
% quadratic B-spline
% kde_pmf2_bspline2()
function y = kde_pmf2_bspline2(x)
y = (3/4 - x.^2) .* (abs(x) < 1/2) + ...
(abs(x) - 3/2).^2 / 2 .* (1/2 <= abs(x) & abs(x) < 1.5);
% test routine
function kde_pmf2_test
randn('state', 0)
n = 500;
sig = 5;
rho = 0.9; % correlated gaussian
Cov = sig^2 * [1 rho; rho 1];
%h1 = (1 + log(2*pi*sig^2)) / 2; % differential entropy for 1D gaussian
h = (size(Cov,1) + log(det(2*pi*Cov))) / 2; % differential entropy for gaussian
pr h
tmp = randn(n, 2) * sqrtm(Cov);
x = tmp(:,1);
y = tmp(:,2);
if 0 % uniform
x = 10 * (rand(n,1) - 0.5);
y = 10 * (rand(n,1) - 0.5);
end
if 1 % check h
dx = 2.4;
dy = 2.8;
[pmf xs ys] = kde_pmf2(x, y, 'dx', dx, 'dy', dy);
equivs(sum(pmf(:)), 1)
Hf = @(p) sum(-p(p>0) .* log(p(p>0)));
H = Hf(pmf);
pr H
pr H + log(dx*dy)
end
args = {x, y, 'dx', 'silverman'};
[pmf xs ys] = kde_pmf2(args{:}, 'chat', 1);
if 1 % check other loop methods
loop_list = {'none', 'pmf', 'data'};
if has_mex_jf
loop_list{end+1} = 'mex';
end
for ii=1:numel(loop_list)
cpu etic
[pmfn xsn ysn] = kde_pmf2(args{:}, 'loop', loop_list{ii});
equivs(pmf, pmfn, 'thresh', 2e-6)
equivs(xs, xsn)
equivs(ys, ysn)
cpu('etoc', sprintf('%s: %4s', mfilename, loop_list{ii}))
end
end
if 0 && has_mex_jf
[pmfm xsm ysm] = kde_pmf2(args{:}, 'loop', 'mex');
% im(xsm, ysm, pmfm)
equivs(xsm, xs)
equivs(ysm, ys)
equivs(pmf, pmfm)
end
if im
im plc 1 3
[hist cent] = jf_histn([x y], 'nbin', 30);
im(1, cent{:}, hist/n)
im(2, xs, ys, pmf)
dx = linspace(0.5, 3.5, 11);
nd = numel(dx);
for id=1:nd
tmp = kde_pmf2(x, y, 'dx', dx(id));
Hv(id) = Hf(tmp); % H for several dx values
end
im subplot 3
plot(dx([1 end]), [h h], '-', ...
dx, Hv, 'o', ...
dx, Hv + log(dx.*dx), '+') % H + log(dx*dy) approximately is h
legend('h', 'H', 'H + log(dx dy)', 3), grid
end
if 0
clf
while(1)
im(cent{:}, hist/n)
axis([-1 1 -1 1]*10)
prompt
im(xs, ys, pmf)
axis([-1 1 -1 1]*10)
prompt
end
end
|
github
|
sunhongfu/scripts-master
|
rms.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/rms.m
| 728 |
utf_8
|
0d6bd4bfbbbaefcae75fe8279a34586a
|
function [rhat, s] = rms(x)
%function [rhat, s] = rms(x)
% function [r, s] = rms(err)
% in:
% x: NxM error vectors
% out:
% r: Mx1 estimate of rms error
% s: Mx1 estimate of std. dev. of that estimate
if streq(x, 'test'), rms_test, return, end
N = nrow(x); if (N==1), error('ERROR: use column vector'), end
bs = mean(x);
st = std(x);
rhat = sqrt(mean(abs(x).^2, 1));
var_mse = (2*st.^4 + 4*st.^2 .* bs.^2)/N;
if rhat > 0
s = sqrt( var_mse / 4 ./ rhat.^2 );
else
s = 0;
if nargout > 1
warning 's meaningless'
end
end
if ~nargout
base = '';
fprintf('%srms(%s) =', base, inputname(1))
fprintf(' %g', rhat)
fprintf('\n')
clear rhat
end
function rms_test
rand('state', 7)
r = (rand(10^4,3)-0.5) * sqrt(12);
rms(r)
|
github
|
sunhongfu/scripts-master
|
stackup.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/stackup.m
| 1,652 |
utf_8
|
cb32cb88cf030cac059a98ae7524b920
|
function ss = stackup(varargin)
%|function ss = stackup(x1, x2, ...)
%|
%| stack up 2D arrays to make 3D array
%| or stack up 3D arrays to make 4D array
%| This generalizes how [a; b] "stacks up" 1D vectors to make a 2D array.
%| This is useful in conjunction with stackpick().
%| It is akin to cat(ndims(x1)+1, x1, x2, ...)
%|
%| Copyright 2005-6-18, Jeff Fessler, University of Michigan
if nargin < 1, help(mfilename), error(mfilename), end
if nargin == 1 && streq(varargin{1}, 'test'), stackup_test, return, end
arg1 = varargin{1};
switch ndims(arg1)
case 2
% special usage: stackup(x, 'n3', n3)
%|function ss = stackup(x1, 'n3', n3) is like "op rep"
if length(varargin) == 3 & streq(varargin{2}, 'n3')
fail 'no longer supported'
% fix: redo with repmat?
n3 = varargin{3};
ss = zeros([size(arg1) n3]);
for i3=1:n3
ss(:,:,i3) = arg1;
end
return
end
% 2d stackup, allowing some of the others to be 3d
% fix: refine
nz = 0;
for ii=1:length(varargin)
varargin{ii} = squeeze(varargin{ii});
nz = nz + size(varargin{ii},3);
end
ss = zeros([size(arg1) nz]);
iz = 0;
for ii=1:length(varargin)
nz = size(varargin{ii},3);
ss(:,:,iz+[1:nz]) = varargin{ii};
iz = iz + nz;
end
case 3
ss = zeros([size(arg1) length(varargin)]);
for ii=1:length(varargin)
ss(:,:,:,ii) = varargin{ii};
end
otherwise
error 'only stacking 2d -> 3d and 3d -> 4d done'
end
% stackup_test
function stackup_test
x1 = ones(5,3);
x2 = 2*x1;
y1 = stackup(x1, x2);
jf_equal(y1, cat(3, x1, x2))
%y1 = stackup(x1, 'n3', 5);
%jf_equal(y1, repmat(x1, [1 1 5]))
x1 = ones(5,4,3);
x2 = 2*x1;
y1 = stackup(x1, x2);
jf_equal(y1, cat(4, x1, x2))
|
github
|
sunhongfu/scripts-master
|
bspline_1d_synth.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/bspline_1d_synth.m
| 7,547 |
utf_8
|
22d198ab32dbead6b3027041488ae871
|
function ft = bspline_1d_synth(coef, ti, varargin)
%|function ft = bspline_1d_synth(coef, ti, varargin)
%|
%| Given c[n], the b-spline coefficients for the following model:
%| f(t) = \sum_{k=0}^{N-1} coef_k b(t - k),
%| and given sorted sample locations ti, synthesize signal samples f(t_i).
%|
%| in
%| coef [N,(L)] bspline coefficients for k=0,...,N-1
%| usually from bspline_1d_coef
%| ti [M,1] or [M,(L)] desired sample points (unitless)
%| option
%| order 1|2|3 b-spline order, default: 3
%| ending end / boundary conditions: mirror / periodic / zero
%| out
%| ft [M,(L)] f(t_i) interpolated signal values
%|
%| Copyright 2005-12-7, Jeff Fessler, University of Michigan
if nargin == 1 && streq(coef, 'test'), bspline_1d_synth_test, return, end
if nargin == 1 && streq(coef, 'plot'), bspline_1d_synth_plot, return, end
if nargin < 2, help(mfilename), error(mfilename), end
arg.order = 3;
arg.ending = 'periodic';
arg.mex = 1; % default is to try mex version
arg = vararg_pair(arg, varargin);
if arg.mex
ii = strvcat('mirror', 'periodic', 'zero');
ii = strmatch(arg.ending, ii, 'exact');
if length(ii) ~= 1, error 'unknown end conditions', end
try
ft = jf_mex('bspline,synth,1d', single(coef), single(ti), ...
int32(arg.order), int32(ii));
return
catch
printm 'Warn: mex version failed; reverting to matlab version'
end
end
dims = size(coef);
dims(1) = size(ti,1); % output dim is [M,(L)]
N = size(coef, 1);
coef = reshape(coef, N, []); % [N,*L]
nc = ncol(coef);
[coef ti] = bspline_1d_setup(coef, ti, arg.order, arg.ending);
if (ncol(ti) ~= 1 & ncol(ti) ~= ncol(coef)), error 'ti size mismatch', end
ft = zeros(size(ti,1), size(coef,2));
switch arg.order
case 1
for ic = 1:nc
it = 1 + (ic <= ncol(ti)) * (ic-1); % 1 or ic
ft(:,ic) = bspline1_1d_synth(coef(:,ic), ti(:,it));
end
case 2
for ic = 1:nc
it = 1 + (ic <= ncol(ti)) * (ic-1); % 1 or ic
ft(:,ic) = bspline2_1d_synth(coef(:,ic), ti(:,it));
end
case 3
for ic = 1:ncol(coef)
it = 1 + (ic <= ncol(ti)) * (ic-1); % 1 or ic
ft(:,ic) = bspline3_1d_synth(coef(:,ic), ti(:,it));
end
otherwise
fail('order %d not done', arg.order)
end
ft = reshape(ft, dims); % [N,(L)]
%
% bspline_1d_setup()
% trick: preprocess locations and pad coefficients to avoid conditionals!
% and to handle boundary conditions cleanly.
%
function [coef, ti] = bspline_1d_setup(coef, ti, order, ending)
[N L] = size(coef);
if streq(ending, 'mirror')
% map ti into [0,N-1] using mirror conditions
ti = mod(ti, 2*(N-1)); ti(ti > N-1) = 2*(N-1)-ti(ti > N-1);
switch order
case 1
coef = [coef; zeros(1,L)];
case 3
coef = [coef(2,:); coef; coef(N-1,:); zeros(1,L)];
ti = ti + 1;
otherwise
fail('order %d not done', order)
end
elseif streq(ending, 'periodic')
ti = mod(ti, N); % now ti is in [0,N)
switch order
case 1
coef = [coef; coef(1,:)];
case 3
coef = [coef(N,:); coef; coef(1:2,:)];
ti = ti + 1;
otherwise
fail('order %d not done', order)
end
elseif streq(ending, 'zero')
switch order
case 1
ti = max(ti, -1);
ti = min(ti, N);
coef = [zeros(1,L); coef; zeros(2,L)];
ti = ti + 1; % [0,N+1]
case 2
ti = max(ti, -1.5);
ti = min(ti, N+0.5);
coef = [zeros(2,L); coef; zeros(3,L)];
ti = ti + 2; % [0.5,N+2.5]
case 3
ti = max(ti, -2);
ti = min(ti, N+1);
coef = [zeros(3,L); coef; zeros(4,L)];
ti = ti + 3; % [1,N+4]
otherwise
fail('order %d not done', order)
end
end
%
% 1d linear bspline
% coef [N,L] b-spline coefficients. trick: with padding at head and tail!
% ti [M,1] trick: must be in range [0,N-2]
% ft [M,L]
%
function ft = bspline1_1d_synth(coef, ti)
n0 = floor(ti);
%if any(n0 < 0 | 2+n0 > length(coef)), keyboard, error bug, end
ft = coef(1+n0) .* (1 - (ti - n0)) + coef(2+n0) .* (ti - n0);
%
% 1d quadratic bspline
% coef [N,L] b-spline coefficients. trick: with padding at head and tail!
% ti [M,1] trick: must be in range [1/2,N-7/2)
% ft [M,L]
%
function ft = bspline2_1d_synth(coef, ti)
N = size(coef,1);
M = length(ti);
n0 = floor(ti - 1/2);
b2f0 = @(t) 3/4 - t.^2;
b2f1 = @(t) (abs(t) - 3/2).^2 / 2;
ft = coef(1+n0) .* b2f1(ti - (n0)) + ...
coef(2+n0) .* b2f0(ti - (n0+1)) + ...
coef(3+n0) .* b2f1(ti - (n0+2));
%
% 1d cubic bspline
% coef [N,L], ti [M,1]
% ft [M,L]
% coef [N,L] b-spline coefficients. trick: with padding at head and tail!
% ti [M,1] trick: must be in range [1,N-4)
% ft [M,L]
%
function ft = bspline3_1d_synth(coef, ti)
N = size(coef,1);
M = length(ti);
n0 = floor(ti-1);
%if any(n0 < 1) | any(3+n0 > N), minmax(n0), N, keyboard, error, end
ft = coef(1+n0) .* b3f0(ti - (n0)) + ...
coef(2+n0) .* b3f1(ti - (n0+1)) + ...
coef(3+n0) .* b3f2(ti - (n0+2)) + ...
coef(4+n0) .* b3f3(ti - (n0+3));
%
% 1d cubic bspline. this version does not require padding, but is slow
% coef [N,L], ti [M,1]
% ft [M,L]
%
function ft = bspline3_1d_synth_old(coef, ti, is_periodic)
N = size(coef,1);
M = length(ti);
ft = zeros(M, ncol(coef));
n0 = floor(ti);
i0 = (n0 >= 1) & (n0 < N+1);
i1 = (n0 >= 0) & (n0 < N);
i2 = (n0 >= -1) & (n0 < N-1);
i3 = (n0 >= -2) & (n0 < N-2);
for ic = 1:ncol(coef)
ft(i0,ic) = coef(0+n0(i0),ic) .* b3f0(ti(i0) - (n0(i0)-1));
ft(i1,ic) = ft(i1,ic) + coef(1+n0(i1),ic) .* b3f1(ti(i1) - n0(i1));
ft(i2,ic) = ft(i2,ic) + coef(2+n0(i2),ic) .* b3f2(ti(i2) - (n0(i2)+1));
ft(i3,ic) = ft(i3,ic) + coef(3+n0(i3),ic) .* b3f3(ti(i3) - (n0(i3)+2));
if is_periodic
ie = (n0 == 0);
ft(ie,ic) = ft(ie,ic) + coef(N,ic) .* b3f0(ti(ie) + 1);
ie = (n0 == N-1);
ft(ie,ic) = ft(ie,ic) + coef(1,ic) .* b3f2(ti(ie) - N);
ft(ie,ic) = ft(ie,ic) + coef(2,ic) .* b3f3(ti(ie) - (N+1));
ie = (n0 == N-2);
ft(ie,ic) = ft(ie,ic) + coef(1,ic) .* b3f3(ti(ie) - N);
end
end
% piece of bspline function for each offset
%b3f = inline(['1/6*(2 - abs(t)).^3 .* (1 < abs(t) & abs(t) < 2) ' ...
%' + (2/3 - t.^2 + 1/2 * abs(t).^3) .* (abs(t) <= 1)']);
function out = b3f0(t), out = (2 - t).^3 / 6;
%function out = b3f1(t), out = 2/3 - t.^2 + 1/2 * t.^3;
function out = b3f1(t), out = 2/3 - t.^2 .* (1 - t/2);
%function out = b3f2(t), out = 2/3 - t.^2 - 1/2 * t.^3;
function out = b3f2(t), out = 2/3 - t.^2 .* (1 + t/2);
function out = b3f3(t), out = (2 + t).^3 / 6;
%
% test
%
function bspline_1d_synth_test
N = 12;
fn = eye(N);
ti = linspace(-3,N+3,41*(N+6)+1)';
M = length(ti);
orders = [1 3];
endings = {'mirror', 'periodic', 'zero'};
for io=1:length(orders)
order = orders(io);
for ie=1:length(endings)
ending = endings{ie};
printm([ending ' ' num2str(order)])
arg = {'order', order, 'ending', ending};
% coef = bspline_1d_coef(fn, arg{:});
coef = eye(N);
if 1
fmex = bspline_1d_synth(coef, ti, arg{:}, 'mex', 1);
fmat = bspline_1d_synth(coef, ti, arg{:}, 'mex', 0);
max_percent_diff(fmex,fmat)
end
if has_mex_jf % test adjoint
A = bspline_1d_synth(eye(N), ti, arg{:}, 'mex', 1);
B = jf_mex('bspline,synth,adj,1d', single(eye(M)), ...
single(ti), int32(N), int32(order), int32(ie));
if max(col(abs(A-B'))) > 1e-5, error 'adjoint', end
end
end
end
if im
clf, pl=210;
n = 0:N-1;
subplot(pl+1)
plot(n, fn, '+', n, coef, 'o', ti, fmat, '-')
subplot(pl+2)
plot(n, sum(fn,2), '+', ti, sum(fmat,2), '-')
prompt
bspline_1d_synth_plot
end
%
% bspline_1d_synth_plot
%
function bspline_1d_synth_plot
ti = linspace(-1,5,601)';
for order = 1:3
bn(:,order) = bspline_1d_synth([0 0 1 0 0]', ti, 'order', order, ...
'mex', 0, 'ending', 'zero');
end
clf, plot(ti-2, bn)
ytick([0 1/8 1/6 2/3 3/4 1])
set(gca, 'yticklabel', strvcat({'0', '1/8', '1/6', '2/3', '3/4', '1'}))
legend('1', '2', '3')
grid
|
github
|
sunhongfu/scripts-master
|
strum_test.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/strum_test.m
| 1,450 |
utf_8
|
5f9ccc49384242173e665bfc02436bde
|
function strum_test
%function strum_test
% test strum object
% Copyright 2006-1-19, Jeff Fessler, University of Michigan
dat.a = 'a';
dat.b = 'b';
h0 = @strum_test_fun0;
h1 = @(st, arg) [st.a arg];
h2 = @(st, arg) sum(arg);
% with comment
st = strum(dat, {'fun0', h0, ''; 'fun1', h1, '(arg)'; 'fun2', h2, '(arg)'})
st.a;
st.fun0;
jf_equal(st.fun1('c'), 'ac')
jf_equal(st.fun2(1:2), 3)
% augment base strum with more methods
new.c = 'c';
s2 = strum(new, {'fun4', @strum_test_fun4, 'fun4(s)'}, 'base', st);
jf_equal(s2.fun4('d'), 'cd')
jf_equal(s2.fun2(1:2), 3)
% without comment
st = strum(dat, {'fun0', h0, 'fun1', h1, 'fun2', h2});
jf_equal(st.fun1('c'), 'ac')
jf_equal(st.fun2(1:2), 3)
st = strum(dat, {'fun0', h0, 'fun3', @strum_test_fun3});
jf_equal(st.fun3('c', 'd'), 'ac')
% [a b] = st.fun3('c', 'd'); % "Too many output arguments" says matlab
% cell arguments
dat.a = {10, 20};
st = strum(dat, {});
st.a;
dat.a{1};
st.a{1};
jf_equal(st.a{1}, dat.a{1})
jf_equal(st.a{2}, dat.a{2})
% jf_equal(dat.a, st.a{:}) % FAILS DUE TO MATLAB LIMITATION :-(
tmp = st.a; jf_equal(dat.a, tmp) % this is the workaround
%st.a{1:2}; % fails
%st.a{:} % fails
try
[a b] = st.fun2(3)
catch
warn 'darn, matlab cannot handle multiple outputs, as matt said'
end
function strum_test_fun0(ob)
printm 'ok'
% do nothing
function [a, b] = strum_test_fun3(ob, arg1, arg2)
a = [ob.a arg1];
b = [ob.b arg2];
function c = strum_test_fun4(ob, arg)
c = [ob.c arg];
|
github
|
sunhongfu/scripts-master
|
highrate_centers.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/highrate_centers.m
| 1,973 |
utf_8
|
fa074a06d856dfb3fc5ae1f1901a054a
|
function centers = highrate_centers(data, L, M)
%|function centers = highrate_centers(data, L, M)
%| According to high-rate scalar quantization theory (Gersho, T-IT, 1979),
%| the density of MMSE quantization cell centroids should be f^{k/(k+2)},
%| for k-dimensional data distributed with pdf f.
%| This m-file designs L centroids for scalar data (k=1) using this principle.
%| M is the number of histogram bins used to approximate the data pdf.
%| out: centers is [L,1]
%| Copyright 2004-7-7, Jeff Fessler, University of Michigan
if nargin < 1, help(mfilename), error(mfilename), end
if streq(data, 'test'), highrate_centers_test, return, end
if ~isvar('M'), M=100; end
data = data(:);
[wt data] = hist(data, M);
dens = wt .^ (1/3); % from high-rate scalar quantization theory
cdf = cumsum(dens / sum(dens));
[cdf ii] = unique(cdf);
m1 = [1:M]-0.5;
m1 = m1(ii);
uu = ([1:L]-0.5)/L;
m2 = interp1(cdf, m1, uu, 'cubic');
%plot(cdf, m1, '.', uu, m2, 'o')
m2 = max(m2,1);
%try
centers = data(round(m2));
%catch
%minmax(m2)
%keyboard
%end
function highrate_centers_test
rand('state', 0)
N = 10^6;
g = rand(N, 1);
f = 2 ./ (2 - g); fun = @(f) 2./f.^2 .* (1 <= f & f <= 2); % pdf on [1,2]
%f = 3+2*g; fun = @(f) 1/2 .* (3 <= f & f <= 5); % pdf on [3,5]
im plc 2 2
im subplot 1
if 1
hist(f, 100)
hold on
u = linspace(1,2,100); du = u(2) - u(1);
plot(u, fun(u)*N*du, 'g-')
hold off
xlabel 'f'
ylabel 'histogram'
axis([1 2 1 2e4])
end
L = 2^4; % even this is high enough for this example!
l1 = [1:L]';
rl_compand = 2 ./ (2 - (l1-1/2)/L); % compand levels for 2/f^2
%rl_ideal = 3 + (l1-1/2)/L * (5-3); % ideal levels for U(3,5)
rl_high = highrate_centers(f, L, 2^9);
% todo: run lloyd-max to find "ideal" and compare!
rl_ideal = lloyd_max_hist(f, rl_compand, 10^3);
im subplot 2
plot(l1, rl_compand, '-o', l1, rl_high, '-+', l1, rl_ideal, '-*')
legend('companding', 'high rate', 'lloyd-max', 2)
axis([0 L 1 2])
xlabel 'l'
ylabel 'r_l'
%savefig cw highrate_centers
|
github
|
sunhongfu/scripts-master
|
padn.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/padn.m
| 1,336 |
utf_8
|
4822bab375497160ba2c475697fec6a7
|
function out = padn(mat, newdim)
%|function out = padn(mat, newdim)
%| pad input matrix to newdim, preserving 'center point'
%| todo: replace by matlab's "padarray"
if nargin < 1, help(mfilename), error(mfilename), end
if streq(mat, 'test'), padn_test, return, end
% default: round to next up power of 2
if nargin < 2
newdim = 2 .^ ceil(log2(size(mat)))
end
olddim = size(mat);
if any(newdim < olddim), error('must be bigger'), end
idx = cell(1, length(newdim));
for ii=1:length(newdim)
pad = newdim(ii) - olddim(ii);
if ~rem(pad,2) % even
offset = pad/2;
else
if rem(olddim(ii),2) % odd
offset = ceil(pad/2);
else
offset = floor(pad/2);
end
end
idx{ii} = [1:olddim(ii)] + offset;
end
out = zeros1(newdim);
out(idx{:}) = mat;
function z = zeros1(dim)
%function z = zeros1(dim)
% make array of zeros(dims(1), dims(2), ...)
% works logically even if the input is a scalar
% jeff fessler
if nargin < 1, help(mfilename), error(mfilename), end
if length(dim) == 1
dim = [dim 1]
end
z = zeros(dim);
function padn_test
x = ones(3,4);
jf_equal(x, unpadn(padn(x, [4 6]), size(x)))
jf_equal(x, unpadn(padn(x, [5 7]), size(x)))
jf_equal(padn([1 2 1], [1 5]), [0 1 2 1 0])
jf_equal(padn([0 1 2 1], [1 5]), [0 1 2 1 0])
jf_equal(padn([0 1 2 1], [1 6]), [0 0 1 2 1 0])
jf_equal(padn([1 2 1], [1 6]), [0 0 1 2 1 0])
|
github
|
sunhongfu/scripts-master
|
reale.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/reale.m
| 1,973 |
utf_8
|
d7514474903cc0261796237d78f5ae02
|
function y = reale(x, arg2, arg3)
%|
%| y = reale(x)
%| y = reale(x, tol)
%| y = reale(x, 'warn', 'message')
%| y = reale(x, 'error')
%| y = reale(x, 'report')
%| y = reale(x, 'prompt')
%| y = reale(x, 'disp')
%|
%| return real part of complex data (with error checking).
%| checks that imaginary part is negligible (or warning etc. if not)
%|
%| Copyright Jeff Fessler, University of Michigan
if nargin < 1, help(mfilename), error(mfilename), end
if nargin == 1 & streq(x, 'test'), reale_test, return, end
com = 'error';
if isa(x, 'double')
tol = 1e-13;
else
tol = 1e-6;
end
if nargin > 1
if ischar(arg2)
com = arg2;
elseif isnumeric(arg2)
tol = arg2;
end
end
if streq(com, 'disp')
;
elseif streq(com, 'warn')
onlywarn = 1;
elseif streq(com, 'error')
onlywarn = 0;
elseif streq(com, 'prompt')
;
elseif streq(com, 'report')
;
else
fail('bad argument %s', com)
end
max_abs_x = max(abs(x(:)));
if max_abs_x == 0
if any(imag(x(:)) ~= 0)
error 'max real 0, but imaginary!'
else
y = real(x);
return
end
end
frac = max(abs(imag(x(:)))) / max_abs_x;
if streq(com, 'report')
printm('imaginary part %g%%', frac * 100)
return
end
if frac > tol
[cname line] = caller_name;
t = sprintf('%s(%d): %s: imaginary fraction of %s is %g', ...
cname, line, mfilename, inputname(1), frac);
if isvar('arg3')
t = [t ', ' arg3];
end
if streq(com, 'disp')
disp(t)
elseif streq(com, 'prompt')
printm('reale() called for input with imaginary part %g%%', frac * 100)
printm('reale() called in context where a large imaginary part')
printm('is likely an *error*. proceed with caution!')
t = input('proceed? [y|n]: ', 's');
if isempty(t) || t(1) ~= 'y'
printm('ok, aborting is probably wise!')
error ' '
end
elseif onlywarn
disp(t)
else
error(t)
end
end
y = real(x);
function reale_test
x = 7 + 1i*eps;
reale(x, 'warn');
reale(x, 'prompt');
%reale(x, 'report'); % check error reporting
%reale(x, eps/100) % check error faulting
|
github
|
sunhongfu/scripts-master
|
equivs.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/equivs.m
| 1,610 |
utf_8
|
f9ca1bd1ae3239b4f775ac31f6874f9a
|
function out = equivs(var1, var2, varargin)
%|function out = equivs(var1, var2, command)
%| verify that var1 and var2 are equivalent to within single precision accuracy
%| if not, print error message. an alternative to isequal().
%| See also: jf_equal
%| option
%| 'thresh' threshold (default: 1e-6)
%| Copyright 2007, Jeff Fessler, University of Michigan
if nargin == 1 && streq(var1, 'test'), equivs_test, return, end
if nargin < 2, help(mfilename), error(mfilename), end
arg.thresh = 1e-6;
arg = vararg_pair(arg, varargin);
if isempty(var1) && isempty(var2)
ok = true;
elseif ~isequal(size(var1), size(var2))
printm([': size(%s) = %s'], inputname(1), mat2str(size(var1)))
printm([': size(%s) = %s'], inputname(2), mat2str(size(var2)))
error 'incompatible dimensions'
else
var1 = var1(:);
var2 = var2(:);
norm = (max(abs(var1)) + max(abs(var2))) / 2;
if ~norm
ok = true; % both zero!
else
err = max(abs(var1-var2)) / norm;
ok = err < arg.thresh;
end
end
if nargout
out = ok;
end
if ok
return
end
[name line] = caller_name;
if isempty(name)
str = '';
else
str = sprintf('%s %d:', name, line);
end
name1 = inputname(1);
name2 = inputname(2);
minmax(var1, ['equivs ' name1 ':'])
minmax(var2, ['equivs ' name2 ':'])
diff = var1 - var2;
minmax(diff)
tmp = sprintf([str ' normalized difference of %g between "%s" "%s"'], ...
err, name1, name2);
error(tmp)
function equivs_test
randn('state', 0)
x = randn(1000,200);
y = dsingle(x);
equivs(x,y)
passed = 0;
try
y = x + 2e-6 * max(x(:));
equivs(x,y)
passed = 1;
catch
end
if passed, error 'this should have failed!', end
|
github
|
sunhongfu/scripts-master
|
jf_rm_toolbox.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/private/jf_rm_toolbox.m
| 686 |
utf_8
|
97251af0ce7418ae4ee9e0a24ae04b72
|
function jf_rm_toolbox
% remove matlab toolboxes from path
% for testing my toolbox with vanilla matlab
rm aero
rm aeroblks
rm bioinfo
rm comm
rm commblks
rm compiler
rm control
rm curvefit
rm database
rm des
rm distcomp
rm dspblks
rm eml
rm emlcoder
rm filterdesign
rm finance
rm fixedpoint
rm fuzzy
rm geoweb
rm ident
rm images
rm instrument
%rm local
rm map
%rm matlab
rm nnet
rm optim
rm pde
rm physmod
rm rf
rm rfblks
rm robust
rm rtw
%rm shared
rm signal
rm simulink
rm sl3d
rm slcontrol
rm slvnv
rm splines
rm stateflow
rm stats
rm symbolic
rm vipblks
rm wavelet
function rm(box)
dir = '/Volumes/a2/pub/matlab/matlab-2010a.app/toolbox/';
tmp = genpath([dir box]);
rmpath(tmp);
|
github
|
sunhongfu/scripts-master
|
jf_prctile.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/private/jf_prctile.m
| 1,066 |
utf_8
|
4f9221f4120fbff5aa6add943c5a1ac9
|
function y = jf_prctile(pn, x, p, dim)
% mimic matlab's prctile which is in the "stats" toolbox
if streq(x, 'test'), jf_prctile_test, y = []; return, end
if nargin < 3, help(mfilename), error(mfilename), end
% work with permuted dimensions if needed
if nargin > 3 && ~isempty(dim)
order = [dim:ndims(x) 1:dim-1];
x = permute(x, order);
y = jf_prctile(pn, x, p);
y = ipermute(y, order);
return
end
if ndims(x) > 2
dim = size(x);
x = reshapee(x, [], prod(dim(2:end)));
y = jf_prctile(pn, x, p);
y = reshapee(y, [], dim(2:end));
return
end
if any(isnan(x(:)))
fail 'nan values unsupported'
end
if ~isreal(x)
fail 'complex values unsupported'
end
% at this point x is 2d and we work along 1st dimension
n = size(x, 1);
q = [0 100*(0.5:(n-0.5))./n 100]';
x = sort(x,1);
x = [x(1,:); x(1:n,:); x(n,:)];
y = interp1q(q, x, p(:));
function jf_prctile_test
%x = zeros(1,51,1);
%x(1,:,1) = 200:-4:0;
%x(1,:,1) = 0:2:100;
x = rand(10,40,20);
p = [20 50 60];
y1 = jf_prctile([], x, p, 2);
if exist('prctile') == 2
y2 = prctile(x, p, 2);
jf_equal(y1, y2)
end
|
github
|
sunhongfu/scripts-master
|
jf_color_order.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/private/jf_color_order.m
| 984 |
utf_8
|
009a5177b58c46e4e5ed781f43bdf930
|
function out = jf_color_order(pn, varargin)
%function out = jf_color_order(pn, varargin)
% set color order to start with yellow then cyan etc., for black background
if ~length(varargin)
out = jf_color_order_bw;
return
end
out = [];
switch varargin{1}
case 'revert'
set(0, 'DefaultAxesColorOrder', 'default')
return
case 'setup'
set(0, 'DefaultAxesColorOrder', jf_color_order_bw)
% set(gca, 'NextPlot', 'replacechildren')
% set(gca, 'colororder', jf_color_order_bw)
return
otherwise % 'test'
tmp = jf_color_order_bw;
N = nrow(tmp) * 2;
n = 1:N;
x = [n; n];
y = repmat([0 1]', [1, N]);
cla
set(gca, 'NextPlot', 'replacechildren')
set(gca, 'colororder', tmp)
plot(x, y, 'linewidth', 9)
axis([0 N+1 0 2])
xlabel 'color'
end
function out = jf_color_order_bw
out = [
1 1 0; % bright yellow
0 1 1; % bright cyan
1 0 1; % bright magenta
0 1 0; % green
1 0 0; % red
0 0 1; % blue
%0 3/4 3/4;
%3/4 0 3/4;
% 3/4 3/4 0;
1 1/2 0; % orange
1 1 1; % white
%1/2 1/2 1/2; % gray
];
|
github
|
sunhongfu/scripts-master
|
jf_struct_recurse.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/private/jf_struct_recurse.m
| 1,824 |
utf_8
|
d7849c16991e5a735db1c20c9bfe3a79
|
function out = jf_struct_recurse(pn, st, varargin)
%|function out = jf_struct_recurse(pn, st, varargin)
%|
%| Recursively descend a structure and examine its (numeric) members
%|
% Copyright 2010-04-05, Jeff Fessler, University of Michigan
if nargin < 1, help(mfilename), error(mfilename), end
arg.type = 'minmax_nan';
arg.other = false; % show other types (e.g., char?)
arg.top = '';
arg.fun = [];
arg = vararg_pair(arg, varargin);
switch arg.type
case 'minmax_nan'
arg.fun = @(x) minmax_nan(x);
otherwise
if isempty(arg.fun)
fail 'need ''type'' or ''fun'' option'
end
end
jf_struct_recurse_do(st, arg.top, arg.fun, arg)
out = [];
% jf_struct_recurse_do()
function jf_struct_recurse_do(x, prefix, fun, arg)
%if isa(x, 'strum')
% x = struct(x);
%end
if isempty(x)
% ignore
elseif isnumeric(x) || islogical(x)
r = fun(x);
if numel(r) == 1
printf('%s : %g', prefix, r)
elseif numel(r) == 2
printf('%s : %g %g', prefix, r(1), r(2))
else
printf('%s :', prefix)
disp(r)
end
elseif ischar(x)
if arg.other
printf('%s : %s', prefix, x)
end
elseif iscell(x)
for ii = 1:length(x)
tmp = [prefix sprintf('{%d}', ii)];
jf_struct_recurse_do(x{ii}, tmp, fun, arg)
end
elseif isstruct(x)
names = fieldnames(x);
for ii = 1:length(names)
tmp = [prefix '.' names{ii}];
jf_struct_recurse_do(x.(names{ii}), tmp, fun, arg)
end
elseif isa(x, 'function_handle')
% ignore
else
try % try to convert other classes to struct, e.g., strum or Fatrix
x = struct(x);
jf_struct_recurse_do(x, prefix, fun, arg)
catch
warn('unknown class %s', class(x))
end
end
function out = min_nan(x)
if any(isnan(x(:)))
out = nan;
else
out = min(x(:));
end
function out = max_nan(x)
if any(isnan(x(:)))
out = nan;
else
out = max(x(:));
end
function out = minmax_nan(x)
out = [min_nan(x) max_nan(x)];
|
github
|
sunhongfu/scripts-master
|
display.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/@strum/display.m
| 1,036 |
utf_8
|
bf17c2af3d0e12d5ea0fb3c4ae23eeb8
|
function display(ob)
%function display(ob)
% "display" method for this class
name = inputname(1);
printm('"%s" is an object of class "%s":', name, class(ob))
ob = struct(ob);
disp(ob)
fnames = fieldnames(ob);
for ii=1:length(fnames)
fname = fnames{ii};
if isstruct(ob.(fname))
printf('%s.%s :', inputname(1), fname)
if streq(fname, 'meth') && ~isempty(ob.docs)
display_method(ob.meth, ob.docs)
else
disp(ob.(fname))
end
end
end
function display_method(meth, docs)
mnames = fieldnames(meth);
nmax = 1; % find max length method name
for im=1:length(mnames)
nmax = max(nmax, length(mnames{im}));
end
nmax = min(nmax, 40);
hmax = 1; % find max length handle name
for im=1:length(mnames)
hmax = max(hmax, length( func2str(meth.(mnames{im})) ));
end
hmax = min(hmax, 40);
format = ['\t%' sprintf('%d', nmax) 's: @%' sprintf('%d', hmax) 's %s'];
for im=1:length(mnames)
tmp = func2str(meth.(mnames{im}));
if tmp(1) == '@', tmp = tmp(2:end); end % implicit functions
printf(format, mnames{im}, tmp, docs{im})
end
|
github
|
sunhongfu/scripts-master
|
mat_write.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/utilities/arch/mat_write.m
| 2,626 |
utf_8
|
51f2b89c210296ee2a33b698ceaa1ab8
|
function mat_write(file, data, varargin)
%function mat_write(file, data,
% ['-check', '-nocheck', '-type', datatype, '-name', varname])
%
% Save matlab "data" to "file", first checking if "file" exists!
% If file suffix is .fld, then save as AVS .fld file in xdr_float.
%
% datatype can be 'xdr_float' 'xdr_int' ...
% Jeff Fessler, The University of Michigan
if nargin == 1 & streq(file, 'test'), mat_write_test, return, end
if nargin < 2, help(mfilename), error(mfilename), end
% use .fld file if filename ends in .fld, or if filename is t0, t1, ...
isfld = 0;
if length(file) > 4
isfld = streq(file((end-3):end), '.fld');
elseif length(file) == 2 & file(1) == 't'
isfld = true;
end
check1st = true;
if isfld
varname = '';
datatype = 'xdr_float';
else
varname = 'data';
datatype = '';
end
while length(varargin)
if streq(varargin{1}, '-nocheck')
check1st = 0;
varargin = {varargin{2:end}};
elseif streq(varargin{1}, '-check')
check1st = 1;
varargin = {varargin{2:end}};
elseif streq(varargin{1}, '-type')
if length(varargin) < 2
error '-type needs arg'
else
datatype = varargin{2};
varargin = {varargin{3:end}};
end
elseif streq(varargin{1}, '-name')
if length(varargin) < 2
error '-name needs arg'
else
varname = varargin{2};
varargin = {varargin{3:end}};
end
else
error(sprintf('bad arg "%s"', varargin{1}))
end
end
if isfld & ~isempty(varname)
warning('variable name for .fld file ignored')
end
if ~isfld & ~isempty(datatype)
warning('datatype for .mat file ignored')
end
if 2==exist(file) & check1st
if has_aspire
if isfld
os_run(['op range ' file])
else
os_run(['op -chat 0 matls ' file])
end
end
t = sprintf('file "%s" exists. overwrite? [y|n]: ', file);
t = input(t, 's');
if ~streq(t, 'y')
return
end
end
% avs file
if isfld
if check1st
fld_write(file, data, '-check', datatype)
else
fld_write(file, data, '-nocheck', datatype)
end
% matlab file
else
error 'writing to matlab file for reading by aspire no longer supported because mathworks changes the file format too often. use fld_write'
if ~streq(varname, 'data')
eval([varname '= data']) % caution: dangerous!
end
t = version;
if t(1) == '4'
save(file, varname)
elseif t(1) == '5' | t(1) == '6'
save(file, varname, '-v4')
else
error version
end
end
printm('file "%s" written ok', file)
% mat_write_test()
function mat_write_test
dat = [5:8 1:4];
file = 'tmp.fld';
mat_write(file, dat, '-check', '-name', 'tester')
%d = load(file);
d = fld_read(file);
if any(d.tester ~= dat), error 'bug', else, printf('%s test ok', mfilename), end
delete(file)
|
github
|
sunhongfu/scripts-master
|
fftn_fast.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/nufft/fftn_fast.m
| 2,536 |
utf_8
|
45eea8a7988be9d007556ae10931481b
|
function Xs = fftn_fast(xs, ns)
%|function Xs = fftn_fast(xs, ns)
%|
%| For some reason, in matlab versions before about 7.4 (R2007a),
%| matlab's fftn routine was suboptimal for the case of 2D FFTs,
%| at least on some machines.
%| The improvement herein was found by Hugo Shi.
%| After 7.4, fftn worked fine so this routine is no longer needed.
%|
%| Note: At ISMRM 2009, Phil Beatty mentioned that sequential 1D FFT approach
%| can be faster particularly when "trimming" of excess FOV is used.
%|
%| Copyright 2004-6-28, Jeff Fessler, University of Michigan
if nargin < 1, help(mfilename), error(mfilename), return, end
if streq(xs, 'test'), fftn_fast_test, return, end
% around version 7.4, fftn was fastest, so hardwire that!
if nargin < 2
Xs = fftn(xs);
else
if length(ns) == 1
Xs = fft(xs, ns);
else
Xs = fftn(xs, ns);
end
end
return
if nargin < 2, ns = size(xs); end
if ndims(xs) == 2 % 2D or 1D case
if min(size(xs)) == 1
if ns(2) ~= 1, error 'bug', end
Xs = fft(xs, ns(1));
else
Xs = fftn_fast_fftfft(xs, ns);
end
else
Xs = fftn(xs, ns);
end
function Xs = fftn_fast_fftfft(xs, ns)
Xs = fft(fft(xs, ns(1)).', ns(2)).';
% test configuration of fftn_fast for this machine
function fftn_fast_test
fftn_fast_test2 % 2D
% test configuration of fftn_fast for this machine for 2D
function fftn_fast_test2
n = 2^8;
x = rand(n,n);
ns = [2*n n];
printf('starting test; be patient.')
% first loop is to get everything in cache or whatever.
% doing it twice is the only way to get an accurate comparison!
for nloop = [2 40];
tic, for ii=1:nloop, X{1} = fftn_fast(x, ns); end
tt(1) = toc; ty{1} = 'fftn_fast';
tic, for ii=1:nloop, X{2} = fftn(x, ns); end
tt(2) = toc; ty{2} = 'fftn';
tic, for ii=1:nloop, X{3} = fft(fft(x, ns(1)).', ns(2)).'; end
tt(3) = toc; ty{3} = 'fftfft_inline';
tic, for ii=1:nloop, X{4} = fft(fft(x, ns(1), 1), ns(2), 2); end
tt(4) = toc; ty{4} = 'fftfft_brack';
tic, for ii=1:nloop, X{5} = fft2(x, ns(1), ns(2)); end
tt(5) = toc; ty{5} = 'fft2';
tic, for ii=1:nloop, X{6} = fftn_fast_fftfft(x, ns); end
tt(6) = toc; ty{6} = 'fftfft_func';
end
for ii = 1:length(tt)
printf('time %14s = %g', ty{ii}, tt(ii))
if max_percent_diff(X{1}, X{ii}) > 1e-11, error 'bug', end
end
if tt(1) > 1.05 * min(tt(2:end))
warn 'fftn_fast may be configured supoptimally for your machine!'
printf('fftn / fftn_fast = %g%% ', tt(2) / tt(1) * 100.)
else
printf('fftn_fast is configured appropriately for your machine')
printf('fftn / fftn_fast = %g%% ', tt(2) / tt(1) * 100.)
end
|
github
|
sunhongfu/scripts-master
|
nufft_init.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/nufft/nufft_init.m
| 9,078 |
utf_8
|
8404dab6a378286f60e1ec96e8a03af3
|
function st = nufft_init(om, Nd, Jd, Kd, varargin)
%|function st = nufft_init(om, Nd, Jd, Kd, [n_shift,] ...)
%|
%| Initialize structure for d-dimension NUFFT using KB interpolator,
%| particularly the interpolation matrix in sparse format.
%| caution: this routine can require a lot of memory!
%| in
%| om [M d] "digital" frequencies in radians
%| Nd [d] image dimensions (N1,N2,...,Nd)
%| Jd [d] # of neighbors used (in each direction)
%| Kd [d] FFT sizes (should be >= N1,N2,...)
%| optional arguments
%| n_shift [d] n = 0-n_shift to N-1-n_shift (must be first)
%| 'minmax:kb' minmax interpolator with excellent KB scaling!
%| (minmax:kb is recommended, and used by default)
%| 'minmax:tuned' minmax interpolator, somewhat numerically tuned
%| 'minmax:user' minmax interpolator with user ({alpha}, {beta})
%| 'uniform' uniform scaling factors (not recommended)
%| 'kaiser' kaiser-bessel (KB) interpolator (minmax best alpha, m)
%| or 'kaiser', [alpha], [m] to specify parameter (vectors)
%| 'linear' linear interpolator (a terrible straw man)
%| kernel user-provided inline interpolation kernel(k,J)
%| (or a cell array of kernels, one for each dimension)
%| 'table' use table-based interpolation rather than sparse matrix.
%| this can save a lot of memory for large problems.
%| example ..., 'table', 2^11, 'minmax:kb'
%| where 2^11 is the table over-sampling factor.
%| out
%| st.p [M *Kd] sparse interpolation matrix
%| (or empty if table-based)
%| st.sn [(Nd)] scaling factors
%| st.Nd,Jd,Kd,om copies of inputs
%|
%| *Nd is shorthand for prod(Nd).
%| (Nd) is shorthand for (N1,N2,...,Nd)
%|
%| Like fft(), the NUFFT expects the signals to be x(0,0), ...
%| Use n_shift = [N1/2, N2/2, ...] for x(-N1/2,-N2/2,...), ...
%|
%| Copyright 2002-5-30, Jeff Fessler, University of Michigan
if nargin == 1 && streq(om, 'test'), nufft_init_test, return, end
if nargin < 4, help(mfilename), error(mfilename), end
% dimensionality of input space (usually 2 or 3)
dd = length(Nd);
if dd ~= length(Jd) | dd ~= length(Kd)
error 'inconsistent dim'
end
if any(Kd < Nd), warning 'Kd < Nd unlikely to work. Try Kd=2*Nd', end
% special cases of input sampling pattern
if ischar(om)
om = nufft_samples(om, Nd);
end
if dd ~= size(om,2), error('omega needs %d columns', dd), end
%
% process optional arguments
%
% n_shift argument? (must be first)
if length(varargin) > 0 & isnumeric(varargin{1})
n_shift = varargin{1};
if dd ~= length(n_shift)
error('n_shift needs %d columns', dd)
end
varargin = {varargin{2:end}};
else
n_shift = zeros(size(Nd));
end
st.n_shift = n_shift;
% default/recommended interpolator is minmax with KB scaling factors
if length(varargin) == 0
varargin = {'minmax:kb'};
end
st.alpha = {};
st.beta = {};
is_kaiser_scale = false;
% table based?
if ischar(varargin{1}) & streq(varargin{1}, 'table')
st = nufft_table_init(om, Nd, Jd, Kd, n_shift, varargin{2:end});
return
end
ktype = varargin{1};
% cell array of kernel functions: {kernel1, kernel2, ..., kernelD}
if isa(ktype, 'cell')
if isa(ktype{1}, 'inline') | isa(ktype{1}, 'function_handle')
ktype = 'inline';
if length(varargin) > 1, error 'excess arguments?', end
if length(varargin{1}) ~= dd, error 'wrong # of kernels', end
st.kernel = varargin{1};
else
error 'cell array should be inline kernels!?'
end
% or a single inline kernel for all dimension
elseif isa(ktype, 'inline') | isa(ktype, 'function_handle')
ktype = 'inline';
if length(varargin) > 1, error 'excess arguments?', end
for id = 1:dd
st.kernel{id} = varargin{1}; % all same
end
% or a string that describes the type of interpolator
elseif ~ischar(ktype)
error 'non-string kernel type?'
end
st.ktype = ktype;
%
% set up whatever is needed for each interpolator
%
if streq(ktype, 'inline')
% already did it above
% linear interpolator straw man
elseif streq(ktype, 'linear')
ktype = 'inline';
kernel = inline('(1 - abs(k/(J/2))) .* (abs(k) < J/2)', 'k', 'J');
for id = 1:dd
st.kernel{id} = kernel;
end
% KB interpolator
elseif streq(ktype, 'kaiser')
is_kaiser_scale = true;
% with minmax-optimized parameters
if length(varargin) == 1
for id = 1:dd
[st.kernel{id} st.kb_alf(id) st.kb_m(id)] = ...
kaiser_bessel('inline', Jd(id));
end
% with user-defined parameters
elseif length(varargin) == 3
alpha_list = varargin{2};
m_list = varargin{3};
if (length(alpha_list) ~= dd) | (length(m_list) ~= dd)
error('#alpha=%d #m=%d vs dd=%d', ...
length(alpha_list), length(m_list), dd)
end
for id = 1:dd
[st.kernel{id} st.kb_alf(id) st.kb_m(id)] = ...
kaiser_bessel('inline', Jd(id), ...
alpha_list(id), m_list(id));
end
else
error 'kaiser should have no arguments, or both alpha and m'
end
% minmax interpolator with KB scaling factors (recommended default)
elseif streq(ktype, 'minmax:kb')
for id = 1:dd
[st.alpha{id}, st.beta{id}] = ...
nufft_alpha_kb_fit(Nd(id), Jd(id), Kd(id));
end
% minmax interpolator with numerically "tuned" scaling factors
elseif streq(ktype, 'minmax:tuned')
for id = 1:dd
[st.alpha{id}, st.beta{id}, ok] = ...
nufft_best_alpha(Jd(id), 0, Kd(id)/Nd(id));
if ~ok, error 'unknown J,K/N', end
end
% minmax interpolator with user-provided scaling factors
elseif streq(ktype, 'minmax:user')
if length(varargin) ~= 3, error 'user must provide alpha/beta', end
st.alpha = varargin{2};
st.beta = varargin{3};
if length(st.alpha) ~= dd | length(st.beta) ~= dd
error 'alpha/beta size mismatch'
end
elseif streq(ktype, 'uniform')
for id = 1:dd
st.alpha{id} = 1;
st.beta{id} = 0;
end
else
error 'unknown kernel type'
end
st.tol = 0;
st.Jd = Jd;
st.Nd = Nd;
st.Kd = Kd;
M = size(om,1);
st.M = M;
st.om = om;
%
% scaling factors: "outer product" of 1D vectors
%
st.sn = 1;
for id=1:dd
if is_kaiser_scale
nc = [0:Nd(id)-1]'-(Nd(id)-1)/2;
tmp = 1 ./ kaiser_bessel_ft(...
nc/Kd(id), Jd(id), st.kb_alf(id), st.kb_m(id), 1);
elseif streq(ktype, 'inline')
tmp = 1 ./ nufft_interp_zn(0, Nd(id), Jd(id), Kd(id), st.kernel{id});
else
tmp = nufft_scale(Nd(id), Kd(id), st.alpha{id}, st.beta{id});
end
st.sn = st.sn(:) * tmp';
end
if length(Nd) > 1
st.sn = reshape(st.sn, Nd); % [(Nd)]
else
st.sn = st.sn(:); % [(Nd)]
end
%
% [J? M] interpolation coefficient vectors. will need kron of these later
%
for id=1:dd
N = Nd(id);
J = Jd(id);
K = Kd(id);
if isvar('st.kernel')
[c, arg] = ...
nufft_coef(om(:,id), J, K, st.kernel{id}); % [J? M]
else
alpha = st.alpha{id};
beta = st.beta{id};
T = nufft_T(N, J, K, st.tol, alpha, beta); % [J? J?]
[r, arg] = ...
nufft_r(om(:,id), N, J, K, alpha, beta); % [J? M]
c = T * r; clear T r
end
gam = 2*pi/K;
phase_scale = 1i * gam * (N-1)/2;
phase = exp(phase_scale * arg); % [J? M] linear phase
ud{id} = phase .* c; % [J? M]
%
% indices into oversampled FFT components
%
koff = nufft_offset(om(:,id), J, K); % [M 1] to leftmost near nbr
kd{id} = mod(outer_sum([1:J]', koff'), K) + 1; % [J? M] {1,...,K?}
if id > 1 % trick: pre-convert these indices into offsets!
kd{id} = (kd{id}-1) * prod(Kd(1:(id-1)));
end
end, clear c arg gam phase phase_scale koff N J K
%
% build sparse matrix that is [M,*Kd]
% with *Jd nonzero entries per frequency point
%
if dd >= 3, printm('Needs at least %g Gbyte RAM', prod(Jd)*M*8/10^9*2), end
kk = kd{1}; % [J1 M]
uu = ud{1}; % [J1 M]
for id = 2:dd
Jprod = prod(Jd(1:id));
kk = block_outer_sum(kk, kd{id}); % outer sum of indices
kk = reshape(kk, Jprod, M);
uu = block_outer_prod(uu, ud{id}); % outer product of coefficients
uu = reshape(uu, Jprod, M);
end % now kk and uu are [*Jd M]
%
% apply phase shift
% pre-do Hermitian transpose of interpolation coefficients
%
phase = exp(1i * (om * n_shift(:))).'; % [1 M]
uu = conj(uu) .* phase(ones(1,prod(Jd)),:); % [*Jd M]
mm = [1:M]; mm = mm(ones(prod(Jd),1),:); % [*Jd M]
% make sparse matrix, ensuring arguments are double for stupid matlab
st.p = sparse(mm(:), double(kk(:)), double(uu(:)), M, prod(Kd));
% sparse object, to better handle single precision operations!
st.p = Gsparse(st.p, 'odim', [M 1], 'idim', [prod(Kd) 1]);
%
% in
% x1 [J1 M]
% x2 [J2 M]
% out
% y [J1 J2 M] y(i1,i2,m) = x1(i1,m) + x2(i2,m)
%
function y = block_outer_sum(x1, x2)
[J1 M] = size(x1);
[J2 M] = size(x2);
xx1 = reshape(x1, [J1 1 M]); % [J1 1 M] from [J1 M]
xx1 = xx1(:,ones(J2,1),:); % [J1 J2 M], emulating ndgrid
xx2 = reshape(x2, [1 J2 M]); % [1 J2 M] from [J2 M]
xx2 = xx2(ones(J1,1),:,:); % [J1 J2 M], emulating ndgrid
y = xx1 + xx2; % [J1 J2 M]
function y = block_outer_prod(x1, x2)
[J1 M] = size(x1);
[J2 M] = size(x2);
xx1 = reshape(x1, [J1 1 M]); % [J1 1 M] from [J1 M]
xx1 = xx1(:,ones(J2,1),:); % [J1 J2 M], emulating ndgrid
xx2 = reshape(x2, [1 J2 M]); % [1 J2 M] from [J2 M]
xx2 = xx2(ones(J1,1),:,:); % [J1 J2 M], emulating ndgrid
y = xx1 .* xx2; % [J1 J2 M]
%
% nufft_init_test()
% for a more complete test, use "nufft test"
%
function nufft_init_test
Nd = [20 10];
st = nufft_init('epi', Nd, [5 5], 2*Nd);
if 0
clf
om = st.om;
plot(om(:,1), om(:,2), 'o-')
axis_pipi set
end
st;
st.alpha{1};
|
github
|
sunhongfu/scripts-master
|
dtft.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/nufft/dtft.m
| 2,364 |
utf_8
|
78368b81b43c5297ff33dc20d9dc0974
|
function X = dtft(x, omega, n_shift, useloop)
%|function X = dtft(x, omega, n_shift, useloop)
%| Compute d-dimensional DTFT of signal x at frequency locations omega
%| in
%| x [[Nd] L] signal values
%| omega [M dd] frequency locations (radians)
%| n_shift [dd 1] use [0:N-1]-n_shift (default [0 0])
%| useloop 1 to reduce memory use (slower)
%| out
%| X [M L] DTFT values
%|
%| Requires enough memory to store M * prod(Nd) size matrices (for testing)
%|
%| Copyright 2001-9-17, Jeff Fessler, University of Michigan
if nargin == 1 & streq(x, 'test'), dtft_test, return, end
if nargin < 2, help(mfilename), error(mfilename), end
if ~isvar('n_shift') | isempty(n_shift), n_shift = [0 0]; end
if ~isvar('useloop') | isempty(useloop), useloop = 0; end
dd = size(omega, 2);
Nd = size(x);
if length(Nd) == dd % just one image
x = x(:);
elseif length(Nd) == dd+1 % multiple images
Nd = Nd(1:(end-1));
% x = reshape(x, prod(Nd), numel(x))/prod(Nd); % [*Nd L]
x = reshape(x, prod(Nd), []); % [*Nd L]
else
error 'bad input signal size'
end
if dd > 3
error 'only up to 3D is done'
else
Nd = [Nd(:); ones(3-length(Nd),1)];
n_shift = [n_shift(:); zeros(3-length(n_shift),1)];
end
for id=1:3 % fix: dd
nn{id} = [0:(Nd(id)-1)]-n_shift(id);
end
[nn{1} nn{2} nn{3}] = ndgrid(nn{1}, nn{2}, nn{3});
%
% loop way: slower but less memory
%
if useloop
M = length(omega);
X = zeros(numel(x)/prod(Nd),M); % [L M]
% t1 = col(nn{1})';
t1 = nn{1}(:)';
t2 = col(nn{2})';
t3 = col(nn{3})';
if size(omega,2) < 3, omega(1,3) = 0; end % trick: make '3d'
for mm=1:M
tmp = omega(mm,1)*t1 + omega(mm,2)*t2 + omega(mm,3)*t3;
X(:,mm) = exp(-1i * tmp) * x;
end
X = X.'; % [M L]
else
X = 0;
for id=1:dd
X = X + omega(:,id) * col(nn{id})';
end
X = exp(-1i*X) * x;
end
%
% if no arguments, then run a simple test
%
function dtft_test
Nd = [4 6 5];
n_shift = [1 3 2];
randn('state', 0), x = randn(Nd); % test signal
o1 = 2*pi*[0:(Nd(1)-1)]'/Nd(1); % test with uniform frequency locations
o2 = 2*pi*[0:(Nd(2)-1)]'/Nd(2);
o3 = 2*pi*[0:(Nd(3)-1)]'/Nd(3);
[o1 o2 o3] = ndgrid(o1, o2, o3);
om = [o1(:) o2(:) o3(:)];
Xd = dtft(x, om, n_shift);
Xl = dtft(x, om, n_shift, 1);
printm('loop max %% difference = %g', max_percent_diff(Xl,Xd))
Xf = fftn(x);
Xf = Xf(:) .* exp(1i * (om * n_shift(:))); % phase shift
printm('fftn max %% difference = %g', max_percent_diff(Xf,Xd))
|
github
|
sunhongfu/scripts-master
|
newfft.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/nufft/newfft.m
| 18,090 |
utf_8
|
ebae560263354d06eae466d1a6dd77f9
|
function st = newfft(om_in, Nd_in, varargin)
%|function st = newfft(om, Nd, [options])
%|
%| New version of NUFFT (pun intended) that uses real interpolation kernels.
%| (The original NUFFT code used complex interpolation needlessly.)
%|
%| This returns a "strum" object with methods for both forward and adjoint
%| d-dimensional NUFFT operations.
%| The forward operation is:
%| X(om_m) = \sum_{n=0}^{N-1} x[n] exp(-1i * om_m * n) for m=1,...,M
%| The adjoint operation is:
%| x_adj[n] = \sum_{m=1}^M X(om_m) exp(+1i * om_m * n) for n=0,...,N-1
%| Note that the adjoint is not the "inverse" NUFFT in general.
%|
%| This routine has numerous options for investigative purposes, but is
%| designed so that the default options should be very good choices.
%| Providing the frequencies and the image size and should suffice.
%| Reducing the neighborhood size 'Jd' (default 6) and/or reducing the
%| over-sampled DFT size 'Kd' (default 2*Nd) may be useful for acceleration.
%|
%| in
%| om [M,d] "digital" frequencies in radians (can be empty!)
%| (if empty, then user must provide 'om' to methods)
%| Nd [d] image dimensions (N1,N2,...,Nd)
%|
%| options
%| 'Jd' [d] # of neighbors used (in each direction). (default: 6)
%| 'Kd' [d] FFT sizes (should be >= Nd). (default: 2*Nd)
%| n_shift [d] n = 0-n_shift to N-1-n_shift (default: 0)
%| Like fft(), the NUFFT expects the signals to be x(0,0), ...
%| Use n_shift = [N1/2, N2/2, ...] for x(-N1/2,-N2/2,...), ...
%|
%| 'mode' char how to compute the NUFFT (default: 'table1')
%| 'exact' slow FT
%| 'table0' table with nearest neighbor interpolation
%| 'table1' table with linear interpolation (default)
%| 'gg' gaussian factorization of Greengard & Lee 04 (todo)
%| 'sparse' precompute large sparse matrix
%| caution: this option may require lots of memory!
%| (this option used internally to make tables too)
%| recommended: table0 or table1 to save memory.
%|
%| 'oversample' int table oversampling factor (default: 2^9 for table1)
%| 'gram' 0|1 if 1, precompute additional terms needed for gram matrix
%| 'printmem' 0|1 if 1, print memory usage
%| 'phasing' char 'real' : new real kernels (strongly recommended default)
%| 'complex' : original nufft.m complex kernels
%| 'none' : no phase (straw man; table uses it internally)
%| 'flipreal' : real kernels with sign flips (unsupported)
%| 'dotime' char report cpu time? (default: '')
%|
%| 'ktype' char type of interpolation kernel (default: 'minmax:kb')
%|
%| ktype options:
%| 'diric' Dirichlet interpolator (exact only if Jd = Kd)
%| 'linear' linear interpolator (a terrible straw man)
%| 'minmax:kb' minmax interpolator with excellent KB scaling!
%| 'minmax:tuned' minmax interpolator, somewhat numerically tuned scaling
%| 'minmax:unif' minmax with uniform scaling factors (not recommended)
%| 'minmax:user' minmax interpolator with user parameters required:
%| 'alpha', {alpha}, 'beta', {beta}
%| 'kb:minmax' kaiser-bessel (KB) interpolator (minmax best alpha, m)
%| 'kb:beatty' KB with parameters from Beatty et al T-MI Jun 2005
%| 'kb:user' KB with user-specified KB parameters required:
%| 'kb_m', [m] 'kb_alf', [alpha]
%| @kernel user-provided inline interpolation kernel(k,J)
%| (or a cell array of kernels, one for each dimension)
%| example ..., 'table', 2^11, 'minmax:kb'
%| where 2^11 is the table over-sampling factor.
%|
%| out
%| st strum object with several methods including the following:
%| st.fft(x, [om])
%| st.adj(Xo, [om])
%| st.p [M, *Kd] sparse interpolation matrix
%| (or empty if table-based)
%| st.sn [(Nd)] scaling factors
%| st.Nd,Jd,Kd,om copies of inputs
%|
%| *Nd is shorthand for prod(Nd).
%| (Nd) is shorthand for (N1,N2,...,Nd)
%|
%| Copyright 2007-6-3, Jeff Fessler, The University of Michigan
if nargin == 1 && streq(om_in, 'test'), newfft_test, return, end
if nargin < 2, help(mfilename), error(mfilename), end
cpu etic
% inputs
st.om = om_in; % [M,d] frequency samples
st.Nd = Nd_in; % [d] signal dimentions
st.dd = length(st.Nd); % dimensionality of input space (usually 2 or 3)
% defaults
st.gram = false;
st.Jd = 6 * ones(1, st.dd);
st.Kd = 2 * st.Nd;
st.n_shift = zeros(1, st.dd);
st.mode = 'table1';
st.oversample = []; % aka Ld for table mode
st.order = []; % for table mode
st.ktype = 'kb:minmax';
st.kb_m = []; % [dd] KB parameters
st.kb_alf = [];
st.alpha = {}; % [dd] minmax parameters
st.beta = {};
st.tol = 0;
st.printmem = false;
st.is_kaiser_scale = false;
st.phasing = 'real'; % use new real table by default
st.dotime = '';
% options
st = vararg_pair(st, varargin);
dotime = st.dotime; st = rmfield(st, 'dotime');
st.phase_before = []; % place holders
st.phase_after = [];
st.flips = [];
% special cases of input sampling pattern
if ischar(st.om)
st.om = nufft_samples(st.om, st.Nd);
end
% checks
if st.dd ~= length(st.Jd) | st.dd ~= length(st.Kd)
error 'inconsistent dim'
end
if st.dd ~= length(st.n_shift)
fail('n_shift needs %d columns', st.dd)
end
if ~isempty(st.om) && st.dd ~= size(st.om,2)
fail('omega needs %d columns', st.dd)
end
if st.gram, fail 'todo: gram not done', end
if any(st.Kd < st.Nd), warning 'Kd < Nd unlikely to work. Try Kd=2*Nd', end
%
% "midpoint" of scaling factors
%
switch st.phasing
case 'real'
st.Nmid = floor(st.Nd / 2); % new
otherwise
st.Nmid = (st.Nd - 1) / 2; % old
end
%
% different interpolation modes
%
switch st.mode
case 'exact' % exact interpolation for testing
st = strum(st, { ...
'fft', @newfft_exact_for, '(x, [om])';
'adj', @newfft_exact_adj, '(X, [om])';
'p', @newfft_exact_p, '([om])';
'sn', @(st) ones(st.Nd), '()';
});
case {'table0', 'table1'} % precomuted interpolator table
st = newfft_table_init(st);
% set up phase corrections not included in table initialization
if streq(st.phasing, 'real') || streq(st.phasing, 'flipreal')
st.phase_before = newfft_phase_before(st.Kd, st.Nmid);
st.phase_after = @(om) newfft_phase_after(om, st.Nmid, st.n_shift);
if ~isempty(st.om) % phase that goes after interpolation:
st.phase_after = st.phase_after(st.om);
end
end
case 'gg' % greengard's gaussian
error 'todo: gg'
st = strum(st, { ...
'fft', @newfft_gg_for, '(x, [om])';
'adj', @newfft_gg_adj, '(X, [om])';
'p', @newfft_gg_p, '([om])';
'sn', @newfft_gg_sn, '()';
});
case 'sparse' % interpolator based on a sparse matrix
if isempty(st.om), error 'sparse mode requires "om"', end
st = newfft_init_sparse(st);
otherwise
fail('unknown mode %s', st.mode)
end
if ~isempty(dotime)
tmp = whos('st');
tmp = num2str(tmp.bytes);
tmp = ['newfft setup ' st.mode ' ' st.phasing(1) ' ' tmp ' ' dotime];
cpu('etoc', tmp)
end
%
% newfft_init_sparse()
%
% create an interpolator based on a sparse matrix.
% this matrix will be large for intersting problem sizes, so this
% mode is not recommended. but it is supported in part because it
% is needed for generating samples of the interpolator for the table mode.
%
function st = newfft_init_sparse(st)
om = st.om;
%
% different interpolation kernel mechanisms
%
ktype = st.ktype;
switch class(ktype)
case 'cell' % cell array of kernel functions: {kernel1, kernel2, ..., kernelD}
if isa(ktype{1}, 'inline') | isa(ktype{1}, 'function_handle')
if length(ktype) ~= dd, error 'wrong # of kernels', end
st.kernel = ktype;
ktype = 'inline';
else
error 'cell array should be inline kernels!?'
end
case {'inline', 'function_handle'} % single inline kernel for all dimensions
for id = 1:st.dd
st.kernel{id} = ktype; % all same
end
ktype = 'inline';
case 'char'
% a string that describes the type of interpolator, see below
otherwise
fail('unknown kernel type %s', class(ktype))
end
%
% interpolator set up
%
Nd = st.Nd;
Jd = st.Jd;
Kd = st.Kd;
dd = st.dd;
is_kaiser_scale = false;
switch ktype
case 'inline'
% already did it above
case 'diric' % exact interpolator
if any(Jd ~= Kd), warn 'diric inexact unless Jd=Kd', end
ktype = 'inline';
for id = 1:dd
N = Nd(id);
K = Kd(id);
if 1 && streq(st.phasing, 'real')
N = 2 * floor((K+1)/2) - 1; % trick
end
st.kernel{id} = @(k,J) N / K * nufft_diric(k, N, K, true);
end
case 'linear' % linear interpolator straw man
ktype = 'inline';
kernel = inline('(1 - abs(k/(J/2))) .* (abs(k) < J/2)', 'k', 'J');
for id = 1:dd
st.kernel{id} = kernel;
end
case 'kb:beatty' % KB with Beatty et al parameters
is_kaiser_scale = true;
if ~isempty(st.kb_alf) || ~isempty(st.kb_m)
warn 'kb_alf and kb_m ignored'
end
K_N = Kd ./ Nd;
st.kb_alf = pi * sqrt( Jd.^2 ./ K_N.^2 .* (K_N - 1/2).^2 - 0.8 );
% pr st.kb_alf ./ Jd % approximately 2.34 for K_N = 2
st.kb_m = zeros(1,dd);
for id = 1:dd
st.kernel{id} = kaiser_bessel('inline', Jd(id), ...
st.kb_alf(id), st.kb_m(id));
end
case 'kb:minmax' % KB with minmax-optimized parameters
is_kaiser_scale = true;
if ~isempty(st.kb_alf) || ~isempty(st.kb_m)
warn 'kb_alf and kb_m ignored'
end
for id = 1:dd
[st.kernel{id} st.kb_alf(id) st.kb_m(id)] = ...
kaiser_bessel('inline', Jd(id));
end
case 'kb:user' % KB with user-defined parameters
is_kaiser_scale = true;
if isempty(st.kb_alf) || isempty(st.kb_m)
fail 'kb_alf and kb_m required'
end
if (length(st.kb_alf) ~= dd) | (length(st.kb_m) ~= dd)
fail('#alpha=%d #m=%d vs dd=%d', ...
length(st.kb_alf), length(st.kb_m), dd)
end
for id = 1:dd
st.kernel{id} = kaiser_bessel('inline', Jd(id), ...
st.kb_alf(id), st.kb_m(id));
end
case 'minmax:kb' % minmax interpolator with KB scaling factors
for id = 1:dd
[st.alpha{id}, st.beta{id}] = ...
nufft_alpha_kb_fit(Nd(id), Jd(id), Kd(id), ...
'Nmid', st.Nmid(id));
end
case 'minmax:tuned' % minmax with numerically "tuned" scaling factors
for id = 1:dd
[st.alpha{id}, st.beta{id}, ok] = ...
nufft_best_alpha(Jd(id), 0, Kd(id)/Nd(id));
if ~ok, error 'unknown J,K/N', end
end
case 'minmax:user' % minmax interpolator with user-provided scaling factors
if isempty(st.alpha) || isempty(st.beta)
error 'user must provide alpha/beta'
end
if length(st.alpha) ~= dd | length(st.beta) ~= dd
error 'alpha/beta size mismatch'
end
case 'minmax:unif' % minmax with straw man uniform scaling factors
for id = 1:dd
st.alpha{id} = 1;
st.beta{id} = 0;
end
otherwise
fail('unknown kernel type %s', ktype)
end
%
% scaling factors: "outer product" of 1D vectors
%
st.sn = 1;
for id=1:dd
if 1 & streq(st.ktype, 'linear')
tmp = newfft_scale_tri(Nd(id), Jd(id), Kd(id), st.Nmid);
elseif streq(st.ktype, 'diric')
tmp = ones(Nd(id),1);
elseif is_kaiser_scale
nc = [0:Nd(id)-1]' - st.Nmid(id);
tmp = 1 ./ kaiser_bessel_ft(...
nc/Kd(id), Jd(id), st.kb_alf(id), st.kb_m(id), 1);
elseif streq(ktype, 'inline')
tmp = 1 ./ nufft_interp_zn(0, Nd(id), Jd(id), Kd(id), ...
st.kernel{id}, st.Nmid(id));
else
tmp = nufft_scale(Nd(id), Kd(id), ...
st.alpha{id}, st.beta{id}, st.Nmid(id));
end
tmp = reale(tmp);
st.sn = st.sn(:) * tmp';
end
if length(Nd) > 1
st.sn = reshape(st.sn, Nd); % [(Nd)]
else
st.sn = st.sn(:); % [(Nd)]
end
%
% [J?,M] interpolation coefficient vectors. will need kron of these later
%
for id=1:dd
N = Nd(id);
J = Jd(id);
K = Kd(id);
if isfield(st, 'kernel')
[c, arg] = ...
nufft_coef(om(:,id), J, K, st.kernel{id}); % [J?,M]
else
alpha = st.alpha{id};
beta = st.beta{id};
T = nufft_T(N, J, K, st.tol, alpha, beta); % [J?,J?]
[r, arg] = ...
nufft_r(om(:,id), N, J, K, alpha, beta); % [J?,M]
c = T * r;
clear T r
end
%
% indices into oversampled FFT components
%
koff = nufft_offset(om(:,id), J, K); % [M,1] to leftmost near nbr
k0 = outer_sum([1:J]', koff'); % [J?,M] arbitrary integers
kd{id} = mod(k0, K); % [J?,M] {0,...,K?-1} (DFT indices)
gam = 2*pi/K;
switch st.phasing
case {'real', 'none'}
phase = 1;
case 'complex'
phase_scale = 1i * gam * (N-1)/2;
phase = exp(phase_scale * arg); % [J?,M] linear phase
case 'flipreal'
isodd = @(n) mod(n,2) == 1;
phase = ones(size(k0)); % [J?,M]
flip = isodd((kd{id} - k0) / K * (N-1)); % sign flip every K
phase(flip) = -1; % sign flip (if N is even)
otherwise
fail('unknown phasing %s', st.phasing)
end
ud{id} = phase .* c; % [J?,M]
end % id
clear c arg gam phase phase_scale koff k0 N J K
% st.M = size(om,1);
M = size(om,1);
%
% build sparse matrix that is [M,*Kd]
% with *Jd nonzero entries per frequency point
%
if st.printmem
printm('Needs at least %g Gbyte RAM', prod(Jd)*M*8/2^30*2)
end
kk = kd{1}; % [J1,M]
uu = ud{1}; % [J1,M]
for id = 2:dd
Jprod = prod(Jd(1:id));
tmp = kd{id} * prod(Kd(1:(id-1)));
kk = block_outer_sum(kk, tmp); % outer sum of indices
kk = reshape(kk, Jprod, M);
uu = block_outer_prod(uu, ud{id}); % outer product of coefficients
uu = reshape(uu, Jprod, M);
end % now kk and uu are [*Jd, M]
%
% handle phase shifts
%
uu = conj(uu); % [*Jd,M] ala Hermitian transpose of interpolation coefficients
switch st.phasing
case 'complex'
phase = exp(1i * (om * st.n_shift(:))).'; % [1,M]
uu = uu .* phase(ones(1,prod(Jd)),:); % [*Jd,M]
if streq(st.mode, 'table', 5) % moved from newfft_table_init.m to here
st.phase_after = @(om) exp(1i * (om * col(st.n_shift))); % [M,1]
end
case {'real', 'flipreal'}
st.phase_before = newfft_phase_before(Kd, st.Nmid);
if ~isempty(st.om) % precompute phase that goes after interpolation
st.phase_after = newfft_phase_after(st.om, st.Nmid, st.n_shift);
else
st.phase_after = @(om) newfft_phase_after(om, st.Nmid, st.n_shift);
end
case 'none'
% do nothing
otherwise
error 'bug'
end
mm = repmat(1:M, prod(Jd), 1); % [*Jd,M]
st.p = sparse(mm(:), 1+kk(:), uu(:), M, prod(Kd)); % [M, *Kd] sparse matrix
% sparse object, to better handle single precision operations!
st.p = Gsparse(st.p, 'odim', [M 1], 'idim', [prod(Kd) 1]);
st = strum(st, { ...
'fft', @newfft_approx_for, '(x, [om])';
'adj', @newfft_approx_adj, '(X, [om])';
});
%
% in
% x1 [J1,M]
% x2 [J2,M]
% out
% y [J1,J2,M] y(i1,i2,m) = x1(i1,m) + x2(i2,m)
%
function y = block_outer_sum(x1, x2)
[J1 M] = size(x1);
[J2 M] = size(x2);
xx1 = reshape(x1, [J1 1 M]); % [J1,1,M] from [J1,M]
xx1 = xx1(:,ones(J2,1),:); % [J1,J2,M], emulating ndgrid
xx2 = reshape(x2, [1 J2 M]); % [1,J2,M] from [J2,M]
xx2 = xx2(ones(J1,1),:,:); % [J1,J2,M], emulating ndgrid
y = xx1 + xx2; % [J1,J2,M]
function y = block_outer_prod(x1, x2)
[J1 M] = size(x1);
[J2 M] = size(x2);
xx1 = reshape(x1, [J1 1 M]); % [J1,1,M] from [J1,M]
xx1 = xx1(:,ones(J2,1),:); % [J1,J2,M], emulating ndgrid
xx2 = reshape(x2, [1 J2 M]); % [1,J2,M] from [J2,M]
xx2 = xx2(ones(J1,1),:,:); % [J1,J2,M], emulating ndgrid
y = xx1 .* xx2; % [J1,J2,M]
%
% newfft_phase_before()
% phase factor that gets multiplied by DFT (before interpolation)
%
function phase = newfft_phase_before(Kd, Nmid)
phase = 0;
for id = 1:length(Kd)
tmp = 2 * pi * [0:Kd(id)-1] / Kd(id) * Nmid(id);
phase = outer_sum(phase, tmp); % [(Kd)] when done
end
phase = exp(1i * phase);
%
% newfft_phase_after()
% phase factor that multiplies the DTFT (after interpolation)
%
function phase = newfft_phase_after(om, Nmid, n_shift)
phase = exp(1i * (om * col(n_shift - Nmid))); % [M,1]
%
% newfft_scale_tri()
% scale factors when kernel is 'linear'
% tri(u/J) <-> J sinc^2(J x)
%
function sn = newfft_scale_tri(N, J, K, Nmid)
nc = [0:N-1] - Nmid;
fun = @(x) J * nufft_sinc(J * x / K).^2;
cent = fun(nc);
sn = 1 ./ cent;
% try the optimal formula
tmp = 0;
LL = 3;
for ll=-LL:LL
tmp = tmp + abs(fun(nc - ll*K)).^2;
end
sn = cent ./ tmp;
%
% newfft_test_time()
% compare compute times of real vs complex, sparse vs table
%
function newfft_test_time
Nd = [1 1] * 2^8;
[tmp om] = mri_trajectory('radial', {}, Nd, Nd);
pr length(om)
rand('state', 0)
x0 = rand([Nd 1]);
arg = {om, Nd, 'dotime', ' '};
s0r = newfft(arg{:}, 'mode', 'table0');
s0c = newfft(arg{:}, 'mode', 'table0', 'phasing', 'complex');
s1r = newfft(arg{:}, 'mode', 'table1');
ssr = newfft(arg{:}, 'mode', 'sparse');
ssc = newfft(arg{:}, 'mode', 'sparse', 'phasing', 'complex');
tmp = @(st) newfft_test_time_one(st, x0, 2);
tmp(s0r)
tmp(s0c)
tmp(s1r)
tmp(ssr)
tmp(ssc)
function newfft_test_time_one(st, x0, nn)
st.fft(x0); % warm up
tmp = [st.mode ' ' st.phasing(1)];
cpu etic
for ii=1:nn
st.fft(x0); % trial
end
cpu('etoc', tmp)
%
% newfft_test()
%
function newfft_test
newfft_test_time
prompt
modes = {'sparse', 'table0', 'table1'};
phasings = {'complex', 'real'};
% 'flipreal' no longer needed thanks to floor(N/2)
% 'none' is for internal table only
Nd_list = [20 10 8];
for id=0:3
if id == 0
Nd = 1 + Nd_list(1); % test odd case
else
Nd = Nd_list(1:id);
end
dd = length(Nd);
rand('state', 0)
om = 3 * 2 * pi * (rand(100,length(Nd)) - 0.5);
% om = sort(om);
% om = linspace(-1,1,601)' * 3*pi;
% om = [-8:8]'/2 * pi;
%om = 'epi';
x0 = rand([Nd 1]);
% x0 = zeros([Nd 1]); x0(1) = 1; % unit vector for testing
% x0 = ones([Nd 1]);
% exact
st_e = newfft(om, Nd, 'mode', 'exact');
Xe = st_e.fft(x0);
xe = st_e.adj(Xe);
if 0
pe = st_e.p;
equivs(pe * x0(:), Xe)
equivs(reshape(pe' * Xe, [Nd 1]), xe)
end
ktypes = {{'linear', 'Jd', 2*ones(1,dd)}, ...
'minmax:unif', ...
{'minmax:user', 'alpha', num2cell(ones(1,dd)), ...
'beta', num2cell(0.5 * ones(1,dd))}, ...
{'diric', 'Jd', 2*Nd-0, 'oversample', []}, ...
'minmax:kb', 'minmax:tuned', ...
'kb:minmax', 'kb:beatty', ...
{'kb:user', 'kb_m', 0*Nd, 'kb_alf', 2.34 * 6 + 0*Nd}
};
for ii=4:length(ktypes) % skip poor ones
ktype = ktypes{ii};
if ~iscell(ktype), ktype = {ktype}; end
for jj=1:length(modes)
for ip=1:length(phasings)
sc = newfft(st_e.om, st_e.Nd, 'phasing', 'complex', ...
'mode', 'table0', 'ktype', ktype{:});
st = newfft(st_e.om, st_e.Nd, 'phasing', phasings{ip}, ...
'mode', modes{jj}, 'ktype', ktype{:});
if streq(st.phasing, 'complex') && streq(st.mode, 'table1')
continue
end
% pr minmax(st.sn)
pad = @(s,n) [s blanks(n-length(s))];
key = [sprintf('%2d ', st.Jd(1)) st.ktype];
key = [st.mode ' ' num2str(id) st.phasing(1) ' ' pad(key,16)];
Xs = st.fft(x0);
max_percent_diff(Xe, Xs, key)
% plot(abs(Xe), abs(Xs), 'o'), prompt
xs = st.adj(Xe);
max_percent_diff(xe, xs, key)
end % ip
end % jj
end % ii
end
|
github
|
sunhongfu/scripts-master
|
kaiser_bessel.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/nufft/kaiser_bessel.m
| 4,245 |
utf_8
|
eb663e2f74fb509c947663fb2c6d4b88
|
function [kb, alpha, kb_m] = kaiser_bessel(x, J, alpha, kb_m, K_N)
%|function [kb, alpha, kb_m] = kaiser_bessel(x, J, alpha, kb_m)
%|function [kb, alpha, kb_m] = kaiser_bessel(x, J, 'best', 0, K_N)
%|
%| generalized Kaiser-Bessel function for x in support [-J/2,J/2]
%| shape parameter "alpha" (default 2.34 J)
%| order parameter "kb_m" (default 0)
%| see (A1) in lewitt:90:mdi, JOSA-A, Oct. 1990
%| in
%| x [M,1] arguments
%| out
%| kb [M,1] KB function values, if x is numbers
%| or string for kernel(k,J), if x is 'string'
%| or inline function, if x is 'inline'
%| alpha
%| kb_m
%|
%| Copyright 2001-3-30, Jeff Fessler, University of Michigan
% Modification 2002-10-29 by Samuel Matej
% - for Negative & NonInteger kb_m the besseli() function has
% singular behavior at the boundaries - KB values shooting-up/down
% (worse for small alpha) leading to unacceptable interpolators
% - for real arguments and higher/reasonable values of alpha the
% besseli() gives similar values for positive and negative kb_m
% except close to boundaries - tested for kb_m=-2.35:0.05:2.35
% (besseli() gives exactly same values for integer +- kb_m)
% => besseli(kb_m,...) approximated by besseli(abs(kb_m),...), which
% behaves well at the boundaries
% WARNING: it is not clear how correct the FT formula (JOSA) is
% for this approximation (for NonInteger Negative kb_m)
% NOTE: Even for the original KB formula, the JOSA FT formula
% is derived only for m > -1 !
% if no arguments, make example plots
if nargin < 2
help(mfilename)
J = 8; alpha = 2.34 * J;
x = linspace(-(J+1)/2, (J+1)/2, 1001)';
% x = linspace(J/2-1/4, J/2+1/4, 1001)';
mlist = [-4 0 2 7];
leg = {};
for ii=1:length(mlist)
kb_m = mlist(ii);
yy(:,ii) = kaiser_bessel(x, J, alpha, kb_m);
func = kaiser_bessel('inline', 0, alpha, kb_m);
yf = func(x, J);
if any(yf ~= yy(:,ii)),
[yf yy(:,ii)]
error 'bug', end
leg{ii} = sprintf('m=%d', kb_m);
end
yb = kaiser_bessel(x, J, 'best', [], 2);
plot( x, yy(:,1), 'c-', x, yy(:,2), 'y-', ...
x, yy(:,3), 'm-', x, yy(:,4), 'g-', x, yb, 'r--')
leg{end+1} = 'best';
axis tight, legend(leg)
% axisy(0, 0.01) % to see endpoints
xlabel \kappa, ylabel F(\kappa)
titlef('KB functions, J=%g \\alpha=%g', J, alpha)
return
end
if ~isvar('J'), J = 6; end
if ~isvar('alpha') | isempty('alpha'), alpha = 2.34 * J; end
if ~isvar('kb_m') | isempty('kb_m'), kb_m = 0; end
if ischar(alpha)
[alpha kb_m] = kaiser_bessel_params(alpha, J, K_N);
end
if ischar(x)
if ischar(alpha)
if ~isvar('K_N'), error 'K_N required', end
kb = 'kaiser_bessel(k, J, ''%s'', [], %g)';
kb = sprintf(kb, alpha, K_N);
else
kernel_string = 'kaiser_bessel(k, J, %g, %g)';
kb = sprintf(kernel_string, alpha, kb_m);
end
if streq(x, 'inline')
kb = inline(kb, 'k', 'J');
elseif ~streq(x, 'string')
error '1st argument must be "inline" or "string"'
end
return
end
%
% Warn about use of modified formula for negative kb_m
%
if (kb_m < 0) & ((abs(round(kb_m)-kb_m)) > eps)
persistent warned
if isempty(warned) % print this reminder only the first time
printf('\nWarning: Negative NonInt kb_m=%g in kaiser_bessel()', kb_m)
printf(' - using modified definition of KB function\n')
warned = 1;
end
end
kb_m_bi = abs(kb_m); % modified "kb_m" as described above
ii = abs(x) < J/2;
f = sqrt(1 - (x(ii)/(J/2)).^2);
denom = besseli(kb_m_bi,alpha);
if ~denom
printf('m=%g alpha=%g', kb_m, alpha)
end
kb = zeros(size(x));
kb(ii) = f.^kb_m .* besseli(kb_m_bi, alpha*f) / denom;
kb = reale(kb);
%
% optimized shape and order parameters
%
function [alpha, kb_m] = kaiser_bessel_params(alpha, J, K_N)
if streq(alpha, 'best')
if K_N ~= 2
warn 'kaiser_bessel optimized only for K/N=2'
printm 'using good defaults: m=0 and alpha = 2.34*J'
kb_m = 0;
alpha = 2.34 * J;
else
kb_m = 0; % hardwired, because it was nearly the best!
try
s = ['private' filesep 'kaiser,m=0'];
s = load(s);
ii = find(J == s.Jlist);
if isempty(ii)
ii = imin(abs(J - s.Jlist));
warn('J=%d not found, using %d', J, s.Jlist(ii))
end
alpha = J * s.abest.zn(ii);
catch
warn(['could not open file "' s '" so using default alpha = 2.34 J which should be fine.'])
alpha = 2.34 * J;
end
end
else
error 'unknown alpha mode'
end
|
github
|
sunhongfu/scripts-master
|
kaiser_bessel_xray.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/nufft/kaiser_bessel_xray.m
| 2,169 |
utf_8
|
5d1893ab2d3217a9310948fe67ff7453
|
function [proj, J, alpha, kb_m, d] = kaiser_bessel_xray(r, J, alpha, kb_m, d)
%function [proj, J, alpha, kb_m, d] = kaiser_bessel_xray(r, J, alpha, kb_m, d)
%
% X-ray transform of generalized Kaiser-Bessel function,
% See (A7) in lewitt:90:mdi, JOSA-A, Oct. 1990.
%
% in
% r [?] radial locations in projection space (unitless)
%
% options
% J diameter of blob (a = J/2), default 4
% alpha shape parameter, default 10.83
% kb_m order parameter, default 2
% d dimension, default 2
%
% out
% proj [?] x-ray transform values
%
% Copyright 2005-7-29, Jeff Fessler, The University of Michigan
if nargin < 1, help(mfilename), error(mfilename), end
if nargin == 1 && streq(r, 'test'), kaiser_bessel_xray_test, return, end
if ~isvar('J'), J = 4; end
if ~isvar('alpha') | isempty('alpha'), alpha = 10.83; end
if ~isvar('kb_m') | isempty('kb_m'), kb_m = 2; end
if ~isvar('d'), d = 2; end
tol = 1e-4;
%
% trick to yield inline functions
%
if ischar(r)
kernel = sprintf('kaiser_bessel_xray(r, %d, %g, %g, %g)', ...
J, alpha, kb_m, d);
if streq(r, 'string')
proj = kernel;
elseif streq(r, 'inline')
proj = inline(kernel, 'r');
else
error 'bad argument'
end
return
end
%
% Check for validity of FT formula
%
persistent warned
if (kb_m < 0 || (abs(round(kb_m)-kb_m) > eps))
if isempty(warned)
printf([mfilename: 'kb_m=%g in kaiser_bessel_xray()'], kb_m)
printf('validity of formula uncertain')
warned = 1;
end
end
a = J/2;
factor = a / besseli(kb_m, alpha) * sqrt(2*pi/alpha);
root = sqrt(1 - (r/a).^2);
nu = kb_m + 1/2;
proj = factor * root.^nu .* besseli(nu, alpha * root);
proj = reale(proj, tol);
%
% test
%
function kaiser_bessel_xray_test
x = linspace(-2.5,2.5,501)';
y = x;
[xx yy] = ndgrid(x, y);
r = sqrt(xx.^2 + yy.^2);
[proj J kb_m alpha] = kaiser_bessel_xray(x);
dx = x(2) - x(1);
f0 = kaiser_bessel(r, J, kb_m, alpha);
psum = sum(f0,2) * dx;
if im
clf
im(221, x, y, f0, 'blob'), grid
subplot(222)
plot(x, f0(:,y==0)), title 'profile', axis tight
xtick([-2:1.0:2]), grid
subplot(212)
plot(x, proj, '-', x, psum, '--'), axis tight, title 'projection'
legend('Analytical', 'Numerical')
end
max_percent_diff(proj, psum, mfilename)
|
github
|
sunhongfu/scripts-master
|
kaiser_bessel_ft.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/nufft/kaiser_bessel_ft.m
| 2,914 |
utf_8
|
13471fc4abc2633a97527aa5e19431f1
|
function y = kaiser_bessel_ft(u, J, alpha, kb_m, d)
%function y = kaiser_bessel_ft(u, J, alpha, kb_m, d)
%
% Fourier transform of generalized Kaiser-Bessel function,
% in dimension d (default 1).
% shape parameter "alpha" (default 2.34 J)
% order parameter "kb_m" (default 0)
% See (A3) in lewitt:90:mdi, JOSA-A, Oct. 1990.
% in
% u [M,1] frequency arguments
% out
% y [M,1] transform values
%
% Copyright 2001-3-30, Jeff Fessler, The University of Michigan
if nargin < 1, help(mfilename), error(mfilename), end
if nargin == 1 && streq(u, 'test'), kaiser_bessel_ft_test, return, end
if ~isvar('J'), J = 6; end
if ~isvar('alpha') | isempty('alpha'), alpha = 2.34 * J; end
if ~isvar('kb_m') | isempty('kb_m'), kb_m = 0; end
if ~isvar('d'), d = 1; end
%
% trick to yield inline functions
%
if ischar(u)
kernel_ft = sprintf('kaiser_bessel_ft(t, %d, %g, %g, 1)', ...
J, alpha, kb_m);
if streq(u, 'string')
y = kernel_ft;
elseif streq(u, 'inline')
y = inline(kernel_ft, 't');
else
error 'bad argument'
end
return
end
%
% Check for validity of FT formula
%
persistent warned
if (kb_m < -1)
if isempty(warned) % only print this reminder the first time
printf('\nWarning: kb_m=%g < -1 in kaiser_bessel_ft()', kb_m)
printf(' - validity of FT formula uncertain for kb_m < -1\n')
warned = 1;
end
elseif (kb_m < 0) & ((abs(round(kb_m)-kb_m)) > eps)
if isempty(warned) % only print this reminder the first time
printf('\nWarning: Neg NonInt kb_m=%g in kaiser_bessel_ft()', kb_m)
printf(' - validity of FT formula uncertain\n')
warned = 1;
end
end
% trick: simplified since matlab's besselj can handle complex args!
z = sqrt( (2*pi*(J/2)*u).^2 - alpha^2 );
nu = d/2 + kb_m;
y = (2*pi)^(d/2) .* (J/2)^d .* alpha^kb_m ./ besseli(kb_m, alpha) ...
.* besselj(nu, z) ./ z.^nu;
y = reale(y);
% old inefficient way:
%Lambda = gamma(nu+1) * (z/2).^(-nu) .* besselj(nu, z);
%y2 = (1/2)^kb_m * pi^(d/2) * (J/2)^d * alpha^kb_m ...
% .* Lambda ./ gamma(d/2+kb_m+1) ./ besseli(kb_m, alpha);
%
% kaiser_bessel_ft_test
%
function kaiser_bessel_ft_test
J = 5; alpha = 6.8;
N = 2^10;
x = [-N/2:N/2-1]'/N * (J+3)/2;
dx = x(2) - x(1);
du = 1 / N / dx;
u = [-N/2:N/2-1]' * du;
uu = 1.5*linspace(-1,1,201)';
mlist = [-2 0 2 7];
leg = {};
for ii=1:length(mlist)
kb_m = mlist(ii);
yy(:,ii) = kaiser_bessel(x, J, alpha, kb_m);
Yf(:,ii) = reale(fftshift(fft(fftshift(yy(:,ii))))) * dx;
Y(:,ii) = kaiser_bessel_ft(u, J, alpha, kb_m, 1);
Yu(:,ii) = kaiser_bessel_ft(uu, J, alpha, kb_m, 1);
leg{ii} = sprintf('m=%d', kb_m);
end
if 0
plot( u, Yf(:,3), 'cx', u, Y(:,3), 'yo', uu, Yu(:,3), 'y-')
legend('FFT', 'FT coarse', 'FT fine')
axis tight, axisx(range(uu)), grid
return
end
plot( uu, Yu(:,1), 'c-', uu, Yu(:,2), 'y-', ...
uu, Yu(:,3), 'm-', uu, Yu(:,4), 'g-')
axis tight, legend(leg)
hold on, plot(u, Yf(:,2), 'y.'), hold off
xlabel u, ylabel Y(u), titlef('KB FT, \\alpha=%g', alpha)
|
github
|
sunhongfu/scripts-master
|
ifftn_fast.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/nufft/ifftn_fast.m
| 2,149 |
utf_8
|
3749fee0395f552bc7cf2430bba890df
|
function ys = ifftn_fast(xs)
%|function ys = ifftn_fast(xs)
%|
%| For some reason, matlab's ifftn routine is suboptimal
%| for the case of 2D FFTs, at least on some machines.
%| The improvement herein was found by Hugo Shi.
%|
%| Note: matlab's ifft() and ifftn() handle an optional second "N" argument in
%| different ways! So to be safe I am not allowing any second argument here.
%|
%| Copyright 2004-6-28, Jeff Fessler, University of Michigan
if nargin ~= 1, help(mfilename), error(mfilename), return, end
if streq(xs, 'test'), ifftn_fast_test, return, end
% around version 7.4, ifftn was fastest, so hardwire that!
ys = ifftn(xs);
return
if ndims(xs) == 2 % 2D or 1D cases
if min(size(xs)) == 1 % 1D
ys = ifft(xs);
else
ys = ifftn_fast_fftfft(xs);
end
else
ys = ifftn(xs);
end
function ys = ifftn_fast_fftfft(xs)
ys = ifft(ifft(xs).').';
% test configuration of ifftn_fast for this machine
function ifftn_fast_test
ifftn_fast_test2
%ifftn_fast_test3
% test configuration of ifftn_fast for this machine for 2D
function ifftn_fast_test2
n = 2^8;
x = rand(n,n);
printf('starting test; be patient.')
% first loop is to get everything in cache or whatever.
% doing it twice is the only way to get an accurate comparison!
for nloop = [2 40];
tic, for ii=1:nloop, y{1} = ifftn_fast(x); end
tt(1) = toc; ty{1} = 'fftn_fast';
tic, for ii=1:nloop, y{2} = ifftn(x); end
tt(2) = toc; ty{2} = 'fftn';
tic, for ii=1:nloop, y{3} = ifft(ifft(x).').'; end
tt(3) = toc; ty{3} = 'fftfft_inline';
tic, for ii=1:nloop, y{4} = ifft(ifft(x, [], 1), [], 2); end
tt(4) = toc; ty{4} = 'fftfft_brack';
tic, for ii=1:nloop, y{5} = ifft2(x); end
tt(5) = toc; ty{5} = 'ifft2';
tic, for ii=1:nloop, y{6} = ifftn_fast_fftfft(x); end
tt(6) = toc; ty{6} = 'fftfft_func';
end
for ii = 1:length(tt)
printf('time %14s = %g', ty{ii}, tt(ii))
if max_percent_diff(y{1}, y{ii}) > 1e-11, error 'bug', end
end
printf('ifftn / ifftn_fast = %g%% ', tt(2) / tt(1) * 100.)
if tt(1) > 1.40 * min(tt(2:end))
error 'ifftn_fast is configured supoptimally for your machine!'
else
printf('ifftn_fast is configured appropriately for your machine')
end
|
github
|
sunhongfu/scripts-master
|
nufft1_build.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/nufft/nufft1_build.m
| 6,859 |
utf_8
|
1cd441b39294fac147ef52f7458c84b7
|
function st = nufft1_build(J, varargin)
%function st = nufft1_build(J, [option])
% Build 1D LS-NUFFT interpolation coefficients by brute force.
%
% in
% J neighborhood size: [-J/2,J/2]
% option
% om [M,1] frequency locations, if not provided build fine table
% N # of signal values (default: 2^8)
% K # of DFT frequencies (default: 2*N)
% sn [N,1] scaling factors (default: uniform)
% or 'uniform', 'cos', 'gauss', 'kb'='kb:beatty', 'kb:mm'
% wn [N,1] weighting factors (default: uniform)
% type 'kb'='kb:beatty' or 'kb:mm' or default: 'minmax'
% out
% st strum with various data and methods
%
% methods:
% st.eon [M,N] exact exp(1i*omega*n)
% st.kap [M,J] "k" value associated with each interpolator value
% st.approx [M,N] approximation to exp(1i*omega*n)
% st.err [M,1] (weighted) approximation error for each omega
% st.slow1(Fm) [N,1] slow type1 "nufft" of [M,1] spectral data Fm
% data:
% st.uj [M,J] complex interpolator
% st.core [M,1] real interpolator core
%
% Copyright 2006-4-15, Jeff Fessler, The University of Michigan
if nargin == 1 && streq(J, 'test'), nufft1_build_test, return, end
if nargin < 4, help(mfilename), error(mfilename), end
% defaults
st.J = J;
st.N = 2^8;
st.K = [];
st.sn = [];
st.wn = [];
st.om = [];
st.type = '';
st = vararg_pair(st, varargin);
if isempty(st.K), st.K = 2 * st.N; end
if isempty(st.wn), st.wn = ones(st.N,1); end
if isempty(st.type), st.type = 'minmax'; end
st.type = lower(st.type);
if streq(st.type, 'kb'), st.type = 'kb:beatty'; end
if isempty(st.om), error 'empty om not done', end
if isempty(st.sn)
switch lower(st.type)
case {'kb:beatty', 'kb:mm'}
st.sn = st.type;
case 'minmax'
st.sn = ones(st.N,1);
otherwise
error('unknown type "%s", cannot infer sn', st.type)
end
else
if ischar(st.sn)
st.sn = lower(st.sn);
if streq(st.sn, 'kb'), st.sn = 'kb:beatty'; end
end
end
if size(st.om,2) ~= 1, error 'om must be Mx1', end
st = nufft1_build_setup_init(st); % misc and sn
switch st.type
case 'minmax'
st = nufft1_build_setup_mm(st, st.om);
case {'kb:beatty', 'kb:mm'}
st = nufft1_build_setup_kb(st, st.om);
otherwise
error('unknown type "%s"', st.type)
end
meth = {
'approx', @nufft1_build_approx, ...
'eon', @nufft1_build_eon, ...
'kap', @nufft1_build_kap, ...
'err', @nufft1_build_err, ...
'slow1', @nufft1_build_slow1, ...
};
st = strum(st, meth);
%
% nufft1_build_setup_init()
%
function st = nufft1_build_setup_init(st)
st.Nmid = (st.N-1)/2;
st.gam = 2*pi/st.K;
st.nn = [0:st.N-1]';
st.M = length(st.om);
st.koff = nufft_offset(st.om, st.J, st.K);
st = nufft1_build_sn(st);
%
% nufft1_build_setup_kb()
% Conventional KB interpolator, with reasonably optimized parameters.
%
function st = nufft1_build_setup_kb(st, om)
[kb_alf kb_m] = nufft1_build_kb_alf(st, st.type);
J = st.J;
for jj=1:J
otmp = om - st.gam * (st.koff + jj);
st.core(:,jj) = ...
kaiser_bessel(otmp / st.gam, J, kb_alf, kb_m, st.K/st.N);
end
% include linear phase term of the ideal interpolator!
otmp = outer_sum(om-st.gam*st.koff, -st.gam*[1:J]); % [M,J]
lamjo = exp(-1i * st.Nmid * otmp); % [M,J]
%lamjo = exp(-1i * (st.N/2) * otmp); % [M,J] % todo: try wrong midpoint
%lamjo = 1 % exp(-1i * st.Nmid * otmp); % [M,J] % todo: try disregarding phase
st.uj = conj(lamjo) .* st.core;
%
% nufft1_build_setup_mm()
%
function st = nufft1_build_setup_mm(st, om)
J = st.J;
K = st.K;
N = st.N;
M = st.M;
% [J,1] <= [J,N] * [N,1]
st.T = cos(st.gam*[0:J-1]'*(st.nn'-st.Nmid)) * (st.wn .* st.sn.^2);
st.T = toeplitz(st.T); % [J,J]
Joff = (J + rem(J,2)) / 2; % J/2 if even, (J+1)/2 if odd
st.ro = zeros(M,J);
for jj=1:J
otmp = om - st.gam * (st.koff + jj);
st.ro(:,jj) = cos(otmp * (st.nn'-st.Nmid)) * (st.wn .* st.sn); % [M,1]
end
st.core = st.ro * inv(st.T); % [M,J]
otmp = outer_sum(om-st.gam*st.koff, -st.gam*[1:J]); % [M,J]
lamjo = exp(-1i * st.Nmid * otmp); % [M,J]
st.uj = conj(lamjo) .* st.core;
%
% nufft1_build_sn()
% handle default scaling factor types
%
function st = nufft1_build_sn(st)
if ~ischar(st.sn), return, end
tt = (st.nn - st.Nmid) / st.K;
K_N = st.K / st.N;
switch st.sn
case {'', 'uniform'}
st.sn = ones(size(tt));
case {'cos', 'cosine'}
st.sn = 1 ./ cos(pi * tt);
case {'gauss', 'gaussian'}
[sig gauss_kern gauss_ft] = nufft_best_gauss(st.J, K_N, 'ft');
sn_gauss = inline(gauss_ft, 't');
st.sn = 1 ./ sn_gauss(tt);
case {'kb:beatty', 'kb:mm'}
if streq(st.sn, st.type, 3) & ~streq(st.sn, st.type)
warning 'kb type mismatch - are you sure you want this?'
end
[kb_alf kb_m] = nufft1_build_kb_alf(st, st.sn);
st.sn = 1 ./ kaiser_bessel_ft(tt, st.J, kb_alf, kb_m, 1);
otherwise
fail('unknown type "%s"', st.sn)
end
%
% nufft1_build_kb_alf()
% "optimal" alpha from beatty:05:rgr, roughly 2.34 * J for K/N=2 !
%
function [kb_alf, kb_m] = nufft1_build_kb_alf(st, type)
K_N = st.K / st.N;
kb_m = 0;
switch type
case 'kb:beatty'
kb_alf = pi * sqrt( st.J^2 / K_N^2 * (K_N - 1/2)^2 - 0.8 );
case 'kb:mm'
[kb kb_alf kb_m] = kaiser_bessel(0, st.J, 'best', 0, K_N);
otherwise
error 'unknown kb type'
end
% pr kb_alf / J
%
% nufft1_build_kap()
%
function kap = nufft1_build_kap(st)
kap = outer_sum(st.om/st.gam-st.koff, -[1:st.J]); % [M,J]
%
% nufft1_build_eon()
% return the exact exponentials: exp(1i * om * n) [M,N]
%
function eon = nufft1_build_eon(st, varargin)
eon = exp(1i * st.om * st.nn');
eon = eon(varargin{:});
%
% nufft1_build_approx()
% return the NUFFT approximation to exp(1i * om * n) [M,N]
%
function out = nufft1_build_approx(st, varargin)
out = zeros(st.M, st.N);
for jj=1:st.J
uj = st.uj(:,jj);
out = out + repmat(uj, [1 st.N]) ...
.* exp(1i * st.gam * (st.koff + jj) * st.nn');
end
out = out .* repmat(st.sn', [st.M 1]); % [M,N] apply scaling
out = out(varargin{:});
%
% nufft1_build_err()
% return the NUFFT approximation error for each frequency [M,1]
% note: this error is normalized by 1/N
%
function err = nufft1_build_err(st)
err = sqrt(sum(abs(st.eon - st.approx).^2, 2) / st.N);
%
% nufft1_build_slow1()
% a slow but easy to implement "type 1 nufft" of [M,L] data Fm
%
function fn = nufft1_build_slow1(st, Fm)
fn = st.approx.' * Fm; % [N,1] <= [N,M] * [M,L]
%
% nufft1_build_test
%
function nufft1_build_test
N = 2^5;
K = 2*N;
J = 5;
om = linspace(0, 2*pi/K, 101)';
types = {'Uniform', 'Cosine', 'Gaussian', 'KB:mm', 'KB:beatty'};
for it=1:length(types)
type = types{it};
st = nufft1_build(J, 'om', om, 'N', N, 'K', K, ...
'sn', types{it}, 'type', 'minmax');
err(:,it) = st.err;
end
if 1
st = nufft1_build(J, 'om', om, 'N', N, 'K', K, 'type', 'KB:beatty');
err(:,it+1) = st.err;
types{it+1} = 'KB std be';
st = nufft1_build(J, 'om', om, 'N', N, 'K', K, 'type', 'Kb:mm');
err(:,it+2) = st.err;
types{it+2} = 'KB std mm';
end
if im
semilogy(om/st.gam, err), xlabel '\omega/\gamma', ylabel 'E'
axisy(10.^[-J -2])
axisy(10.^[-J 0]) % todo: for trying phase errors
legend(types{:})
end
|
github
|
sunhongfu/scripts-master
|
nufft_scale.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/nufft/nufft_scale.m
| 1,781 |
utf_8
|
478adbf2f70bd98ff5d978defd79cdda
|
function sn = nufft_scale(Nd, Kd, alpha, beta, Nmid)
%function sn = nufft_scale(Nd, Kd, alpha, beta, Nmid)
% Compute scaling factors for NUFFT
% in
% Nd,Kd
% alpha {d}
% beta {d}
% option
% Nmid [d] midpoint: floor(Nd/2) or default (Nd-1)/2
% out
% sn [[Nd]] scaling factors
%
% Copyright 2004-7-8, Jeff Fessler, The University of Michigan
if nargin == 1 && streq(Nd, 'test'), nufft_scale_test, return, end
if nargin < 4, help(mfilename), help(mfilename), error(mfilename), end
if nargin < 5, Nmid = (Nd-1)/2; end
dd = length(Nd);
if dd == 1 & ~iscell(alpha) % 1D case
sn = nufft_scale1(Nd(1), Kd(1), alpha, beta, Nmid(1));
return
end
%
% scaling factors: "outer product" of 1D vectors
%
sn = 1;
for id=1:dd
tmp = nufft_scale1(Nd(id), Kd(id), alpha{id}, beta{id}, Nmid(id));
sn = sn(:) * tmp';
end
if length(Nd) > 1
sn = reshape(sn, Nd); % [(Nd)]
else
sn = sn(:); % [(Nd)]
end
% Compute scaling factors for 1D NUFFT (from Fourier series coefficients)
% in:
% N,K
% alpha
% beta
% out:
% sn [N] scaling factors
%
% Copyright 2001-10-4, Jeff Fessler, The University of Michigan
function sn = nufft_scale1(N, K, alpha, beta, Nmid)
if ~isreal(alpha(1)), error 'need real alpha_0', end
L = length(alpha) - 1;
%
% compute scaling factors from Fourier coefficients
%
if L > 0
sn = zeros(N,1);
n = [0:(N-1)]';
i_gam_n_n0 = 1i * (2*pi/K) * (n - Nmid) * beta;
for l1=-L:L
alf = alpha(abs(l1)+1);
if l1 < 0, alf = conj(alf); end
sn = sn + alf * exp(i_gam_n_n0 * l1);
end
else
sn = alpha * ones(N,1);
end
%
% self test
%
function nufft_scale_test
N = 100;
K = 2*N;
alpha = [1.0 -0.0 -0.2];
sn = nufft_scale(N, K, alpha, 1);
if im
clf, plot(1:N, real(sn), 'y-', 1:N, imag(sn), 'g-')
legend('sn real', 'sn imag')
end
pr minmax(real(sn))
pr minmax(imag(sn))
|
github
|
sunhongfu/scripts-master
|
nufft_sinc.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/nufft/nufft_sinc.m
| 695 |
utf_8
|
e6857ad90712d847152c31e539b33d09
|
function y = nufft_sinc(x)
%|function y = nufft_sinc(x)
%|
%| my version of "sinc" function, because matlab's sinc() is in a toolbox
%|
%| Copyright 2001-12-8, Jeff Fessler, University of Michigan
if nargin < 1, help(mfilename), error(mfilename), end
if streq(x, 'test'), nufft_sinc_test, return, end
iz = find(x == 0); % indices of zero arguments
x(iz) = 1;
y = sin(pi*x) ./ (pi*x);
y(iz) = 1;
% test
function nufft_sinc_test
x = linspace(-4, 4, 2^21+1)';
nufft_sinc(0); % warm up
cpu etic
y1 = nufft_sinc(x);
cpu etoc 'nufft_sinc time'
if 2 == exist('sinc')
sinc(0); % warm up
cpu etic
y2 = sinc(x);
cpu etoc 'matlab sinc time'
jf_equal(y1, y2)
end
if im, plot(x, y1, '-'), end
|
github
|
sunhongfu/scripts-master
|
nufft_diric.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/nufft/nufft_diric.m
| 1,999 |
utf_8
|
271ee48427961a368e4e0f64f481e0c1
|
function f = nufft_diric(k, N, K, use_true_diric)
%|function f = nufft_diric(k, N, K, use_true_diric)
%|
%| "regular fourier" Dirichlet-function WITHOUT phase
%| nufft_diric(t) = sin(pi N t / K) / ( N * sin(pi t / K) )
%| \approx sinc(t / (K/N))
%|
%| caution: matlab's version is different: sin(N * x / 2) / (N * sin(x / 2))
%|
%| caution: nufft_diric() is K-periodic for odd N but 2K-periodic for even N.
%|
%| in
%| k [...] sample locations (unitless real numbers)
%| N signal length
%| K DFT length
%| use_true_diric 1 = use true Diric function.
%| (default is to use sinc approximation)
%| out
%| f [...] corresponding function values
%|
%| Copyright 2001-12-8, Jeff Fessler, University of Michigan
if nargin == 1 && streq(k, 'test'), nufft_diric_test, return, end
if nargin < 3, help(mfilename), error(mfilename), end
if nargin < 4
use_true_diric = false;
end
% diric version
if use_true_diric
t = (pi/K) * k;
f = sin(t);
i = abs(f) > 1e-12; % nonzero denominator
f(i) = sin(N*t(i)) ./ (N * f(i));
f(~i) = sign(cos(t(~i)*(N-1)));
% sinc version
else
f = nufft_sinc(k / (K/N));
end
function nufft_diric_test
kmax = 2 * (10 + 1 * 4);
kf = linspace(-kmax,kmax,201); % fine grid
ki = [-kmax:kmax];
Nlist = [2^3 2^5 2^3-1];
Klist = 2*Nlist; Klist(end) = Nlist(end);
jf pl 3 1
for ii=1:length(Nlist)
N = 0 + Nlist(ii);
K = 0 + Klist(ii);
gf = nufft_diric(kf, N, K, 1);
gi = nufft_diric(ki, N, K, 1);
sf = nufft_diric(kf, N, K);
if exist('diric') == 2 % matlab's diric is in signal toolbox
dm = diric((2*pi/K)*kf,N);
jf_equal(gf, dm)
if ii == 1
printf('max %% difference vs matlab = %g', max_percent_diff(gf,dm))
end
else
dm = zeros(size(kf));
end
jf('sub', ii)
plot(kf, gf, 'y-', kf, sf, 'c-', kf, dm, 'r--', ki, gi, 'y.')
axis tight
if ii==1, xtick([-1 -0.5 0 0.5 1]*K), end
legend('nufft diric', 'sinc', 'matlab diric')
xlabel k, ylabel diric(k)
printf('max %% difference vs sinc = %g', max_percent_diff(gf,sf))
titlef('N = %d, K = %d', N, K)
end
|
github
|
sunhongfu/scripts-master
|
dtft_adj.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/nufft/dtft_adj.m
| 2,511 |
utf_8
|
6c948619bad55598699158ec924d0363
|
function x = dtft_adj(X, omega, Nd, n_shift, useloop)
%|function x = dtft_adj(X, omega, Nd, n_shift, useloop)
%| Compute adjoint of d-dim DTFT for spectrum X at frequency locations omega
%| in
%| X [M L] dD DTFT values
%| omega [M d] frequency locations (radians)
%| n_shift [d 1] use [0:N-1]-n_shift (default [0 ... 0])
%| useloop 1 to reduce memory use (slower)
%| out
%| x [(Nd) L] signal values
%|
%| Requires enough memory to store M * (*Nd) size matrices. (For testing only.)
%|
%| Copyright 2003-4-13, Jeff Fessler, University of Michigan
% if no arguments, then run a simple test
if nargin < 2
help(mfilename)
Nd = [4 6 5];
n_shift = [2 1 3];
n_shift = 0*[2 1 3];
% test with uniform frequency locations:
o1 = 2*pi*[0:(Nd(1)-1)]'/Nd(1);
o2 = 2*pi*[0:(Nd(2)-1)]'/Nd(2);
o3 = 2*pi*[0:(Nd(3)-1)]'/Nd(3);
[o1 o2 o3] = ndgrid(o1, o2, o3);
X = o1 + o2 - o3; % test spectrum
om = [o1(:) o2(:) o3(:)];
xd = dtft_adj(X(:), om, Nd, n_shift);
xl = dtft_adj(X(:), om, Nd, n_shift, 1);
printm('loop max %% difference = %g', max_percent_diff(xl,xd))
Xp = X .* reshape(exp(-1i * om * n_shift(:)), size(X));
xf = ifftn(Xp) * prod(Nd);
printm('ifft max %% difference = %g', max_percent_diff(xf,xd))
return
end
if ~isvar('n_shift') | isempty(n_shift), n_shift = zeros(size(Nd)); end
if ~isvar('useloop') | isempty(useloop), useloop = 0; end
if length(Nd) == 1
nn{1} = [0:(Nd(1)-1)] - n_shift(1);
elseif length(Nd) == 2
nn{1} = [0:(Nd(1)-1)] - n_shift(1);
nn{2} = [0:(Nd(2)-1)] - n_shift(2);
[nn{1} nn{2}] = ndgrid(nn{1}, nn{2});
elseif length(Nd) == 3
nn{1} = [0:(Nd(1)-1)] - n_shift(1);
nn{2} = [0:(Nd(2)-1)] - n_shift(2);
nn{3} = [0:(Nd(3)-1)] - n_shift(3);
[nn{1} nn{2} nn{3}] = ndgrid(nn{1}, nn{2}, nn{3});
else
'only 1D-3D done'
end
%
% loop way: slower but less memory
%
if useloop
for id = (length(Nd)+1):3
nn{id} = 0;
end
M = length(omega);
x = zeros([Nd ncol(X)]); % [(Nd) M]
for mm=1:M
t = omega(mm,1)*nn{1} + omega(mm,2)*nn{2} + omega(mm,3)*nn{3};
x = x + exp(1i*t) * X(mm,:);
end
else
x = nn{1}(:) * omega(:,1)';
for id = 2:length(Nd)
x = x + nn{id}(:) * omega(:,id)';
end
x = exp(1i*x) * X; % [(*Nd) L]
x = reshape(x, [Nd numel(x)/prod(Nd)]); % [(Nd) L]
end
% outer_prod()
% this generalizes z = y * x.' to higher dimensions
% in
% y [N1,...,Nd]
% x [M]
% out
% z [N1,...,Nd,M]
function z = outer_prod(y, x)
if isempty(y)
z = x(:);
elseif size(y,2) == 1
z = y * x(:).';
else
z = y(:) * x(:).';
dd = [size(y) length(x)];
z = reshape(z, dd);
end
|
github
|
sunhongfu/scripts-master
|
interp1_table1_import.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/nufft/table/interp1_table1_import.m
| 413 |
utf_8
|
0e4818f872ba8ea210db56495b187e58
|
function interp1_table1_import
libname = 'interp1_table1.a';
type11r = ['double[K1] r_ck, double[K1] i_ck, int32 K1, ' ...
'double[J1*L1+1] r_h1, int32 J1, int32 L1, ' ...
'double[M] p_tm, int32 M, double[M] &r_fm, double[M] &i_fm'];
myimport(libname, 'interp1_table1_real_per', 'void', type11r);
function myimport(libname, name, type_return, type_call)
import(libname, name, name, type_return, type_call);
|
github
|
sunhongfu/scripts-master
|
nufft_interp_zn.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/nufft/private/nufft_interp_zn.m
| 2,194 |
utf_8
|
19b50f0ee43faa6a8824265f0516a25a
|
function zn = nufft_interp_zn(alist, N, J, K, func, Nmid)
%|function zn = nufft_interp_zn(alist, N, J, K, func, Nmid)
%| compute the "zn" terms for a conventional "shift-invariant" interpolator
%| as described in T-SP paper. needed for error analysis and for user-
%| defined kernels since i don't provide a means to put in an analytical
%| Fourier transform for such kernels.
%|
%| in
%| alist [M] omega / gamma (fractions) in [0,1)
%| func func(k,J) support limited to [-J/2,J/2)
%| interpolator should not include the linear
%| phase term. this routine provides it.
%| option
%| Nmid [1] midpoint: floor(N/2) or default: (N-1)/2
%| out
%| zn [N,M] reciprocal of scaling factors
%|
%| Copyright 2001-12-11, Jeff Fessler, University of Michigan
%|
%| zn = \sum_{j=-J/2}^{J/2-1} exp(i gam (alf - j) * n) F1(alf - j)
%| = \sum_{j=-J/2}^{J/2-1} exp(i gam (alf - j) * (n-Nmid)) F0(alf - j)
%|
if nargin == 1 && streq(alist, 'test'), nufft_interp_zn_test, return, end
if nargin < 5, help(mfilename), error(mfilename), end
if nargin < 6
Nmid = (N-1)/2; % default: old version
end
gam = 2*pi/K;
if any(alist < 0 | alist > 1), warning 'alist exceeds [0,1]', end
% natural phase function. trick: force it to be 2pi periodic
%Pfunc = inline('exp(-i * mod0(om,2*pi) * (N-1)/2)', 'om', 'N');
if ~rem(J,2) % even
jlist = [(-J/2+1):J/2]';
else % odd
jlist = [-(J-1)/2:(J-1)/2]';
alist(alist > 0.5) = 1 - alist(alist > 0.5); % force symmetry!
end
n0 = [0:(N-1)]' - Nmid; % include effect of phase shift!
[nn0, jj] = ndgrid(n0, jlist); % [N,J]
zn = zeros(N, length(alist));
for ia=1:length(alist)
alf = alist(ia);
jarg = alf - jj; % [N,J]
e = exp(1i * gam * jarg .* nn0); % [N,J]
F = func(jarg, J); % [N,J]
zn(:,ia) = sum(F .* e, 2); % [N]
end
function nufft_interp_zn_test
alist = [0:19]/20;
N = 2^7;
K = 2 * N;
% linear
J = 4;
func = '(1 - abs(k/(J/2))) .* (abs(k) < J/2)';
func = inline(func, 'k', 'J');
z = nufft_interp_zn(alist, N, J, K, func);
% plot interpolator
k = linspace(-J/2-1, J/2+1, 101);
clf, jf pl 1 3
jf sub 1, plot(k, func(k, J))
xlabel k, ylabel F_0(k), axis tight
jf sub 2, plot(1:N, real(z)), axis tight
jf sub 3, plot(1:N, imag(z)), axis tight
|
github
|
sunhongfu/scripts-master
|
newfft_approx_for.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/nufft/private/newfft_approx_for.m
| 1,794 |
utf_8
|
9f6f995e5bc3c9e4502d112ffc5c7b8c
|
function X = newfft_approx_for(st, x, om)
%|function X = newfft_approx_for(st, x, om)
%| (approximate) forward NUFFT
Nd = st.Nd;
Kd = st.Kd;
dims = size(x);
dd = length(Nd);
if ndims(x) < dd, error 'input signal has too few dimensions', end
if any(dims(1:dd) ~= Nd), error 'input signal has wrong size', end
%
% the usual case is where L=1, i.e., there is just one input signal.
%
if ndims1(x) == dd
x = x .* st.sn; % apply scaling factors
Xk = col(fftn_fast(x, Kd)); % [*Kd] oversampled FFT, padded at end
%
% otherwise, collapse all excess dimensions into just one
%
else
xx = reshape(x, [prod(Nd) prod(dims((dd+1):end))]); % [*Nd,*L]
L = size(xx, 2);
Xk = zeros(prod(Kd),L); % [*Kd,*L]
for ll=1:L
xl = reshape(xx(:,ll), [Nd 1]); % l'th signal
xl = xl .* st.sn; % scaling factors
Xk(:,ll) = col(fftn_fast(xl, [Kd 1]));
end
end
if ~isempty(st.phase_before)
Xk = Xk .* repmat(st.phase_before(:), ncol(Xk));
end
%
% interpolate using precomputed sparse matrix or table
%
if isfield(st, 'interp_for') % table or other functional method
if ~isvar('om') || isempty(om)
om = st.om;
end
if isempty(om), error 'om or st.om required', end
X = st.interp_for(Xk, om);
else
if isvar('om') && ~isempty(om) && ~isequal(om, st.om)
error 'om given that does not match st.om'
end
X = st.p * Xk; % [M,*L]
end
if ndims1(x) > dd
M = size(om,1);
X = reshape(X, [M dims((dd+1):end)]); % [M,(L)]
end
if isfield(st, 'phase_after') && ~isempty(st.phase_after)
if isnumeric(st.phase_after)
X = X .* repmat(st.phase_after, ncol(X));
else
phase = st.phase_after(om);
X = X .* repmat(phase, ncol(X));
end
end
%
% ndims1()
% variant of ndims() that returns "1" if x has size [N,1]
%
function nd = ndims1(x)
nd = ndims(x);
if nd == 2 && size(x,2) == 1
nd = 1;
end
|
github
|
sunhongfu/scripts-master
|
newfft_table_init.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/nufft/private/newfft_table_init.m
| 5,809 |
utf_8
|
7d5daa487f47227d1e7c4f7aa4d09e1f
|
function st = newfft_table_init(st, varargin)
%|function st = newfft_table_init(st, varargin)
%|
%| Initialize structure for d-dimension NUFFT using table-based interpolator,
%| This should be called only by newfft for its 'table0' or 'table1' mode!
%| Note: default oversample factor is 2^11 or 2^13
%|
%| in
%| st structure initialized in newfft.m
%| uses st.phasing to choose complex or real kernel
%|
%| option
%| 'how' char 'slow' | 'ratio' | 'fast'
%| (default depends on kernel type)
%|
%| out
%| st strum (see newfft)
%|
%| Copyright 2008-7-11, Jeff Fessler, University of Michigan
if nargin < 1, help(mfilename), error(mfilename), end
arg.how = '';
arg = vararg_pair(arg, varargin);
if isempty(arg.how)
if streq(st.ktype, 'kb:', 3) % todo: others?
arg.how = 'ratio';
else
arg.how = 'fast';
end
end
st.phase_shift = []; % compute on-the-fly
Nd = st.Nd;
Jd = st.Jd;
Kd = st.Kd;
dd = length(Nd);
Ld = st.oversample;
if isempty(Ld)
switch st.mode
case 'table0'
st.order = 0; % 0th order
Ld = 2^11; % default
case 'table1'
st.order = 1; % 1st order
Ld = 2^9; % default
otherwise
fail 'bad mode'
end
end
% dimensionality of input space (usually 2 or 3)
if dd > 1 & length(Ld) == 1
Ld = repmat(Ld, [1 dd]); % allow scalar L to be used for all dimensions
end
st.oversample = Ld;
st.Ld = Ld;
if dd ~= length(Jd) | dd ~= length(Kd) | dd ~= length(Ld)
whos
error 'inconsistent dim'
end
% desired scaling factors, using fake omega=[0]
ktype_args = {'ktype', st.ktype}; % user's interpolator
if ~isempty(st.kb_m)
ktype_args = {ktype_args{:}, 'kb_m', st.kb_m, 'kb_alf', st.kb_alf};
elseif ~isempty(st.alpha)
ktype_args = {ktype_args{:}, 'alpha', st.alpha, 'beta', st.beta};
end
tmp = newfft(zeros(size(Nd)), st.Nd, 'Jd', st.Jd, 'Kd', st.Kd, ...
'n_shift', 0*st.n_shift, ktype_args{:}, 'mode', 'sparse', ...
'phasing', st.phasing);
st.sn = tmp.sn;
if streq(st.phasing, 'flipreal')
iseven = @(n) mod(n,2) == 0;
st.flips = iseven(st.Nd); % [1,dd]
end
%
% 1D tables for each dimension
%
for id = 1:dd
ktype_args = {'ktype', st.ktype}; ... % user's interpolator
if ~isempty(st.kb_m)
ktype_args = {ktype_args{:}, ...
'kb_m', st.kb_m(id), 'kb_alf', st.kb_alf(id)};
elseif ~isempty(st.alpha)
ktype_args = {ktype_args{:}, ...
'alpha', {st.alpha{id}}, 'beta', {st.beta{id}}};
end
make_args = {Nd(id), Jd(id), Kd(id), Ld(id), ktype_args, st.phasing};
st.h{id} = newfft_table_make(arg.how, make_args{:});
if 0 % test fast vs slow
[h0 t0] = newfft_table_make('slow', make_args{:});
h = st.h{id};
jf plc 2 2
jf sub 1, plot(t0, real(h0), 'c-', t0, real(h), 'y.')
jf sub 2, plot(t0, real(h0-h), 'y.')
jf sub 3, plot(t0, imag(h0), 'c-', t0, imag(h), 'y.')
jf sub 4, plot(t0, imag(h0-h), 'y.')
max_percent_diff(h0, h)
prompt
end
switch st.phasing
case 'complex'
if isreal(st.h{id})
warn 'real kernel?'
% st.h{id} = complex(st.h{id});
end
case {'real', 'flipreal', 'none'}
if ~isreal(st.h{id})
fail 'nonreal kernel bug'
end
otherwise
error bug
end
end
st = strum(st, { ...
'fft', @newfft_approx_for, '(x, [om])';
'adj', @newfft_approx_adj, '(X, [om])';
'interp_for', @newfft_table_for, '(Xk, [om])';
'interp_adj', @newfft_table_adj, '(Xk, [om])';
'plot', @newfft_table_plot, '()';
});
%
% newfft_table_make()
%
function [h, t0] = newfft_table_make(how, N, J, K, L, ktype_args, phasing)
if streq(phasing, 'flipreal')
phasing = 'none'; % trick: get pure real kernel (with no sign flips)
end
% note: if phasing is already 'real' then keep it that way!
mode_args = {'mode', 'sparse', 'Jd', J, 'n_shift', 0, 'phasing', phasing};
t0 = [-J*L/2:J*L/2]' / L; % [J*L+1]
switch how
% This is a slow and inefficient (but simple) way to get the table
% because it builds a huge sparse matrix but only uses 1 column!
case 'slow'
om0 = t0 * 2*pi/K; % gam
s1 = newfft(om0, N, 'Kd', K, ktype_args{:}, mode_args{:});
h = full(s1.p(:,1));
% This way is "J times faster" than the slow way, but still not ideal.
% It works for any user-specified interpolator.
case 'fast'
t1 = J/2-1 + [0:(L-1)]' / L; % [L]
om1 = t1 * 2*pi/K; % * gam
s1 = newfft(om1, N, 'Kd', K, ktype_args{:}, mode_args{:});
h = col(full(s1.p(:,J:-1:1))); % [J*L+0]
% h = [h; 0]; % [J*L+1]
h = [h; h(1)]; % [J*L+1] - assuming symmetric
% This efficient way uses only "J" columns of sparse matrix!
% The trick to this is to use fake small values for N and K,
% which works for interpolators that depend only on the ratio K/N.
case 'ratio' % e.g., 'minmax:kb' | 'kb:*'
Nfake = J;
Kfake = Nfake * K/N;
t1 = J/2-1 + [0:(L-1)]' / L; % [L]
om1 = t1 * 2*pi/Kfake; % "gam"
s1 = newfft(om1, Nfake, 'Kd', Kfake, ktype_args{:}, mode_args{:});
h = col(full(s1.p(:,J:-1:1))); % [J*L+0]
% h = [h; 0]; % [J*L+1]
h = [h; h(1)]; % [J*L+1] assuming symmetric
if streq(phasing, 'complex')
h = h .* exp(1i * pi * t0 * (1/K - 1/Kfake)); % fix phase
end
otherwise
fail('bad type %s', how)
end
%
% newfft_table_plot()
%
function newfft_table_plot(st)
color = 'cym';
arg = {};
for id = 1:st.dd
J = st.Jd(id);
L = st.Ld(id);
t0 = [-J*L/2:J*L/2]' / L; % [J*L+1]
arg = {arg{:}, t0, real(st.h{id}), [color(id) '-']};
arg = {arg{:}, t0, imag(st.h{id}), [color(id) '--']};
end
plot(arg{:})
%
% newfft_table_for()
%
function X = newfft_table_for(st, Xk, om)
if ~isvar('om') || isempty(om)
om = st.om;
end
if isempty(om)
fail 'need om or st.om'
end
if st.dd ~= size(om,2), fail('omega needs %d columns', dd), end
X = nufft_table_interp(st, Xk, st.order, st.flips, om);
%
% newfft_exact_adj()
%
function Xk = newfft_table_adj(st, X, om)
if ~isvar('om') || isempty(om)
om = st.om;
end
if isempty(om)
fail 'need om or st.om'
end
if st.dd ~= size(om,2), fail('omega needs %d columns', dd), end
Xk = nufft_table_adj(st, X, st.order, st.flips, om);
|
github
|
sunhongfu/scripts-master
|
nufft_offset.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/nufft/private/nufft_offset.m
| 1,160 |
utf_8
|
484e73add0ea3fc089c87836e367f318
|
function k0 = nufft_offset(om, J, K)
%|function k0 = nufft_offset(om, J, K)
%| offset for NUFFT
%| in
%| om [M,1] omega (radians), typically in [-pi, pi) (not essential!)
%| J # of neighbors used for NUFFT interpolation
%| K FFT size
%|
%| out
%| k0 [M,1] prepared for mod(k0 + [1:J], K) (+ 1 for matlab)
%|
%| Copyright 2000-1-9, Jeff Fessler, University of Michigan
if nargin < 3, help(mfilename), error(mfilename), end
gam = 2*pi/K;
k0 = floor(om / gam - J/2); % new way
return
% old way:
if mod(J,2) % odd J
k0 = round(om / gam) - (J+1)/2;
else % even J
k0 = floor(om / gam) - J/2;
end
% compare old and new version of nufft_offset
% they match perfectly for even J
% they match for odd J too for nonnegative arguments,
% but do not match at -0.5, -1.5, etc., because round()
% rounds *away* from zero which means rounding up for
% positive arguments but rounding down for negative arguments.
function nufft_offset_test
for J=3:4
x = linspace(-4,4,81);
% old way
if mod(J,2) % odd J
y = round(x) - (J+1)/2;
else % even J
y = floor(x) - J/2;
end
% new way
z = floor(x - J/2);
plot(x, y, 'c.', x, z, 'yo')
pr x(find(z ~= y))
end
|
github
|
sunhongfu/scripts-master
|
nufft2_bilinear.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/nufft/archive/nufft2_bilinear.m
| 3,187 |
utf_8
|
ea5b3bd8bd47648f7f1c97dcfd1dd051
|
function X = nufft2_bilinear(omega, x, K1, K2, n_shift)
%function X = nufft2_bilinear(omega, x, K1, K2, n_shift)
% in:
% omega [M 2] frequencies in radians
% x [N1 N2] image dimensions
% J # of neighbors used
% K1,K2 FFT sizes (should be > N1,N2)
% n_shift [2] n = 0-n_shift to N-1-n_shift
% out:
% X [M 1] DTFT2 at omega, approximated by bilinear interp
%
% Like fft(), this expects the signals to be x(0,0), ...
% Use n_shift = [N1/2 N2/2] for x(-N1/2,-N2/2), ...
%
% Copyright 2001-9-20, Jeff Fessler, University of Michigan
warn('This function is obsolete. Use nufft_init with the "linear" option')
% if no arguments, then run a simple test
if nargin < 1
N1 = 4;
N2 = 8;
n_shift = [2.7 3.3];
x = [[1:N1]'*ones(1,3), ones(N1,N2-3)]; % test signal
% x = zeros(N1,N2); x(1,1) = 1;
if 0 % test with uniform frequency locations
o1 = 2 * pi * [0:(N1-1)]' / N1;
o2 = 2 * pi * [0:(N2-1)]' / N2;
[o1, o2] = ndgrid(o1, o2);
omega = [o1(:) o2(:)];
else % nonuniform frequencies
o1 = [0 7.2 2.6 3.3]';
o2 = [0 4.2 -1 5.5]';
omega = [o1(:) o2(:)];
end
Xd = dtft2(x, omega, n_shift);
Xb = nufft2_bilinear(omega, x, 2*N1, 2*N2, n_shift);
% Xb = reshape(Xb, N1, N2)
% disp([Xd Xb Xb-Xd])
help(mfilename)
disp(sprintf('max %% difference = %g', max_percent_diff(Xd,Xb)))
return
end
if ~isvar('n_shift') | isempty(n_shift), n_shift = [0 0]; end
if ~isvar('useloop') | isempty(useloop), useloop = 0; end
M = size(omega,1);
[N1 N2] = size(x);
koff1 = bilinear_offset(omega(:,1), K1); % [M 1] nearest
koff2 = bilinear_offset(omega(:,2), K2); % [M 1] nearest
% indices into oversampled FFT components
k1 = mod(outer_sum(koff1, [0 1]), K1) + 1; % [M 2] {1,...,K1}
k2 = mod(outer_sum(koff2, [0 1]), K2) + 1; % [M 2] {1,...,K2}
% 1D interpolation coefficient vectors
[u1l u1r] = interp_coef(omega(:,1), koff1, K1, N1); % [M 1]
[u2l u2r] = interp_coef(omega(:,2), koff2, K2, N2); % [M 1]
% precorrect for bilinear interpolation filtering
if 0
warning 'applying precorrection'
[i1, i2] = ndgrid([0:(N1-1)]-n_shift(1), [0:(N2-1)]-n_shift(2));
tmp = (nufft_sinc(i1 / K1) .* nufft_sinc(i2 / K2)).^2;
printm('sinc correction min=%g', min(tmp(:)))
x = x ./ tmp;
end
% FFT and bilinear interpolation
% can't use interp2 here because we want periodic end conditions!
% oh, maybe i could with a little padding of ends...
Xk = fft2(x, K1, K2);
kk11 = k1(:,1) + (k2(:,1) - 1) * K1;
kk21 = k1(:,2) + (k2(:,1) - 1) * K1;
kk12 = k1(:,1) + (k2(:,2) - 1) * K1;
kk22 = k1(:,2) + (k2(:,2) - 1) * K1;
t1 = u1l .* Xk(kk11) + u1r .* Xk(kk21);
t2 = u1l .* Xk(kk12) + u1r .* Xk(kk22);
X = u2l .* t1 + u2r .* t2;
% apply phase shift
phase = exp(i * (omega * n_shift(:))); % [M 1]
X = X .* phase;
% index from 0 to K-1 (will modulo later)
function koff = bilinear_offset(om, K)
gam = 2*pi/K;
koff = floor(om / gam);
% make 1D interpolation coefficient vectors
function [ul, ur] = interp_coef(om, koff, K, N)
gam = 2*pi/K;
ul = 1 - (om/gam - koff);
ur = 1 - ul;
ul = ul .* kphase(om - koff * gam, N);
ur = ur .* kphase(om - (koff+1) * gam, N);
% natural phase function. trick: force it to be 2pi periodic
function ph = kphase(om, N)
ph = exp(-i * mod0(om,2*pi) * (N-1)/2);
|
github
|
sunhongfu/scripts-master
|
montager.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/graph/montager.m
| 1,486 |
utf_8
|
56c813a7853447d57d7757288a423902
|
function xo = montager(xi, varargin)
%|function xo = montager(xi, varargin)
%|
%| Make montage or mosaic of set of images.
%|
%| in
%| xi [3d or 4d] set of images
%|
%| options
%| 'col' # of cols
%| 'row' # of rows
%| 'aspect' aspect ratio (default 1.2)
%|
%| out
%| xo [2d] 3d or 4d images arrange a as a 2d rectangular montage
%|
%| Copyright 1997, Jeff Fessler, University of Michigan
if nargin < 1, help(mfilename), error(mfilename), end
if nargin == 1 & streq(xi, 'test'), montager_test, return, end
arg.aspect = 1.2; % trick: default 1.2/1 aspect ratio
arg.col = [];
arg.row = [];
arg.chat = 0;
arg = vararg_pair(arg, varargin);
dims = size(xi);
nx = dims(1);
ny = dims(2);
nz = prod(dims(3:end));
if ndims(xi) > 3
xi = reshape(xi, [nx ny nz]);
end
if isempty(arg.col)
if isempty(arg.row)
if ndims(xi) == 4
arg.col = n3;
elseif nx == ny && nz == round(sqrt(nz)).^2 % perfect square
arg.col = round(sqrt(nz));
else
arg.col = ceil(sqrt(nz * ny / nx * arg.aspect));
end
else
arg.col = ceil(nz / arg.row);
end
end
if isempty(arg.row)
arg.row = ceil(nz / arg.col);
end
if arg.chat
pr [arg.row arg.col]
end
xo = zeros(nx * arg.col, ny * arg.row);
for iz=0:(nz-1)
iy = floor(iz / arg.col);
ix = iz - iy * arg.col;
xo([1:nx]+ix*nx, [1:ny]+iy*ny) = xi(:,:,iz+1);
end
%
% montager_test()
%
function montager_test
t = [20 30 5];
%t = [224 4422 8];
t = reshape([1:prod(t)], t);
im plc 1 2
im(1, montager(t, 'chat', 0))
im(2, montager(t, 'row', 4))
|
github
|
sunhongfu/scripts-master
|
slicer3.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/graph/slicer3.m
| 1,429 |
utf_8
|
f975ace030ccb2102007d5c425a50c64
|
function slicer3(vol, varargin)
%function slicer3(vol, varargin)
% show transaxial, coronal, and saggital slices of a 3D volume
% in
% vol [nx,ny,nz] 3d image volume
% option
% 'how' 'c|cent|center|max'
% 'args' {} for im(..., args{:})
% 'clim' [2] color limits
%
% Copyright 2007-1-28, Jeff Fessler, The University of Michigan
if nargin < 1, help(mfilename), error(mfilename), end
if nargin == 1 && streq(vol, 'test'), slicer3_test, return, end
arg.how = 'center';
arg.clim = [];
arg.args = {'cbar'};
arg = vararg_pair(arg, varargin);
[nx ny nz] = size(vol);
switch arg.how
case {'c', 'cent', 'center'}
% position of center point (where 3 planes intersect)
cx = round((nx+1)/2);
cy = round((ny+1)/2);
cz = round((nz+1)/2);
case 'max'
tmp = imax(vol, 3);
[cx cy cz] = deal(tmp(1), tmp(2), tmp(3));
otherwise
fail('bad arg.how "%s"', arg.how)
end
if ~isempty(arg.clim)
arg.args = {arg.args{:}, arg.clim};
end
im clf
im pl 2 2
im(1, vol(:,:,cz), sprintf('Transaxial, cz=%g', cz), arg.args{:})
im(2, vol(:,cy,:), sprintf('Coronal?, cy=%g', cy), arg.args{:})
im(3, vol(cx,:,:), sprintf('Sagital?, cx=%g', cx), arg.args{:})
%
% slicer3_test
%
function slicer3_test
ig = image_geom('nx', 2^6, 'ny', 2^6-2, 'nz', 2^5, 'fov', 240, 'zfov', 90);
vol = ellipsoid_im(ig, [], 'oversample', 2);
clim = [0.98 1.05];
% clf, im(vol, clim), cbar
slicer3(vol, 'args', {'cbar'}, 'clim', clim, 'how', 'c')
im(4, vol, clim), cbar
|
github
|
sunhongfu/scripts-master
|
cbar.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/graph/cbar.m
| 5,199 |
utf_8
|
4a691eb6a64ad37fb694f841a53e44db
|
function hh = cbar(varargin)
%|function hh = cbar(varargin)
%|
%| colorbar with options
%| 'h' 'horiz' horizontal
%| 'v' 'vert' vertical
%| 'below' horizontal colorbar below current plot (jf)
%| 'hide' make room for it, but hide it (invisible)
%| 'fSIZE' font size
%| 1d-array ytick
%| 'notick' disable tick marks
%|
%| Copyright 2007, Jeff Fessler, University of Michigan
if nargin == 1 && streq(varargin{1}, 'test'), cbar_test, return, end
if isfreemat
return % freemat 3.6 colorbar does not work with subplot
end
if ~im('ison')
% disp 'im disabled'
return
end
%
% handle state of display or not
%
persistent Display
if ~isvar('Display') || isempty(Display)
Display = true;
end
st.dotick = 1;
st.ytick = [];
st.orient = [];
st.fontsize = [];
st.new = 0;
st.label = '';
while length(varargin)
arg = varargin{1};
if streq(arg, 'on')
Display = true;
printm 'enabling cbar'
return
elseif streq(arg, 'off')
Display = false;
printm 'disabling cbar'
return
%
% new
%
elseif streq(arg, 'new')
st.new = 1;
%
% notick
%
elseif streq(arg, 'notick')
st.dotick = 0;
%
% ytick
%
elseif isa(arg, 'double')
st.ytick = arg;
%
% 'h' or 'horiz' for horizontal
%
elseif ischar(arg) & streq(arg, 'h') | streq(arg, 'horiz')
if (is_pre_v7)
st.orient = 'horiz';
else
st.orient = 'horiz';
% colorbar horiz; return % fixed
end
%
% 'v' or 'vert' for vertical
%
elseif ischar(arg) & streq(arg, 'v') | streq(arg, 'vert')
st.orient = [];
%
% 'below'
%
elseif ischar(arg) & streq(arg, 'below')
st.orient = 'below';
%
% 'hide'
%
elseif ischar(arg) & streq(arg, 'hide')
set(colorbar, 'ytick', [], 'visible', 'off')
return
%
% 'fSIZE'
%
elseif ischar(arg) & streq(arg, 'f', 1)
st.fontsize = sscanf(arg, 'f%d');
else
if ischar(arg) && isempty(st.label)
st.label = arg;
else
error 'arg'
end
end
varargin = {varargin{2:end}};
end
clear arg
if ~Display
return
end
if isempty(get(gcf, 'children'))
warn 'no figure children?'
help(mfilename)
return
end
% explore new way
if st.new
ha = gca;
% get(ha)
hi = get(ha, 'children');
hi = hi(end); % for pre_v7
% get(hi)
dat = get(hi, 'cdata');
clim = get(ha, 'clim');
[nv nh] = size(dat);
if streq(st.orient, 'below')
error 'not done'
else
arg.npad = ceil(0.08*nh);
arg.nramp = ceil(0.1*nh);
arg.padv = 0;
ramp = linspace(clim(1), clim(2), nv)';
ramp = flipud(ramp);
dat(:,end+[1:arg.npad]) = arg.padv;
dat(:,end+[1:arg.nramp]) = repmat(ramp, 1, arg.nramp);
end
set(hi, 'cdata', dat)
% get(hi)
nh = size(dat,2);
set(ha, 'xlim', [0.5 nh+0.5])
xlim = get(ha, 'xlim');
ylim = get(ha, 'ylim');
text(1.05*xlim(2), ylim(2), sprintf('%g', clim(1)))
text(1.05*xlim(2), ylim(1), sprintf('%g', clim(2)))
% set(ha, 'xlim', [0.5 size(dat,2)+0.5+arg.npad+arg.nramp])
% minmax(dat)
% axis off
if ~isempty(st.label)
text(1.05*xlim(2), mean(ylim(1:2)), st.label)
end
return
end
if isempty(st.orient)
h = colorbar;
elseif ~streq(st.orient, 'below')
h = colorbar(st.orient);
else
h = cbar_below;
st.orient = 'horiz';
end
if streq(st.orient, 'horiz')
xtick = st.ytick;
if isempty(xtick)
xtick = get(gca, 'clim');
if xtick(2) > 100
xtick(2) = floor(xtick(2));
end
end
else
if isempty(st.ytick)
% st.ytick = get(h, 'ytick');
% st.ytick = st.ytick([1 end]);
clim0 = get(gca, 'clim');
clim1 = clim0;
if clim1(2) > 100
clim1(2) = floor(clim1(2));
end
% truncate to 3 digits of precision:
st.ytick = truncate_precision(clim1, 3);
% todo: this loses the bottom label sometimes, by rounding down ...
end
end
if st.dotick
if streq(st.orient, 'horiz')
set(h, 'xtick', xtick)
else
if is_pre_v7
set(h, 'ytick', st.ytick)
elseif 0 % disabled because not working
% trick: for v7, move ticks in slightly
yticks = num2str(st.ytick');
ytick = st.ytick + [1 -1] * 0.005 * diff(st.ytick);
if 0 && length(ytick) == 2 % kludge:
tmp1 = get(h, 'yticklabel');
tmp2 = strvcat(yticks, tmp1);
yticks = tmp2([1 4:end-1 2], :);
yticks(2:end-1,:) = ' ';
set(h, 'yticklabel', yticks)
else % this way should work but has had problems:
% set(h, 'fontsize', 7)
set(h, ...
'YTickMode', 'manual', ...
'Ytick', ytick, ...
'YTickLabelMode', 'manual', ...
'YtickLabel', yticks)
end
end
end
else
set(h, 'ytick', [])
end
if ~isempty(st.fontsize)
set(h, 'fontsize', st.fontsize)
end
if ~isempty(st.label)
xlim = get(h, 'xlim'); % [-0.5 1.5]
ylim = get(h, 'ylim');
htmp = gca;
axes(h)
text(2.2, mean(ylim), st.label, ...
'rotation', 90, ...
'verticalalign', 'top', ...
'horizontalalign', 'center')
% ylabel(label)
% [x y] = ginput(1)
axes(htmp) % return current axis to image
end
if nargout
hh = h;
end
function h = cbar_below(vfrac)
pos = get(gca, 'position');
clim = get(gca, 'clim');
h = pos(4);
pos(2) = pos(2) - 0.11 * h;
pos(4) = 0.1 * h;
axes('position', pos)
x = linspace(clim(1),clim(2),101);
y = 1:10;
im(x, y, x'*ones(size(y)), clim, ' ');
h = gca;
ytick off
axis normal
function cbar_test
im clf, im pl 2 3
clim = [5 20];
x = 10 * eye(9);
im(4, x, clim)
cbar %notick
prompt
im(6, x, clim)
cbar new
prompt
im(1, x, clim)
cbar 'label'
prompt
|
github
|
sunhongfu/scripts-master
|
plot_cell.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/graph/plot_cell.m
| 1,135 |
utf_8
|
8109ef0ab7cf2160a09fa70e6cfc775a
|
function plot_cell(xc, yc, types, varargin)
%function plot_cell(xc, yc, types, varargin)
% plot several "y" curves against x curve(s)
% in:
% xc {N} or 1 cell array of x points
% or a single vector if all x's are the same
% yc {N} cell array of y points
% types {N} cell array of line types
% options:
% 'use', function_handle
if nargin == 1 & streq(xc, 'test'), plot_cell_test, return, end
yc = {yc{:}};
if ~isvar('types') | isempty(types)
types = cell(size(yc));
end
handle = @plot;
while length(varargin)
arg = varargin{1};
if streq(arg, 'use')
handle = varargin{2};
varargin = {varargin{3:end}};
else
error 'unknown option'
end
end
% build arguments to plot()
arg = {};
for ii=1:length(yc)
if iscell(xc)
x = xc{ii}
else
x = xc;
end
if isempty(types{ii})
types{ii} = '-';
end
arg = {arg{:}, x, yc{ii}, types{ii}};
end
feval(handle, arg{:})
title(sprintf('showing %d plots', length(yc)))
function plot_cell_test
x = linspace(0,3,501);
y = {sin(2*pi*x), cos(2*pi*x), x};
clf
subplot(121),
plot_cell(x, y, {'r-', 'g--', 'm:'})
subplot(122),
plot_cell(10.^x, y, {'r-', 'g--', 'm:'}, 'use', @semilogx)
|
github
|
sunhongfu/scripts-master
|
xaxis_pi.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/graph/xaxis_pi.m
| 1,997 |
utf_8
|
025f8ca74646acc95d1f5db9259358d0
|
function xaxis_pi(varargin)
%function xaxis_pi(varargin)
% label x axis with various forms of "pi"
% the argument can be a string with p's in it, or fractions of pi:
% [0 1/2 1] or '0 p/2 p' -> [0 pi/2 pi]
% [-1 0 1] or '-p 0 p' -> [-pi 0 pi]
% etc.
%
% There is one catch: this changes the axes font, so subsequent
% calls to title or xlabel or ylabel will have the wrong font.
% so title, xlabel, ylabel should be done *before* calling this routine.
%
% Jeff Fessler
if length(varargin) == 0
ticks = '0 p';
elseif length(varargin) == 1
ticks = varargin{1};
else
error 'only one arg allowed'
end
if ischar(ticks)
str = ticks;
str = strrep(str, ' ', ' | ');
str = strrep(str, '*', ''); % we don't need the "*" in label
ticks = strrep(ticks, '2p', '2*p');
ticks = strrep(ticks, '4p', '4*p');
ticks = strrep(ticks, 'p', 'pi');
ticks = eval(['[' ticks ']']);
else
if same(ticks, [0])
str = '0';
elseif same(ticks, [0 1])
str = '0 | p';
elseif same(ticks, [0 1/2 1])
str = '0 | p/2 | p';
elseif same(ticks, [-1 0 1])
str = '-p | 0 | p';
elseif same(ticks, [0 1 2])
str = '0 | p | 2p';
else
error 'this ticks not done'
end
end
% here is the main part
axisx(min(ticks), max(ticks))
xtick(ticks)
set(gca, 'xticklabel', str)
set_gca_fontname('symbol')
%
% set_gca_fontname()
%
function set_gca_fontname(type)
% ideally the following line would just work:
%set(gca, 'fontname', type)
% but at least in version 7.5 matlab has a bug where
% it sets the font not only of the current axis, but
% also of the legend. so get all the current font
% names first and then fix them up.
ax = get(gcf, 'children');
for ii=1:length(ax)
name{ii} = get(ax(ii), 'fontname');
end
set(gca, 'fontname', type)
for ii=1:length(ax)
if ax(ii) ~= gca
if ~streq(name{ii}, get(ax(ii), 'fontname'))
warn 'fixing matlab font bug, hopefully!'
set(ax(ii), 'fontname', name{ii})
end
end
end
function is = same(x,y)
if length(x) ~= length(y)
is = 0;
return
end
is = all(x == y);
|
github
|
sunhongfu/scripts-master
|
plot_ellipse.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/graph/plot_ellipse.m
| 1,048 |
utf_8
|
2d49c04f3121cc0bb1ff3280612b457b
|
function [xo, yo] = plot_ellipse(cx, cy, rx, ry, theta, varargin)
%|function [xo, yo] = plot_ellipse(cx, cy, rx, ry, theta, [options])
%| plot an ellipse
%| option
%| 'n' # of points for half of ellipse. default: 301
%| 'c' line type. default: 'b-'
%| 'hold' 1|0 if 1, then add to current plot. default: 0
if nargin == 1 && streq(cx, 'test'), plot_ellipse_test, return, end
if nargin < 5, help(mfilename), error(mfilename), end
arg.n = 301;
arg.c = 'b-';
arg.hold = false;
arg = vararg_pair(arg, varargin);
xe = linspace(-rx, rx, arg.n)';
yp = ry * sqrt(1 - (xe/rx).^2);
ym = -yp;
xp = cx + (cos(theta) * xe - sin(theta) * yp);
yp = cy + (sin(theta) * xe + cos(theta) * yp);
xm = cx + (cos(theta) * xe - sin(theta) * ym);
ym = cy + (sin(theta) * xe + cos(theta) * ym);
xo = [xp; flipud(xm)];
yo = [yp; flipud(ym)];
if ~nargout
if im
if arg.hold, hold on, end
plot(xo, yo, arg.c)
if arg.hold, hold off, end
end
clear xo yo
end
function plot_ellipse_test
plot_ellipse(5, 10, 10, 20, 1)
[xo yo] = plot_ellipse(5, 10, 10, 20, 1);
|
github
|
sunhongfu/scripts-master
|
axis_pipi.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/graph/axis_pipi.m
| 1,908 |
utf_8
|
0f1812f505b6d839ee608755ac05f6d6
|
function axis_pipi(varargin)
%function axis_pipi(['set',] xo, yo, omx, omy)
% label x and y axes from -pi to pi for 2D DSFT
if nargin <= 1
% trick: axes labels must *precede* the symbol font below
xlabel '\omega_X'
ylabel '\omega_Y'
if nargin == 1
if streq(varargin{1}, 'set')
axis([-pi pi -pi pi])
else
error 'unknown option'
end
end
% axis square
xtick([-pi 0 pi])
ytick([-pi 0 pi])
set(gca, 'xticklabel', '-p | 0 | p', 'fontname', 'symbol')
set(gca, 'yticklabel', '-p | 0 | p', 'fontname', 'symbol')
return
end
warning 'the old style is obsolete!'
% fix: use varargin hereafter...
if ~isvar('xo') | isempty(xo), xo = 0.05; end
if ~isvar('yo') | isempty(yo), yo = 0.05; end
if ~isvar('omx'), omx = '\omega_X'; end
if ~isvar('omy'), omy = '\omega_Y'; end
t = axis;
if (strcmp(get(gca, 'XScale'), 'log'))
t = log10(t);
xo = 10^(t(1) - (t(2)-t(1))*xo);
else
xo = t(1) - (t(2)-t(1))*xo;
end
t = axis;
if (strcmp(get(gca, 'YScale'), 'log'))
t = log10(t);
yo = 10^(t(3) - (t(4)-t(3))*yo);
else
yo = t(3) - (t(4)-t(3))*yo;
end
axis(pi * [-1 1 -1 1])
set(gca, 'xtick', [-pi -pi/2 0 pi/2 pi])
set(gca, 'xticklabel', [])
%set(gca, 'xticklabel', ['-pi '; '-pi/2'; ' 0 '; 'pi/2 '; 'pi '])
set(text(pi, yo, '\pi'), 'horizontalalign', 'center')
set(text(-pi, yo, '-\pi'), 'horizontalalign', 'center')
set(text(pi/2, yo, '\pi/2'), 'horizontalalign', 'center')
set(text(-pi/2, yo, '-\pi/2'), 'horizontalalign', 'center')
%set(text(0, yo, '0'), 'horizontalalign', 'center')
if ~isempty(omx)
set(text(0, yo, omx), 'horizontalalign', 'center')
end
set(gca, 'ytick', [-pi -pi/2 0 pi/2 pi])
set(gca, 'yticklabel', [])
rtext(xo, pi, '\pi')
rtext(xo, -pi, '-\pi')
rtext(xo, pi/2, '\pi/2')
rtext(xo, -pi/2, '-\pi/2')
%rtext(xo, 0, '0')
if ~isempty(omy)
rtext(xo, 0, omy)
end
function rtext(x, y, s)
set(text(x, y, s), ...
'verticalalign', 'middle', ...
'horizontalalign', 'right');
|
github
|
sunhongfu/scripts-master
|
savefig.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/graph/savefig.m
| 3,208 |
utf_8
|
31d7c12287268f8e357687e3cdea1dd3
|
function savefig(varargin)
%|function savefig([rootdir,] base, ['c'])
%|
%| save current figure to eps file rootdir/base.eps with prompting.
%|
%| options:
%| 'eps_c' save to color .eps file without inverting!
%| 'cw' color .eps file for use in white paper
%| 'c' save both color and b/w files (for talks)
%| name.epsc color with black background for presentations
%| name.eps black text on white background for printing
%| '-rmap' reverse colormap for color figure (NOT DONE!)
%| 'tall' orient tall
%|
%| note: there is another savefig version at mathworks that probably does
%| a better job of cropping unwanted white space from borders of figures:
%|
%| http://www.mathworks.com/matlabcentral/fileexchange/10889
%|
%| http://www.mathworks.com/access/helpdesk/jhelp/techdoc/printing/printfi7.shtml
%|
%| Copyright 2002-2-1, Jeff Fessler, University of Michigan
if nargin < 1, help(mfilename), error(mfilename), end
if nargin == 1 && streq(varargin{1}, 'test'), savefig_test, return, end
persistent Savefig
if isempty(Savefig), Savefig = true; end
if streq(varargin{1}, 'off'), Savefig = false; return, end
if streq(varargin{1}, 'on'), Savefig = true; return, end
if ~Savefig, disp 'savefig off', return, end
rootdir = '.';
base = 'default';
docolor = false;
doeps_c = false;
do_cw = false;
suff = '.eps';
old_orient = orient;
while length(varargin)
arg = varargin{1};
if ischar(arg) & exist(arg, 'dir') & streq(base, 'default')
rootdir = arg;
elseif ischar(arg) & streq(arg, 'eps_c')
doeps_c = true;
elseif ischar(arg) & streq(arg, 'c')
docolor = true;
elseif ischar(arg) & streq(arg, 'cw')
do_cw = true;
elseif ischar(arg) & streq(arg, 'tall')
orient tall
else
if ~ischar('arg'), error string, end
if ~streq(base, 'default')
printf('WARN %s: ignoring bad names "%s" "%s"', ...
[mfilename '.m'], base, arg)
return
end
base = arg;
end
varargin = {varargin{2:end}};
end
base = [rootdir '/' base];
keepask = 1;
while (keepask)
keepask = 0;
name = [base suff];
if exist(name, 'file')
prompt = sprintf('overwrite figure "%s"? y/a/d/[n]: ', name);
else
prompt = sprintf('print new figure "%s"? y/n: ', name);
end
ans = input(prompt, 's');
% alternate filename
if streq(ans, 'a')
base = input('enter alternate basename (no .eps): ', 's');
keepask = 1;
end
end
% difference between current plot and saved version
% fix: no-color only!
if streq(ans, 'd')
printf('running test to compare to "%s"', name)
print('t-savefig-test', '-deps')
os_run(['diff ' 't-savefig-test.eps ' name])
delete('t-savefig-test.eps')
return
end
if isempty(ans) | ~streq(ans, 'y'), return, end
if doeps_c
print(base, '-depsc')
elseif do_cw % color version but allowing 'inverthardcopy' for white paper
'ok'
print([base '.eps'], '-depsc')
elseif ~docolor
print(base, '-deps')
else
% color version
set(gcf, 'InvertHardCopy', 'off')
print([base '.epsc'], '-depsc')
% b/w version
c = colormap;
colormap(flipud(c))
set(gcf, 'InvertHardCopy', 'on')
print(base, '-deps')
colormap(c)
end
printf('printed ok to "%s"', name)
orient(old_orient)
function savefig_test
jf plc 1 2
jf sub 1
im([rand(9), zeros(9)])
jf sub 2
plot(rand(3))
savefig cw test1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.