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
|
pad_into_center.m
|
.m
|
scripts-master/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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/cs-phase/_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
|
mtimes_block.m
|
.m
|
scripts-master/cs-phase/_src/_NUFFT/@Fatrix/mtimes_block.m
| 1,276 |
utf_8
|
11f89a7167f3f66a965c297a8620dcd5
|
function y = mtimes_block(ob, x, istart, nblock)
%function y = mtimes_block(ob, x, istart, nblock)
% y = G(i'th block) * x or y = G'(i'th block) * x
% in either case the projection data will be "small"
% istart is 1,...,nblock
% support 'exists' option for seeing if this routine is available
if nargin == 2 & ischar(x) & streq(x, 'exists')
y = ~isempty(ob.handle_mtimes_block);
return
end
if nargin ~= 4
error(mfilename)
end
if isempty(ob.handle_mtimes_block)
error 'bug: no mtimes_block() method for this object'
end
if ob.is_transpose
y = Fatrix_mtimes_block_back(ob, x, istart, nblock);
else
y = Fatrix_mtimes_block_forw(ob, x, istart, nblock);
end
% caution: cascade_* may not work except for scalars here
function y = Fatrix_mtimes_block_forw(ob, x, istart, nblock);
x = do_cascade(ob.cascade_before, x, false, istart, nblock, true);
y = feval(ob.handle_mtimes_block, ob.arg, ob.is_transpose, x, istart, nblock);
y = do_cascade(ob.cascade_after, y, false, istart, nblock, false);
function x = Fatrix_mtimes_block_back(ob, y, istart, nblock);
y = do_cascade(ob.cascade_after, y, true, istart, nblock, false);
x = feval(ob.handle_mtimes_block, ob.arg, ob.is_transpose, y, istart, nblock);
x = do_cascade(ob.cascade_before, x, true, istart, nblock, true);
|
github
|
sunhongfu/scripts-master
|
mtimes.m
|
.m
|
scripts-master/cs-phase/_src/_NUFFT/@Fatrix/mtimes.m
| 1,374 |
utf_8
|
b01e213ce10f513c5f91f944f5e7d1f4
|
function y = mtimes(ob, x)
%function y = mtimes(ob, x)
% y = M * x or x = M' * y
if ~isa(ob, 'Fatrix')
error 'only multiplication on right is done'
end
if isa(x, 'Fatrix') % object1 * object2, tested in Gcascade
y = Gcascade(ob, x);
return
end
%
% partial multiplication?
%
if ob.is_subref
error 'subref not done'
end
%
% block multiplication (if needed)
%
if ~isempty(ob.nblock) % block object
if ~isempty(ob.handle_mtimes_block) % proper block object
if ~isempty(ob.iblock) % Gb{?} * ?
y = mtimes_block(ob, x, ob.iblock, ob.nblock);
return
% else: % Gb * ?
end
% else should be a 1-block object
elseif ob.nblock > 1
error 'nblock > 1 but no mtimes_block?'
end
end
%
% ordinary multiplication
%
if ob.is_transpose
y = Fatrix_mtimes_back(ob, x);
else
y = Fatrix_mtimes_forw(ob, x);
end
%
% full forward multiplication ("projection")
% y = after * ob * before * x;
%
function y = Fatrix_mtimes_forw(ob, x);
x = do_cascade(ob.cascade_before, x, false, 0, 1, true);
y = feval(ob.handle_forw, ob.arg, x);
y = do_cascade(ob.cascade_after, y, false, 0, 1, false);
%
% full transposed multiplication ("back-projection")
% x = before' * ob' * after' * y;
%
function x = Fatrix_mtimes_back(ob, y);
y = do_cascade(ob.cascade_after, y, true, 0, 1, false);
x = feval(ob.handle_back, ob.arg, y);
x = do_cascade(ob.cascade_before, x, true, 0, 1, true);
|
github
|
sunhongfu/scripts-master
|
do_cascade.m
|
.m
|
scripts-master/cs-phase/_src/_NUFFT/@Fatrix/private/do_cascade.m
| 870 |
utf_8
|
c5e864c129913ce1841a0ce0b0ddacda
|
function y = do_cascade(cascade, x, is_transpose, istart, nblock, is_before)
%function y = do_cascade(cascade, x, is_transpose, istart, nblock, is_before)
% do cascade * x or cascade' * x
if isempty(cascade)
y = x;
elseif isa(cascade, 'function_handle') | isa(cascade, 'inline')
if nargin(cascade) == 4
y = feval(cascade, x, is_transpose, istart, nblock);
elseif nargin(cascade) == 2 | nblock == 1
y = feval(cascade, x, is_transpose);
else
error 'cascade_* should have 2 or 4 arguments?'
end
else % matrix or object
if is_transpose
if is_before
do_cascade_warn(cascade, nblock)
end
y = cascade' * x;
else
if ~is_before
do_cascade_warn(cascade, nblock)
end
y = cascade * x;
end
end
function do_cascade_warn(cascade, nblock)
if max(size(cascade)) > 1 & nblock ~= 1
warning 'non scalar array/object cascade not tested with block!'
end
|
github
|
sunhongfu/scripts-master
|
read_twix_hdr.m
|
.m
|
scripts-master/cs-phase/_src/_mapVDVD/read_twix_hdr.m
| 5,914 |
utf_8
|
c62a37e267b68781bba89e01ddf83da4
|
function [prot,rstraj] = read_twix_hdr(fid)
% function to read raw data header information from siemens MRI scanners
% (currently VB and VD software versions are supported and tested).
%
% Author: Philipp Ehses ([email protected]), Mar/11/2014
nbuffers = fread(fid, 1,'uint32');
prot = [];
for b=1:nbuffers
%now read string up to null termination
bufname = fread(fid, 10, 'uint8=>char').';
bufname = regexp(bufname, '^\w*', 'match');
bufname = bufname{1};
fseek(fid, numel(bufname)-9, 'cof');
buflen = fread(fid, 1,'uint32');
buffer = fread(fid, buflen, 'uint8=>char').';
buffer = regexprep(buffer,'\n\s*\n',''); % delete empty lines
prot.(bufname) = parse_buffer(buffer);
end
if nargout>1
rstraj = [];
if isfield(prot.Meas,'alRegridMode') && prot.Meas.alRegridMode(1)>1
ncol = prot.Meas.alRegridDestSamples(1);
dwelltime = prot.Meas.aflRegridADCDuration(1)/ncol;
gr_adc = zeros(1,ncol,'single');
% start = prot.Meas.alRegridRampupTime(1) - (prot.Meas.aflRegridADCDuration(1)-prot.Meas.alRegridFlattopTime(1))/2;
start = prot.Meas.alRegridDelaySamplesTime(1);
time_adc = start + dwelltime * (0.5:ncol);
ixUp = time_adc < prot.Meas.alRegridRampupTime(1);
ixFlat = (time_adc <= prot.Meas.alRegridRampupTime(1)+prot.Meas.alRegridFlattopTime(1)) & ~ixUp;
ixDn = ~ixUp & ~ixFlat;
gr_adc(ixFlat) = 1;
if prot.Meas.alRegridMode(1) == 2
% trapezoidal gradient
gr_adc(ixUp) = time_adc(ixUp)/prot.Meas.alRegridRampupTime(1);
gr_adc(ixDn) = 1 - (time_adc(ixDn)-prot.Meas.alRegridRampupTime(1)-prot.Meas.alRegridFlattopTime(1))/prot.Meas.alRegridRampdownTime(1);
elseif prot.Meas.alRegridMode(1) == 4
% sinusoidal gradient
gr_adc(ixUp) = sin(pi/2*time_adc(ixUp)/prot.Meas.alRegridRampupTime(1));
gr_adc(ixDn) = sin(pi/2*(1+(time_adc(ixDn)-prot.Meas.alRegridRampupTime(1)-prot.Meas.alRegridFlattopTime(1))/prot.Meas.alRegridRampdownTime(1)));
else
warning('regridding mode unknown');
return;
end
% make sure that gr_adc is always positive (rstraj needs to be
% strictly monotonic):
gr_adc = max(gr_adc,1e-4);
rstraj = (cumtrapz(gr_adc(:)) - ncol/2)/sum(gr_adc(:));
rstraj = rstraj - mean(rstraj(ncol/2:ncol/2+1));
% scale rstraj by kmax (only works if all slices have same FoV!!!)
kmax = prot.MeasYaps.sKSpace.lBaseResolution/...
prot.MeasYaps.sSliceArray.asSlice{1}.dReadoutFOV;
rstraj = kmax * rstraj;
end
end
end
function prot = parse_buffer(buffer)
[ascconv, xprot] = regexp(buffer,'### ASCCONV BEGIN[^\n]*\n(.*)\s### ASCCONV END ###','tokens','split');
if ~isempty(ascconv)
ascconv = ascconv{:}{:};
prot = parse_ascconv(ascconv);
else
prot = struct();
end
if ~isempty(xprot)
xprot = strcat(xprot{:}); % bug fix by Qiuting Wen (added strcat)
xprot = parse_xprot(xprot);
if isstruct(xprot)
name = cat(1,fieldnames(prot),fieldnames(xprot));
val = cat(1,struct2cell(prot),struct2cell(xprot));
[~,ix] = unique(name);
prot = cell2struct(val(ix),name(ix));
end
end
end
function xprot = parse_xprot(buffer)
xprot = [];
tokens = regexp(buffer, '<Param(?:Bool|Long|String)\."(\w+)">\s*{([^}]*)','tokens');
tokens = [tokens, regexp(buffer, '<ParamDouble\."(\w+)">\s*{\s*(<Precision>\s*[0-9]*)?\s*([^}]*)','tokens')];
for m=1:numel(tokens)
name = char(tokens{m}(1));
% field name has to start with letter
if (~isletter(name(1)))
name = strcat('x', name);
end
value = char(strtrim(regexprep(tokens{m}(end), '("*)|( *<\w*> *[^\n]*)', '')));
value = regexprep(value, '\s*', ' ');
try %#ok<TRYNC>
value = eval(['[' value ']']); % inlined str2num()
end
xprot.(name) = value;
end
end
function mrprot = parse_ascconv(buffer)
mrprot = [];
% [mv] was: vararray = regexp(buffer,'(?<name>\S*)\s*=\s(?<value>\S*)','names');
vararray = regexp(buffer,'(?<name>\S*)\s*=\s*(?<value>\S*)','names');
isOctave = exist('OCTAVE_VERSION', 'builtin') ~= 0;
for var=vararray
try
value = eval(['[' var.value ']']); % inlined str2num()
catch
value = var.value;
end
% now split array name and index (if present)
v = regexp(var.name,'(?<name>\w*)\[(?<ix>[0-9]*)\]|(?<name>\w*)','names');
cnt = 0;
tmp = cell(2, numel(v));
breaked = false;
for k=1:numel(v)
if isOctave
vk = v{k};
if iscell(vk.name)
% lazy fix that throws some info away
vk.name = vk.name{1};
vk.ix = vk.ix{1};
end
else
vk = v(k);
end
if ~isletter(vk.name(1))
breaked = true;
break;
end
cnt = cnt+1;
tmp{1,cnt} = '.';
tmp{2,cnt} = vk.name;
if ~isempty(vk.ix)
cnt = cnt+1;
tmp{1,cnt} = '{}';
tmp{2,cnt}{1} = 1 + str2double(vk.ix);
end
end
if ~breaked && ~isempty(tmp)
S = substruct(tmp{:});
mrprot = subsasgn(mrprot,S,value);
end
end
end
|
github
|
sunhongfu/scripts-master
|
mapVBVD.m
|
.m
|
scripts-master/cs-phase/_src/_mapVDVD/mapVBVD.m
| 34,998 |
windows_1250
|
609b42aff0dc8a0c266c8ef4aab4e389
|
function twix_obj = mapVBVD(filename,varargin)
% Reads Siemens raw .dat file from VB/VD MRI raw data.
% requires twix_map_obj.m & read_twix_hdr.m
%
%
% Author: Philipp Ehses ([email protected])
%
%
% Philipp Ehses 11.02.07, original version
% [..]
% Philipp Ehses 22.03.11, port to VD11
% Felix Breuer 31.03.11, added support for noise & ref scans, speed fixes
% Philipp Ehses 19.08.11, complete reorganization of code, added
% siemens_data_obj class to improve readability
% Wolf Blecher 15.05.12, readout of slice position parameters for VB Data sets
% Wolf Blecher 11.06.12, added distinction between PATREF and PATREF PHASCOR
% Philipp Ehses 02.08.12, again massive code reorganization. The new class
% twix_map_obj.m now stores the memory position of
% each dataset (coils are included - size: NCol*NCha)
% The actual data is not read until it is demanded
% by a "data_obj()" call. This makes it possible
% to selectively read in only parts of the data
% (e.g. to preserve memory).
% Philipp Ehses 27.08.12, speed optimizations (avoiding of .-subsref calls)
% 07.09.12 Thanks to Stephen Yutzy for implementing support for raw data
% correction (currently only supported for VB software version).
% 15.01.13 Thanks to Zhitao Li for proper handling of SYNCDATA.
% Philipp Ehses 28.08.13, added support for VD13 multi-raid files
% Michael Völker May-Aug 15 * Better error tolerance with incomplete files.
% * Swapped out parsing loop into a separate function
% without access to twix object (no thousands of subsref calls).
% * For parsing, use an as-minimalistic-as-possible loop
% to gather all mdhs in binary form. They are all stored
% in one array "mdh_blob".
% * Translation of mdhs from binary to struct is vectorized
% and almost instant. It's done in evalMDH(), replacing
% evalMDHvb() and evalMDHvd(), no more freads inside!
% * vectorized readMDH(), quasi-instant
% * When parsing, actually read the entire file without jumps.
% This is weirdly faster than fseek(), plus the entire file is
% kept in the file system cache, if possible. Next read
% is therefore faster, too.
% * => Parsing speed improved by factor 3...7 or so
% * Speed increase for reading data, esp. when slicing,
% os-removal or reflected lines. Also for random acquisitions.
% Jonas Bause, 18.11.16 receiver phase for ramp-sampling fixed, now takes into account
% Chris Mirkes & PE offcenter shifts in readout direction
%
%
% Input:
%
% filename or simply meas. id, e.g. mapVBVD(122) (if file is in same path)
% optional arguments (see below)
%
% Output: twix_obj structure with elements (if available):
% .image: image scan
% .noise: for noise scan
% .phasecor: phase correction scan
% .phasestab: phase stabilization scan
% .phasestabRef0: phase stab. ref. (MDH_REFPHASESTABSCAN && !MDH_PHASESTABSCAN)
% .phasestabRef1: phase stab. ref. (MDH_REFPHASESTABSCAN && MDH_PHASESTABSCAN)
% .refscan: parallel imaging reference scan
% .refscanPC: phase correction scan for reference data
% .refscanPS: phase stabilization scan for reference data
% .refscanPSRef0: phase stab. ref scan for reference data
% .refscanPSRef1: phase stab. ref scan for reference data
% .RTfeedback: realtime feedback data
% .vop: vop rf data
%
%
% The raw data can be obtained by calling e.g. twix_obj.image() or for
% squeezed data twix_obj.image{''} (the '' are needed due to a limitation
% of matlab's overloading capabilities).
% Slicing is supported as well, e.g. twix_obj.image(:,:,1,:) will return
% only the first line of the full data set (all later dimensions are
% squeezed into one). Thus, slicing of the "memory-mapped" data objects
% works exactly the same as regular matlab array slicing - with one
% exception:
% The keyword 'end' is not supported.
% Overloading of the '()' and '{}' operators works by overloading matlab's
% built-in 'subsref' function. Matlab calls subsref whenever the operators
% '()', '{}', or '.' are called. In the latter case, the overloaded subsref
% just calls the built-in subsref function since we don't want to change
% the behaviour for '.'-calls. However, this has one minor consequence:
% There's no way (afaik) to know whether the original call was terminated
% with a semicolon. Thus, a call to e.g. twix_obj.image.NLin will produce
% no output with or without semicolon termination. 'a = twix_obj.image.NLin'
% will however produce the expected result.
%
%
% Order of raw data:
% 1) Columns
% 2) Channels/Coils
% 3) Lines
% 4) Partitions
% 5) Slices
% 6) Averages
% 7) (Cardiac-) Phases
% 8) Contrasts/Echoes
% 9) Measurements
% 10) Sets
% 11) Segments
% 12) Ida
% 13) Idb
% 14) Idc
% 15) Idd
% 16) Ide
%
%
% Optional parameters/flags:
%
% removeOS: removes oversampling (factor 2) in read direction
% doAverage: performs average (resulting avg-dim has thus size 1)
% ignoreSeg: ignores segment mdh index (works basically the same as
% the average flag)
% rampSampRegrid optional on-the-fly regridding of ramp-sampled readout
% doRawDataCorrect: enables raw data correction if used in the acquisition
% (only works for VB atm)
%
% These flags can also be set/unset later, e.g "twix_obj.image.flagRemoveOS = 1"
%
%
% Examples:
% twix_obj = mapVBVD(measID);
%
% % return all image-data:
% image_data = twix_obj.image();
% % return all image-data with all singular dimensions removed/squeezed:
% image_data = twix_obj.image{''}; % '' necessary due to a matlab limitation
% % return only data for line numbers 1 and 5; all dims higher than 4 are
% % grouped into dim 5):
% image_data = twix_obj.image(:,:,[1 5],:,:);
% % return only data for coil channels 2 to 6; all dims higher than 4 are
% % grouped into dim 5); but work with the squeezed data order
% % => use '{}' instead of '()':
% image_data = twix_obj.image{:,2:6,:,:,:};
%
% So basically it works like regular matlab array slicing (but 'end' is
% not supported; note that there are still a few bugs with array slicing).
%
% % NEW: unsorted raw data (in acq. order):
% image_data = twix_obj.image.unsorted(); % no slicing supported atm
%
%
% Suppress silly editor warnings in the entire file, barking about
% unused variables:
%#ok<*NASGU>
if ~exist('filename','var') || isempty(filename)
info = 'Please select binary file to read';
[fname,pathname]=uigetfile('*.dat',info);
if isempty(pathname)
return
end
filename=[pathname fname];
else
if ischar(filename)
% assume that complete path is given
if ~strcmpi(filename(end-3:end),'.dat')
filename=[filename '.dat']; %% adds filetype ending to file
end
else
% filename not a string, so assume that it is the MeasID
measID = filename;
filelist = dir('*.dat');
filesfound = 0;
for k=1:numel(filelist)
if regexp(filelist(k).name,['^meas_MID0*' num2str(measID) '_.*\.dat'])==1
if filesfound == 0
filename = filelist(k).name;
end
filesfound = filesfound+1;
end
end
if filesfound == 0
error(['File with meas. id ' num2str(measID) ' not found.']);
elseif filesfound > 1
disp(['Multiple files with meas. id ' num2str(measID) ' found. Choosing first occurence.']);
end
end
end
% add absolute path, when no path is given
[pathstr, name, ext] = fileparts(filename);
if isempty(pathstr)
pathstr = pwd;
filename = fullfile(pathstr, [name ext]);
end
%%%%% Parse varargin %%%%%
arg.bReadImaScan = true;
arg.bReadNoiseScan = true;
arg.bReadPCScan = true;
arg.bReadRefScan = true;
arg.bReadRefPCScan = true;
arg.bReadRTfeedback = true;
arg.bReadPhaseStab = true;
arg.bReadHeader = true;
k=1;
while k <= numel(varargin)
if ~ischar(varargin{k})
error('string expected');
end
switch lower(varargin{k})
case {'readheader','readhdr','header','hdr'}
if numel(varargin) > k && ~ischar(varargin{k+1})
arg.bReadHeader = logical(varargin{k+1});
k = k+2;
else
arg.bReadHeader = true;
k = k+1;
end
case {'removeos','rmos'}
if numel(varargin) > k && ~ischar(varargin{k+1})
arg.removeOS = logical(varargin{k+1});
k = k+2;
else
arg.removeOS = true;
k = k+1;
end
case {'doaverage','doave','ave','average'}
if numel(varargin) > k && ~ischar(varargin{k+1})
arg.doAverage = logical(varargin{k+1});
k = k+2;
else
arg.doAverage = true;
k = k+1;
end
case {'averagereps','averagerepetitions'}
if numel(varargin) > k && ~ischar(varargin{k+1})
arg.averageReps = logical(varargin{k+1});
k = k+2;
else
arg.averageReps = true;
k = k+1;
end
case {'averagesets'}
if numel(varargin) > k && ~ischar(varargin{k+1})
arg.averageSets = logical(varargin{k+1});
k = k+2;
else
arg.averageSets = true;
k = k+1;
end
case {'ignseg','ignsegments','ignoreseg','ignoresegments'}
if numel(varargin) > k && ~ischar(varargin{k+1})
arg.ignoreSeg = logical(varargin{k+1});
k = k+2;
else
arg.ignoreSeg = true;
k = k+1;
end
case {'rampsampregrid','regrid'}
if numel(varargin) > k && ~ischar(varargin{k+1})
arg.rampSampRegrid = logical(varargin{k+1});
k = k+2;
else
arg.rampSampRegrid = true;
k = k+1;
end
case {'rawdatacorrect','dorawdatacorrect'}
if numel(varargin) > k && ~ischar(varargin{k+1})
arg.doRawDataCorrect = logical(varargin{k+1});
k = k+2;
else
arg.doRawDataCorrect = true;
k = k+1;
end
otherwise
error('Argument not recognized.');
end
end
clear varargin
%%%%%%%%%%%%%%%%%%%%%%%%%%
tic;
fid = fopen(filename, 'r', 'ieee-le');
% get file size
fseek(fid,0,'eof');
fileSize = ftell(fid);
% start of actual measurement data (sans header)
fseek(fid,0,'bof');
firstInt = fread(fid,1,'uint32');
secondInt = fread(fid,1,'uint32');
% lazy software version check (VB or VD?)
if and(firstInt < 10000, secondInt <= 64)
version = 'vd';
disp('Software version: VD (!?)');
% number of different scans in file stored in 2nd in
NScans = secondInt;
measID = fread(fid,1,'uint32');
fileID = fread(fid,1,'uint32');
measOffset = cell(1, NScans);
measLength = cell(1, NScans);
for k=1:NScans
measOffset{k} = fread(fid,1,'uint64');
measLength{k} = fread(fid,1,'uint64');
fseek(fid, 152 - 16, 'cof');
end
else
% in VB versions, the first 4 bytes indicate the beginning of the
% raw data part of the file
version = 'vb';
% % disp('Software version: VB (!?)'); %MC
measOffset{1} = 0;
measLength{1} = fileSize;
NScans = 1; % VB does not support multiple scans in one file
end
%SRY read data correction factors
% do this for all VB datasets, so that the factors are available later
% in the image_obj if the user chooses to set the correction flag
if (strcmp(version, 'vb')) % not implemented/tested for vd, yet
datStart = measOffset{1} + firstInt;
frewind(fid);
while ( (ftell(fid) < datStart) && ~exist('rawfactors', 'var'))
line = fgetl(fid);
%find the section of the protocol
%note: the factors are also available in <ParamArray."CoilSelects">
%along with element name and FFT scale, but the parsing is
%significantly more difficult
if (~isempty(strfind(line, '<ParamArray."axRawDataCorrectionFactor">')))
while (ftell(fid) < datStart)
line = fgetl(fid);
%find the line with correction factors
%the factors are on the first line that begins with this
%pattern
if (~isempty(strfind(line, '{ { { ')))
line = strrep(line, '} { } ', '0.0');
line = strrep(line, '{', '');
line = strrep(line, '}', '');
rawfactors = textscan(line, '%f');
rawfactors = rawfactors{1}; %textscan returns a 1x1 cell array
% this does not work in this location because the MDHs
% have not been parsed yet
% if (length(rawfactors) ~= 2*max(image_obj.NCha))
% error('Number of raw factors (%f) does not equal channel count (%d)', length(rawfactors)/2, image_obj.NCha);
% end;
if (mod(length(rawfactors),2) ~= 0)
error('Error reading rawfactors');
end;
%note the transpose, this makes the vector
%multiplication during the read easier
arg.rawDataCorrectionFactors = rawfactors(1:2:end).' + 1i*rawfactors(2:2:end).';
break;
end
end
end
end
% % disp('Read raw data correction factors'); %MC
end
% data will be read in two steps (two while loops):
% 1) reading all MDHs to find maximum line no., partition no.,... for
% ima, ref,... scan
% 2) reading the data
tic;
twix_obj = cell(1,NScans);
for s=1:NScans
cPos = measOffset{s};
fseek(fid,cPos,'bof');
hdr_len = fread(fid, 1,'uint32');
% read header and calculate regridding (optional)
rstraj = [];
isInplacePATref = false;
if arg.bReadHeader
[twix_obj{s}.hdr, rstraj] = read_twix_hdr(fid);
if isfield(twix_obj{s}.hdr.MeasYaps, 'sPat')
isInplacePATref = str2double(twix_obj{s}.hdr.MeasYaps.sPat.ucRefScanMode(end))==2;
end
end
% declare data objects:
twix_obj{s}.image = twix_map_obj(arg,'image',filename,version,rstraj);
twix_obj{s}.noise = twix_map_obj(arg,'noise',filename,version);
twix_obj{s}.phasecor = twix_map_obj(arg,'phasecor',filename,version,rstraj);
twix_obj{s}.phasestab = twix_map_obj(arg,'phasestab',filename,version,rstraj);
twix_obj{s}.phasestabRef0 = twix_map_obj(arg,'phasestab_ref0',filename,version,rstraj);
twix_obj{s}.phasestabRef1 = twix_map_obj(arg,'phasestab_ref1',filename,version,rstraj);
twix_obj{s}.refscan = twix_map_obj(arg,'refscan',filename,version,rstraj);
twix_obj{s}.refscanPC = twix_map_obj(arg,'refscan_phasecor',filename,version,rstraj);
twix_obj{s}.refscanPS = twix_map_obj(arg,'refscan_phasestab',filename,version,rstraj);
twix_obj{s}.refscanPSRef0 = twix_map_obj(arg,'refscan_phasestab_ref0',filename,version,rstraj);
twix_obj{s}.refscanPSRef1 = twix_map_obj(arg,'refscan_phasestab_ref1',filename,version,rstraj);
twix_obj{s}.RTfeedback = twix_map_obj(arg,'rtfeedback',filename,version,rstraj);
twix_obj{s}.vop = twix_map_obj(arg,'vop',filename,version); % tx-array rf pulses
% print reader version information %MC hide
% % if s==1
% % fprintf('Reader version: %d', twix_obj{s}.image.readerVersion);
% % isOctave = exist('OCTAVE_VERSION', 'builtin') ~= 0;
% % if isOctave
% % date_str = ctime(twix_obj{s}.image.readerVersion);
% % date_str = date_str(1:end-1);
% % else
% % date_str = datetime(twix_obj{s}.image.readerVersion, 'ConvertFrom','posixtime');
% % end
% % fprintf(' (UTC: %s)\n', char(date_str));
% % end
% jump to first mdh
cPos = cPos + hdr_len;
fseek( fid, cPos, 'bof' );
% find all mdhs and save them in binary form, first:
% % fprintf('Scan %d/%d, read all mdhs:\n', s, NScans )
[mdh_blob, filePos, isEOF] = loop_mdh_read( fid, version, NScans, s, measOffset{s}, measLength{s}); % uint8; size: [ byteMDH Nmeas ]
cPos = filePos( end );
filePos( end ) = [];
% get mdhs and masks for each scan, no matter if noise, image, RTfeedback etc:
[mdh, mask] = evalMDH( mdh_blob, version, isInplacePATref); % this is quasi-instant (< 1s) :-)
clear mdh_blob
% Assign mdhs to their respective scans and parse it in the correct twix objects.
%
if arg.bReadImaScan
clear tmpMdh
isCurrScan = logical( mask.MDH_IMASCAN );
for f = fieldnames( mdh ).'
tmpMdh.(f{1}) = mdh.(f{1})( isCurrScan, : );
end
twix_obj{s}.image.readMDH( tmpMdh, filePos(isCurrScan) );
end
if arg.bReadNoiseScan
clear tmpMdh
isCurrScan = logical( mask.MDH_NOISEADJSCAN );
for f = fieldnames( mdh ).'
tmpMdh.(f{1}) = mdh.(f{1})( isCurrScan, : );
end
twix_obj{s}.noise.readMDH( tmpMdh, filePos(isCurrScan) );
end
if arg.bReadRefScan
clear tmpMdh
isCurrScan = ( mask.MDH_PATREFSCAN | mask.MDH_PATREFANDIMASCAN )...
& ~( mask.MDH_PHASCOR | mask.MDH_PHASESTABSCAN | ...
mask.MDH_REFPHASESTABSCAN | ...
mask.MDH_RTFEEDBACK | mask.MDH_HPFEEDBACK);
for f = fieldnames( mdh ).'
tmpMdh.(f{1}) = mdh.(f{1})( isCurrScan, : );
end
twix_obj{s}.refscan.readMDH( tmpMdh, filePos(isCurrScan) );
end
if arg.bReadRTfeedback
clear tmpMdh
isCurrScan = ( mask.MDH_RTFEEDBACK | mask.MDH_HPFEEDBACK ) & ~mask.MDH_VOP;
for f = fieldnames( mdh ).'
tmpMdh.(f{1}) = mdh.(f{1})( isCurrScan, : );
end
twix_obj{s}.RTfeedback.readMDH( tmpMdh, filePos(isCurrScan) );
clear tmpMdh
isCurrScan = ( mask.MDH_RTFEEDBACK & mask.MDH_VOP );
for f = fieldnames( mdh ).'
tmpMdh.(f{1}) = mdh.(f{1})( isCurrScan, : );
end
twix_obj{s}.vop.readMDH( tmpMdh, filePos(isCurrScan) );
end
if arg.bReadPCScan
% logic really correct?
clear tmpMdh
isCurrScan = mask.MDH_PHASCOR & ( ~mask.MDH_PATREFSCAN | mask.MDH_PATREFANDIMASCAN );
for f = fieldnames( mdh ).'
tmpMdh.(f{1}) = mdh.(f{1})( isCurrScan, : );
end
twix_obj{s}.phasecor.readMDH( tmpMdh, filePos(isCurrScan) );
clear tmpMdh
isCurrScan = mask.MDH_PHASCOR & ( mask.MDH_PATREFSCAN | mask.MDH_PATREFANDIMASCAN );
for f = fieldnames( mdh ).'
tmpMdh.(f{1}) = mdh.(f{1})( isCurrScan, : );
end
twix_obj{s}.refscanPC.readMDH( tmpMdh, filePos(isCurrScan) );
end
if arg.bReadPhaseStab
clear tmpMdh
isCurrScan = ( mask.MDH_PHASESTABSCAN & ~mask.MDH_REFPHASESTABSCAN ) ...
& (~mask.MDH_PATREFSCAN | mask.MDH_PATREFANDIMASCAN );
for f = fieldnames( mdh ).'
tmpMdh.(f{1}) = mdh.(f{1})( isCurrScan, : );
end
twix_obj{s}.phasestab.readMDH( tmpMdh, filePos(isCurrScan) );
clear tmpMdh
isCurrScan = ( mask.MDH_PHASESTABSCAN & ~mask.MDH_REFPHASESTABSCAN ) ...
& ( mask.MDH_PATREFSCAN | mask.MDH_PATREFANDIMASCAN );
for f = fieldnames( mdh ).'
tmpMdh.(f{1}) = mdh.(f{1})( isCurrScan, : );
end
twix_obj{s}.refscanPS.readMDH( tmpMdh, filePos(isCurrScan) );
clear tmpMdh
isCurrScan = ( mask.MDH_REFPHASESTABSCAN & ~mask.MDH_PHASESTABSCAN ) ...
& (~mask.MDH_PATREFSCAN | mask.MDH_PATREFANDIMASCAN );
for f = fieldnames( mdh ).'
tmpMdh.(f{1}) = mdh.(f{1})( isCurrScan, : );
end
twix_obj{s}.phasestabRef0.readMDH( tmpMdh, filePos(isCurrScan) );
clear tmpMdh
isCurrScan = ( mask.MDH_REFPHASESTABSCAN & ~mask.MDH_PHASESTABSCAN ) ...
& ( mask.MDH_PATREFSCAN | mask.MDH_PATREFANDIMASCAN );
for f = fieldnames( mdh ).'
tmpMdh.(f{1}) = mdh.(f{1})( isCurrScan, : );
end
twix_obj{s}.refscanPSRef0.readMDH( tmpMdh, filePos(isCurrScan) );
clear tmpMdh
isCurrScan = ( mask.MDH_REFPHASESTABSCAN & mask.MDH_PHASESTABSCAN ) ...
& (~mask.MDH_PATREFSCAN | mask.MDH_PATREFANDIMASCAN );
for f = fieldnames( mdh ).'
tmpMdh.(f{1}) = mdh.(f{1})( isCurrScan, : );
end
twix_obj{s}.phasestabRef1.readMDH( tmpMdh, filePos(isCurrScan) );
clear tmpMdh
isCurrScan = ( mask.MDH_REFPHASESTABSCAN & mask.MDH_PHASESTABSCAN ) ...
& ( mask.MDH_PATREFSCAN | mask.MDH_PATREFANDIMASCAN );
for f = fieldnames( mdh ).'
tmpMdh.(f{1}) = mdh.(f{1})( isCurrScan, : );
end
twix_obj{s}.refscanPSRef1.readMDH( tmpMdh, filePos(isCurrScan) );
end
clear mdh tmpMdh filePos isCurrScan
for scan = { 'image', 'noise', 'phasecor', 'phasestab', ...
'phasestabRef0', 'phasestabRef1', 'refscan', ...
'refscanPC', 'refscanPS', 'refscanPSRef0', ...
'refscanPSRef1', 'RTfeedback', 'vop' }
f = scan{1};
% remove unused fields
if twix_obj{s}.(f).NAcq == 0
twix_obj{s} = rmfield(twix_obj{s}, f );
else
if isEOF
% recover from read error
twix_obj{s}.(f).tryAndFixLastMdh();
else
twix_obj{s}.(f).clean();
end
end
end
end % NScans loop
if NScans == 1
twix_obj = twix_obj{1};
end
end % of mapVBVD()
function [mdh_blob, filePos, isEOF] = loop_mdh_read( fid, version, Nscans, scan, measOffset, measLength)
% Goal of this function is to gather all mdhs in the dat file and store them
% in binary form, first. This enables us to evaluate and parse the stuff in
% a MATLAB-friendly (vectorized) way. We also yield a clear separation between
% a lengthy loop and other expressions that are evaluated very few times.
%
% The main challenge is that we never know a priori, where the next mdh is
% and how many there are. So we have to actually evaluate some mdh fields to
% find the next one.
%
% All slow things of the parsing step are found in the while loop.
% => It is the (only) place where micro-optimizations are worthwhile.
%
% The current state is that we are close to sequential disk I/O times.
% More fancy improvements may be possible by using workers through parfeval()
% or threads using a java class (probably faster + no toolbox):
% http://undocumentedmatlab.com/blog/explicit-multi-threading-in-matlab-part1
switch version
case 'vb'
isVD = false;
byteMDH = 128;
case 'vd'
isVD = true;
byteMDH = 184;
szScanHeader = 192; % [bytes]
szChannelHeader = 32; % [bytes]
otherwise
% arbitrary assumptions:
isVD = false;
byteMDH = 128;
warning( [mfilename() ':UnknownVer'], 'Software version "%s" is not supported.', version );
end
cPos = ftell(fid);
n_acq = 0;
allocSize = 4096;
ulDMALength = byteMDH;
isEOF = false;
last_progress = 0;
mdh_blob = zeros( byteMDH, 0, 'uint8' );
szBlob = size( mdh_blob, 2 );
filePos = zeros(0, 1, class(cPos)); % avoid bug in Matlab 2013b: https://scivision.co/matlab-fseek-bug-with-uint64-offset/
fseek(fid,cPos,'bof');
% ======================================
% constants and conditional variables
% ======================================
bit_0 = uint8(2^0);
bit_5 = uint8(2^5);
mdhStart = 1-byteMDH;
u8_000 = zeros( 3, 1, 'uint8'); % for comparison with data_u8(1:3)
% 20 fill bytes in VD (21:40)
evIdx = uint8( 21 + 20*isVD); % 1st byte of evalInfoMask
dmaIdx = uint8((29:32) + 20*isVD); % to correct DMA length using NCol and NCha
if isVD
dmaOff = szScanHeader;
dmaSkip = szChannelHeader;
else
dmaOff = 0;
dmaSkip = byteMDH;
end
% ======================================
isOctave = exist('OCTAVE_VERSION', 'builtin') ~= 0;
if isOctave % octave does not support a cancel button
h = waitbar(0,'','Name', sprintf('Reading Scan ID %d/%d', scan, Nscans));
else
h = waitbar(0,'','Name', sprintf('Reading Scan ID %d/%d', scan, Nscans),...
'CreateCancelBtn',...
'setappdata(gcbf,''canceling'',1)');
setappdata(h,'canceling',0)
end
t0 = tic;
while true
% Read mdh as binary (uint8) and evaluate as little as possible to know...
% ... where the next mdh is (ulDMALength / ushSamplesInScan & ushUsedChannels)
% ... whether it is only for sync (MDH_SYNCDATA)
% ... whether it is the last one (MDH_ACQEND)
% evalMDH() contains the correct and readable code for all mdh entries.
try
% read everything and cut out the mdh
data_u8 = fread( fid, ulDMALength, 'uint8=>uint8' );
data_u8 = data_u8( mdhStart+end : end );
catch exc
warning( [mfilename() ':UnxpctdEOF'], ...
[ '\nAn unexpected read error occurred at this byte offset: %d (%g GiB)\n'...
'Will stop reading now.\n' ...
'=== MATLABs error message ================\n' ...
exc.message ...
'\n=== end of error =========================\n' ...
], cPos, cPos/1024^3 )
isEOF = true;
break
end
if ~isOctave && getappdata(h,'canceling')
break;
end
bitMask = data_u8(evIdx); % the initial 8 bit from evalInfoMask are enough
if isequal( data_u8(1:3), u8_000 ) ... % probably ulDMALength == 0
|| bitand(bitMask, bit_0) % MDH_ACQEND
% ok, look closer if really all *4* bytes are 0:
data_u8(4)= bitget( data_u8(4),1); % ubit24: keep only 1 bit from the 4th byte
ulDMALength = double( typecast( data_u8(1:4), 'uint32' ) );
if ulDMALength == 0 || bitand(bitMask, bit_0)
cPos = cPos + ulDMALength;
% jump to next full 512 bytes
if mod(cPos,512)
cPos = cPos + 512 - mod(cPos,512);
end
break;
end
end
if bitand(bitMask, bit_5) % MDH_SYNCDATA
data_u8(4)= bitget( data_u8(4),1); % ubit24: keep only 1 bit from the 4th byte
ulDMALength = double( typecast( data_u8(1:4), 'uint32' ) );
cPos = cPos + ulDMALength;
continue
end
% pehses: the pack bit indicates that multiple ADC are packed into one
% DMA, often in EPI scans (controlled by fRTSetReadoutPackaging in IDEA)
% since this code assumes one adc (x NCha) per DMA, we have to correct
% the "DMA length"
% if mdh.ulPackBit
% it seems that the packbit is not always set correctly
NCol_NCha = double( typecast( data_u8(dmaIdx), 'uint16' ) ); % [ushSamplesInScan ushUsedChannels]
ulDMALength = dmaOff + (8*NCol_NCha(1) + dmaSkip) * NCol_NCha(2);
n_acq = n_acq + 1;
% grow arrays in batches
if n_acq > szBlob
mdh_blob( :, end + allocSize ) = 0;
filePos( end + allocSize ) = 0;
szBlob = size( mdh_blob, 2 );
end
mdh_blob(:,n_acq) = data_u8;
filePos( n_acq ) = cPos;
progress = (cPos-measOffset)/measLength;
if progress > last_progress + 0.01
last_progress = progress;
elapsed_time = toc(t0);
time_left = elapsed_time * (1/progress-1);
progress_str = sprintf('%3.0f %% read in %4.0f s;\nestimated time left: %4.0f s', round(100*progress), elapsed_time, time_left);
waitbar(progress, h, progress_str);
end
cPos = cPos + ulDMALength;
end % while true
delete(h);
if isEOF
n_acq = n_acq-1; % ignore the last attempt
end
filePos( n_acq+1 ) = cPos; % save pointer to the next scan
% discard overallocation:
mdh_blob = mdh_blob(:,1:n_acq);
filePos = reshape( filePos(1:n_acq+1), 1, [] ); % row vector
% % fprintf('%8.1f MB read in %4.0f s\n', measLength/1024^2, round(toc(t0)));
end % of loop_mdh_read()
function [mdh,mask] = evalMDH( mdh_blob, version, isInplacePATref )
% see pkg/MrServers/MrMeasSrv/SeqIF/MDH/mdh.h
% and pkg/MrServers/MrMeasSrv/SeqIF/MDH/MdhProxy.h
if ~isa( mdh_blob, 'uint8' )
error([mfilename() ':NoInt8'], 'mdh data must be a uint8 array!')
end
if version(end) == 'd'
isVD = true;
mdh_blob = mdh_blob([1:20 41:end], :); % remove 20 unnecessary bytes
else
isVD = false;
end
Nmeas = size( mdh_blob, 2 );
mdh.ulPackBit = bitget( mdh_blob(4,:), 2).';
mdh.ulPCI_rx = bitset(bitset(mdh_blob(4,:), 7, 0), 8, 0).'; % keep 6 relevant bits
mdh_blob(4,:) = bitget( mdh_blob(4,:),1); % ubit24: keep only 1 bit from the 4th byte
% unfortunately, typecast works on vectors, only
data_uint32 = typecast( reshape(mdh_blob(1:76,:), [],1), 'uint32' );
data_uint16 = typecast( reshape(mdh_blob(29:end,:),[],1), 'uint16' );
data_single = typecast( reshape(mdh_blob(69:end,:),[],1), 'single' );
data_uint32 = reshape( data_uint32, [], Nmeas ).';
data_uint16 = reshape( data_uint16, [], Nmeas ).';
data_single = reshape( data_single, [], Nmeas ).';
% byte pos.
%mdh.ulDMALength = data_uint32(:,1); % 1 : 4
mdh.lMeasUID = data_uint32(:,2); % 5 : 8
mdh.ulScanCounter = data_uint32(:,3); % 9 : 12
mdh.ulTimeStamp = data_uint32(:,4); % 13 : 16
mdh.ulPMUTimeStamp = data_uint32(:,5); % 17 : 20
mdh.aulEvalInfoMask = data_uint32(:,6:7); % 21 : 28
mdh.ushSamplesInScan = data_uint16(:,1); % 29 : 30
mdh.ushUsedChannels = data_uint16(:,2); % 31 : 32
mdh.sLC = data_uint16(:,3:16); % 33 : 60
mdh.sCutOff = data_uint16(:,17:18); % 61 : 64
mdh.ushKSpaceCentreColumn = data_uint16(:,19); % 66 : 66
mdh.ushCoilSelect = data_uint16(:,20); % 67 : 68
mdh.fReadOutOffcentre = data_single(:, 1); % 69 : 72
mdh.ulTimeSinceLastRF = data_uint32(:,19); % 73 : 76
mdh.ushKSpaceCentreLineNo = data_uint16(:,25); % 77 : 78
mdh.ushKSpaceCentrePartitionNo = data_uint16(:,26); % 79 : 80
if isVD
mdh.SlicePos = data_single(:, 4:10); % 81 : 108
mdh.aushIceProgramPara = data_uint16(:,41:64); % 109 : 156
mdh.aushFreePara = data_uint16(:,65:68); % 157 : 164
else
mdh.aushIceProgramPara = data_uint16(:,27:30); % 81 : 88
mdh.aushFreePara = data_uint16(:,31:34); % 89 : 96
mdh.SlicePos = data_single(:, 8:14); % 97 : 124
end
% inlining of evalInfoMask
evalInfoMask1 = mdh.aulEvalInfoMask(:,1);
mask.MDH_ACQEND = min(bitand(evalInfoMask1, 2^0), 1);
mask.MDH_RTFEEDBACK = min(bitand(evalInfoMask1, 2^1), 1);
mask.MDH_HPFEEDBACK = min(bitand(evalInfoMask1, 2^2), 1);
mask.MDH_SYNCDATA = min(bitand(evalInfoMask1, 2^5), 1);
mask.MDH_RAWDATACORRECTION = min(bitand(evalInfoMask1, 2^10),1);
mask.MDH_REFPHASESTABSCAN = min(bitand(evalInfoMask1, 2^14),1);
mask.MDH_PHASESTABSCAN = min(bitand(evalInfoMask1, 2^15),1);
mask.MDH_SIGNREV = min(bitand(evalInfoMask1, 2^17),1);
mask.MDH_PHASCOR = min(bitand(evalInfoMask1, 2^21),1);
mask.MDH_PATREFSCAN = min(bitand(evalInfoMask1, 2^22),1);
mask.MDH_PATREFANDIMASCAN = min(bitand(evalInfoMask1, 2^23),1);
mask.MDH_REFLECT = min(bitand(evalInfoMask1, 2^24),1);
mask.MDH_NOISEADJSCAN = min(bitand(evalInfoMask1, 2^25),1);
mask.MDH_VOP = min(bitand(mdh.aulEvalInfoMask(2), 2^(53-32)),1); % was 0 in VD
mask.MDH_IMASCAN = ones( Nmeas, 1, 'uint32' );
noImaScan = ( mask.MDH_ACQEND | mask.MDH_RTFEEDBACK | mask.MDH_HPFEEDBACK ...
| mask.MDH_PHASCOR | mask.MDH_NOISEADJSCAN | mask.MDH_PHASESTABSCAN ...
| mask.MDH_REFPHASESTABSCAN | mask.MDH_SYNCDATA );
if ~isInplacePATref
noImaScan = (noImaScan | (mask.MDH_PATREFSCAN & ~mask.MDH_PATREFANDIMASCAN));
end
mask.MDH_IMASCAN( noImaScan ) = 0;
end % of evalMDH()
|
github
|
sunhongfu/scripts-master
|
phantom3d.m
|
.m
|
scripts-master/YangGao/phantom3d.m
| 8,305 |
utf_8
|
b9b524c7621b925703851eece75cedde
|
function [p,ellipse]=phantom3d(varargin)
%PHANTOM3D Three-dimensional analogue of MATLAB Shepp-Logan phantom
% P = PHANTOM3D(DEF,N) generates a 3D head phantom that can
% be used to test 3-D reconstruction algorithms.
%
% DEF is a string that specifies the type of head phantom to generate.
% Valid values are:
%
% 'Shepp-Logan' A test image used widely by researchers in
% tomography
% 'Modified Shepp-Logan' (default) A variant of the Shepp-Logan phantom
% in which the contrast is improved for better
% visual perception.
%
% N is a scalar that specifies the grid size of P.
% If you omit the argument, N defaults to 64.
%
% P = PHANTOM3D(E,N) generates a user-defined phantom, where each row
% of the matrix E specifies an ellipsoid in the image. E has ten columns,
% with each column containing a different parameter for the ellipsoids:
%
% Column 1: A the additive intensity value of the ellipsoid
% Column 2: a the length of the x semi-axis of the ellipsoid
% Column 3: b the length of the y semi-axis of the ellipsoid
% Column 4: c the length of the z semi-axis of the ellipsoid
% Column 5: x0 the x-coordinate of the center of the ellipsoid
% Column 6: y0 the y-coordinate of the center of the ellipsoid
% Column 7: z0 the z-coordinate of the center of the ellipsoid
% Column 8: phi phi Euler angle (in degrees) (rotation about z-axis)
% Column 9: theta theta Euler angle (in degrees) (rotation about x-axis)
% Column 10: psi psi Euler angle (in degrees) (rotation about z-axis)
%
% For purposes of generating the phantom, the domains for the x-, y-, and
% z-axes span [-1,1]. Columns 2 through 7 must be specified in terms
% of this range.
%
% [P,E] = PHANTOM3D(...) returns the matrix E used to generate the phantom.
%
% Class Support
% -------------
% All inputs must be of class double. All outputs are of class double.
%
% Remarks
% -------
% For any given voxel in the output image, the voxel's value is equal to the
% sum of the additive intensity values of all ellipsoids that the voxel is a
% part of. If a voxel is not part of any ellipsoid, its value is 0.
%
% The additive intensity value A for an ellipsoid can be positive or negative;
% if it is negative, the ellipsoid will be darker than the surrounding pixels.
% Note that, depending on the values of A, some voxels may have values outside
% the range [0,1].
%
% Example
% -------
% ph = phantom3d(128);
% figure, imshow(squeeze(ph(64,:,:)))
%
% Copyright 2005 Matthias Christian Schabel (matthias @ stanfordalumni . org)
% University of Utah Department of Radiology
% Utah Center for Advanced Imaging Research
% 729 Arapeen Drive
% Salt Lake City, UT 84108-1218
%
% This code is released under the Gnu Public License (GPL). For more information,
% see : http://www.gnu.org/copyleft/gpl.html
%
% Portions of this code are based on phantom.m, copyrighted by the Mathworks
%
[ellipse,n] = parse_inputs(varargin{:});
p = zeros([n n n]);
rng = ( (0:n-1)-(n-1)/2 ) / ((n-1)/2);
[x,y,z] = meshgrid(rng,rng,rng);
coord = [flatten(x); flatten(y); flatten(z)];
p = flatten(p);
for k = 1:size(ellipse,1)
A = ellipse(k,1); % Amplitude change for this ellipsoid
asq = ellipse(k,2)^2; % a^2
bsq = ellipse(k,3)^2; % b^2
csq = ellipse(k,4)^2; % c^2
x0 = ellipse(k,5); % x offset
y0 = ellipse(k,6); % y offset
z0 = ellipse(k,7); % z offset
phi = ellipse(k,8)*pi/180; % first Euler angle in radians
theta = ellipse(k,9)*pi/180; % second Euler angle in radians
psi = ellipse(k,10)*pi/180; % third Euler angle in radians
cphi = cos(phi);
sphi = sin(phi);
ctheta = cos(theta);
stheta = sin(theta);
cpsi = cos(psi);
spsi = sin(psi);
% Euler rotation matrix
alpha = [cpsi*cphi-ctheta*sphi*spsi cpsi*sphi+ctheta*cphi*spsi spsi*stheta;
-spsi*cphi-ctheta*sphi*cpsi -spsi*sphi+ctheta*cphi*cpsi cpsi*stheta;
stheta*sphi -stheta*cphi ctheta];
% rotated ellipsoid coordinates
coordp = alpha*coord;
idx = find((coordp(1,:)-x0).^2./asq + (coordp(2,:)-y0).^2./bsq + (coordp(3,:)-z0).^2./csq <= 1);
p(idx) = p(idx) + A;
end
p = reshape(p,[n n n]);
return;
function out = flatten(in)
out = reshape(in,[1 prod(size(in))]);
return;
function [e,n] = parse_inputs(varargin)
% e is the m-by-10 array which defines ellipsoids
% n is the size of the phantom brain image
n = 128; % The default size
e = [];
defaults = {'shepp-logan', 'modified shepp-logan', 'yu-ye-wang'};
for i=1:nargin
if ischar(varargin{i}) % Look for a default phantom
def = lower(varargin{i});
idx = strmatch(def, defaults);
if isempty(idx)
eid = sprintf('Images:%s:unknownPhantom',mfilename);
msg = 'Unknown default phantom selected.';
error(eid,'%s',msg);
end
switch defaults{idx}
case 'shepp-logan'
e = shepp_logan;
case 'modified shepp-logan'
e = modified_shepp_logan;
case 'yu-ye-wang'
e = yu_ye_wang;
end
elseif numel(varargin{i})==1
n = varargin{i}; % a scalar is the image size
elseif ndims(varargin{i})==2 && size(varargin{i},2)==10
e = varargin{i}; % user specified phantom
else
eid = sprintf('Images:%s:invalidInputArgs',mfilename);
msg = 'Invalid input arguments.';
error(eid,'%s',msg);
end
end
% ellipse is not yet defined
if isempty(e)
e = modified_shepp_logan;
end
return;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Default head phantoms: %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function e = shepp_logan
e = modified_shepp_logan;
e(:,1) = [1 -.98 -.02 -.02 .01 .01 .01 .01 .01 .01];
return;
function e = modified_shepp_logan
%
% This head phantom is the same as the Shepp-Logan except
% the intensities are changed to yield higher contrast in
% the image. Taken from Toft, 199-200.
%
% A a b c x0 y0 z0 phi theta psi
% -----------------------------------------------------------------
e = [ -.1 .6900 .920 .810 0 0 0 0 0 0
.05 .6624 .874 .780 0 -.0184 0 0 0 0
.4 .1100 .310 .220 .22 0 0 -18 0 10
.2 .1600 .410 .280 -.22 0 0 18 0 10
-.2 .2100 .250 .410 0 .35 -.15 0 0 0
-.1 .0460 .046 .050 0 .1 .25 0 0 0
-.15 .0460 .046 .050 0 -.1 .25 0 0 0
-.15 .0460 .023 .050 -.08 -.605 0 0 0 0
-.15 .0230 .023 .020 0 -.606 0 0 0 0
-.15 .0230 .046 .020 .06 -.605 0 0 0 0 ];
return;
function e = yu_ye_wang
%
% Yu H, Ye Y, Wang G, Katsevich-Type Algorithms for Variable Radius Spiral Cone-Beam CT
%
% A a b c x0 y0 z0 phi theta psi
% -----------------------------------------------------------------
e = [ 1 .6900 .920 .900 0 0 0 0 0 0
-.8 .6624 .874 .880 0 0 0 0 0 0
-.2 .4100 .160 .210 -.22 0 -.25 108 0 0
-.2 .3100 .110 .220 .22 0 -.25 72 0 0
.2 .2100 .250 .500 0 .35 -.25 0 0 0
.2 .0460 .046 .046 0 .1 -.25 0 0 0
.1 .0460 .023 .020 -.08 -.65 -.25 0 0 0
.1 .0460 .023 .020 .06 -.65 -.25 90 0 0
.2 .0560 .040 .100 .06 -.105 .625 90 0 0
-.2 .0560 .056 .100 0 .100 .625 0 0 0 ];
return;
|
github
|
sunhongfu/scripts-master
|
recon_all_data.m
|
.m
|
scripts-master/AHEAD/tinaroo/recon_all_data.m
| 10,136 |
utf_8
|
1f4230494bdf29cdfbe9e994c3e2f0c7
|
% recon code for AHEAD sample data
function recon_all_data(sub_no)
curDir = '/QRISdata/Q1041/AHEAD/AHEAD_v2';
cd(curDir)
% for sub_no = 1 : 1 : 105
% load in phase and mag
if sub_no < 51
datafolder = 'part1_v2';
else
datafolder = 'part2_v2';
end
des_folder = ['./', datafolder, '/sub-', sprintf('%04d', sub_no - 1), '/ses-1/anat/wb/source/'];
cd(des_folder)
for echo = 1:4
mag_path = ['./sub-',sprintf('%04d', sub_no - 1),'_ses-1_acq-wb_inv-2_echo-' num2str(echo) '_part-mag_orient-std_brain.nii.gz'];
unix(sprintf('gunzip -f %s', mag_path));
nii = load_untouch_nii(['./sub-',sprintf('%04d', sub_no - 1),'_ses-1_acq-wb_inv-2_echo-' num2str(echo) '_part-mag_orient-std_brain.nii']);
mag(:,:,:,echo) = double(nii.img +32768);
ph_path = ['./sub-',sprintf('%04d', sub_no - 1),'_ses-1_acq-wb_inv-2_echo-' num2str(echo) '_part-ph_orient-std_brain.nii.gz']
unix(sprintf('gunzip -f %s', ph_path));
nii = load_untouch_nii(['./sub-',sprintf('%04d', sub_no - 1),'_ses-1_acq-wb_inv-2_echo-' num2str(echo) '_part-ph_orient-std_brain.nii']);
ph(:,:,:,echo) = double(nii.img);
end
ph = 2*pi.*(ph - min(ph(:)))/(max(ph(:)) - min(ph(:))) - pi;
% extract z_prjs from nifti header
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% for example:
% srow_x: [-0.0163 0.0357 0.6987 -83.8686]
% srow_y: [-0.6085 -0.2014 -0.0047 114.1026]
% srow_z: [-0.2008 0.6075 -0.0426 -43.3919]
% R = [ srow_x(1:3)
% srow_y(1:3)
% srow_z(1:3)]
% R(:,1)=R(:,1)/pixdim(2)
% R(:,2)=R(:,2)/pixdim(3)
% R(:,3)=R(:,3)/pixdim(4)
% R is the affine matrix map FOV to scanner coordinate
% therefore R(3,:) is the z_prjs
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
z_prjs = nii.hdr.hist.srow_z(1:3)./nii.hdr.dime.pixdim(2:4)
vox = nii.hdr.dime.pixdim(2:4)
TE = [3, 11.5, 19, 28.5]*1e-3;
imsize = size(mag);
% unipolar readout according to Caan paper
mkdir('QSM_AHEAD');
cd('QSM_AHEAD');
% BEGIN THE QSM RECON PIPELINE
% initial quick brain mask
% simple sum-of-square combination
nii = make_nii((mag(:,:,:,1)),vox);
save_nii(nii,'mag1_sos.nii');
% unix('N4BiasFieldCorrection -i mag1_sos.nii -o mag1_sos_n4.nii');
unix('bet2 mag1_sos.nii BET -f 0.4 -m');
% set a lower threshold for postmortem
% unix('bet2 mag1_sos.nii BET -f 0.1 -m');
unix('gunzip -f BET.nii.gz');
unix('gunzip -f BET_mask.nii.gz');
nii = load_nii('BET_mask.nii');
mask = double(nii.img);
% coil combination
[ph_corr,mag_corr] = poem(mag,ph,vox,TE,mask,[],0);
nii = make_nii(ph_corr);
save_nii(nii,'ph_corr.nii');
% save niftis after coil combination
mkdir('src');
for echo = 1:imsize(4)
nii = make_nii(mag_corr(:,:,:,echo),vox);
save_nii(nii,['src/mag_corr' num2str(echo) '.nii']);
nii = make_nii(ph_corr(:,:,:,echo),vox);
save_nii(nii,['src/ph_corr' num2str(echo) '.nii']);
end
save('raw.mat','ph_corr','mag_corr','mask');
% unwrap the phase using best path
disp('--> unwrap aliasing phase using bestpath...');
mask_unwrp = uint8(abs(mask)*255);
fid = fopen('mask_unwrp.dat','w');
fwrite(fid,mask_unwrp,'uchar');
fclose(fid);
[pathstr, ~, ~] = fileparts(which('3DSRNCP.m'));
setenv('pathstr',pathstr);
setenv('nv',num2str(imsize(1)));
setenv('np',num2str(imsize(2)));
setenv('ns',num2str(imsize(3)));
unph = zeros(imsize(1:4));
for echo_num = 1:imsize(4)
setenv('echo_num',num2str(echo_num));
fid = fopen(['wrapped_phase' num2str(echo_num) '.dat'],'w');
fwrite(fid,ph_corr(:,:,:,echo_num),'float');
fclose(fid);
bash_script = ['${pathstr}/3DSRNCP wrapped_phase${echo_num}.dat mask_unwrp.dat ' ...
'unwrapped_phase${echo_num}.dat $nv $np $ns reliability${echo_num}.dat'];
unix(bash_script) ;
fid = fopen(['unwrapped_phase' num2str(echo_num) '.dat'],'r');
tmp = fread(fid,'float');
% tmp = tmp - tmp(1);
unph(:,:,:,echo_num) = reshape(tmp - round(mean(tmp(mask==1))/(2*pi))*2*pi ,imsize(1:3)).*mask;
fclose(fid);
end
nii = make_nii(unph,vox);
save_nii(nii,'unph_bestpath_before_jump_correction.nii');
% remove all the temp files
! rm *.dat
% 2pi jumps correction
nii = load_nii('unph_diff.nii');
unph_diff = double(nii.img);
for echo = 2:imsize(4)
meandiff = unph(:,:,:,echo)-unph(:,:,:,1)-double(echo-1)*unph_diff;
meandiff = meandiff(mask==1);
meandiff = mean(meandiff(:));
njump = round(meandiff/(2*pi));
disp([' ' num2str(njump) ' 2pi jumps for TE' num2str(echo)]);
unph(:,:,:,echo) = unph(:,:,:,echo) - njump*2*pi;
unph(:,:,:,echo) = unph(:,:,:,echo).*mask;
end
nii = make_nii(unph,vox);
save_nii(nii,'unph_bestpath.nii');
save('raw.mat','unph','-append');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% set parameters
fit_thr = 40;
tik_reg = 1e-6;
% cgs_num = 500; % probably don't need this many, too slow
lsqr_num = 500; % probably don't need this many, too slow
% tv_reg = 2e-4;
inv_num = 500;
dicom_info.MagneticFieldStrength = 7;
% fit phase images with echo times
disp('--> magnitude weighted LS fit of phase to TE ...');
[tfs_0, fit_residual_0] = echofit(unph,mag_corr,TE,0);
% [tfs_0, fit_residual_0] = echofit(unph,mag_corr,TE,1);
% normalize to main field
% ph = gamma*dB*TE
% dB/B = ph/(gamma*TE*B0)
% units: TE s, gamma 2.675e8 rad/(sT), B0 7T
tfs_0 = tfs_0/(2.675e8*dicom_info.MagneticFieldStrength)*1e6; % unit ppm
nii = make_nii(tfs_0,vox);
save_nii(nii,'tfs_0.nii');
nii = make_nii(fit_residual_0,vox);
save_nii(nii,'fit_residual_0.nii');
% extra filtering according to fitting residuals
% generate reliability map
fit_residual_0_blur = smooth3(fit_residual_0,'box',round(1./vox)*2+1);
nii = make_nii(fit_residual_0_blur,vox);
save_nii(nii,'fit_residual_0_blur.nii');
R_0 = ones(size(fit_residual_0_blur));
R_0(fit_residual_0_blur >= fit_thr) = 0;
% % save('raw.mat','tfs_0','fit_residual_0','fit_residual_0_blur','R_0','fit_thr','lsqr_num','tik_reg','inv_num','-append');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% load('raw.mat','tfs_0','mask','R_0','vox','cgs_num','dicom_info','z_prjs','mag_corr','imsize','TE');
for smv_rad = [1 2 3]
% for smv_rad = [1 2 3]
% RE-SHARP (tik_reg: Tikhonov regularization parameter)
disp('--> RESHARP to remove background field ...');
[lfs_resharp_0, mask_resharp_0] = resharp_lsqr(tfs_0,mask.*R_0,vox,smv_rad,lsqr_num);
% [lfs_resharp_0, mask_resharp_0] = resharp(tfs_0,mask.*R_0,vox,smv_rad,tik_reg,cgs_num);
% save nifti
mkdir('RESHARP');
nii = make_nii(lfs_resharp_0,vox);
save_nii(nii,['RESHARP/lfs_resharp_0_smvrad' num2str(smv_rad) '_lsqr.nii']);
% save_nii(nii,['RESHARP/lfs_resharp_0_smvrad' num2str(smv_rad) '_cgs_' num2str(tik_reg) '.nii']);
% iLSQR
chi_iLSQR_0 = QSM_iLSQR(lfs_resharp_0*(2.675e8*dicom_info.MagneticFieldStrength)/1e6,mask_resharp_0,'H',z_prjs,'voxelsize',vox,'niter',50,'TE',1000,'B0',dicom_info.MagneticFieldStrength);
nii = make_nii(chi_iLSQR_0,vox);
save_nii(nii,['RESHARP/chi_iLSQR_smvrad' num2str(smv_rad) '.nii']);
% % MEDI
% %%%%% normalize signal intensity by noise to get SNR %%%
% %%%% Generate the Magnitude image %%%%
% iMag = sqrt(sum(mag_corr.^2,4));
% % [iFreq_raw N_std] = Fit_ppm_complex(ph_corr);
% matrix_size = single(imsize(1:3));
% voxel_size = vox;
% delta_TE = TE(2) - TE(1);
% B0_dir = z_prjs';
% CF = dicom_info.ImagingFrequency *1e6;
% iFreq = [];
% N_std = 1;
% RDF = lfs_resharp_0*2.675e8*dicom_info.MagneticFieldStrength*delta_TE*1e-6;
% Mask = mask_resharp_0;
% save RDF.mat RDF iFreq iMag N_std Mask matrix_size...
% voxel_size delta_TE CF B0_dir;
% QSM = MEDI_L1('lambda',1000);
% nii = make_nii(QSM.*Mask,vox);
% save_nii(nii,['RESHARP/MEDI1000_RESHARP_smvrad' num2str(smv_rad) '.nii']);
% %TVDI
% sus_resharp = tvdi(lfs_resharp_0,mask_resharp_0,vox,2e-4,iMag,z_prjs,500);
% nii = make_nii(sus_resharp.*mask_resharp_0,vox);
% save_nii(nii,['RESHARP/TV_2e-4_smvrad' num2str(smv_rad) '.nii']);
end
cd(curDir)
end
|
github
|
sunhongfu/scripts-master
|
phantom_lcurve.m
|
.m
|
scripts-master/LN-QSM/phantom_lcurve.m
| 4,102 |
utf_8
|
de2edf5838b6fd782d17c0f8b21a3556
|
function [Res_term,TV_term,Tik_term] = phantom_lcurve(mask_tissue, field)
TIKs={'10.0000e-006', '18.3298e-006', '33.5982e-006', '61.5848e-006', '112.8838e-006', '206.9138e-006', '379.2690e-006', '695.1928e-006', '1.2743e-003', '2.3357e-003', '4.2813e-003', '7.8476e-003', '14.3845e-003', '26.3665e-003', '48.3293e-003', '88.5867e-003', '162.3777e-003', '297.6351e-003', '545.5595e-003', '1.0000e+000'};
% TIKs={'206.9138e-006'};
% TVs={'1e-4','2e-4','3e-4','4e-4','5e-4'};
TVs={'1e-4'};
% rmse_tik = zeros(length(TVs),length(TIKs));
for i = 1:length(TVs)
for j = 1:length(TIKs)
nii = load_nii(['TIK_tissue_ero0_TV_' num2str(str2num(TVs{i})) '_Tik_' num2str(str2num(TIKs{j})) '_PRE_5000.nii']);
tik = double(nii.img);
vox = [1 1 1];
z_prjs = [0 0 1]
% create K-space filter kernel D
%%%%% make this a seperate function in the future
[Nx, Ny, Nz] = size(tik);
FOV = vox.*[Nx, Ny, Nz];
FOVx = FOV(1);
FOVy = FOV(2);
FOVz = FOV(3);
x = -Nx/2:Nx/2-1;
y = -Ny/2:Ny/2-1;
z = -Nz/2:Nz/2-1;
[kx, ky, kz] = ndgrid(x/FOVx,y/FOVy,z/FOVz);
D = 1/3 - (kx.*z_prjs(1) + ky.*z_prjs(2) + kz.*z_prjs(3)).^2 ./ (kx.^2 + ky.^2 + kz.^2);
D(floor(Nx/2+1), floor(Ny/2+1), floor(Nz/2+1)) = 0;
D = fftshift(D);
% parameter structures for inversion
% data consistancy and TV term objects
params.FT = cls_dipconv([Nx, Ny, Nz], D); % class for dipole kernel convolution
params.TV = cls_tv; % class for TV operation
params.Tik_mask = mask_tissue;
params.TV_mask = mask_tissue;
params.sus_mask = mask_tissue;
params.Res_wt = mask_tissue;
params.P = 1;
params.data = field;
[Res_term(i,j),TV_term(i,j),Tik_term(i,j)] = objFunc(tik, params);
% tik_mean = tik(logical(mask_tissue));
% tik_mean = mean(tik_mean(:));
% err_tik = (tik - tik_mean - model + model_mean).*mask_tissue;
% TVs{i}
% TIKs{j}
% rmse_tik(i,j) = sqrt(sum(err_tik(:).^2)/sum(mask_tissue(:)));
% % plot the bar graphs
% tik_normalized = tik - tik_mean + model_mean;
% % y = [0 mean(tik_normalized(ROI_skull(:))); 1e-4 mean(tik_normalized(ROI_WM(:))); 0.02 mean(tik_normalized(ROI_GM(:))); -0.014 mean(tik_normalized(ROI_CSF(:))); 0.45 mean(tik_normalized(ROI_veins(:))); 0.09 mean(tik_normalized(ROI_PU(:))); 0.06 mean(tik_normalized(ROI_CN(:))); 0.18 mean(tik_normalized(ROI_GP(:))); 0.01 mean(tik_normalized(ROI_TH(:))); -3 mean(tik_normalized(ROI_teeth(:)))];
% y = [-0.014 mean(tik_normalized(ROI_CSF(:))) mean(tfi_normalized(ROI_CSF(:))); 1e-4 mean(tik_normalized(ROI_WM(:))) mean(tfi_normalized(ROI_WM(:))); 0.01 mean(tik_normalized(ROI_TH(:))) mean(tfi_normalized(ROI_TH(:))); 0.02 mean(tik_normalized(ROI_GM(:))) mean(tfi_normalized(ROI_GM(:))); 0.06 mean(tik_normalized(ROI_CN(:))) mean(tfi_normalized(ROI_CN(:))); 0.09 mean(tik_normalized(ROI_PU(:))) mean(tfi_normalized(ROI_PU(:))); 0.18 mean(tik_normalized(ROI_GP(:))) mean(tfi_normalized(ROI_GP(:))); 0.45 mean(tik_normalized(ROI_veins(:))) mean(tfi_normalized(ROI_veins(:))); ];
% yy = [0 std(tik_normalized(ROI_CSF(:))) std(tfi_normalized(ROI_CSF(:))); 0 std(tik_normalized(ROI_WM(:))) std(tfi_normalized(ROI_WM(:))); 0 std(tik_normalized(ROI_TH(:))) std(tfi_normalized(ROI_TH(:))); 0 std(tik_normalized(ROI_GM(:))) std(tfi_normalized(ROI_GM(:))); 0 std(tik_normalized(ROI_CN(:))) std(tfi_normalized(ROI_CN(:))); 0 std(tik_normalized(ROI_PU(:))) std(tfi_normalized(ROI_PU(:))); 0 std(tik_normalized(ROI_GP(:))) std(tfi_normalized(ROI_GP(:))); 0 std(tik_normalized(ROI_veins(:))) std(tfi_normalized(ROI_veins(:))); ];
% figure; hold on; bar(y); errorbar(y,yy)
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [Res_term,TV_term,Tik_term] = objFunc(m, params)
p = 1;
w2 = params.TV*(params.P.*m.*params.TV_mask);
TV = (w2.*conj(w2)+eps).^(p/2);
TV_term = sum(TV(:));
Res_term = params.FT*(params.P.*m.*params.sus_mask) - params.data;
Res_term = (params.Res_wt(:).*Res_term(:))'*(params.Res_wt(:).*Res_term(:));
Tik_term = (params.P(:).*params.Tik_mask(:).*m(:))'*(params.P(:).*params.Tik_mask(:).*m(:));
|
github
|
sunhongfu/scripts-master
|
normalize_chi.m
|
.m
|
scripts-master/LN-QSM/atlas_meas/normalize_chi.m
| 4,648 |
utf_8
|
cf2083aa8bb3fc825f4aabb7179bfe6e
|
function normalize_chi(seg_dir, chi, refregion)
%seg_dir = [master_dir, subjectID, '/QSM_baseline/', 'seg/'];
[chi_dir, chi_filename, chi_file_ext] = fileparts(chi);
defineMasks;
if (strcmp(refregion, 'dwm'))
chi_dir = [chi_dir, '/chi_dwm_ref'];
if (~exist(chi_dir, 'dir'))
mkdir(chi_dir);
end
chi_abs = [chi_dir, '/',chi_filename, '_abs', chi_file_ext];
cd(chi_dir)
diary('log_dwm_stats');
ref_mask = [seg_dir, 'DWM_mask_erode2v.mnc'];
%ref_mask_sus = -0.03;
ref_mask_sus = 0.0;
display(['Referened mask used is ', ref_mask]);
[hdr_chi, chi_vol] = niak_read_minc(chi);
[hdr_tmp, ref_mask_vol] = niak_read_minc(ref_mask);
[chi_abs_vol, std_ref] = getAbsSuscWithRef(chi_vol, ref_mask_vol, ref_mask_sus);
hdr_chi.file_name = chi_abs;
niak_write_minc(hdr_chi, chi_abs_vol);
save([chi_filename, '_chi_ref.mat'], 'chi_abs_vol', 'std_ref');
diary off;
elseif (strcmp(refregion, 'pic'))
chi_dir = [chi_dir, '/chi_pic_ref'];
if (~exist(chi_dir, 'dir'))
mkdir(chi_dir);
end
chi_abs = [chi_dir, '/',chi_filename, '_abs', chi_file_ext];
cd(chi_dir)
diary('log_pic_stats');
ref_mask = [seg_dir, 'PIC_mask_erode2v.mnc'];
ref_mask_sus = -0.05;
display(['Referened mask used is ', ref_mask]);
[hdr_chi, chi_vol] = niak_read_minc(chi);
[hdr_tmp, ref_mask_vol] = niak_read_minc(ref_mask);
[chi_abs_vol, std_ref] = getAbsSuscWithRef(chi_vol, ref_mask_vol, ref_mask_sus);
hdr_chi.file_name = chi_abs;
niak_write_minc(hdr_chi, chi_abs_vol);
save([chi_filename, '_chi_ref.mat'], 'chi_abs_vol', 'std_ref');
elseif (strcmp(refregion, 'csf'))
chi_dir = [chi_dir, '/chi_csf_ref'];
if (~exist(chi_dir, 'dir'))
mkdir(chi_dir);
end
chi_abs = [chi_dir, '/',chi_filename, '_abs', chi_file_ext];
cd(chi_dir)
diary('log_csf_stats');
ref_mask = [seg_dir, 'csf_ant_mask.mnc'];
ref_mask_sus = 0;
display(['Referened mask used is ', ref_mask]);
[hdr_chi, chi_vol] = niak_read_minc(chi);
[hdr_tmp, ref_mask_vol] = niak_read_minc(ref_mask);
[chi_abs_vol, std_ref] = getAbsSuscWithRef(chi_vol, ref_mask_vol, ref_mask_sus);
hdr_chi.file_name = chi_abs;
niak_write_minc(hdr_chi, chi_abs_vol);
save([chi_filename, '_chi_ref.mat'], 'chi_abs_vol', 'std_ref');
elseif (strcmp(refregion, 'none'))
chi_dir = [chi_dir, '/chi_none_ref'];
if (~exist(chi_dir, 'dir'))
mkdir(chi_dir);
end
cd(chi_dir);
chi_abs = [chi_dir, '/',chi_filename, '_abs', chi_file_ext];
[hdr_tmp, chi_abs_vol]=niak_read_minc(chi);
hdr_chi.file_name = chi_abs;
niak_write_minc(hdr_chi, chi_abs_vol);
std_ref = 0;
cd(chi_dir);
save([chi_filename, '_chi_ref'], 'chi_abs_vol', 'std_ref');
end
%plotWMhistorgram(chi, seg_dir, mask_names);
end
%%
function [chi_abs_vol, std_chi_masked] = getAbsSuscWithRef(chi_vol, ref_mask_vol, ref_mask_sus)
% use the average susceptibility in ref_mask as a reference
mask = logical(ref_mask_vol);
chi_masked = chi_vol(mask);
avg_chi_masked = mean(chi_masked);
std_chi_masked = std(chi_masked);
chi_abs_vol = chi_vol - (avg_chi_masked - ref_mask_sus);
fprintf('The susceptibility offset of the masked structure is %.5f ppm, the std is %.5f ppm \n', (avg_chi_masked - ref_mask_sus), std_chi_masked);
end
%%
function plotWMhistorgram(chi, seg_dir, mask_names)
[chi_dir, chi_filename, chi_file_ext] = fileparts(chi);
cd(chi_dir);
result_dir = 'chi_in_struct';
if ~(exist(result_dir, 'dir'))
mkdir(result_dir);
end
cd(result_dir);
close all;
set_figure_defaults;
hfig=figure(100),
for ii=1:(length(mask_names)-9) %only wm structures here
if(exist([result_dir, chi_filename, '_', mask_names{ii}, '_chi.mat'], 'file'))
load([result_dir, chi_filename, '_', mask_names{ii}, '_chi']);
else
segmented_mask=[mask_names{ii},'_mask.mnc'];
eroded_mask=[mask_names{ii},'_mask_eroded.mnc'];
system(['mincmorph -clob -successive E ', seg_dir, segmented_mask, ' ', seg_dir, eroded_mask]);
clear avg_chi;
clear std_chi;
clear chi_struct;
[avg_chi, std_chi, chi_struct] = calc_avg_std_w_mask(chi, [seg_dir, eroded_mask]);
save([chi_filename, '_', mask_names{ii}, '_chi'], 'avg_chi', 'std_chi', 'chi_struct');
end
subplot(3,4, ii), h=histogram(chi_struct);
title(sprintf([mask_names{ii}, ' %3.1f +/- %3.1f ppb'], avg_chi*1000,std_chi*1000), 'FontSize', 10);
xlim([-0.1 0.1]);
hold on;
end
savefig(hfig, [chi_filename, '_', 'wm_struct_hist.fig']);
close all;
end
|
github
|
sunhongfu/scripts-master
|
tik_qsm_helix.m
|
.m
|
scripts-master/HELIX/tik_qsm/tik_qsm_helix.m
| 7,399 |
utf_8
|
b26b1e788eb4ce6b9d6a1c9ca7b455f2
|
%Tik-QSM helix script
function tik_qsm_helix(data_path,erosion)
erosion = str2num(erosion);
cd(data_path);
load('all.mat','mask','R','matrix_size','voxel_size','delta_TE','B0_dir','CF','iMag','N_std','iFreq','tfs','vox','dicom_info','z_prjs');
% apply R
mask = mask.*R;
% mask_erosion
r = 1;
[X,Y,Z] = ndgrid(-r:r,-r:r,-r:r);
h = (X.^2/r^2 + Y.^2/r^2 + Z.^2/r^2 <= 1);
ker = h/sum(h(:));
imsize = size(mask);
mask_tmp = convn(mask,ker,'same');
mask_ero1 = zeros(imsize);
mask_ero1(mask_tmp > 0.999999) = 1; % no error tolerance
r = 2;
[X,Y,Z] = ndgrid(-r:r,-r:r,-r:r);
h = (X.^2/r^2 + Y.^2/r^2 + Z.^2/r^2 <= 1);
ker = h/sum(h(:));
imsize = size(mask);
mask_tmp = convn(mask,ker,'same');
mask_ero2 = zeros(imsize);
mask_ero2(mask_tmp > 0.999999) = 1; % no error tolerance
r = 3;
[X,Y,Z] = ndgrid(-r:r,-r:r,-r:r);
h = (X.^2/r^2 + Y.^2/r^2 + Z.^2/r^2 <= 1);
ker = h/sum(h(:));
imsize = size(mask);
mask_tmp = convn(mask,ker,'same');
mask_ero3 = zeros(imsize);
mask_ero3(mask_tmp > 0.999999) = 1; % no error tolerance
nii = make_nii(mask,vox);
save_nii(nii,'mask_ero0.nii');
nii = make_nii(mask_ero1,vox);
save_nii(nii,'mask_ero1.nii');
nii = make_nii(mask_ero2,vox);
save_nii(nii,'mask_ero2.nii');
nii = make_nii(mask_ero3,vox);
save_nii(nii,'mask_ero3.nii');
% or from traditional tfs (prelude+fitting)
iFreq = tfs*2.675e8*dicom_info.MagneticFieldStrength*delta_TE*1e-6;
switch erosion
case 0
mkdir TFS_TIK_PRE_ERO0
cd TFS_TIK_PRE_ERO0
tfs_pad = padarray(iFreq/(2.675e8*dicom_info.MagneticFieldStrength*delta_TE*1e-6),[0 0 20]);
mask_pad = padarray(mask,[0 0 20]);
% R_pad = padarray(R,[0 0 20]);
r=0;
Tik_weight = [1e-3];
TV_weight = 4e-4;
for i = 1:length(Tik_weight)
% chi = tikhonov_qsm(tfs_pad, mask_pad, 1, mask_pad, mask_pad, TV_weight, Tik_weight(i), vox, z_prjs, 200);
% nii = make_nii(chi(:,:,21:end-20).*mask_pad(:,:,21:end-20),vox);
% save_nii(nii,['TIK_ero' num2str(r) '_TV_' num2str(TV_weight) '_Tik_' num2str(Tik_weight(i)) '_PRE_200.nii']);
% chi = tikhonov_qsm(tfs_pad, mask_pad, 1, mask_pad, mask_pad, TV_weight, Tik_weight(i), vox, z_prjs, 500);
% nii = make_nii(chi(:,:,21:end-20).*mask_pad(:,:,21:end-20),vox);
% save_nii(nii,['TIK_ero' num2str(r) '_TV_' num2str(TV_weight) '_Tik_' num2str(Tik_weight(i)) '_PRE_500.nii']);
% chi = tikhonov_qsm(tfs_pad, mask_pad, 1, mask_pad, mask_pad, TV_weight, Tik_weight(i), vox, z_prjs, 2000);
% nii = make_nii(chi(:,:,21:end-20).*mask_pad(:,:,21:end-20),vox);
% save_nii(nii,['TIK_ero' num2str(r) '_TV_' num2str(TV_weight) '_Tik_' num2str(Tik_weight(i)) '_PRE_2000.nii']);
chi = tikhonov_qsm(tfs_pad, mask_pad, 1, mask_pad, mask_pad, TV_weight, Tik_weight(i), vox, z_prjs, 5000);
nii = make_nii(chi(:,:,21:end-20).*mask_pad(:,:,21:end-20),vox);
save_nii(nii,['TIK_ero' num2str(r) '_TV_' num2str(TV_weight) '_Tik_' num2str(Tik_weight(i)) '_PRE_5000.nii']);
end
cd ..
case 1
mkdir TFS_TIK_PRE_ERO1
cd TFS_TIK_PRE_ERO1
tfs_pad = padarray(iFreq/(2.675e8*dicom_info.MagneticFieldStrength*delta_TE*1e-6),[0 0 20]);
mask_pad = padarray(mask_ero1,[0 0 20]);
% R_pad = padarray(R,[0 0 20]);
r=1;
Tik_weight = [1e-3];
TV_weight = 4e-4;
for i = 1:length(Tik_weight)
% chi = tikhonov_qsm(tfs_pad, mask_pad, 1, mask_pad, mask_pad, TV_weight, Tik_weight(i), vox, z_prjs, 200);
% nii = make_nii(chi(:,:,21:end-20).*mask_pad(:,:,21:end-20),vox);
% save_nii(nii,['TIK_ero' num2str(r) '_TV_' num2str(TV_weight) '_Tik_' num2str(Tik_weight(i)) '_PRE_200.nii']);
% chi = tikhonov_qsm(tfs_pad, mask_pad, 1, mask_pad, mask_pad, TV_weight, Tik_weight(i), vox, z_prjs, 500);
% nii = make_nii(chi(:,:,21:end-20).*mask_pad(:,:,21:end-20),vox);
% save_nii(nii,['TIK_ero' num2str(r) '_TV_' num2str(TV_weight) '_Tik_' num2str(Tik_weight(i)) '_PRE_500.nii']);
% chi = tikhonov_qsm(tfs_pad, mask_pad, 1, mask_pad, mask_pad, TV_weight, Tik_weight(i), vox, z_prjs, 2000);
% nii = make_nii(chi(:,:,21:end-20).*mask_pad(:,:,21:end-20),vox);
% save_nii(nii,['TIK_ero' num2str(r) '_TV_' num2str(TV_weight) '_Tik_' num2str(Tik_weight(i)) '_PRE_2000.nii']);
chi = tikhonov_qsm(tfs_pad, mask_pad, 1, mask_pad, mask_pad, TV_weight, Tik_weight(i), vox, z_prjs, 5000);
nii = make_nii(chi(:,:,21:end-20).*mask_pad(:,:,21:end-20),vox);
save_nii(nii,['TIK_ero' num2str(r) '_TV_' num2str(TV_weight) '_Tik_' num2str(Tik_weight(i)) '_PRE_5000.nii']);
end
cd ..
case 2
mkdir TFS_TIK_PRE_ERO2
cd TFS_TIK_PRE_ERO2
tfs_pad = padarray(iFreq/(2.675e8*dicom_info.MagneticFieldStrength*delta_TE*1e-6),[0 0 20]);
mask_pad = padarray(mask_ero2,[0 0 20]);
% R_pad = padarray(R,[0 0 20]);
r=2;
Tik_weight = [1e-3];
TV_weight = 4e-4;
for i = 1:length(Tik_weight)
% chi = tikhonov_qsm(tfs_pad, mask_pad, 1, mask_pad, mask_pad, TV_weight, Tik_weight(i), vox, z_prjs, 200);
% nii = make_nii(chi(:,:,21:end-20).*mask_pad(:,:,21:end-20),vox);
% save_nii(nii,['TIK_ero' num2str(r) '_TV_' num2str(TV_weight) '_Tik_' num2str(Tik_weight(i)) '_PRE_200.nii']);
% chi = tikhonov_qsm(tfs_pad, mask_pad, 1, mask_pad, mask_pad, TV_weight, Tik_weight(i), vox, z_prjs, 500);
% nii = make_nii(chi(:,:,21:end-20).*mask_pad(:,:,21:end-20),vox);
% save_nii(nii,['TIK_ero' num2str(r) '_TV_' num2str(TV_weight) '_Tik_' num2str(Tik_weight(i)) '_PRE_500.nii']);
% chi = tikhonov_qsm(tfs_pad, mask_pad, 1, mask_pad, mask_pad, TV_weight, Tik_weight(i), vox, z_prjs, 2000);
% nii = make_nii(chi(:,:,21:end-20).*mask_pad(:,:,21:end-20),vox);
% save_nii(nii,['TIK_ero' num2str(r) '_TV_' num2str(TV_weight) '_Tik_' num2str(Tik_weight(i)) '_PRE_2000.nii']);
chi = tikhonov_qsm(tfs_pad, mask_pad, 1, mask_pad, mask_pad, TV_weight, Tik_weight(i), vox, z_prjs, 5000);
nii = make_nii(chi(:,:,21:end-20).*mask_pad(:,:,21:end-20),vox);
save_nii(nii,['TIK_ero' num2str(r) '_TV_' num2str(TV_weight) '_Tik_' num2str(Tik_weight(i)) '_PRE_5000.nii']);
end
cd ..
case 3
mkdir TFS_TIK_PRE_ERO3
cd TFS_TIK_PRE_ERO3
tfs_pad = padarray(iFreq/(2.675e8*dicom_info.MagneticFieldStrength*delta_TE*1e-6),[0 0 20]);
mask_pad = padarray(mask_ero3,[0 0 20]);
% R_pad = padarray(R,[0 0 20]);
r=3;
Tik_weight = [1e-3];
TV_weight = 4e-4;
for i = 1:length(Tik_weight)
% chi = tikhonov_qsm(tfs_pad, mask_pad, 1, mask_pad, mask_pad, TV_weight, Tik_weight(i), vox, z_prjs, 200);
% nii = make_nii(chi(:,:,21:end-20).*mask_pad(:,:,21:end-20),vox);
% save_nii(nii,['TIK_ero' num2str(r) '_TV_' num2str(TV_weight) '_Tik_' num2str(Tik_weight(i)) '_PRE_200.nii']);
% chi = tikhonov_qsm(tfs_pad, mask_pad, 1, mask_pad, mask_pad, TV_weight, Tik_weight(i), vox, z_prjs, 500);
% nii = make_nii(chi(:,:,21:end-20).*mask_pad(:,:,21:end-20),vox);
% save_nii(nii,['TIK_ero' num2str(r) '_TV_' num2str(TV_weight) '_Tik_' num2str(Tik_weight(i)) '_PRE_500.nii']);
% chi = tikhonov_qsm(tfs_pad, mask_pad, 1, mask_pad, mask_pad, TV_weight, Tik_weight(i), vox, z_prjs, 2000);
% nii = make_nii(chi(:,:,21:end-20).*mask_pad(:,:,21:end-20),vox);
% save_nii(nii,['TIK_ero' num2str(r) '_TV_' num2str(TV_weight) '_Tik_' num2str(Tik_weight(i)) '_PRE_2000.nii']);
chi = tikhonov_qsm(tfs_pad, mask_pad, 1, mask_pad, mask_pad, TV_weight, Tik_weight(i), vox, z_prjs, 5000);
nii = make_nii(chi(:,:,21:end-20).*mask_pad(:,:,21:end-20),vox);
save_nii(nii,['TIK_ero' num2str(r) '_TV_' num2str(TV_weight) '_Tik_' num2str(Tik_weight(i)) '_PRE_5000.nii']);
end
cd ..
otherwise
warning('Unexpected value')
end
|
github
|
sunhongfu/scripts-master
|
fast_match.m
|
.m
|
scripts-master/MRF/recon/_src/fast_match.m
| 2,367 |
utf_8
|
0553bffb21a5aba89df9d74900aadc61
|
%%-----------------------------------------------------------------------%%
% Authors: M.A. Cloos
% [email protected]
% Date: 2019 april 23
% New York University School of Medicine, www.cai2r.net
%%-----------------------------------------------------------------------%%
function [ maps, fits ] = fast_match( img , dictionary, partSize )
[nSl, nRe, nPh, ~] = size(img);
[nSv, nDi] = size(dictionary.atoms);
posm = zeros(nDi/partSize, nSl*nRe*nPh);
corm = zeros(nDi/partSize, nSl*nRe*nPh);
index = 1;
imv = reshape(img, [ nSl*nRe*nPh nSv ]);
% imv = single(imv');
imv = single(imv.');
%%-----------------------------------------------------------------------%%
% Matching
%%-----------------------------------------------------------------------%%
pb2 = CmdLineProgressBar(' Matching: ');
for ds=1:partSize:nDi
de = ds + partSize - 1;
atom = squeeze(dictionary.atoms(:,(ds:de)));
atom = atom';
[cor, pos] = max(atom*imv);
posm(index, :) = pos(:) + ds - 1;
corm(index, :) = cor(:);
index = index + 1;
pb2.print(de,nDi);
end
%%-----------------------------------------------------------------------%%
% Pick est matches from look uptable
%%-----------------------------------------------------------------------%%
[pdFact, pos] = max(corm);
maps = zeros(4 ,nSl*nRe*nPh);
fits = zeros(nSv,nSl*nRe*nPh);
for i=1:(nSl*nRe*nPh)
maps(:,i) = dictionary.lookup(:,posm(pos(i),i));
fits(:,i) = dictionary.atoms(:,posm(pos(i),i));
end
%%-----------------------------------------------------------------------%%
% Convert norm to PD
%%-----------------------------------------------------------------------%%
maps(1,:) = pdFact./maps(1,:);
%%-----------------------------------------------------------------------%%
% rescale svd images with PD
%%-----------------------------------------------------------------------%%
pdFact = repmat(pdFact,[nSv 1]);
fits = fits.*pdFact;
%%-----------------------------------------------------------------------%%
% reshape
%%-----------------------------------------------------------------------%%
maps = reshape(maps, [4, nSl,nRe,nPh]);
fits = reshape(fits, [nSv, nSl,nRe,nPh]);
% normalize the PD in the images
maps(1,:,:,:) = squeeze(maps(1,:,:,:)./(max(abs(squeeze(maps(1,:))))));
end
|
github
|
sunhongfu/scripts-master
|
make_mask.m
|
.m
|
scripts-master/MRF/recon/_src/make_mask.m
| 1,199 |
utf_8
|
be32180c308123c70236e66645a8f9b9
|
%%-----------------------------------------------------------------------%%
% Authors: M.A. Cloos
% [email protected]
% Date: 2019 March 3
% New York University School of Medicine, www.cai2r.net
%%-----------------------------------------------------------------------%%
function [mask] = make_mask(img, noi, invNoiseCov)
mask = img(:,:,:,1); %extract first eigen image
if numel(noi) == 1
%%-----------------------------------------------------------------------%%
% Mask based on mean signal
%%-----------------------------------------------------------------------%%
disp('Using mean signal to create mask.');
lim = mean(mask(:));
mask(mask < lim) = 0;
mask(mask > 0 ) = 1;
else
%%-----------------------------------------------------------------------%%
% Mask based on noise data
%%-----------------------------------------------------------------------%%
disp('Using std(noise) to create mask.');
% tmp = sum(noi,3); %sum over rx channels
tmp = squeeze(noi(1,1,:,:));
tmp = sum(invNoiseCov*tmp);
lim = std(tmp(:));
mask(mask < lim) = 0;
mask(mask > 0 ) = 1;
end
end
|
github
|
sunhongfu/scripts-master
|
mrf_match_cpp.m
|
.m
|
scripts-master/MRF/recon/_src/mrf_match_cpp.m
| 1,329 |
utf_8
|
08aa32f48dff6ba7d52f53939d4d4aa0
|
% MRF_MATCH_CPP: performs the dictionary matching via a exteral c++ program
%%-----------------------------------------------------------------------%%
% Authors: M.A. Cloos
% [email protected]
% Date: 2016 Oct 4
% New York University School of Medicine, www.cai2r.net
%%-----------------------------------------------------------------------%%
function [] = mrf_match_cpp(img)
%%-----------------------------------------------------------------------%%
% Make directory to hold the binary data
%%-----------------------------------------------------------------------%%
if ~exist('./4_cpp', 'dir')
mkdir('./4_cpp');
end
%%-----------------------------------------------------------------------%%
% Export data for C++ dictionary matching
%%-----------------------------------------------------------------------%%
for sl=1:size(img,1)
data = real(permute(squeeze(img(sl,:,:,:)), [3 1 2]));
data = single(data(:));
file_id = sprintf('./4_cpp/mrf_data_4_cpp_match_%04d', sl);
fid = fopen(file_id,'w');
fwrite(fid, data, 'single');
fclose(fid);
end
mask = single(ones(size(img,2),size(img,3)));
fid = fopen('./4_cpp/mrf_mask_4_cpp_matc.float','w');
fwrite(fid, mask, 'single');
fclose(fid);
end
|
github
|
sunhongfu/scripts-master
|
make_im.m
|
.m
|
scripts-master/MRF/recon/_src/make_im.m
| 1,301 |
utf_8
|
4af368d0a66197174fd5090e9cb63fb7
|
%%-----------------------------------------------------------------------%%
% Authors: M.A. Cloos
% [email protected]
% Date: 2019 March 3
% New York University School of Medicine, www.cai2r.net
%%-----------------------------------------------------------------------%%
function [img] = make_im(MrData)
%%-----------------------------------------------------------------------%%
% Extract the tradjectory & dimenions
%%-----------------------------------------------------------------------%%
trj = get_trajectory(MrData);
dim = MrData.Dim;
%%-----------------------------------------------------------------------%%
% Reconstruct the images
%%-----------------------------------------------------------------------%%
I_rx = zeros(dim.nSl,dim.nRe,dim.nRe,dim.nCh);
echo = 1;
FT = NUFFT(squeeze(trj.k(1,:,:,:)), squeeze(trj.w(1,:,:,:)), 1, 0, [dim.nRe,dim.nRe], 2);
for sl=1:dim.nSl
for ch=1:dim.nCh
I_rx(sl,:,:,ch)=FT'*double(squeeze(MrData.data(echo,sl,ch,:,:)));
end
end
%%-----------------------------------------------------------------------%%
% sum of squares
%%-----------------------------------------------------------------------%%
img = sqrt(abs(sum(I_rx.*conj(I_rx),4)));
end
|
github
|
sunhongfu/scripts-master
|
opt_comb.m
|
.m
|
scripts-master/MRF/recon/_src/opt_comb.m
| 805 |
utf_8
|
726066a1c0e3471e0fdf31cc29553ff9
|
%%-----------------------------------------------------------------------%%
% Authors: M.A. Cloos
% [email protected]
% Date: 2019 March 3
% New York University School of Medicine, www.cai2r.net
%%-----------------------------------------------------------------------%%
function [opt_img] = opt_comb(imgs, rx, invNoiseCov)
if(numel(invNoiseCov)>1)
nRe = size(imgs,1);
nPh = size(imgs,2);
opt_img = zeros(nRe,nPh);
for irow = 1:nRe
for icol = 1:nPh
s_matrix = squeeze(rx(irow,icol,:));
i_matrix = squeeze(imgs(irow,icol,:));
opt_img(irow,icol) = (s_matrix')*invNoiseCov*i_matrix;
end
end
else
opt_img = squeeze(imgs);
end
end
|
github
|
sunhongfu/scripts-master
|
make_rx.m
|
.m
|
scripts-master/MRF/recon/_src/make_rx.m
| 2,625 |
utf_8
|
11c81b237689886f8c4b3833a00333f2
|
%%-----------------------------------------------------------------------%%
% Authors: M.A. Cloos
% [email protected]
% Date: 2019 March 3
% New York University School of Medicine, www.cai2r.net
%%-----------------------------------------------------------------------%%
function [I_rx] = make_rx(MrData, r, mode)
%%-----------------------------------------------------------------------%%
% Extract the tradjectory & dimenions
%%-----------------------------------------------------------------------%%
trj = get_trajectory(MrData);
dim = MrData.Dim;
r = round(r);
%%-----------------------------------------------------------------------%%
% Reconstruct the images
%%-----------------------------------------------------------------------%%
I_rx = zeros(dim.nSl,dim.nRe,dim.nRe,dim.nCh);
echo = 1;
if r < 1
p1 = 1;
p2 = dim.nRe;
elseif r<dim.nRe
p1 = (dim.nRe-r)/2;
p2 = round(dim.nRe/2 +r/2 +1);
else
p1 = 1;
p2 = dim.nRe;
end
FT = NUFFT(squeeze(trj.k(1,:,:,1)), squeeze(trj.w(1,:,:,1)), 1, 0, [dim.nRe,dim.nRe], 2);
for sl=1:dim.nSl
for ch=1:dim.nCh
tmp = squeeze(MrData.data(echo,sl,ch,:,:,1));
tmp(1:p1 ,:) = 0.0;
tmp(p2:end,:) = 0.0;
I_rx(sl,:,:,ch)=FT'*double(tmp);
end
end
%%-----------------------------------------------------------------------%%
% Extract images from radial pre-scan
%%-----------------------------------------------------------------------%%
if strcmp(mode, 'SOS')
I_body__rx = sqrt(abs(sum(I_rx.*conj(I_rx),4)));
else
I_body__rx = abs(I_rx(:,:,:,1));
end
% save('I_rx.mat','I_rx');
% save('ref','I_body__rx');
%%-----------------------------------------------------------------------%%
% Calculate ratios
%%-----------------------------------------------------------------------%%
I_rx = I_rx./repmat(I_body__rx,1,1,1,size(I_rx,4));
% %%-----------------------------------------------------------------------%%
% % Mask
% %%-----------------------------------------------------------------------%%
% mask = I_body__rx;
% lim = mean(mask(:));
% mask(mask < lim) = 0;
% mask(mask > lim) = 1;
% I_rx = I_rx.*repmat(mask,1,1,1,size(I_rx,4));
%
% %%-----------------------------------------------------------------------%%
% % Normalize
% %%-----------------------------------------------------------------------%%
% I_rx = I_rx/max(abs(I_rx(:)));
end
|
github
|
sunhongfu/scripts-master
|
mapVBVD.m
|
.m
|
scripts-master/MRF/recon/_src/_mapVBVD/mapVBVD.m
| 26,600 |
utf_8
|
a53854086a152c018d77f2e6027b0633
|
function twix_obj = mapVBVD(filename,varargin)
% Reads Siemens raw .dat file from VB/VD MRI raw data.
%
% Requires twix_map_obj.m
%
% Author: Philipp Ehses ([email protected])
%
%
% Philipp Ehses 11.02.07, original version
% [..]
% Philipp Ehses 22.03.11, port to VD11
% Felix Breuer 31.03.11, added support for noise & ref scans, speed fixes
% Philipp Ehses 19.08.11, complete reorganization of code, added
% siemens_data_obj class to improve readability
% Wolf Blecher 15.05.12, readout of slice position parameters for VB Data sets
% Wolf Blecher 11.06.12, added distinction between PATREF and PATREF PHASCOR
% Philipp Ehses 02.08.12, again massive code reorganization. The new class
% twix_map_obj.m now stores the memory position of
% each dataset (coils are included - size: NCol*NCha)
% The actual data is not read until it is demanded
% by a "data_obj()" call. This makes it possible
% to selectively read in only parts of the data
% (e.g. to preserve memory).
% Philipp Ehses 27.08.12, speed optimizations (avoiding of .-subsref calls)
% 07.09.12 Thanks to Stephen Yutzy for implementing support for raw data
% correction (currently only supported for VB software version).
% 15.01.13 Thanks to Zhitao Li for proper handling of SYNCDATA.
% Philipp Ehses 28.08.13, added support for VD13 multi-raid files
%
% Input:
%
% filename or simply meas. id, e.g. mapVBVD(122) (if file is in same path)
% optional arguments (see below)
%
% Output: twix_obj structure with elements (if available):
% .image: object for image scan
% .noise: object for noise scan
% .phasecor: object for phase correction scan
% .refscan: object for reference scan
% .refscanPC: object for phase correction scan for reference data
% .RTfeedback: object for realtime feedback data
% .phasestab: object for phase stabilization scan
%
%
% The raw data can be obtained by calling e.g. twix_obj.image() or for
% squeezed data twix_obj.image{''} (the '' are needed due to a limitation
% of matlab's overloading capabilities).
% Slicing is supported as well, e.g. twix_obj.image(:,:,1,:) will return
% only the first line of the full data set (all later dimensions are
% squeezed into one). Thus, slicing of the "memory-mapped" data objects
% works exactly the same as regular matlab array slicing - with one
% exception:
% The keyword 'end' is not supported.
% Overloading of the '()' and '{}' operators works by overloading matlab's
% built-in 'subsref' function. Matlab calls subsref whenever the operators
% '()', '{}', or '.' are called. In the latter case, the overloaded subsref
% just calls the built-in subsref function since we don't want to change
% the behaviour for '.'-calls. However, this has one minor consequence:
% There's no way (afaik) to know whether the original call was terminated
% with a semicolon. Thus, a call to e.g. twix_obj.image.NLin will produce
% no output with or without semicolon termination. 'a = twix_obj.image.NLin'
% will however produce the expected result.
%
%
% Order of raw data:
% 1) Columns
% 2) Channels/Coils
% 3) Lines
% 4) Partitions
% 5) Slices
% 6) Averages
% 7) (Cardiac-) Phases
% 8) Contrasts/Echoes
% 9) Measurements
% 10) Sets
% 11) Segments
% 12) Ida
% 13) Idb
% 14) Idc
% 15) Idd
% 16) Ide
%
%
% Optional parameters/flags:
%
% removeOS: removes oversampling (factor 2) in read direction
% doAverage: performs average (resulting avg-dim has thus size 1)
% ignoreSeg: ignores segment mdh index (works basically the same as
% the average flag)
% noWeightedAverage: disables proper weighting of averages (i.e. data is
% summed up instead of averaged)
% doRawDataCorrect: enables raw data correction if used in the acquisition
% (only works for VB atm)
%
% These flags can also be set/unset later, e.g "twix_obj.image.flagRemoveOS = 1"
%
%
% Examples:
% twix_obj = mapVBVD(measID);
%
% % return all image-data:
% image_data = twix_obj.image();
% % return all image-data with all singular dimensions removed/squeezed:
% image_data = twix_obj.image{''}; % '' necessary due to a matlab limitation
% % return only data for line numbers 1 and 5; all dims higher than 4 are
% % grouped into dim 5):
% image_data = twix_obj.image(:,:,[1 5],:,:);
% % return only data for coil channels 2 to 6; all dims higher than 4 are
% % grouped into dim 5); but work with the squeezed data order
% % => use '{}' instead of '()':
% image_data = twix_obj.image{:,2:6,:,:,:};
%
% So basically it works like regular matlab array slicing (but 'end' is
% not supported; note that there are still a few bugs with array slicing).
%
% % NEW: unsorted raw data (in acq. order):
% image_data = twix_obj.image.unsorted(); % no slicing supported atm
%
if ischar(filename)
% assume that complete path is given
if ~strcmpi(filename(end-3:end),'.dat');
filename=[filename '.dat']; %% adds filetype ending to file
end
else
% filename not a string, so assume that it is the MeasID
measID = filename;
filelist = dir('*.dat');
filesfound = 0;
for k=1:numel(filelist)
if regexp(filelist(k).name,['^meas_MID0*' num2str(measID) '.*\.dat'])==1
if filesfound == 0
filename = filelist(k).name;
end
filesfound = filesfound+1;
end
end
if filesfound == 0
error(['File with meas. id ' num2str(measID) ' not found.']);
elseif filesfound > 1
disp(['Multiple files with meas. id ' num2str(measID) ' found. Choosing first occurence.']);
end
end
% add absolute path, when no path is given
[pathstr, name, ext] = fileparts(filename);
if isempty(pathstr)
pathstr = pwd;
filename = fullfile(pathstr, [name ext]);
end
%%%%% Parse varargin %%%%%
% Definition of default parameters
arg.removeOS = false;
arg.doAverage = false;
arg.averageReps = false;
arg.averageSets = false;
arg.ignoreSeg = false;
arg.noWeightedAverage = false;
arg.bReadImaScan = true;
arg.bReadNoiseScan = true;
arg.bReadPCScan = true;
arg.bReadRefScan = true;
arg.bReadRefPCScan = true;
arg.bReadRTfeedback = true;
arg.bReadPhaseStab = true;
arg.doRawDataCorrect = false; %SRY
arg.onlyoneline = false;
k=1;
while k <= numel(varargin)
if ~ischar(varargin{k})
error('string expected');
end
switch lower(varargin{k})
case {'removeos','rmos'}
if numel(varargin) > k && ~ischar(varargin{k+1})
arg.removeOS = logical(varargin{k+1});
k = k+2;
else
arg.removeOS = true;
k = k+1;
end
case {'doaverage','doave','ave','average'}
if numel(varargin) > k && ~ischar(varargin{k+1})
arg.doAverage = logical(varargin{k+1});
k = k+2;
else
arg.doAverage = true;
k = k+1;
end
case {'averagereps','averagerepetitions'}
if numel(varargin) > k && ~ischar(varargin{k+1})
arg.averageReps = logical(varargin{k+1});
k = k+2;
else
arg.averageReps = true;
k = k+1;
end
case {'averagesets'}
if numel(varargin) > k && ~ischar(varargin{k+1})
arg.averageSets = logical(varargin{k+1});
k = k+2;
else
arg.averageSets = true;
k = k+1;
end
case {'ignseg','ignsegments','ignoreseg','ignoresegments'}
if numel(varargin) > k && ~ischar(varargin{k+1})
arg.ignoreSeg = logical(varargin{k+1});
k = k+2;
else
arg.ignoreSeg = true;
k = k+1;
end
case {'noweightedaverage','noweightedave','noweighting'}
if numel(varargin) > k && ~ischar(varargin{k+1})
arg.noWeightedAverage = logical(varargin{k+1});
k = k+2;
else
arg.noWeightedAverage = true;
k = k+1;
end
case {'rawdatacorrect','dorawdatacorrect'}
%SRY: handle raw data correct arguments
if numel(varargin) > k && ~ischar(varargin{k+1})
arg.doRawDataCorrect = logical(varargin{k+1});
k = k+2;
else
arg.doRawDataCorrect = true;
k = k+1;
end
case {'onlyoneline'}
arg.onlyoneline = true;
k = k+1;
otherwise
error('Argument not recognized.');
end
end
clear varargin
%%%%%%%%%%%%%%%%%%%%%%%%%%
tic;
fid = fopen(filename,'r','l','US-ASCII');
fseek(fid,0,'eof');
fileSize = ftell(fid);
% start of actual measurment data (sans header)
fseek(fid,0,'bof');
firstInt = fread(fid,1,'uint32');
secondInt = fread(fid,1,'uint32');
% lazy software version check (VB or VD?)
if and(firstInt < 10000, secondInt <= 64)
version = 'vd';
disp('Software version: VD (!?)');
% number of different scans in file stored in 2nd in
NScans = secondInt;
measID = fread(fid,1,'uint32');
fileID = fread(fid,1,'uint32');
% measOffset: points to beginning of header, usually at 10240 bytes
measOffset = fread(fid,1,'uint64');
measLength = fread(fid,1,'uint64');
fseek(fid,measOffset,'bof');
hdrLength = fread(fid,1,'uint32');
datStart = measOffset + hdrLength;
else
% in VB versions, the first 4 bytes indicate the beginning of the
% raw data part of the file
version = 'vb';
disp('Software version: VB (!?)');
datStart = firstInt;
NScans = 1; % VB does not support multiple scans in one file
end
%SRY read data correction factors
% do this for all VB datasets, so that the factors are available later
% in the image_obj if the user chooses to set the correction flag
if (strcmp(version, 'vb')) % not implemented/tested for vd, yet
frewind(fid);
while ( (ftell(fid) < datStart) && ~exist('rawfactors', 'var'))
line = fgetl(fid);
%find the section of the protocol
%note: the factors are also available in <ParamArray."CoilSelects">
%along with element name and FFT scale, but the parsing is
%significantly more difficult
if (~isempty(strfind(line, '<ParamArray."axRawDataCorrectionFactor">')))
while (ftell(fid) < datStart)
line = fgetl(fid);
%find the line with correction factors
%the factors are on the first line that begins with this
%pattern
if (~isempty(strfind(line, '{ { { ')))
line = strrep(line, '} { } ', '0.0');
line = strrep(line, '{', '');
line = strrep(line, '}', '');
rawfactors = textscan(line, '%f');
rawfactors = rawfactors{1}; %textscan returns a 1x1 cell array
% this does not work in this location because the MDHs
% have not been parsed yet
% if (length(rawfactors) ~= 2*max(image_obj.NCha))
% error('Number of raw factors (%f) does not equal channel count (%d)', length(rawfactors)/2, image_obj.NCha);
% end;
if (mod(length(rawfactors),2) ~= 0)
error('Error reading rawfactors');
end;
%note the transpose, this makes the vector
%multiplication during the read easier
arg.rawDataCorrectionFactors = rawfactors(1:2:end).' + 1i*rawfactors(2:2:end).';
break;
end
end
end
end
disp('Read raw data correction factors');
end
% data will be read in two steps (two while loops):
% 1) reading all MDHs to find maximum line no., partition no.,... for
% ima, ref,... scan
% 2) reading the data
prevLength = 0;
tic;
percentFinished = 0;
cPos = datStart;
twix_obj = cell(1,NScans);
for s=1:NScans
% declare data objects:
twix_obj{s}.image = twix_map_obj(arg,'image',filename,version);
twix_obj{s}.noise = twix_map_obj(arg,'noise',filename,version);
twix_obj{s}.phasecor = twix_map_obj(arg,'phasecor',filename,version);
twix_obj{s}.refscan = twix_map_obj(arg,'refscan',filename,version);
twix_obj{s}.refscanPC = twix_map_obj(arg,'refscan_phasecor',filename,version);
twix_obj{s}.RTfeedback = twix_map_obj(arg,'rtfeedback',filename,version);
twix_obj{s}.phasestab = twix_map_obj(arg,'phasestab',filename,version);
mask.MDH_ACQEND = 0;
frewind(fid);
while cPos+128<fileSize % fail-safe; in case we miss MDH_ACQEND
switch version
case 'vb'
[mdh mask] = evalMDHvb(fid,cPos);
case 'vd'
[mdh mask] = evalMDHvd(fid,cPos);
otherwise
disp('error: only vb/vd software versions supported');
end
if mask.MDH_ACQEND || mdh.ulDMALength==0
if s<NScans
cPos = cPos + mdh.ulDMALength;
% jump to next full 512 bytes
cPos = cPos + 512 - mod(cPos,512);
fseek(fid,cPos,'bof');
hdrLength = fread(fid,1,'uint32');
cPos = cPos + hdrLength;
end
break;
end
if mask.MDH_SYNCDATA
% skip SYNCDATA
cPos = cPos + mdh.ulDMALength;
continue;
end
if (mask.MDH_IMASCAN && arg.bReadImaScan)
twix_obj{s}.image.readMDH(mdh,cPos);
if (arg.onlyoneline)
elapsed_time = toc;
progress_str = sprintf('one line parsed in %4.0f s; estimated time left: 0 s \n', elapsed_time);
fprintf([repmat('\b',1,prevLength) '%s'],progress_str);
return;
end;
end
if (mask.MDH_NOISEADJSCAN && arg.bReadNoiseScan)
twix_obj{s}.noise.readMDH(mdh,cPos);
end
if (and(mask.MDH_PHASCOR,~mask.MDH_PATREFSCAN) && arg.bReadPCScan)
twix_obj{s}.phasecor.readMDH(mdh,cPos);
end
if (and(~mask.MDH_PHASCOR,(mask.MDH_PATREFSCAN || mask.MDH_PATREFANDIMASCAN)) && arg.bReadRefScan)
twix_obj{s}.refscan.readMDH(mdh,cPos);
end
if (and(mask.MDH_PATREFSCAN,mask.MDH_PHASCOR) && arg.bReadRefPCScan)
twix_obj{s}.refscanPC.readMDH(mdh,cPos);
end
if ((mask.MDH_RTFEEDBACK || mask.MDH_HPFEEDBACK) && arg.bReadRTfeedback)
twix_obj{s}.RTfeedback.readMDH(mdh,cPos);
end
if ((mask.MDH_PHASESTABSCAN || mask.MDH_REFPHASESTABSCAN) && arg.bReadPhaseStab)
twix_obj{s}.phasestab.readMDH(mdh,cPos);
end
% jump to mdh of next scan
cPos = cPos + mdh.ulDMALength;
if (cPos/fileSize*100 > percentFinished + 1)
percentFinished = floor(cPos/fileSize*100);
elapsed_time = toc;
time_left = (fileSize/cPos-1) * elapsed_time;
if ~exist('progress_str','var')
prevLength = 0;
else
prevLength = numel(progress_str);
end
progress_str = sprintf('%3.0f %% parsed in %4.0f s; estimated time left: %4.0f s \n',...
percentFinished,elapsed_time, time_left);
fprintf([repmat('\b',1,prevLength) '%s'],progress_str);
end
end % while
if twix_obj{s}.image.NAcq == 0
twix_obj{s} = rmfield(twix_obj{s},'image');
else
twix_obj{s}.image.clean();
end
if twix_obj{s}.noise.NAcq == 0
twix_obj{s} = rmfield(twix_obj{s},'noise');
else
twix_obj{s}.noise.clean();
end
if twix_obj{s}.phasecor.NAcq == 0
twix_obj{s} = rmfield(twix_obj{s},'phasecor');
else
twix_obj{s}.phasecor.clean();
end
if twix_obj{s}.refscan.NAcq == 0
twix_obj{s} = rmfield(twix_obj{s},'refscan');
else
twix_obj{s}.refscan.clean();
end
if twix_obj{s}.refscanPC.NAcq == 0
twix_obj{s} = rmfield(twix_obj{s},'refscanPC');
else
twix_obj{s}.refscanPC.clean();
end
if twix_obj{s}.RTfeedback.NAcq == 0
twix_obj{s} = rmfield(twix_obj{s},'RTfeedback');
else
twix_obj{s}.RTfeedback.clean();
end
if twix_obj{s}.phasestab.NAcq == 0
twix_obj{s} = rmfield(twix_obj{s},'phasestab');
else
twix_obj{s}.phasestab.clean();
end
end % NScans loop
if NScans == 1
twix_obj = twix_obj{1};
end
elapsed_time = toc;
progress_str = sprintf('100 %% parsed in %4.0f s; estimated time left: 0 s \n', elapsed_time);
fprintf([repmat('\b',1,prevLength) '%s'],progress_str);
end
function [mdh mask] = evalMDHvb(fid,cPos)
% see pkg/MrServers/MrMeasSrv/SeqIF/MDH/mdh.h
% and pkg/MrServers/MrMeasSrv/SeqIF/MDH/MdhProxy.h
% no difference between 'scan' and 'channel' header in VB
szMDH = 128; % [bytes]
% inlining of readMDH
fseek(fid,cPos,'bof');
mdh.ulDMALength = fread(fid, 1, 'ubit25');
mdh.ulPackBit = fread(fid, 1, 'ubit1');
mdh.ulPCI_rx = fread(fid, 1, 'ubit6');
fseek(fid,cPos,'bof');
mdh.ulFlagsAndDMALength = fread(fid, 1, 'uint32');
fseek(fid,cPos+20,'bof');
mdh.aulEvalInfoMask = fread(fid, [1 2], 'uint32');
dummy = fread(fid, 2, 'uint16');
mdh.ushSamplesInScan = dummy(1);
mdh.ushUsedChannels = dummy(2);
mdh.sLC = fread(fid, [1 14], 'ushort');
dummy = fread(fid, 18, 'uint16');
% mdh.sCutOff = dummy(1:2);
mdh.ushKSpaceCentreColumn = dummy(3);
% mdh.ushCoilSelect = dummy(4);
mdh.ushKSpaceCentreLineNo = dummy(9);
mdh.ushKSpaceCentrePartitionNo = dummy(10);
mdh.aushIceProgramPara = dummy(11:14);
mdh.aushFreePara = dummy(15:18);
mdh.SlicePos = fread(fid, 7, 'float');
% inlining of evalInfoMask
mask.MDH_ACQEND = min(bitand(mdh.aulEvalInfoMask(1), 2^0),1);
mask.MDH_RTFEEDBACK = min(bitand(mdh.aulEvalInfoMask(1), 2^1),1);
mask.MDH_HPFEEDBACK = min(bitand(mdh.aulEvalInfoMask(1), 2^2),1);
mask.MDH_SYNCDATA = min(bitand(mdh.aulEvalInfoMask(1), 2^5), 1);
mask.MDH_RAWDATACORRECTION = min(bitand(mdh.aulEvalInfoMask(1), 2^10),1);
mask.MDH_REFPHASESTABSCAN = min(bitand(mdh.aulEvalInfoMask(1), 2^14),1);
mask.MDH_PHASESTABSCAN = min(bitand(mdh.aulEvalInfoMask(1), 2^15),1);
mask.MDH_SIGNREV = min(bitand(mdh.aulEvalInfoMask(1), 2^17),1);
mask.MDH_PHASCOR = min(bitand(mdh.aulEvalInfoMask(1), 2^21),1);
mask.MDH_PATREFSCAN = min(bitand(mdh.aulEvalInfoMask(1), 2^22),1);
mask.MDH_PATREFANDIMASCAN = min(bitand(mdh.aulEvalInfoMask(1), 2^23),1);
mask.MDH_REFLECT = min(bitand(mdh.aulEvalInfoMask(1), 2^24),1);
mask.MDH_NOISEADJSCAN = min(bitand(mdh.aulEvalInfoMask(1), 2^25),1);
mask.MDH_IMASCAN = 1;
if (mask.MDH_ACQEND || mask.MDH_RTFEEDBACK || mask.MDH_HPFEEDBACK...
|| mask.MDH_PHASCOR || mask.MDH_NOISEADJSCAN...
|| mask.MDH_SYNCDATA)
mask.MDH_IMASCAN = 0;
end
% otherwise the PATREFSCAN may be overwritten
if mask.MDH_PHASESTABSCAN || mask.MDH_REFPHASESTABSCAN
mask.MDH_PATREFSCAN = 0;
mask.MDH_PATREFANDIMASCAN = 0;
mask.MDH_IMASCAN = 0;
end
if ( mask.MDH_PATREFSCAN && ~mask.MDH_PATREFANDIMASCAN )
mask.MDH_IMASCAN = 0;
end
% pehses: the pack bit indicates that multiple ADC are packed into one
% DMA, often in EPI scans (controlled by fRTSetReadoutPackaging in IDEA)
% since this code assumes one adc (x NCha) per DMA, we have to correct
% the "DMA length"
% if mdh.ulPackBit
% it seems that the packbit is not always set correctly
if ~mask.MDH_SYNCDATA && ~mask.MDH_ACQEND
mdh.ulDMALength = (2*4*mdh.ushSamplesInScan + szMDH) * mdh.ushUsedChannels;
end
end
function [mdh mask] = evalMDHvd(fid,cPos)
% see pkg/MrServers/MrMeasSrv/SeqIF/MDH/mdh.h
% and pkg/MrServers/MrMeasSrv/SeqIF/MDH/MdhProxy.h
% we need to differentiate between 'scan header' and 'channel header'
% since these are used in VD versions:
szScanHeader = 192; % [bytes]
szChannelHeader = 32; % [bytes]
% inlining of readScanHeader
fseek(fid,cPos,'bof');
mdh.ulDMALength = fread(fid, 1, 'ubit25');
mdh.ulPackBit = fread(fid, 1, 'ubit1');
mdh.ulPCI_rx = fread(fid, 1, 'ubit6');
dummy = fread(fid, 1, 'int32');
dummy = fread(fid, 2, 'uint32'); % see pkg/MrServeres/MrMeasSrv/SeqIF/MDH/ time since midnight in 2.5ms steps
mdh.ulTimeStamp = dummy(2);
fseek(fid,cPos+40,'bof');
mdh.aulEvalInfoMask = fread(fid, [1 2], 'uint32');
dummy = fread(fid, 2, 'uint16');
mdh.ushSamplesInScan = dummy(1);
mdh.ushUsedChannels = dummy(2);
mdh.sLC = fread(fid, [1 14], 'ushort');
dummy = fread(fid, 10, 'uint16');
% mdh.sCutOff = dummy(1:2);
mdh.ushKSpaceCentreColumn = dummy(3);
% mdh.ushCoilSelect = dummy(4);
mdh.ushKSpaceCentreLineNo = dummy(9);
mdh.ushKSpaceCentrePartitionNo = dummy(10);
mdh.SlicePos = fread(fid, 7, 'float');
dummy = fread(fid, 28, 'uint16');
mdh.aushIceProgramPara = dummy(1:24);
mdh.aushFreePara = dummy(25:28); % actually aushReservedPara;
% there's no freePara in VD
% inlining of evalInfoMask
mask.MDH_ACQEND = min(bitand(mdh.aulEvalInfoMask(1), 2^0),1);
mask.MDH_RTFEEDBACK = min(bitand(mdh.aulEvalInfoMask(1), 2^1),1);
mask.MDH_HPFEEDBACK = min(bitand(mdh.aulEvalInfoMask(1), 2^2),1);
mask.MDH_SYNCDATA = min(bitand(mdh.aulEvalInfoMask(1), 2^5), 1);
mask.MDH_RAWDATACORRECTION = min(bitand(mdh.aulEvalInfoMask(1), 2^10),1);
mask.MDH_REFPHASESTABSCAN = min(bitand(mdh.aulEvalInfoMask(1), 2^14),1);
mask.MDH_PHASESTABSCAN = min(bitand(mdh.aulEvalInfoMask(1), 2^15),1);
mask.MDH_SIGNREV = min(bitand(mdh.aulEvalInfoMask(1), 2^17),1);
mask.MDH_PHASCOR = min(bitand(mdh.aulEvalInfoMask(1), 2^21),1);
mask.MDH_PATREFSCAN = min(bitand(mdh.aulEvalInfoMask(1), 2^22),1);
mask.MDH_PATREFANDIMASCAN = min(bitand(mdh.aulEvalInfoMask(1), 2^23),1);
mask.MDH_REFLECT = min(bitand(mdh.aulEvalInfoMask(1), 2^24),1);
mask.MDH_NOISEADJSCAN = min(bitand(mdh.aulEvalInfoMask(1), 2^25),1);
mask.MDH_IMASCAN = 1;
if (mask.MDH_ACQEND || mask.MDH_RTFEEDBACK || mask.MDH_HPFEEDBACK...
|| mask.MDH_PHASCOR || mask.MDH_NOISEADJSCAN...
|| mask.MDH_SYNCDATA)
mask.MDH_IMASCAN = 0;
end
% otherwise the PATREFSCAN may be overwritten
if mask.MDH_PHASESTABSCAN || mask.MDH_REFPHASESTABSCAN
mask.MDH_PATREFSCAN = 0;
mask.MDH_PATREFANDIMASCAN = 0;
mask.MDH_IMASCAN = 0;
end
if ( mask.MDH_PATREFSCAN && ~mask.MDH_PATREFANDIMASCAN )
mask.MDH_IMASCAN = 0;
end
% pehses: the pack bit indicates that multiple ADC are packed into one
% DMA, often in EPI scans (controlled by fRTSetReadoutPackaging in IDEA)
% since this code assumes one adc (x NCha) per DMA, we have to correct
% the "DMA length"
% if mdh.ulPackBit
% it seems that the packbit is not always set correctly
if ~mask.MDH_SYNCDATA && ~mask.MDH_ACQEND && mdh.ulDMALength~=0
mdh.ulDMALength = szScanHeader + (2*4*mdh.ushSamplesInScan + szChannelHeader) * mdh.ushUsedChannels;
end
end
|
github
|
sunhongfu/scripts-master
|
twix_map_obj.m
|
.m
|
scripts-master/MRF/recon/_src/_mapVBVD/twix_map_obj.m
| 36,408 |
utf_8
|
8ed9b559d38d7c95030609766d195fd5
|
classdef twix_map_obj < handle
% class to hold information about raw data from siemens MRI scanners
% (currently VB and VD software versions are supported and tested).
%
% Author: Philipp Ehses ([email protected]), Aug/19/2011
%
%
% Modified by Wolf Blecher ([email protected]), Apr/26/2012
% Added reorder index to indicate which lines are reflected
% Added slice position for sorting, Mai/15/2012
%
% Order of many mdh parameters are now stored (including the reflected ADC
% bit); PE, Jun/14/2012
%
% data is now 'memory mapped' and not read until demanded;
% (see mapVBVD for a description) PE, Aug/02/2012
%
% twix_obj.image.unsorted now returns the data in its acq. order
% [NCol,NCha,nsamples in acq. order], all average flags don't have an
% influence on the output, but 'flagRemoveOS' still works, PE, Sep/04/13
%
properties(Dependent=true)
% flags
flagRemoveOS % removes oversampling in read (col) during read operation
flagDoAverage % averages over all avg during read operation
flagAverageReps % averages over all repetitions
flagAverageSets % averages over all sets
end
properties
flagNoWeightedAverage % scaling/weighting of averages is disabled
end
properties(Dependent=true)
flagIgnoreSeg % sum over all segments during read operation
flagSkipToFirstLine % skips lines/partitions up to the first
% actually acquired line/partition
% (e.g. only the center k-space is acquired in
% refscans, we don't want all the leading zeros
% in our data)
% this is the default behaviour for everything
% but image scans (but can be changed manually)
flagDoRawDataCorrect %SRY: apply raw data correction factors during read operation
RawDataCorrectionFactors %SRY: allow the user to set/get the factors
end
properties(GetAccess='public', SetAccess='protected')
% properties:
filename
softwareVersion
dataType
dataSize % this is the current output size, depends on fullSize + some flags
dataDims
sqzSize
sqzDims
NCol % mdh information
NCha % mdh information
NLin % mdh information
NPar % mdh information
NSli % mdh information
NAve % mdh information
NPhs % mdh information
NEco % mdh information
NRep % mdh information
NSet % mdh information
NSeg % mdh information
NIda % mdh information
NIdb % mdh information
NIdc % mdh information
NIdd % mdh information
NIde % mdh information
NAcq % simple counter
% mdh information
Lin
Par
Sli
Ave
Phs
Eco
Rep
Set
Seg
Ida
Idb
Idc
Idd
Ide
ulTimeStamp
centerCol
centerLin
centerPar
IsReflected
IsRawDataCorrect %SRY: storage for MDH flag raw data correct
slicePos
freeParam
iceParam
% memory position in file
memPos
% index that translates simple, linear order of mdh info vectors
% to target matrix (of size dataSize)
ixToTarget % inverted page table (physical to virtual addresses)
ixToRaw % page table (virtual to physical addresses)
end
properties(GetAccess='protected', SetAccess='protected')
arg % arguments
allocSize % determines size of allocation
currentAlloc % simple counter, keeps track of allocated memory
fullSize % this is the full size of the data set according to the mdhs, i.e. flags
% like 'reduceOS' have no influence on it
freadInfo
skipLin
skipPar
end
methods
% Constructor:
function this = twix_map_obj(arg,dataType,fname,version)
if ~exist('dataType','var')
this.dataType = 'image';
else
this.dataType = lower(dataType);
end
this.filename = fname;
this.softwareVersion = version;
this.IsReflected = logical([]);
this.IsRawDataCorrect = logical([]); %SRY
this.NAcq = 0;
this.allocSize = 4096;
this.currentAlloc = 0;
if ~isfield(arg,'skipToFirstLine')
if strcmp(this.dataType,'image')
arg.skipToFirstLine = false;
else
arg.skipToFirstLine = true;
end
end
if ~exist('arg','var')
this.arg = [];
else
this.arg = arg;
end
% flags:
this.flagNoWeightedAverage = arg.noWeightedAverage;
switch this.softwareVersion
case 'vb'
% every channel has its own full mdh
this.freadInfo.szScanHeader = 0; % [bytes]
this.freadInfo.szChannelHeader = 128; % [bytes]
this.freadInfo.iceParamSz = 4;
case 'vd'
if ( this.arg.doRawDataCorrect )
error('raw data correction for VD not supported/tested yet');
end
this.freadInfo.szScanHeader = 192; % [bytes]
this.freadInfo.szChannelHeader = 32; % [bytes]
this.freadInfo.iceParamSz = 24; % vd version supports up to 24 ice params
otherwise
error('software version not supported');
end
end
function this = readMDH(this,mdh,filePos)
cLin = mdh.sLC(1) + 1; %%% current line
cPar = mdh.sLC(4) + 1; %%% current partition
cSli = mdh.sLC(3) + 1; %%% current slice
cAve = mdh.sLC(2) + 1; %%% current scan ('average')
cPhs = mdh.sLC(6) + 1; %%% current phase cycling step
cEco = mdh.sLC(5) + 1; %%% current echo no (untested)
cRep = mdh.sLC(7) + 1; %%% current measurement no
cSet = mdh.sLC(8) + 1; %%% current set no
cSeg = mdh.sLC(9) + 1; %%% current segment for future use
cIda = mdh.sLC(10) + 1; %%% ICE dim a
cIdb = mdh.sLC(11) + 1; %%% ICE dim b
cIdc = mdh.sLC(12) + 1; %%% ICE dim c
cIdd = mdh.sLC(13) + 1; %%% ICE dim d
cIde = mdh.sLC(14) + 1; %%% ICE dim e
% subsref overloading makes this.that-calls slow, so we need to
% avoid them whenever possible
cAcq = this.NAcq + 1;
this.NAcq = cAcq;
if cAcq > this.currentAlloc
% we need to allocate more memory...
this.currentAlloc = this.currentAlloc + this.allocSize;
alloc = zeros(1,this.allocSize ,'single');
this.NCol = cat(2, this.NCol , alloc);
this.NCha = cat(2, this.NCha , alloc);
this.Lin = cat(2, this.Lin , alloc);
this.Par = cat(2, this.Par , alloc);
this.Sli = cat(2, this.Sli , alloc);
this.Ave = cat(2, this.Ave , alloc);
this.Phs = cat(2, this.Phs , alloc);
this.Eco = cat(2, this.Eco , alloc);
this.Rep = cat(2, this.Rep , alloc);
this.Set = cat(2, this.Set , alloc);
this.Seg = cat(2, this.Seg , alloc);
this.Ida = cat(2, this.Ida , alloc);
this.Idb = cat(2, this.Idb , alloc);
this.Idc = cat(2, this.Idc , alloc);
this.Idd = cat(2, this.Idd , alloc);
this.Ide = cat(2, this.Ide , alloc);
this.ulTimeStamp = cat(2, this.ulTimeStamp , alloc);
this.centerCol = cat(2, this.centerCol , alloc);
this.centerLin = cat(2, this.centerLin , alloc);
this.centerPar = cat(2, this.centerPar , alloc);
this.IsReflected = cat(2, this.IsReflected , false(1,this.allocSize));
this.IsRawDataCorrect = cat(2, this.IsRawDataCorrect, false(1, this.allocSize)); %SRY
this.slicePos = cat(2, this.slicePos , zeros(7,this.allocSize,'single'));
this.iceParam = cat(2, this.iceParam , zeros(this.freadInfo.iceParamSz, this.allocSize,'single'));
this.freeParam = cat(2, this.freeParam , zeros(4, this.allocSize,'single'));
this.memPos = cat(2, this.memPos , zeros(1,this.allocSize,'double'));
end
% save mdh information about current line
this.NCol (cAcq) = mdh.ushSamplesInScan + 0; % +0 significantly faster??!
this.NCha (cAcq) = mdh.ushUsedChannels + 0;
this.Lin (cAcq) = cLin;
this.Par (cAcq) = cPar;
this.Sli (cAcq) = cSli;
this.Ave (cAcq) = cAve;
this.Phs (cAcq) = cPhs;
this.Eco (cAcq) = cEco;
this.Rep (cAcq) = cRep;
this.Set (cAcq) = cSet;
this.Seg (cAcq) = cSeg;
this.Ida (cAcq) = cIda;
this.Idb (cAcq) = cIdb;
this.Idc (cAcq) = cIdc;
this.Idd (cAcq) = cIdd;
this.Ide (cAcq) = cIde;
% this.ulTimeStamp(cAcq) = mdh.ulTimeStamp; % FK: This field is not in the PET-MR datafile
this.centerCol (cAcq) = mdh.ushKSpaceCentreColumn + 1;
this.centerLin (cAcq) = mdh.ushKSpaceCentreLineNo + 1;
this.centerPar (cAcq) = mdh.ushKSpaceCentrePartitionNo + 1;
this.IsReflected(cAcq) = logical(min(bitand(mdh.aulEvalInfoMask(1),2^24),1));
this.IsRawDataCorrect(cAcq) = logical(min(bitand(mdh.aulEvalInfoMask(1),2^10),1)); %SRY
this.slicePos (:,cAcq) = mdh.SlicePos + 0;
this.iceParam (:,cAcq) = mdh.aushIceProgramPara + 0;
this.freeParam(:,cAcq) = mdh.aushFreePara + 0;
% save memory position
this.memPos (cAcq) = filePos;
end
function this = clean(this)
if this.NAcq == 0
return;
end
% cut mdh data to actual size (remove over-allocated part)
this.NCol = this.NCol (1:this.NAcq);
this.NCha = this.NCha (1:this.NAcq);
this.Lin = this.Lin (1:this.NAcq);
this.Par = this.Par (1:this.NAcq);
this.Sli = this.Sli (1:this.NAcq);
this.Ave = this.Ave (1:this.NAcq);
this.Phs = this.Phs (1:this.NAcq);
this.Eco = this.Eco (1:this.NAcq);
this.Rep = this.Rep (1:this.NAcq);
this.Set = this.Set (1:this.NAcq);
this.Seg = this.Seg (1:this.NAcq);
this.Ida = this.Ida (1:this.NAcq);
this.Idb = this.Idb (1:this.NAcq);
this.Idc = this.Idc (1:this.NAcq);
this.Idd = this.Idd (1:this.NAcq);
this.Ide = this.Ide (1:this.NAcq);
this.ulTimeStamp = this.ulTimeStamp(1:this.NAcq);
this.centerCol = this.centerCol (1:this.NAcq);
this.centerLin = this.centerLin (1:this.NAcq);
this.centerPar = this.centerPar (1:this.NAcq);
this.IsReflected = this.IsReflected(1:this.NAcq);
this.IsRawDataCorrect = this.IsRawDataCorrect(1:this.NAcq); %SRY;
this.slicePos = this.slicePos (:,1:this.NAcq);
this.iceParam = this.iceParam (:,1:this.NAcq);
this.freeParam = this.freeParam(:,1:this.NAcq);
this.memPos = this.memPos (1:this.NAcq);
this.NLin = max(this.Lin);
this.NPar = max(this.Par);
this.NSli = max(this.Sli);
this.NAve = max(this.Ave);
this.NPhs = max(this.Phs);
this.NEco = max(this.Eco);
this.NRep = max(this.Rep);
this.NSet = max(this.Set);
this.NSeg = max(this.Seg);
this.NIda = max(this.Ida);
this.NIdb = max(this.Idb);
this.NIdc = max(this.Idc);
this.NIdd = max(this.Idd);
this.NIde = max(this.Ide);
% ok, let us assume for now that all NCol and NCha entries are
% the same for all mdhs:
this.NCol = this.NCol(1);
this.NCha = this.NCha(1);
this.dataDims = {'Col','Cha','Lin','Par','Sli','Ave','Phs',...
'Eco','Rep','Set','Seg','Ida','Idb','Idc','Idd','Ide'};
% to reduce the matrix sizes of non-image scans, the size
% of the refscan_obj()-matrix is reduced to the area of the
% actually scanned acs lines (the outer part of k-space
% that is not scanned is not filled with zeros)
% this behaviour is controlled by flagSkipToFirstLine which is
% set to true by default for everything but image scans
if ~this.flagSkipToFirstLine
% the output matrix should include all leading zeros
this.skipLin = 0;
this.skipPar = 0;
else
% otherwise, cut the matrix size to the start of the
% first actually scanned line/partition (e.g. the acs/
% phasecor data is only acquired in the k-space center)
this.skipLin = min(this.Lin)-1;
this.skipPar = min(this.Par)-1;
end
NLinAlloc = max(1, this.NLin - this.skipLin);
NParAlloc = max(1, this.NPar - this.skipPar);
this.fullSize = [ this.NCol this.NCha NLinAlloc NParAlloc...
this.NSli this.NAve this.NPhs this.NEco...
this.NRep this.NSet this.NSeg this.NIda...
this.NIdb this.NIdc this.NIdd this.NIde ];
this.dataSize = this.fullSize;
if this.arg.removeOS
this.dataSize(1) = this.NCol/2;
end
if this.arg.doAverage
this.dataSize(6) = 1;
end
if this.arg.averageReps
this.dataSize(9) = 1;
end
if this.arg.averageSets
this.dataSize(10) = 1;
end
if this.arg.ignoreSeg
this.dataSize(11) = 1;
end
% calculate sqzSize
this.calcSqzSize;
% calculate indices to target & source(raw)
this.calcIndices;
nByte = this.NCha*(this.freadInfo.szChannelHeader+8*this.NCol);
% size for fread
this.freadInfo.sz = [2 nByte/8];
% reshape size
this.freadInfo.shape = [this.NCol+this.freadInfo.szChannelHeader/8 ...
, this.NCha];
% we need to cut MDHs from fread data
this.freadInfo.cut = this.freadInfo.szChannelHeader/8+1 ...
: this.NCol+this.freadInfo.szChannelHeader/8;
% SRY: check that the number of raw data correction factors matches the
% % channel count
% if (strcmp(this.softwareVersion, 'vb')) % not implemented/tested for vd, yet
% if (length(this.arg.rawDataCorrectionFactors) ~= this.NCha)
% error('Number of raw data correction factors (%d) does not equal number of channels (%d)',...
% length(rawDataCorrectionFactors), this.NCha);
% end
% end
%
end
function varargout = subsref(this, S)
% this is where the magic happens
% Now seriously. Overloading of the subsref-method and working
% with a gazillion indices got really messy really fast. At
% some point, I should probably clean this code up a bit. But
% good news everyone: It seems to work.
switch S(1).type
case '.'
% We don't want to manage method/variable calls, so we'll
% simply call the built-in subsref-function in this case.
% Note, that this has the limitation that there's no way
% to find out whether the original call was terminated
% with a semicolon! So "this.that" won't produce any
% output and is identical to "this.that;"
if nargout == 0
builtin('subsref', this, S);
else
varargout = cell(1, nargout);
[varargout{:}] = builtin('subsref', this, S);
end
return;
case {'()','{}'}
otherwise
error('operator not supported');
end
[selRange selRangeSz outSize] = this.calcRange(S(1));
tmp = reshape(1:prod(double(this.fullSize(3:end))), this.fullSize(3:end));
tmp = tmp(selRange{3:end});
cIxToRaw = this.ixToRaw(tmp); clear tmp;
cIxToRaw = cIxToRaw(:);
% delete all entries that point to zero (the "NULL"-pointer)
notAcquired = (cIxToRaw == 0);
cIxToRaw (notAcquired) = []; clear notAcquired;
% calculate cIxToTarg for possibly smaller, shifted + segmented
% target matrix:
cIx = zeros(14, numel(cIxToRaw), 'single');
cIx( 1,:) = this.Lin(cIxToRaw) - this.skipLin;
cIx( 2,:) = this.Par(cIxToRaw) - this.skipPar;
cIx( 3,:) = this.Sli(cIxToRaw);
if this.arg.doAverage
cIx( 4,:) = 1;
else
cIx( 4,:) = this.Ave(cIxToRaw);
end
cIx( 5,:) = this.Phs(cIxToRaw);
cIx( 6,:) = this.Eco(cIxToRaw);
if this.arg.averageReps
cIx( 7,:) = 1;
else
cIx( 7,:) = this.Rep(cIxToRaw);
end
if this.arg.averageSets
cIx( 8,:) = 1;
else
cIx( 8,:) = this.Set(cIxToRaw);
end
if this.arg.ignoreSeg
cIx( 9,:) = 1;
else
cIx( 9,:) = this.Seg(cIxToRaw);
end
cIx(10,:) = this.Ida(cIxToRaw);
cIx(11,:) = this.Idb(cIxToRaw);
cIx(12,:) = this.Idc(cIxToRaw);
cIx(13,:) = this.Idd(cIxToRaw);
cIx(14,:) = this.Ide(cIxToRaw);
% make sure that indices fit inside selection range
for k=3:numel(selRange)
tmp = cIx(k-2,:);
for l=1:numel(selRange{k})
cIx(k-2,tmp==selRange{k}(l)) = l;
end
end
cIxToTarg = sub2ind_double(selRangeSz(3:end),cIx(1,:),cIx(2,:),cIx(3,:),...
cIx(4,:),cIx(5,:),cIx(6,:),cIx(7,:),cIx(8,:),cIx(9,:),...
cIx(10,:),cIx(11,:),cIx(12,:),cIx(13,:),cIx(14,:));
mem = this.memPos(cIxToRaw);
% sort mem for quicker access, sort cIxToTarg/Raw accordingly
[mem,ix] = sort(mem);
cIxToTarg = cIxToTarg(ix);
cIxToRaw = cIxToRaw(ix);
clear ix;
out = complex(zeros(outSize,'single'));
out = reshape(out, selRangeSz(1), selRangeSz(2), []);
% counter for proper scaling of averages/segments
count_ave = zeros([1 1 size(out,3)],'single');
% subsref overloading makes this.that-calls slow, so we need to
% avoid them whenever possible
szScanHeader = this.freadInfo.szScanHeader;
readSize = this.freadInfo.sz;
readShape = this.freadInfo.shape;
readCut = this.freadInfo.cut;
cutOS = this.NCol/4+1:this.NCol*3/4;
bRemoveOS = this.arg.removeOS;
bIsReflected = this.IsReflected;
%SRY store information about raw data correction
bDoRawDataCorrect = this.arg.doRawDataCorrect;
bIsRawDataCorrect = this.IsRawDataCorrect;
if (bDoRawDataCorrect)
rawDataCorrect = this.arg.rawDataCorrectionFactors;
end
fid = fopen(this.filename);
for k=1:numel(mem)
% skip scan header
fseek(fid,mem(k) + szScanHeader,'bof');
raw = fread(fid, readSize, 'float=>single').';
raw = reshape( complex(raw(:,1), raw(:,2)), readShape);
raw = raw(readCut,:);
%SRY apply raw data correction if necessary
if ( bDoRawDataCorrect && bIsRawDataCorrect(cIxToRaw(k)) )
%there are two ways to do this: multiply where the flag is
%set, or divide where it is not set. There are significantly
%more points without the flag, so multiplying is more
%efficient
raw = bsxfun(@times, raw, rawDataCorrect);
end
% select channels
raw = raw(:,selRange{2});
if bRemoveOS
% remove oversampling in read
raw = ifft(raw);
raw(cutOS,:) = [];
raw = fft(raw);
end
% if bIsReflected(cIxToRaw(k)) %MC
% raw = raw(end:-1:1,:); %MC
% end %MC
% select columns and sort data
out(:,:,cIxToTarg(k)) = out(:,:,cIxToTarg(k)) +...
raw(selRange{1},:);
count_ave(1,1,cIxToTarg(k)) = count_ave(1,1,cIxToTarg(k)) + 1;
end
fclose(fid);
% proper scaling (we don't want to sum our data but average it)
if ~this.flagNoWeightedAverage
count_ave = 1./max(1,count_ave);
out = bsxfun(@times,out,count_ave);
end
out = reshape(out,outSize);
% For a call of type data{:,:,1:3} matlab expects more than one
% output variable (three in this case) and will throw an error
% otherwise. This is a lazy way (and the only one I know of) to
% fix this.
varargout = cell(1, nargout);
varargout{1} = out;
end
function unsorted = unsorted(this)
% returns the unsorted data [NCol,NCha,#samples in acq. order]
szScanHeader = this.freadInfo.szScanHeader;
readSize = this.freadInfo.sz;
readShape = this.freadInfo.shape;
readCut = this.freadInfo.cut;
cutOS = this.NCol/4+1:this.NCol*3/4;
bRemoveOS = this.arg.removeOS;
bIsReflected = this.IsReflected;
%SRY store information about raw data correction
bDoRawDataCorrect = this.arg.doRawDataCorrect;
bIsRawDataCorrect = this.IsRawDataCorrect;
if (bDoRawDataCorrect)
rawDataCorrect = this.arg.rawDataCorrectionFactors;
end
mem = this.memPos;
unsorted = complex(zeros([this.dataSize(1) this.NCha this.NAcq],'single'));
fid = fopen(this.filename);
for k=1:this.NAcq
% skip scan header
fseek(fid,mem(k) + szScanHeader,'bof');
raw = fread(fid, readSize, 'float=>single').';
raw = reshape( complex(raw(:,1), raw(:,2)), readShape);
raw = raw(readCut,:);
if ( bDoRawDataCorrect && bIsRawDataCorrect(k) )
%SRY apply raw data correction if necessary
raw = bsxfun(@times, raw, rawDataCorrect);
end
if bRemoveOS
% remove oversampling in read
raw = ifft(raw);
raw(cutOS,:) = [];
raw = fft(raw);
end
if bIsReflected(k)
raw = raw(end:-1:1,:);
end
unsorted(:,:,k) = raw;
end
fclose(fid);
end % of get.unsorted()
function set.flagRemoveOS(this,val)
% set method for removeOS
this.arg.removeOS = logical(val);
% we also need to recalculate our data size:
if this.arg.removeOS
this.dataSize(1) = this.NCol(1)/2;
this.sqzSize(1) = this.NCol(1)/2;
else
this.dataSize(1) = this.NCol(1);
this.sqzSize(1) = this.NCol(1);
end
end
function out = get.flagRemoveOS(this)
out = this.arg.removeOS;
end
function set.flagDoAverage(this,val)
% set method for doAverage
this.arg.doAverage = logical(val);
if this.arg.doAverage
this.dataSize(6) = 1;
else
this.dataSize(6) = this.NAve;
end
% update sqzSize
this.calcSqzSize;
end
function out = get.flagDoAverage(this)
out = this.arg.doAverage;
end
function set.flagAverageReps(this,val)
% set method for doAverage
this.arg.averageReps = logical(val);
if this.arg.averageReps
this.dataSize(9) = 1;
else
this.dataSize(9) = this.NRep;
end
% update sqzSize
this.calcSqzSize;
end
function out = get.flagAverageReps(this)
out = this.arg.averageReps;
end
function set.flagAverageSets(this,val)
% set method for doAverage
this.arg.averageSets = logical(val);
if this.arg.averageSets
this.dataSize(10) = 1;
else
this.dataSize(10) = this.NSet;
end
% update sqzSize
this.calcSqzSize;
end
function out = get.flagAverageSets(this)
out = this.arg.averageSets;
end
function set.flagSkipToFirstLine(this,val)
val = logical(val);
if val ~= this.arg.skipToFirstLine
this.arg.skipToFirstLine = val;
if this.arg.skipToFirstLine
this.skipLin = min(this.Lin)-1;
this.skipPar = min(this.Par)-1;
else
this.skipLin = 0;
this.skipPar = 0;
end
NLinAlloc = max(1, this.NLin - this.skipLin);
NParAlloc = max(1, this.NPar - this.skipPar);
this.fullSize(3:4) = [NLinAlloc NParAlloc];
this.dataSize(3:4) = this.fullSize(3:4);
% update sqzSize
this.calcSqzSize;
% update indices
this.calcIndices;
end
end
function out = get.flagSkipToFirstLine(this)
out = this.arg.skipToFirstLine;
end
function set.flagIgnoreSeg(this,val)
% set method for ignoreSeg
this.arg.ignoreSeg = logical(val);
if this.arg.ignoreSeg
this.dataSize(11) = 1;
else
this.dataSize(11) = this.NSeg;
end
% update sqzSize
this.calcSqzSize;
end
function out = get.flagIgnoreSeg(this)
out = this.arg.ignoreSeg;
end
%SRY: accessor methods for raw data correction
function out = get.flagDoRawDataCorrect(this)
out = this.arg.doRawDataCorrect;
end
function set.flagDoRawDataCorrect(this, val)
val = logical(val);
if (val == true && strcmp(this.softwareVersion, 'vd'))
error('raw data correction for VD not supported/tested yet');
end
this.arg.doRawDataCorrect = val;
end
function out = get.RawDataCorrectionFactors(this)
out = this.arg.rawDataCorrectionFactors;
end
function set.RawDataCorrectionFactors(this, val)
%this may not work if trying to set the factors before NCha has
%a meaningful value (ie before calling clean)
if (~isrow(val) || length(val) ~= this.NCha)
error('RawDataCorrectionFactors must be a 1xNCha row vector');
end
this.arg.rawDataCorrectionFactors = val;
end
end
methods (Access='protected')
% helper functions
function [selRange selRangeSz outSize] = calcRange(this,S)
switch S.type
case '()'
bSqueeze = false;
case '{}'
bSqueeze = true;
end
selRange = num2cell(ones(1,numel(this.dataSize)));
outSize = ones(1,numel(this.dataSize));
if ( isempty(S.subs) || strcmpi(S.subs(1),'') )
% obj(): shortcut to select all data
% unfortunately, matlab does not allow the statement
% obj{}, so we can't use it...
% alternative: obj{''} (obj('') also works)
for k=1:numel(this.dataSize)
selRange{k} = 1:this.dataSize(k);
end
if ~bSqueeze
outSize = this.dataSize;
else
outSize = this.sqzSize;
end
else
for k=1:numel(S.subs)
if ~bSqueeze
cDim = k; % nothing to do
else
% we need to rearrange selRange from squeezed
% to original order
cDim = find(strcmp(this.dataDims,this.sqzDims{k}) == 1);
end
if strcmp(S.subs{k},':')
if k<numel(S.subs)
selRange {cDim} = 1:this.dataSize(cDim);
else % all later dimensions selected and 'vectorized'!
for l=cDim:numel(this.dataSize)
selRange{l} = 1:this.dataSize(l);
end
outSize(k) = prod(double(this.dataSize(cDim:end)));
break; % jump out ouf for-loop
end
elseif isnumeric(S.subs{k})
selRange{cDim} = single(S.subs{k});
else
error('unknown string in brackets (e.g. 1:end does not work here)');
end
outSize(k) = numel(selRange{cDim});
end
end
for k=1:numel(selRange)
if max(selRange{k}) > this.dataSize(k)
error('selection out of range');
end
end
selRangeSz = ones(1,numel(this.dataSize));
for k=1:numel(selRange)
selRangeSz(k) = numel(selRange{k});
end
% now select all averages in case doAverage is selected
if this.arg.doAverage
selRange{6} = 1:this.fullSize(6);
end
% now select all repetitions in case averageReps is selected
if this.arg.averageReps
selRange{9} = 1:this.fullSize(9);
end
% now select all sets in case averageSets is selected
if this.arg.averageSets
selRange{10} = 1:this.fullSize(10);
end
% now select all segments in case ignoreSeg is selected
if this.arg.ignoreSeg
selRange{11} = 1:this.fullSize(11);
end
end
function calcSqzSize(this)
% calculate sqzSize and sqzDims
this.sqzSize = [];
this.sqzDims = [];
this.sqzSize(1) = this.dataSize(1);
this.sqzDims{1} = 'Col';
c = 1;
for k=2:numel(this.dataSize)
if this.dataSize(k)>1
c = c+1;
this.sqzSize(c) = this.dataSize(k);
this.sqzDims{c} = this.dataDims{k};
end
end
end
function calcIndices(this)
% calculate indices to target & source(raw)
LinIx = this.Lin - this.skipLin;
ParIx = this.Par - this.skipPar;
this.ixToTarget = sub2ind_double(this.fullSize(3:end),...
LinIx, ParIx, this.Sli, this.Ave, this.Phs, this.Eco,...
this.Rep, this.Set, this.Seg, this.Ida, this.Idb,...
this.Idc, this.Idd, this.Ide);
% now calculate inverse index
% inverse index of lines that are not measured is zero
this.ixToRaw = zeros(1,prod(this.fullSize(3:end)),'double');
% subsref overloading makes this.that-calls slow, so we need to
% avoid them whenever possible
ixToTarg = this.ixToTarget;
for k=1:numel(ixToTarg)
this.ixToRaw(ixToTarg(k)) = k;
end
end
end
end
%%%%%%%%%%%% helper functions %%%%%%%%%%%
function ndx = sub2ind_double(sz,varargin)
%SUB2IND_double Linear index from multiple subscripts.
% Works like sub2ind but always returns double
% also slightly faster, but no checks
%========================================
sz = double(sz);
ndx = double(varargin{end}) - 1;
for i = length(sz)-1:-1:1
ix = double(varargin{i});
ndx = sz(i)*ndx + ix-1;
end
ndx = ndx + 1;
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.