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
|
philippboehmsturm/antx-master
|
gencode.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/matlabbatch/gencode.m
| 8,368 |
utf_8
|
bdf69ad199b1ccbc06171e39793faa4e
|
function [str, tag, cind] = gencode(item, tag, tagctx)
% GENCODE Generate code to recreate any MATLAB struct/cell variable.
% For any MATLAB variable, this function generates a .m file that
% can be run to recreate it. Classes can implement their class specific
% equivalent of gencode with the same calling syntax. By default, classes
% are treated similar to struct variables.
%
% [str, tag, cind] = gencode(item, tag, tagctx)
% Input arguments:
% item - MATLAB variable to generate code for (the variable itself, not its
% name)
% tag - optional: name of the variable, i.e. what will be displayed left
% of the '=' sign. This can also be a valid struct/cell array
% reference, like 'x(2).y'. If not provided, inputname(1) will be
% used.
% tagctx - optional: variable names not to be used (e.g. keywords,
% reserved variables). A cell array of strings.
% Output arguments:
% str - cellstr containing code lines to reproduce the input variable
% tag - name of the generated variable (equal to input tag)
% cind - index into str to the line where the variable assignment is coded
% (usually 1st line for non-object variables)
%
% See also GENCODE_RVALUE, GENCODE_SUBSTRUCT, GENCODE_SUBSTRUCTCODE.
%
% This code has been developed as part of a batch job configuration
% system for MATLAB. See
% http://sourceforge.net/projects/matlabbatch
% for details about the original project.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging
% Volkmar Glauche
% $Id: gencode.m 410 2009-06-23 11:47:26Z glauche $
rev = '$Rev: 410 $'; %#ok
if nargin < 2
tag = inputname(1);
end;
if nargin < 3
tagctx = {};
end
if isempty(tag)
tag = genvarname('val', tagctx);
end;
% Item count
cind = 1;
% try to generate rvalue code
[rstr sts] = gencode_rvalue(item);
if sts
lvaleq = sprintf('%s = ', tag);
if numel(rstr) == 1
str{1} = sprintf('%s%s;', lvaleq, rstr{1});
else
str = cell(size(rstr));
indent = {repmat(' ', 1, numel(lvaleq)+1)};
str{1} = sprintf('%s%s', lvaleq, rstr{1});
str(2:end-1) = strcat(indent, rstr(2:end-1));
str{end} = sprintf('%s%s;', indent{1}, rstr{end});
if numel(str) > 10
% add cell mode comment to structure longer output
str = [{'%%'} str(:)' {'%%'}];
end
end
else
switch class(item)
case 'char'
str = {};
szitem = size(item);
subs = gensubs('()', {':',':'}, szitem(3:end));
for k = 1:numel(subs)
substag = gencode_substruct(subs{k}, tag);
str1 = gencode(subsref(item, subs{k}), substag{1}, tagctx);
str = [str(:)' str1(:)'];
end
case 'cell'
str = {};
szitem = size(item);
subs = gensubs('{}', {}, szitem);
for k = 1:numel(subs)
substag = gencode_substruct(subs{k}, tag);
str1 = gencode(subsref(item, subs{k}), substag{1}, tagctx);
str = [str(:)' str1(:)'];
end
case 'struct'
str = gencode_structobj(item, tag, tagctx);
otherwise
if isobject(item) || ~(isnumeric(item) || islogical(item))
% This branch is hit for objects without a gencode method
try
% try to generate code in a struct-like fashion
str = gencode_structobj(item, tag, tagctx);
catch
% failed - generate a warning in generated code and
% warn directly
str = {sprintf('warning(''%s: No code generated for object of class %s.'')', tag, class(item))};
if any(exist('cfg_message') == 2:6)
cfg_message('matlabbatch:gencode:unknown', ...
'%s: Code generation for objects of class ''%s'' must be implemented as object method.', tag, class(item));
else
warning('gencode:unknown', ...
'%s: Code generation for objects of class ''%s'' must be implemented as object method.', tag, class(item));
end
end
elseif issparse(item)
% recreate sparse matrix from indices
[tmpi tmpj tmps] = find(item);
[stri tagi cindi] = gencode(tmpi);
[strj tagj cindj] = gencode(tmpj);
[strs tags cinds] = gencode(tmps);
str = [stri(:)' strj(:)' strs(:)'];
cind = cind + cindi + cindj + cinds;
str{end+1} = sprintf('%s = sparse(tmpi, tmpj, tmps);', tag);
else
str = {};
szitem = size(item);
subs = gensubs('()', {':',':'}, szitem(3:end));
for k = 1:numel(subs)
substag = gencode_substruct(subs{k}, tag);
str1 = gencode(subsref(item, subs{k}), substag{1}, tagctx);
str = [str(:)' str1(:)'];
end
end
end
end
function subs = gensubs(type, initdims, sz)
% generate a cell array of subscripts into trailing dimensions of
% n-dimensional arrays. Type is the subscript type (either '()' or '{}'),
% initdims is a cell array of leading subscripts that will be prepended to
% the generated subscripts and sz contains the size of the remaining
% dimensions.
% deal with special case of row vectors - only add one subscript in this
% case
if numel(sz) == 2 && sz(1) == 1 && isempty(initdims)
ind = 1:sz(2);
else
% generate index array, rightmost index varying fastest
ind = 1:sz(1);
for k = 2:numel(sz)
ind = [kron(ind, ones(1,sz(k))); kron(ones(1,size(ind,2)), 1:sz(k))];
end;
end;
subs = cell(1,size(ind,2));
% for each column of ind, generate a separate subscript structure
for k = 1:size(ind,2)
cellind = num2cell(ind(:,k));
subs{k} = substruct(type, [initdims(:)' cellind(:)']);
end;
function str = gencode_structobj(item, tag, tagctx)
% Create code for a struct array. Also used as fallback for object
% arrays, if the object does not provide its own gencode implementation.
citem = class(item);
% try to figure out fields/properties that can be set
if isobject(item) && exist('metaclass','builtin')
mobj = metaclass(item);
% Only create code for properties which are
% * not dependent or dependent and have a SetMethod
% * not constant
% * not abstract
% * have public SetAccess
sel = cellfun(@(cProp)(~cProp.Constant && ...
~cProp.Abstract && ...
(~cProp.Dependent || ...
(cProp.Dependent && ...
~isempty(cProp.SetMethod))) && ...
strcmp(cProp.SetAccess,'public')),mobj.Properties);
fn = cellfun(@(cProp)subsref(cProp,substruct('.','Name')),mobj.Properties(sel),'uniformoutput',false);
else
% best guess
fn = fieldnames(item);
end
if isempty(fn)
if isstruct(item)
str{1} = sprintf('%s = struct([]);', tag);
else
str{1} = sprintf('%s = %s;', tag, citem);
end
elseif isempty(item)
if isstruct(item)
fn = strcat('''', fn, '''', ', {}');
str{1} = sprintf('%s = struct(', tag);
for k = 1:numel(fn)-1
str{1} = sprintf('%s%s, ', str{1}, fn{k});
end
str{1} = sprintf('%s%s);', str{1}, fn{end});
else
str{1} = sprintf('%s = %s.empty;', tag, citem);
end
elseif numel(item) == 1
if isstruct(item)
str = {};
else
str{1} = sprintf('%s = %s;', tag, citem);
end
for l = 1:numel(fn)
str1 = gencode(item.(fn{l}), sprintf('%s.%s', tag, fn{l}), tagctx);
str = [str(:)' str1(:)'];
end
else
str = {};
szitem = size(item);
subs = gensubs('()', {}, szitem);
for k = 1:numel(subs)
if ~isstruct(item)
str{end+1} = sprintf('%s = %s;', gencode_substruct(subs{k}, tag), citem);
end
for l = 1:numel(fn)
csubs = [subs{k} substruct('.', fn{l})];
substag = gencode_substruct(csubs, tag);
str1 = gencode(subsref(item, csubs), substag{1}, tagctx);
str = [str(:)' str1(:)'];
end
end
end
|
github
|
philippboehmsturm/antx-master
|
cfg_message.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/matlabbatch/cfg_message.m
| 9,875 |
utf_8
|
8d66022211a225ece4067413b1b99ed7
|
function varargout = cfg_message(varargin)
% function cfg_message(msgid, msgfmt, varargin)
% Display a message. The message identifier msgid will be looked up in a
% message database to decide how to treat this message. This database is
% a struct array with fields:
% .identifier - message id
% .level - message severity level. One of
% 'info' - print message
% 'warning' - print message, raise a warning
% 'error' - print message, throw an error
% .destination - output destination. One of
% 'none' - silently ignore this message
% 'stdout' - standard output
% 'stderr' - standard error output
% 'syslog' - (UNIX) syslog
% Warnings and errors will always be logged to the command
% window and to syslog, if destination == 'syslog'. All
% other messages will only be logged to the specified location.
% .verbose
% .backtrace - control verbosity and backtrace, one of 'on' or 'off'
%
% function [oldsts msgids] = cfg_message('on'|'off', 'verbose'|'backtrace', msgidregexp)
% Set verbosity and backtrace display for all messages where msgid
% matches msgidregexp. To match a message id exactly, use the regexp
% '^msgid$'.
%
% function [olddest msgids] = cfg_message('none'|'stdout'|'stderr'|'syslog', 'destination', msgidregexp)
% Set destination for all messages matching msgidregexp.
%
% function [oldlvl msgids] = cfg_message('info'|'warning'|'error', 'level', msgidregexp)
% Set severity level for all messages matching msgidregexp.
%
% For all matching message ids and message templates, the old value and
% the id are returned as cell strings. These can be used to restore
% previous settings one-by-one.
%
% This code is part of a batch job configuration system for MATLAB. See
% help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging
% Volkmar Glauche
% $Id: cfg_message.m 4863 2012-08-27 08:09:23Z volkmar $
rev = '$Rev: 4863 $'; %#ok
if nargin < 1 || isempty(varargin{1})
return;
end
% Get message settings
msgcfg = cfg_get_defaults('msgcfg');
msgtpl = cfg_get_defaults('msgtpl');
msgdef = cfg_get_defaults('msgdef');
% Helper inline functions
ismsgid = inline('~isempty(regexp(msgidstr,''^([a-zA-Z]\w*:)+[a-zA-Z]\w*$'',''once''))',...
'msgidstr');
findcfg = inline('~cellfun(@isempty,regexp({msgcfg.identifier},msgregexp,''once''))', ...
'msgcfg','msgregexp');
% Input checks
if ~(ischar(varargin{1}) && size(varargin{1},1) == 1) && ...
~(isstruct(varargin{1}) && numel(varargin{1}) == 1 && ...
all(isfield(varargin{1}, {'message', 'identifier'})))
cfg_message('matlabbatch:cfg_message', ...
'First argument must be a one-line character string or an errorstruct.');
return;
end
if any(strcmpi(varargin{1}, {'on', 'off', 'none', 'stdout', 'stderr', ...
'syslog', 'info', 'warning', 'error'}))
% Set message properties
if nargin ~= 3
cfg_message('matlabbatch:cfg_message', ...
'Must specify status, property and msgidregexp.');
return;
end
if any(strcmpi(varargin{1}, {'on', 'off'})) && ~any(strcmpi(varargin{2}, ...
{'verbose', 'backtrace'}))
cfg_message('matlabbatch:cfg_message', ...
['Message property must be one of ''verbose'' or ' ...
'''backtrace''.']);
return;
elseif any(strcmpi(varargin{1}, {'none', 'stdout', 'stderr', 'syslog'})) && ...
~strcmpi(varargin{2}, 'destination')
cfg_message('matlabbatch:cfg_message', ...
'Message property must be ''destination''.');
return;
elseif any(strcmpi(varargin{1}, {'info', 'warning', 'error'})) && ...
~strcmpi(varargin{2}, 'level')
cfg_message('matlabbatch:cfg_message', ...
'Message property must be ''level''.');
return;
end
if ~ischar(varargin{3}) || size(varargin{3},1) ~= 1
cfg_message('matlabbatch:cfg_message', ...
'Third argument must be a one-line character string.');
return;
end
msgstate = lower(varargin{1});
msgprop = lower(varargin{2});
msgregexp = varargin{3};
sel = findcfg(msgcfg, msgregexp);
% Save properties and matching ids
oldmsgprops = {msgcfg(sel).(msgprop)};
mchmsgids = {msgcfg(sel).identifier};
if any(sel)
% Set property on all matching messages
[msgcfg(sel).(msgprop)] = deal(msgstate);
cfg_get_defaults('msgcfg',msgcfg);
elseif ismsgid(msgregexp)
% Add new rule, if msgregexp is a valid id
msgcfg(end+1) = msgdef;
msgcfg(end).identifier = msgregexp;
msgcfg(end).(msgprop) = msgstate;
cfg_get_defaults('msgcfg',msgcfg);
end
if ~ismsgid(msgregexp)
% Update templates
sel = strcmp(msgregexp, {msgtpl.identifier});
% Save properties and matching ids
oldtplprops = {msgtpl(sel).(msgprop)};
mchtplids = {msgtpl(sel).identifier};
if any(sel)
% Update literally matching regexps
[msgtpl(sel).(msgprop)] = deal(msgstate);
else
% Add new template rule
msgtpl(end+1) = msgdef;
msgtpl(end).identifier = msgregexp;
msgtpl(end).(msgprop) = msgstate;
end
cfg_get_defaults('msgtpl',msgtpl);
else
oldtplprops = {};
mchtplids = {};
end
varargout{1} = [oldmsgprops(:); oldtplprops(:)]';
varargout{2} = [mchmsgids(:); mchtplids(:)]';
else
% Issue message
if isstruct(varargin{1})
msgid = varargin{1}.identifier;
msgfmt = varargin{1}.message;
extras = {};
if isfield(varargin{1},'stack')
stack = varargin{1}.stack;
else
stack = dbstack(2);
end
% discard other fields
else
if nargin < 2
cfg_message('matlabbatch:cfg_message', ...
'Must specify msgid and message.');
end
if ~ischar(varargin{2}) || size(varargin{2},1) ~= 1
cfg_message('matlabbatch:cfg_message', ...
'Second argument must be a one-line character string.');
end
msgid = varargin{1};
msgfmt = varargin{2};
extras = varargin(3:end);
stack = dbstack(2);
end
% find msgcfg entry for msgid
sel = strcmp(msgid, {msgcfg.identifier});
if any(sel)
cmsgcfg = msgcfg;
else
% no identity match found, match against regexp templates
sel = ~cellfun(@isempty, regexp(msgid, {msgtpl.identifier}));
cmsgcfg = msgtpl;
[cmsgcfg(sel).identifier] = deal(msgid);
end
switch nnz(sel)
case 0
% no matching id (or invalid msgid), use default setting
cmsgcfg = msgdef;
cmsgcfg.identifier = msgid;
issuemsg(cmsgcfg, msgfmt, extras);
case 1
% exact match
issuemsg(cmsgcfg(sel), msgfmt, extras);
otherwise
% multiple matches, use last match (i.e. least recently added rule)
is = find(sel);
issuemsg(cmsgcfg(is(end)), msgfmt, extras);
end
end
function issuemsg(msgcfg, msgfmt, extras)
if strcmp(msgcfg.level,'error') || ~strcmp(msgcfg.destination, 'none')
switch msgcfg.destination
case 'none'
fid = -1;
case 'stdout'
fid = 1;
case 'stderr'
fid = 2;
case 'syslog'
if isunix
fid = '/usr/bin/logger';
else
fid = -1;
end
end
msg = sprintf(msgfmt, extras{:});
switch msgcfg.level
case 'info'
if ischar(fid)
unix(sprintf('%s -t [MATLAB] %s: %s', fid, msgcfg.identifier, ...
msg));
elseif ~ischar(fid) && fid > 0
% only display, if destination is neither syslog nor none
fprintf(fid, '%s\n', msg);
if strcmp(msgcfg.backtrace, 'on')
dbstack(2) % This will ignore fid
end
if strcmp(msgcfg.verbose, 'on')
fprintf(fid, 'To turn off this message, type %s(''none'', ''destination'', ''%s'').\n',...
mfilename, msgcfg.identifier);
end
end
case 'warning'
if ischar(fid)
unix(sprintf('%s -t [MATLAB] %s: %s', fid, msgcfg.identifier, ...
msg));
elseif ~ischar(fid) && fid > 0
% only display, if destination is neither syslog nor none
bsts = warning('query','backtrace');
vsts = warning('query','verbose');
warning('off', 'backtrace');
warning('off', 'verbose');
warning(msgcfg.identifier, msg);
if strcmp(msgcfg.backtrace, 'on')
dbstack(2)
end
if strcmp(msgcfg.verbose, 'on')
fprintf('To turn off this message, type %s(''none'', ''destination'', ''%s'').\n',...
mfilename, msgcfg.identifier);
end
warning(bsts);
warning(vsts);
end
case 'error'
if ischar(fid)
unix(sprintf('%s -t [MATLAB] %s: %s', fid, msgcfg.identifier, ...
msg));
end
le.identifier = msgcfg.identifier;
le.message = msg;
le.stack = dbstack(2);
error(le);
end
end
|
github
|
philippboehmsturm/antx-master
|
initialise.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/matlabbatch/@cfg_branch/initialise.m
| 1,880 |
utf_8
|
ae5ccc5390fd36b56d02f477649f8a28
|
function item = initialise(item, val, dflag)
% function item = initialise(item, val, dflag)
% Initialise a configuration tree with values. If val is a job
% struct/cell, only the parts of the configuration that are present in
% this job will be initialised.
% If val has the special value '<DEFAULTS>', the entire configuration
% will be updated with values from .def fields. If a .def field is
% present in a cfg_leaf item, the current default value will be inserted,
% possibly replacing a previously entered (default) value.
% dflag is ignored in a cfg_branch.
%
% This code is part of a batch job configuration system for MATLAB. See
% help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging
% Volkmar Glauche
% $Id: initialise.m 326 2008-09-16 14:00:57Z glauche $
rev = '$Rev: 326 $'; %#ok
if strcmp(val,'<DEFAULTS>')
item = initialise_def(item, val, dflag);
elseif isstruct(val)
item = initialise_job(item, val, dflag);
else
cfg_message('matlabbatch:initialise', ...
'Can not initialise %s: job is not a struct.', ...
gettag(item));
end;
function item = initialise_def(item, val, dflag)
citem = subsref(item, substruct('.','val'));
for k = 1:numel(citem)
citem{k} = initialise(citem{k}, val, dflag);
end;
item = subsasgn(item, substruct('.','val'), citem);
function item = initialise_job(item, val, dflag)
% Determine possible tags
vtags = fieldnames(val);
for k = 1:numel(item.cfg_item.val)
% find field in val that corresponds to one of the branch vals
vi = strcmp(gettag(item.cfg_item.val{k}), vtags);
if any(vi) % field names are unique, so there will be at most one match
item.cfg_item.val{k} = initialise(item.cfg_item.val{k}, ...
val.(vtags{vi}), dflag);
end;
end;
|
github
|
philippboehmsturm/antx-master
|
cfg_run_subsrefvar.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/matlabbatch/cfg_basicio/cfg_run_subsrefvar.m
| 6,684 |
utf_8
|
e989b483543339da73d1dfadd792a91e
|
function varargout = cfg_run_subsrefvar(cmd, varargin)
% Template function to implement callbacks for an cfg_exbranch. The calling
% syntax is
% varargout = cfg_run_subsrefvar(cmd, varargin)
% where cmd is one of
% 'run' - out = cfg_run_subsrefvar('run', job)
% Run a job, and return its output argument
% 'vout' - dep = cfg_run_subsrefvar('vout', job)
% Examine a job structure with all leafs present and return an
% array of cfg_dep objects.
% 'check' - str = cfg_run_subsrefvar('check', subcmd, subjob)
% Examine a part of a fully filled job structure. Return an empty
% string if everything is ok, or a string describing the check
% error. subcmd should be a string that identifies the part of
% the configuration to be checked.
% 'defaults' - defval = cfg_run_subsrefvar('defaults', key)
% Retrieve defaults value. key must be a sequence of dot
% delimited field names into the internal def struct which is
% kept in function local_def. An error is returned if no
% matching field is found.
% cfg_run_subsrefvar('defaults', key, newval)
% Set the specified field in the internal def struct to a new
% value.
% Application specific code needs to be inserted at the following places:
% 'run' - main switch statement: code to compute the results, based on
% a filled job
% 'vout' - main switch statement: code to compute cfg_dep array, based
% on a job structure that has all leafs, but not necessarily
% any values filled in
% 'check' - create and populate switch subcmd switchyard
% 'defaults' - modify initialisation of defaults in subfunction local_defs
% Callbacks can be constructed using anonymous function handles like this:
% 'run' - @(job)cfg_run_subsrefvar('run', job)
% 'vout' - @(job)cfg_run_subsrefvar('vout', job)
% 'check' - @(job)cfg_run_subsrefvar('check', 'subcmd', job)
% 'defaults' - @(val)cfg_run_subsrefvar('defaults', 'defstr', val{:})
% Note the list expansion val{:} - this is used to emulate a
% varargin call in this function handle.
%
% This code is part of a batch job configuration system for MATLAB. See
% help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging
% Volkmar Glauche
% $Id: cfg_run_subsrefvar.m 485 2010-06-25 09:45:10Z glauche $
rev = '$Rev: 485 $'; %#ok
if ischar(cmd)
switch lower(cmd)
case 'run'
job = local_getjob(varargin{1});
% do computation, return results in variable out
subs = local_getsubs(job, true);
out.output = subsref(job.input, subs);
if nargout > 0
varargout{1} = out;
end
case 'vout'
job = local_getjob(varargin{1});
subscode = char(gencode_substruct(local_getsubs(job, false)));
dep = cfg_dep;
if isempty(subscode)
dep.sname = 'Referenced part of variable';
else
dep.sname = sprintf('val%s', subscode);
end
dep.src_output = substruct('.','output');
if isequal(job.tgt_spec,'<UNKNOWN>')
dep.tgt_spec = cfg_findspec({{'strtype','e'}});
else
fn = fieldnames(job.tgt_spec);
dep.tgt_spec = job.tgt_spec.(fn{1});
end
varargout{1} = dep;
case 'check'
if ischar(varargin{1})
subcmd = lower(varargin{1});
subjob = varargin{2};
str = '';
switch subcmd
% implement checks, return status string in variable str
case 'subsind'
if (ischar(subjob) && isequal(subjob, ':')) || ...
(isnumeric(subjob) && isequal(subjob, round(subjob)) && all(subjob > 0))
str = '';
else
str = 'Subscript index must be either a vector of natural numbers or the character '':''.';
end
otherwise
cfg_message('unknown:check', ...
'Unknown check subcmd ''%s''.', subcmd);
end
varargout{1} = str;
else
cfg_message('ischar:check', 'Subcmd must be a string.');
end
case 'defaults'
if nargin == 2
varargout{1} = local_defs(varargin{1});
else
local_defs(varargin{1:2});
end
otherwise
cfg_message('unknown:cmd', 'Unknown command ''%s''.', cmd);
end
else
cfg_message('ischar:cmd', 'Cmd must be a string.');
end
function subs = local_getsubs(job, cwarn)
% generate subscript structure
% generate warning for cell references if requested
subs = struct('type',{},'subs',{});
for k = 1:numel(job.subsreference)
switch char(fieldnames(job.subsreference{k}))
case 'subsfield'
subs(k).type = '.';
subs(k).subs = job.subsreference{k}.subsfield;
case 'subsinda'
subs(k).type = '()';
subs(k).subs = job.subsreference{k}.subsinda;
case 'subsindc'
subs(k).type = '{}';
subs(k).subs = job.subsreference{k}.subsindc;
if cwarn && any(cellfun(@(x)(isequal(x,':')||numel(x)>1), ...
job.subsreference{k}.subsindc))
cfg_message('cfg_basicio:subsrefvar', ...
'Trying to access multiple cell elements - only returning first one.');
end
end
end
function varargout = local_defs(defstr, defval)
persistent defs;
if isempty(defs)
% initialise defaults
end
if ischar(defstr)
% construct subscript reference struct from dot delimited tag string
tags = textscan(defstr,'%s', 'delimiter','.');
subs = struct('type','.','subs',tags{1}');
try
cdefval = subsref(local_def, subs);
catch
cdefval = [];
cfg_message('defaults:noval', ...
'No matching defaults value ''%s'' found.', defstr);
end
if nargin == 1
varargout{1} = cdefval;
else
defs = subsasgn(defs, subs, defval);
end
else
cfg_message('ischar:defstr', 'Defaults key must be a string.');
end
function job = local_getjob(job)
if ~isstruct(job)
cfg_message('isstruct:job', 'Job must be a struct.');
end
|
github
|
philippboehmsturm/antx-master
|
cfg_run_call_matlab.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/matlabbatch/cfg_basicio/cfg_run_call_matlab.m
| 5,993 |
utf_8
|
6c951c26ab12e11978df562f45ad4152
|
function varargout = cfg_run_call_matlab(cmd, varargin)
% A generic interface to call any MATLAB function through the batch system
% and make its output arguments available as dependencies.
% varargout = cfg_run_call_matlab(cmd, varargin)
% where cmd is one of
% 'run' - out = cfg_run_call_matlab('run', job)
% Run the function, and return the specified output arguments
% 'vout' - dep = cfg_run_call_matlab('vout', job)
% Return dependencies as specified via the output cfg_repeat.
% 'check' - str = cfg_run_call_matlab('check', subcmd, subjob)
% Examine a part of a fully filled job structure. Return an empty
% string if everything is ok, or a string describing the check
% error. subcmd should be a string that identifies the part of
% the configuration to be checked.
% 'defaults' - defval = cfg_run_call_matlab('defaults', key)
% Retrieve defaults value. key must be a sequence of dot
% delimited field names into the internal def struct which is
% kept in function local_def. An error is returned if no
% matching field is found.
% cfg_run_call_matlab('defaults', key, newval)
% Set the specified field in the internal def struct to a new
% value.
% Application specific code needs to be inserted at the following places:
% 'run' - main switch statement: code to compute the results, based on
% a filled job
% 'vout' - main switch statement: code to compute cfg_dep array, based
% on a job structure that has all leafs, but not necessarily
% any values filled in
% 'check' - create and populate switch subcmd switchyard
% 'defaults' - modify initialisation of defaults in subfunction local_defs
% Callbacks can be constructed using anonymous function handles like this:
% 'run' - @(job)cfg_run_call_matlab('run', job)
% 'vout' - @(job)cfg_run_call_matlab('vout', job)
% 'check' - @(job)cfg_run_call_matlab('check', 'subcmd', job)
% 'defaults' - @(val)cfg_run_call_matlab('defaults', 'defstr', val{:})
% Note the list expansion val{:} - this is used to emulate a
% varargin call in this function handle.
%
% This code is part of a batch job configuration system for MATLAB. See
% help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging
% Volkmar Glauche
% $Id: cfg_run_call_matlab.m 479 2010-04-07 12:40:26Z glauche $
rev = '$Rev: 479 $'; %#ok
if ischar(cmd)
switch lower(cmd)
case 'run'
job = local_getjob(varargin{1});
% do computation, return results in variable out
in = cell(size(job.inputs));
for k = 1:numel(in)
in{k} = job.inputs{k}.(char(fieldnames(job.inputs{k})));
end
out.outputs = cell(size(job.outputs));
[out.outputs{:}] = feval(job.fun, in{:});
% make sure output filenames are cellstr arrays, not char
% arrays
for k = 1:numel(out.outputs)
if isfield(job.outputs{k},'filter') && isa(out.outputs{k},'char')
out.outputs{k} = cellstr(out.outputs{k});
end
end
if nargout > 0
varargout{1} = out;
end
case 'vout'
job = local_getjob(varargin{1});
% initialise empty cfg_dep array
dep = cfg_dep;
dep = dep(false);
% determine outputs, return cfg_dep array in variable dep
for k = 1:numel(job.outputs)
dep(k) = cfg_dep;
dep(k).sname = sprintf('Call MATLAB: output %d - %s %s', k, char(fieldnames(job.outputs{k})), char(fieldnames(job.outputs{k}.(char(fieldnames(job.outputs{k}))))));
dep(k).src_output = substruct('.','outputs','{}',{k});
dep(k).tgt_spec = cfg_findspec({{'strtype','e', char(fieldnames(job.outputs{k})), char(fieldnames(job.outputs{k}.(char(fieldnames(job.outputs{k})))))}});
end
varargout{1} = dep;
case 'check'
if ischar(varargin{1})
subcmd = lower(varargin{1});
subjob = varargin{2};
str = '';
switch subcmd
% implement checks, return status string in variable str
otherwise
cfg_message('unknown:check', ...
'Unknown check subcmd ''%s''.', subcmd);
end
varargout{1} = str;
else
cfg_message('ischar:check', 'Subcmd must be a string.');
end
case 'defaults'
if nargin == 2
varargout{1} = local_defs(varargin{1});
else
local_defs(varargin{1:2});
end
otherwise
cfg_message('unknown:cmd', 'Unknown command ''%s''.', cmd);
end
else
cfg_message('ischar:cmd', 'Cmd must be a string.');
end
function varargout = local_defs(defstr, defval)
persistent defs;
if isempty(defs)
% initialise defaults
end
if ischar(defstr)
% construct subscript reference struct from dot delimited tag string
tags = textscan(defstr,'%s', 'delimiter','.');
subs = struct('type','.','subs',tags{1}');
try
cdefval = subsref(local_def, subs);
catch
cdefval = [];
cfg_message('defaults:noval', ...
'No matching defaults value ''%s'' found.', defstr);
end
if nargin == 1
varargout{1} = cdefval;
else
defs = subsasgn(defs, subs, defval);
end
else
cfg_message('ischar:defstr', 'Defaults key must be a string.');
end
function job = local_getjob(job)
if ~isstruct(job)
cfg_message('isstruct:job', 'Job must be a struct.');
end
|
github
|
philippboehmsturm/antx-master
|
cfg_load_vars.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/matlabbatch/cfg_basicio/cfg_load_vars.m
| 5,290 |
utf_8
|
d9fea1c27279512bee3dd9f1724a21a0
|
function varargout = cfg_load_vars(cmd, varargin)
% Load a .mat file, and return its contents via output dependencies.
% varargout = cfg_load_vars(cmd, varargin)
% where cmd is one of
% 'run' - out = cfg_load_vars('run', job)
% Run a job, and return its output argument
% 'vout' - dep = cfg_load_vars('vout', job)
% Create a virtual output for each requested variable. If
% "all variables" are requested, only one output will be
% generated.
% 'check' - str = cfg_load_vars('check', subcmd, subjob)
% 'isvarname' - check whether the entered string is a valid
% MATLAB variable name. This does not check
% whether the variable is present in the .mat file.
% 'defaults' - defval = cfg_load_vars('defaults', key)
% No defaults.
%
% This code is part of a batch job configuration system for MATLAB. See
% help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging
% Volkmar Glauche
% $Id: cfg_load_vars.m 484 2010-06-23 08:51:04Z glauche $
rev = '$Rev: 484 $'; %#ok
if ischar(cmd)
switch lower(cmd)
case 'run'
job = local_getjob(varargin{1});
% do computation, return results in variable out
var = load(job.matname{1});
if isfield(job.loadvars,'allvars')
out{1} = var;
else
out = cell(size(job.loadvars.varname));
for k = 1:numel(job.loadvars.varname)
try
out{k} = var.(job.loadvars.varname{k});
catch
error(['Variable ''%s'' could not be loaded from ' ...
'file ''%s''.'], job.loadvars.varname{k}, ...
job.matname{1});
end
end
end
if nargout > 0
varargout{1} = out;
end
case 'vout'
job = local_getjob(varargin{1});
% initialise empty cfg_dep array
if isfield(job.loadvars,'allvars')
dep = cfg_dep;
dep(1).sname = 'Loaded Variables (struct)';
dep(1).src_output = substruct('{}',{1});
dep(1).tgt_spec = cfg_findspec({{'class','cfg_entry'}});
else
for k = 1:numel(job.loadvars.varname)
dep(k) = cfg_dep;
if ~isempty(job.loadvars.varname{k}) && ...
ischar(job.loadvars.varname{k}) && ~ ...
strcmpi(job.loadvars.varname{k}, ...
'<UNDEFINED>')
dep(k).sname = sprintf('Loaded Variable ''%s''', ...
job.loadvars.varname{k});
else
dep(k).sname = sprintf('Loaded Variable #%d', k);
end
dep(k).src_output = substruct('{}',{k});
dep(k).tgt_spec = cfg_findspec({{'class','cfg_entry'}});
end
end
% determine outputs, return cfg_dep array in variable dep
varargout{1} = dep;
case 'check'
if ischar(varargin{1})
subcmd = lower(varargin{1});
subjob = varargin{2};
str = '';
switch subcmd
case 'isvarname'
if ~isvarname(subjob)
str = sprintf(['''%s'' is not a valid MATLAB ' ...
'variable name'], subjob);
end
otherwise
cfg_message('unknown:check', ...
'Unknown check subcmd ''%s''.', subcmd);
end
varargout{1} = str;
else
cfg_message('ischar:check', 'Subcmd must be a string.');
end
case 'defaults'
if nargin == 2
varargout{1} = local_defs(varargin{1});
else
local_defs(varargin{1:2});
end
otherwise
cfg_message('unknown:cmd', 'Unknown command ''%s''.', cmd);
end
else
cfg_message('ischar:cmd', 'Cmd must be a string.');
end
function varargout = local_defs(defstr, defval)
persistent defs;
if isempty(defs)
% initialise defaults
end
if ischar(defstr)
% construct subscript reference struct from dot delimited tag string
tags = textscan(defstr,'%s', 'delimiter','.');
subs = struct('type','.','subs',tags{1}');
try
cdefval = subsref(local_def, subs);
catch
cdefval = [];
cfg_message('defaults:noval', ...
'No matching defaults value ''%s'' found.', defstr);
end
if nargin == 1
varargout{1} = cdefval;
else
defs = subsasgn(defs, subs, defval);
end
else
cfg_message('ischar:defstr', 'Defaults key must be a string.');
end
function job = local_getjob(job)
if ~isstruct(job)
cfg_message('isstruct:job', 'Job must be a struct.');
end
|
github
|
philippboehmsturm/antx-master
|
initialise.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/matlabbatch/@cfg_choice/initialise.m
| 3,001 |
utf_8
|
0224d7c84c0e3a40bfb09279d56bc0e7
|
function item = initialise(item, val, dflag)
% function item = initialise(item, val, dflag)
% Initialise a configuration tree with values. If val is a job
% struct/cell, only the parts of the configuration that are present in
% this job will be initialised. If dflag is true, then matching items
% from item.values will be initialised. If dflag is false, the matching
% item from item.values will be added to item.val and initialised after
% copying.
% If val has the special value '<DEFAULTS>', the entire configuration
% will be updated with values from .def fields. If a .def field is
% present in a cfg_leaf item, the current default value will be inserted,
% possibly replacing a previously entered (default) value. If dflag is
% true, defaults will only be set in item.values. If dflag is false,
% defaults will be set for both item.val and item.values.
%
% This code is part of a batch job configuration system for MATLAB. See
% help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging
% Volkmar Glauche
% $Id: initialise.m 568 2012-06-20 12:30:00Z glauche $
rev = '$Rev: 568 $'; %#ok
if strcmp(val,'<UNDEFINED>')
val = struct([]);
end
if strcmp(val,'<DEFAULTS>')
item = initialise_def(item, val, dflag);
elseif isstruct(val)
item = initialise_job(item, val, dflag);
elseif iscell(val) && numel(val) == 1 && isstruct(val{1})
item = initialise_job(item, val{1}, dflag);
else
cfg_message('matlabbatch:initialise', ...
'Can not initialise %s: job is not a struct.', ...
gettag(item));
end;
function item = initialise_def(item, val, dflag)
if ~dflag
% initialise defaults both in current job and in defaults
citem = subsref(item, substruct('.','val'));
for k = 1:numel(citem)
citem{k} = initialise(citem{k}, val, dflag);
end;
item = subsasgn(item, substruct('.','val'), citem);
end;
for k = 1:numel(item.values)
item.values{k} = initialise(item.values{k}, val, dflag);
end;
function item = initialise_job(item, val, dflag)
vtags = fieldnames(val);
if dflag % set defaults
for k = 1:numel(item.values)
% find field in values that corresponds to one of the branch vals
vi = strcmp(gettag(item.values{k}), vtags);
if any(vi) % field names are unique, so there will be at most one match
item.values{k} = initialise(item.values{k}, ...
val.(vtags{vi}), dflag);
end;
end;
else
% select matching values struct, initialise and assign it to val
% field
item.cfg_item.val = {};
if ~isempty(vtags)
for k = 1:numel(item.values)
if strcmp(gettag(item.values{k}), vtags{1})
item.cfg_item.val{1} = initialise(item.values{k}, ...
val.(vtags{1}), dflag);
break;
end;
end;
end;
end;
|
github
|
philippboehmsturm/antx-master
|
subsasgn.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/matlabbatch/@cfg_dep/subsasgn.m
| 4,222 |
utf_8
|
a6857a9c1bd09dc62c519bbf634712b6
|
function dep = subsasgn(dep, subs, varargin)
% function dep = subsasgn(dep, subs, varargin)
% subscript references we have to deal with are:
% one level
% dep.(field) - i.e. struct('type',{'.'} ,'subs',{field})
% dep(idx) - i.e. struct('type',{'()'},'subs',{idx})
% two levels
% dep(idx).(field)
%
% to be dealt with elsewhere
% dep.(field){fidx}
% three levels
% dep(idx).(field){fidx}
%
% This code is part of a batch job configuration system for MATLAB. See
% help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging
% Volkmar Glauche
% $Id: subsasgn.m 4863 2012-08-27 08:09:23Z volkmar $
rev = '$Rev: 4863 $'; %#ok
persistent my_cfg_dep
sflag = false;
if strcmpi(subs(1).type, '()')
% check array boundaries, extend if necessary
if (numel(subs(1).subs) == 1 && numel(dep) < max(subs(1).subs{1})) || ...
(numel(subs(1).subs) > ndims(dep)) || ...
(numel(subs(1).subs) == ndims(dep) && any(cellfun(@max, subs(1).subs) > size(dep)))
if isempty(my_cfg_dep)
my_cfg_dep = cfg_dep;
end
if isempty(dep)
dep = my_cfg_dep;
end
[dep(subs(1).subs{:})] = deal(my_cfg_dep);
end
if numel(subs) == 1
[dep(subs(1).subs{:})] = deal(varargin{:});
return;
else
% select referenced objects from input array, run subsasgn on them an
% put results back into input array
odep = dep;
osubs = subs(1);
dep = dep(subs(1).subs{:});
subs = subs(2:end);
sflag = true;
end
end
if strcmpi(subs(1).type, '.')
% field assignment
if numel(subs) > 1
% Only part of field value(s) assigned. Get old field value(s),
% assign values to it.
val = {dep.(subs(1).subs)};
if nargin == 3
% Same value to assign to all field values.
val = cellfun(@(cval)subsasgn(cval,subs(2:end),varargin{1}), val, 'UniformOutput', false);
else
% Different values to assign to each field value.
val = cellfun(@(cval,cin)subsasgn(cval,subs(2:end),cin), val, varargin, 'UniformOutput', false);
end
else
% Field values to assign
val = varargin;
end
% Assign to fields
[ok val] = valcheck(subs(1).subs, val);
if ok
if isempty(dep)
dep = repmat(cfg_dep,size(val));
end
[dep.(subs(1).subs)] = deal(val{:});
end
else
cfg_message('matlabbatch:subsref:unknowntype', 'Bad subscript type ''%s''.',subs(1).type);
end
if sflag
odep(osubs.subs{:}) = dep;
dep = odep;
end
function [ok val] = valcheck(subs, val)
persistent local_mysubs_fields;
if ~iscell(local_mysubs_fields)
local_mysubs_fields = mysubs_fields;
end
ok = true;
switch subs
case {'tname','sname'}
if ~all(cellfun(@ischar,val))
cfg_message('matlabbatch:subsasgn:name', 'Value for field ''%s'' must be a string.', ...
subs);
ok = false;
end
case {'tgt_spec'}
sel = cellfun(@isempty,val);
if any(sel)
[val{sel}] = deal(cfg_findspec);
end
ok = all(cellfun(@is_cfg_findspec,val));
case local_mysubs_fields,
sel = cellfun(@isempty,val);
if any(sel)
[val{sel}] = deal(struct('type',{}, 'subs',{}));
end
ok = all(cellfun(@(cval)(isstruct(cval) && all(isfield(cval,{'type','subs'}))),val));
if ~ok
cfg_message('matlabbatch:subsasgn:subs', ['Value for field ''%s'' must be a struct with' ...
' fields ''type'' and ''subs''.'], subs);
end
otherwise
cfg_message('matlabbatch:subsasgn:unknownfield', 'Reference to unknown field ''%s''.', subs);
end
function ok = is_cfg_findspec(fs)
ok = iscell(fs) && ...
all(cellfun(@(cs)(isstruct(cs) && ...
((numel(fieldnames(cs))==1 && any(isfield(cs,{'name','value'}))) || ...
(numel(fieldnames(cs))==2 && all(isfield(cs,{'name','value'}))))),fs));
if ~ok
cfg_message('matlabbatch:ok_subsasgn:tgt_spec', ...
'Target specification must be a cfg_findspec.');
end
|
github
|
philippboehmsturm/antx-master
|
cfg_example_cumsum1.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/matlabbatch/examples/cfg_example_cumsum1.m
| 2,889 |
utf_8
|
f5dc70e6d60661de3c6bf62d8ea9487b
|
function cumsum = cfg_example_cumsum1
% Example script that creates an cfg_exbranch to sum two numbers. The
% inputs are entered as vector, the output is a vector containing the
% cumulative sums. This function differs from cfg_example_sum (except from
% names) only in the specification of the output subscript.
%
% This code is part of a batch job configuration system for MATLAB. See
% help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging
% Volkmar Glauche
% $Id: cfg_example_cumsum1.m 269 2008-05-23 07:15:10Z glauche $
rev = '$Rev: 269 $'; %#ok
%% Input Item
input1 = cfg_entry; % This is the generic data entry item
input1.name = 'Input a'; % The displayed name
input1.tag = 'a'; % The name appearing in the harvested job structure. This name must be unique among all items in the val field of the superior node
input1.strtype = 'e'; % No restriction on what type of data is entered. This could be used to restrict input to real numbers, integers ...
input1.num = [1 Inf]; % Number of inputs required (2D-array with exactly one row and two column)
input1.help = {'This is the input vector.','The elements will be added together.'}; % help text displayed
%% Executable Branch
cumsum = cfg_exbranch; % This is the branch that has information about how to run this module
cumsum.name = 'cumsum1'; % The display name
cumsum.tag = 'cfg_example_cumsum1'; % The name appearing in the harvested job structure. This name must be unique among all items in the val field of the superior node
cumsum.val = {input1}; % The items that belong to this branch. All items must be filled before this branch can run or produce virtual outputs
cumsum.prog = @cfg_example_run_cumsum1; % A function handle that will be called with the harvested job to run the computation
cumsum.vout = @cfg_example_vout_cumsum1; % A function handle that will be called with the harvested job to determine virtual outputs
cumsum.help = {'Compute the cumulative sum of two numbers.'};
%% Local Functions
% The cfg_example_vout_cumsum1 function can go here, it is not useful outside
% the batch environment.
function vout = cfg_example_vout_cumsum1(job)
% Determine what outputs will be present if this job is run. In this case,
% the structure of the inputs is fixed, and the output is always a single
% number. Note that input items may not be numbers, they can also be
% dependencies.
vout = cfg_dep; % The dependency object
vout.sname = 'cumsum(a)'; % Displayed dependency name
vout.src_output = substruct('.','cs'); % The output subscript reference. The length of the output vector depends on the unknown length of the input vector. Therefore, the vector output needs to be assigned to a struct field.
|
github
|
philippboehmsturm/antx-master
|
cfg_example_div.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/matlabbatch/examples/cfg_example_div.m
| 3,310 |
utf_8
|
902c541dac987ad9bb5ebf031e4f5180
|
function div = cfg_example_div
% Example script that creates an cfg_exbranch to compute mod and rem of two
% natural numbers. The inputs are entered as two single numbers, the output
% is a struct with two fields 'mod' and 'rem'.
%
% This code is part of a batch job configuration system for MATLAB. See
% help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging
% Volkmar Glauche
% $Id: cfg_example_div.m 269 2008-05-23 07:15:10Z glauche $
rev = '$Rev: 269 $'; %#ok
%% Input Items
% Input a
input1 = cfg_entry; % This is the generic data entry item
input1.name = 'Input a'; % The displayed name
input1.tag = 'a'; % The name appearing in the harvested job structure. This name must be unique among all items in the val field of the superior node
input1.strtype = 'n'; % Natural number required
input1.num = [1 1]; % Number of inputs required (2D-array with exactly one row and one column)
input1.help = {'This is input a.','This input will be divided by the other input.'}; % help text displayed
% Input b
input2 = cfg_entry; % This is the generic data entry item
input2.name = 'Input b'; % The displayed name
input2.tag = 'b'; % The name appearing in the harvested job structure. This name must be unique among all items in the val field of the superior node
input2.strtype = 'n'; % Natural number required
input2.num = [1 1]; % Number of inputs required (2D-array with exactly one row and one column)
input2.help = {'This is input b.','The other input will be divided by this input.'}; % help text displayed
%% Executable Branch
div = cfg_exbranch; % This is the branch that has information about how to run this module
div.name = 'div'; % The display name
div.tag = 'cfg_example_div'; % The name appearing in the harvested job structure. This name must be unique among all items in the val field of the superior node
div.val = {input1 input2}; % The items that belong to this branch. All items must be filled before this branch can run or produce virtual outputs
div.prog = @cfg_example_run_div; % A function handle that will be called with the harvested job to run the computation
div.vout = @cfg_example_vout_div; % A function handle that will be called with the harvested job to determine virtual outputs
div.help = {'Compute mod and rem of two numbers.'};
%% Local Functions
% The cfg_example_vout_div function can go here, it is not useful outside
% the batch environment.
function vout = cfg_example_vout_div(job)
% Determine what outputs will be present if this job is run. In this case,
% the structure of the inputs is fixed, and the output is always a single
% number. Note that input items may not be numbers, they can also be
% dependencies.
vout(1) = cfg_dep; % The dependency object
vout(1).sname = 'a div b: mod'; % Displayed dependency name
vout(1).src_output = substruct('.','mod'); % The output subscript reference.
vout(2) = cfg_dep; % The dependency object
vout(2).sname = 'a div b: rem'; % Displayed dependency name
vout(2).src_output = substruct('.','rem'); % The output subscript reference.
|
github
|
philippboehmsturm/antx-master
|
cfg_example_add2.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/matlabbatch/examples/cfg_example_add2.m
| 2,620 |
utf_8
|
46feab1277369d412b219fc3988a1392
|
function add2 = cfg_example_add2
% Example script that creates an cfg_exbranch to sum two numbers. The
% inputs are entered as 2-vector, the output is just a single
% number.
%
% This code is part of a batch job configuration system for MATLAB. See
% help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging
% Volkmar Glauche
% $Id: cfg_example_add2.m 269 2008-05-23 07:15:10Z glauche $
rev = '$Rev: 269 $'; %#ok
%% Input Item
input1 = cfg_entry; % This is the generic data entry item
input1.name = 'Input a'; % The displayed name
input1.tag = 'a'; % The name appearing in the harvested job structure. This name must be unique among all items in the val field of the superior node
input1.strtype = 'e'; % No restriction on what type of data is entered. This could be used to restrict input to real numbers, integers ...
input1.num = [1 2]; % Number of inputs required (2D-array with exactly one row and two column)
input1.help = {'This is the input vector.','The elements will be added together.'}; % help text displayed
%% Executable Branch
add2 = cfg_exbranch; % This is the branch that has information about how to run this module
add2.name = 'Add2'; % The display name
add2.tag = 'cfg_example_add2'; % The name appearing in the harvested job structure. This name must be unique among all items in the val field of the superior node
add2.val = {input1}; % The items that belong to this branch. All items must be filled before this branch can run or produce virtual outputs
add2.prog = @cfg_example_run_add2; % A function handle that will be called with the harvested job to run the computation
add2.vout = @cfg_example_vout_add2; % A function handle that will be called with the harvested job to determine virtual outputs
add2.help = {'Add two numbers.'};
%% Local Functions
% The cfg_example_vout_add2 function can go here, it is not useful outside
% the batch environment.
function vout = cfg_example_vout_add2(job)
% Determine what outputs will be present if this job is run. In this case,
% the structure of the inputs is fixed, and the output is always a single
% number. Note that input items may not be numbers, they can also be
% dependencies.
vout = cfg_dep; % The dependency object
vout.sname = 'Add2: a + b'; % Displayed dependency name
vout.src_output = substruct('()',{1}); % The output subscript reference. This could be any reference into the output variable created during computation
|
github
|
philippboehmsturm/antx-master
|
cfg_example_add1.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/matlabbatch/examples/cfg_example_add1.m
| 3,289 |
utf_8
|
e1eb2aaadbb170eb366a96d03a8661e8
|
function add1 = cfg_example_add1
% Example script that creates an cfg_exbranch to sum two numbers. The
% inputs are entered as two single numbers, the output is just a single
% number.
%
% This code is part of a batch job configuration system for MATLAB. See
% help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging
% Volkmar Glauche
% $Id: cfg_example_add1.m 269 2008-05-23 07:15:10Z glauche $
rev = '$Rev: 269 $'; %#ok
%% Input Items
% Input a
input1 = cfg_entry; % This is the generic data entry item
input1.name = 'Input a'; % The displayed name
input1.tag = 'a'; % The name appearing in the harvested job structure. This name must be unique among all items in the val field of the superior node
input1.strtype = 'e'; % No restriction on what type of data is entered. This could be used to restrict input to real numbers, integers ...
input1.num = [1 1]; % Number of inputs required (2D-array with exactly one row and one column)
input1.help = {'This is input a.','This input will be added to the other input.'}; % help text displayed
% Input b
input2 = cfg_entry; % This is the generic data entry item
input2.name = 'Input b'; % The displayed name
input2.tag = 'b'; % The name appearing in the harvested job structure. This name must be unique among all items in the val field of the superior node
input2.strtype = 'e'; % No restriction on what type of data is entered. This could be used to restrict input to real numbers, integers ...
input2.num = [1 1]; % Number of inputs required (2D-array with exactly one row and one column)
input2.help = {'This is input b.','This input will be added to the other input.'}; % help text displayed
%% Executable Branch
add1 = cfg_exbranch; % This is the branch that has information about how to run this module
add1.name = 'Add1'; % The display name
add1.tag = 'cfg_example_add1'; % The name appearing in the harvested job structure. This name must be unique among all items in the val field of the superior node
add1.val = {input1 input2}; % The items that belong to this branch. All items must be filled before this branch can run or produce virtual outputs
add1.prog = @cfg_example_run_add1; % A function handle that will be called with the harvested job to run the computation
add1.vout = @cfg_example_vout_add1; % A function handle that will be called with the harvested job to determine virtual outputs
add1.help = {'Add two numbers.'};
%% Local Functions
% The cfg_example_vout_add1 function can go here, it is not useful outside
% the batch environment.
function vout = cfg_example_vout_add1(job)
% Determine what outputs will be present if this job is run. In this case,
% the structure of the inputs is fixed, and the output is always a single
% number. Note that input items may not be numbers, they can also be
% dependencies.
vout = cfg_dep; % The dependency object
vout.sname = 'Add1: a + b'; % Displayed dependency name
vout.src_output = substruct('()',{1}); % The output subscript reference. This could be any reference into the output variable created during computation
|
github
|
philippboehmsturm/antx-master
|
cfg_example_cumsum2.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/matlabbatch/examples/cfg_example_cumsum2.m
| 3,390 |
utf_8
|
2db3649cdb98840abf80534956cbdeed
|
function cumsum = cfg_example_cumsum2
% Example script that creates an cfg_exbranch to sum two numbers. The
% inputs are entered as vector, the output is a vector containing the
% cumulative sums. This function differs from cfg_example_sum (except from
% names) only in the specification of the output subscript.
%
% This code is part of a batch job configuration system for MATLAB. See
% help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging
% Volkmar Glauche
% $Id: cfg_example_cumsum2.m 269 2008-05-23 07:15:10Z glauche $
rev = '$Rev: 269 $'; %#ok
%% Input Item
input1 = cfg_entry; % This is the generic data entry item
input1.name = 'Input a'; % The displayed name
input1.tag = 'a'; % The name appearing in the harvested job structure. This name must be unique among all items in the val field of the superior node
input1.strtype = 'e'; % No restriction on what type of data is entered. This could be used to restrict input to real numbers, integers ...
input1.num = [1 1]; % Number of inputs required (2D-array with exactly one row and two column)
input1.help = {'This is a vector element.'}; % help text displayed
%% Collect Single Numbers to Vector
invec = cfg_repeat;
invec.name = 'Vector';
invec.tag = 'unused'; % According to the harvest rules for cfg_repeat, this tag will never appear in the output, because there is only one cfg_item to repeat and forcestruct is false
invec.values = {input1};
invec.num = [1 Inf]; % At least one input should be there
invec.help = {'Enter a vector element by element.'};
%% Executable Branch
cumsum = cfg_exbranch; % This is the branch that has information about how to run this module
cumsum.name = 'cumsum2'; % The display name
cumsum.tag = 'cfg_example_cumsum2'; % The name appearing in the harvested job structure. This name must be unique among all items in the val field of the superior node
cumsum.val = {invec}; % The items that belong to this branch. All items must be filled before this branch can run or produce virtual outputs
cumsum.prog = @cfg_example_run_cumsum2; % A function handle that will be called with the harvested job to run the computation
cumsum.vout = @cfg_example_vout_cumsum2; % A function handle that will be called with the harvested job to determine virtual outputs
cumsum.help = {'Compute the cumulative sum of a vector.'};
%% Local Functions
% The cfg_example_vout_cumsum2 function can go here, it is not useful outside
% the batch environment.
function vout = cfg_example_vout_cumsum2(job)
% Determine what outputs will be present if this job is run. In this case,
% the structure of the inputs is fixed, and the output is always a single
% number. Note that input items may not be numbers, they can also be
% dependencies.
for k = 1:numel(job.a)
% Create a subscript reference for each element of the cumsum vector
vout(k) = cfg_dep; % The dependency object
vout(k).sname = sprintf('cumsum(a(1:%d))', k); % Displayed dependency name
vout(k).src_output = substruct('.','cs','()',{k}); % The output subscript reference. The length of the output vector depends on the unknown length of the input vector. Therefore, the generic ':' subscript is needed.
end;
|
github
|
philippboehmsturm/antx-master
|
cfg_example_sum.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/matlabbatch/examples/cfg_example_sum.m
| 2,704 |
utf_8
|
ded78850aa3b7a740bb1d79cbcdccbc4
|
function sum = cfg_example_sum
% Example script that creates an cfg_exbranch to sum two numbers. The
% inputs are entered as vector, the output is just a single
% number. This function differs from cfg_example_add2 (except from names)
% only in the specification of input1.num.
%
% This code is part of a batch job configuration system for MATLAB. See
% help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging
% Volkmar Glauche
% $Id: cfg_example_sum.m 269 2008-05-23 07:15:10Z glauche $
rev = '$Rev: 269 $'; %#ok
%% Input Item
input1 = cfg_entry; % This is the generic data entry item
input1.name = 'Input a'; % The displayed name
input1.tag = 'a'; % The name appearing in the harvested job structure. This name must be unique among all items in the val field of the superior node
input1.strtype = 'e'; % No restriction on what type of data is entered. This could be used to restrict input to real numbers, integers ...
input1.num = [1 Inf]; % Number of inputs required (2D-array with exactly one row and two column)
input1.help = {'This is the input vector.','The elements will be added together.'}; % help text displayed
%% Executable Branch
sum = cfg_exbranch; % This is the branch that has information about how to run this module
sum.name = 'sum'; % The display name
sum.tag = 'cfg_example_sum'; % The name appearing in the harvested job structure. This name must be unique among all items in the val field of the superior node
sum.val = {input1}; % The items that belong to this branch. All items must be filled before this branch can run or produce virtual outputs
sum.prog = @cfg_example_run_sum; % A function handle that will be called with the harvested job to run the computation
sum.vout = @cfg_example_vout_sum; % A function handle that will be called with the harvested job to determine virtual outputs
sum.help = {'Add two numbers.'};
%% Local Functions
% The cfg_example_vout_sum function can go here, it is not useful outside
% the batch environment.
function vout = cfg_example_vout_sum(job)
% Determine what outputs will be present if this job is run. In this case,
% the structure of the inputs is fixed, and the output is always a single
% number. Note that input items may not be numbers, they can also be
% dependencies.
vout = cfg_dep; % The dependency object
vout.sname = 'sum(a)'; % Displayed dependency name
vout.src_output = substruct('()',{1}); % The output subscript reference. This could be any reference into the output variable created during computation
|
github
|
philippboehmsturm/antx-master
|
num2str.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/matlabbatch/private/num2str.m
| 6,229 |
utf_8
|
35ba81d9ba6b78d182aa2136612ac3b2
|
function s = num2str(x, f)
%NUM2STR Convert numbers to a string.
% T = NUM2STR(X) converts the matrix X into a string representation T
% with about 4 digits and an exponent if required. This is useful for
% labeling plots with the TITLE, XLABEL, YLABEL, and TEXT commands.
%
% T = NUM2STR(X,N) converts the matrix X into a string representation
% with a maximum N digits of precision. The default number of digits is
% based on the magnitude of the elements of X.
%
% T = NUM2STR(X,FORMAT) uses the format string FORMAT (see SPRINTF for
% details).
%
% If the input array is integer-valued, num2str returns the exact string
% representation of that integer. The term integer-valued includes large
% floating-point numbers that lose precision due to limitations of the
% hardware.
%
% Example:
% num2str(randn(2,2),3) produces the string matrix
%
% '-0.433 0.125'
% ' -1.67 0.288'
%
% See also INT2STR, SPRINTF, FPRINTF, MAT2STR.
% Copyright 1984-2005 The MathWorks, Inc.
% $Revision: 299 $ $Date: 2006/11/11 22:45:08 $
%------------------------------------------------------------------------------
% if input does not exist or is empty, throw an exception
if nargin<1
cfg_message('MATLAB:num2str:NumericArrayUnspecified',...
'Numeric array is unspecified')
end
% If input is a string, return this string.
if ischar(x)
s = x;
return
end
if isempty(x)
s = '';
return
end
if issparse(x)
x = full(x);
end
maxDigitsOfPrecision = 256;
floatFieldExtra = 7;
intFieldExtra = 2;
maxFieldWidth = 12;
floatWidthOffset = 4;
% Compose sprintf format string of numeric array.
if nargin < 2 && ~isempty(x) && isequalwithequalnans(x, fix(x))
if isreal(x)
% The precision is unspecified; the numeric array contains whole numbers.
s = int2str(x);
return;
else
%Complex case
% maximum field width is 12 digits
xmax = double(max(abs(x(:))));
if xmax == 0
d = 1;
else
d = min(maxFieldWidth, floor(log10(xmax)) + 1);
end
% Create ANSI C print format string.
f = ['%' sprintf('%d',d+intFieldExtra) 'd']; % real numbers
fi = ['%-' sprintf('%d',d+intFieldExtra) 's']; % imaginary numbers
end
elseif nargin < 2
% The precision is unspecified; the numeric array contains floating point
% numbers.
xmax = double(max(abs(x(:))));
if xmax == 0
d = 1;
else
d = min(maxFieldWidth, max(1, floor(log10(xmax))+1))+floatWidthOffset;
end
% Create ANSI C print format string.
% real numbers
f = sprintf('%%%.0f.%.0fg', d+floatFieldExtra, d);
% imaginary numbers
fi = sprintf('%%-%.0fs',d+floatFieldExtra);
elseif ~ischar(f)
% Precision is specified, not as ANSI C format string, but as a number.
% Windows gets a segmentation fault at around 512 digits of precision,
% as if it had an internal buffer that cannot handle more than 512 digits
% to the RIGHT of the decimal point. Thus, allow half of the windows buffer
% of digits of precision, as it should be enough for most computations.
% Large numbers of digits to the LEFT of the decimal point seem to be allowed.
if f > maxDigitsOfPrecision
cfg_message('MATLAB:num2str:exceededMaxDigitsOfPrecision', ...
'Exceeded maximum %d digits of precision.',maxDigitsOfPrecision);
end
% Create ANSI C print format string
fi = ['%-' sprintf('%.0f',f+floatFieldExtra) 's'];
f = ['%' sprintf('%.0f',f+floatFieldExtra) '.' int2str(f) 'g'];
else
% Precistion is specified as an ANSI C print format string.
% Validate format string
k = strfind(f,'%');
if isempty(k), cfg_message('MATLAB:num2str:fmtInvalid', ...
'''%s'' is an invalid format.',f);
end
% If digits of precision to the right of the decimal point are specified,
% make sure it will not cause a segmentation fault under Windows.
dotPositions = strfind(f,'.');
if ~isempty(dotPositions)
decimalPosition = find(dotPositions > k(1)); % dot to the right of '%'
if ~isempty(decimalPosition)
digitsOfPrecision = sscanf(f(dotPositions(decimalPosition(1))+1:end),'%d');
if digitsOfPrecision > maxDigitsOfPrecision
cfg_message('MATLAB:num2str:exceededMaxDigitsOfPrecision', ...
'Exceeded maximum %d digits of precision.',maxDigitsOfPrecision);
end
end
end
d = sscanf(f(k(1)+1:end),'%f');
fi = ['%-' int2str(d) 's'];
end
%-------------------------------------------------------------------------------
% Print numeric array as a string image of itself.
[m,n] = size(x);
scell = cell(1,m);
xIsReal = isreal(x);
t = cell(n,1);
pads = logical([]);
for i = 1:m
if xIsReal && (max(x(i,:)) < 2^31-1)
scell{i} = sprintf(f,x(i,:));
if n > 1 && (min(x(i,:)) < 0)
pads(regexp(scell{i}, '([^\sEe])-')) = true;
end
else
for j = 1:n
u0 = sprintf(f,real(x(i,j)));
% we add a space infront of the negative sign
% because Win32 version of sprintf does not.
if (j>1) && u0(1)=='-'
pads(length(u)) = true;
end
u = u0;
% If we are printing integers and have overflowed, then
% add in an extra space.
if (real(x(i,j)) > 2^31-1) && (~isempty(strfind(f,'d')))
u = [' ' u];%#ok
end
if ~xIsReal
if imag(x(i,j)) < 0
u = [u '-' formatimag(f,fi,-imag(x(i,j)))];%#ok
else
u = [u '+' formatimag(f,fi,imag(x(i,j)))];%#ok
end
end
t{j} = u;
end
scell{i} = horzcat(t{:});
end
end
if m > 1
s = strvcat(scell{:});%#ok
else
s = scell{1};
end
pads = find(pads);
if ~isempty(pads)
pads = fliplr(pads);
spacecol = char(ones(m,1)*' ');
for pad = pads
s = [s(:,1:pad) spacecol s(:,pad+1:end)];
end
end
s = strtrim(s);
%------------------------------------------------------------------------------
function v = formatimag(f,fi,x)
% Format imaginary part
v = [sprintf(f,x) 'i'];
v = fliplr(deblank(fliplr(v)));
v = sprintf(fi,v);
|
github
|
philippboehmsturm/antx-master
|
inputdlg.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/matlabbatch/private/inputdlg.m
| 12,680 |
utf_8
|
3b9117e7e6d82e331df98e955c8f1203
|
function Answer=inputdlg(Prompt, Title, NumLines, DefAns, Resize)
%INPUTDLG Input dialog box.
% ANSWER = INPUTDLG(PROMPT) creates a modal dialog box that returns user
% input for multiple prompts in the cell array ANSWER. PROMPT is a cell
% array containing the PROMPT strings.
%
% INPUTDLG uses UIWAIT to suspend execution until the user responds.
%
% ANSWER = INPUTDLG(PROMPT,NAME) specifies the title for the dialog.
%
% ANSWER = INPUTDLG(PROMPT,NAME,NUMLINES) specifies the number of lines for
% each answer in NUMLINES. NUMLINES may be a constant value or a column
% vector having one element per PROMPT that specifies how many lines per
% input field. NUMLINES may also be a matrix where the first column
% specifies how many rows for the input field and the second column
% specifies how many columns wide the input field should be.
%
% ANSWER = INPUTDLG(PROMPT,NAME,NUMLINES,DEFAULTANSWER) specifies the
% default answer to display for each PROMPT. DEFAULTANSWER must contain
% the same number of elements as PROMPT and must be a cell array of
% strings.
%
% ANSWER = INPUTDLG(PROMPT,NAME,NUMLINES,DEFAULTANSWER,OPTIONS) specifies
% additional options. If OPTIONS is the string 'on', the dialog is made
% resizable. If OPTIONS is a structure, the fields Resize, WindowStyle, and
% Interpreter are recognized. Resize can be either 'on' or
% 'off'. WindowStyle can be either 'normal' or 'modal'. Interpreter can be
% either 'none' or 'tex'. If Interpreter is 'tex', the prompt strings are
% rendered using LaTeX.
%
% Examples:
%
% prompt={'Enter the matrix size for x^2:','Enter the colormap name:'};
% name='Input for Peaks function';
% numlines=1;
% defaultanswer={'20','hsv'};
%
% answer=inputdlg(prompt,name,numlines,defaultanswer);
%
% options.Resize='on';
% options.WindowStyle='normal';
% options.Interpreter='tex';
%
% answer=inputdlg(prompt,name,numlines,defaultanswer,options);
%
% See also DIALOG, ERRORDLG, HELPDLG, LISTDLG, MSGBOX,
% QUESTDLG, TEXTWRAP, UIWAIT, WARNDLG .
% Copyright 1994-2007 The MathWorks, Inc.
% $Revision: 311 $
%%%%%%%%%%%%%%%%%%%%
%%% Nargin Check %%%
%%%%%%%%%%%%%%%%%%%%
cfg_message(nargchk(0,5,nargin,'struct'));
cfg_message(nargoutchk(0,1,nargout,'struct'));
%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Handle Input Args %%%
%%%%%%%%%%%%%%%%%%%%%%%%%
if nargin<1
Prompt='Input:';
end
if ~iscell(Prompt)
Prompt={Prompt};
end
NumQuest=numel(Prompt);
if nargin<2,
Title=' ';
end
if nargin<3
NumLines=1;
end
if nargin<4
DefAns=cell(NumQuest,1);
for lp=1:NumQuest
DefAns{lp}='';
end
end
if nargin<5
Resize = 'off';
end
WindowStyle='modal';
Interpreter='none';
Options = struct([]); %#ok
if nargin==5 && isstruct(Resize)
Options = Resize;
Resize = 'off';
if isfield(Options,'Resize'), Resize=Options.Resize; end
if isfield(Options,'WindowStyle'), WindowStyle=Options.WindowStyle; end
if isfield(Options,'Interpreter'), Interpreter=Options.Interpreter; end
end
[rw,cl]=size(NumLines);
OneVect = ones(NumQuest,1);
if (rw == 1 & cl == 2) %#ok Handle []
NumLines=NumLines(OneVect,:);
elseif (rw == 1 & cl == 1) %#ok
NumLines=NumLines(OneVect);
elseif (rw == 1 & cl == NumQuest) %#ok
NumLines = NumLines';
elseif (rw ~= NumQuest | cl > 2) %#ok
cfg_message('MATLAB:inputdlg:IncorrectSize', 'NumLines size is incorrect.')
end
if ~iscell(DefAns),
cfg_message('MATLAB:inputdlg:InvalidDefaultAnswer', 'Default Answer must be a cell array of strings.');
end
%%%%%%%%%%%%%%%%%%%%%%%
%%% Create InputFig %%%
%%%%%%%%%%%%%%%%%%%%%%%
FigWidth=175;
FigHeight=100;
FigPos(3:4)=[FigWidth FigHeight]; %#ok
FigColor=get(0,'DefaultUicontrolBackgroundcolor');
InputFig=dialog( ...
'Visible' ,'off' , ...
'KeyPressFcn' ,@doFigureKeyPress, ...
'Name' ,Title , ...
'Pointer' ,'arrow' , ...
'Units' ,'pixels' , ...
'UserData' ,'Cancel' , ...
'Tag' ,Title , ...
'HandleVisibility' ,'callback' , ...
'Color' ,FigColor , ...
'NextPlot' ,'add' , ...
'WindowStyle' ,WindowStyle, ...
'DoubleBuffer' ,'on' , ...
'Resize' ,Resize ...
);
%%%%%%%%%%%%%%%%%%%%%
%%% Set Positions %%%
%%%%%%%%%%%%%%%%%%%%%
DefOffset = 5;
DefBtnWidth = 53;
DefBtnHeight = 23;
TextInfo.Units = 'pixels' ;
TextInfo.FontSize = get(0,'FactoryUIControlFontSize');
TextInfo.FontWeight = get(InputFig,'DefaultTextFontWeight');
TextInfo.HorizontalAlignment= 'left' ;
TextInfo.HandleVisibility = 'callback' ;
StInfo=TextInfo;
StInfo.Style = 'text' ;
StInfo.BackgroundColor = FigColor;
EdInfo=StInfo;
EdInfo.FontWeight = get(InputFig,'DefaultUicontrolFontWeight');
EdInfo.Style = 'edit';
EdInfo.BackgroundColor = 'white';
BtnInfo=StInfo;
BtnInfo.FontWeight = get(InputFig,'DefaultUicontrolFontWeight');
BtnInfo.Style = 'pushbutton';
BtnInfo.HorizontalAlignment = 'center';
% Add VerticalAlignment here as it is not applicable to the above.
TextInfo.VerticalAlignment = 'bottom';
TextInfo.Color = get(0,'FactoryUIControlForegroundColor');
% adjust button height and width
btnMargin=1.4;
ExtControl=uicontrol(InputFig ,BtnInfo , ...
'String' ,'OK' , ...
'Visible' ,'off' ...
);
% BtnYOffset = DefOffset;
BtnExtent = get(ExtControl,'Extent');
BtnWidth = max(DefBtnWidth,BtnExtent(3)+8);
BtnHeight = max(DefBtnHeight,BtnExtent(4)*btnMargin);
delete(ExtControl);
% Determine # of lines for all Prompts
TxtWidth=FigWidth-2*DefOffset;
ExtControl=uicontrol(InputFig ,StInfo , ...
'String' ,'' , ...
'Position' ,[ DefOffset DefOffset 0.96*TxtWidth BtnHeight ] , ...
'Visible' ,'off' ...
);
WrapQuest=cell(NumQuest,1);
QuestPos=zeros(NumQuest,4);
for ExtLp=1:NumQuest
if size(NumLines,2)==2
[WrapQuest{ExtLp},QuestPos(ExtLp,1:4)]= ...
textwrap(ExtControl,Prompt(ExtLp),NumLines(ExtLp,2));
else
[WrapQuest{ExtLp},QuestPos(ExtLp,1:4)]= ...
textwrap(ExtControl,Prompt(ExtLp),80);
end
end % for ExtLp
delete(ExtControl);
QuestWidth =QuestPos(:,3);
QuestHeight=QuestPos(:,4);
TxtHeight=QuestHeight(1)/size(WrapQuest{1,1},1);
EditHeight=TxtHeight*NumLines(:,1);
EditHeight(NumLines(:,1)==1)=EditHeight(NumLines(:,1)==1)+4;
FigHeight=(NumQuest+2)*DefOffset + ...
BtnHeight+sum(EditHeight) + ...
sum(QuestHeight);
TxtXOffset=DefOffset;
QuestYOffset=zeros(NumQuest,1);
EditYOffset=zeros(NumQuest,1);
QuestYOffset(1)=FigHeight-DefOffset-QuestHeight(1);
EditYOffset(1)=QuestYOffset(1)-EditHeight(1);
for YOffLp=2:NumQuest,
QuestYOffset(YOffLp)=EditYOffset(YOffLp-1)-QuestHeight(YOffLp)-DefOffset;
EditYOffset(YOffLp)=QuestYOffset(YOffLp)-EditHeight(YOffLp);
end % for YOffLp
QuestHandle=[]; %#ok
EditHandle=[];
AxesHandle=axes('Parent',InputFig,'Position',[0 0 1 1],'Visible','off');
inputWidthSpecified = false;
lfont = cfg_get_defaults('cfg_ui.lfont');
fn = fieldnames(lfont);
fs = struct2cell(lfont);
lfont = [fn'; fs'];
for lp=1:NumQuest,
if ~ischar(DefAns{lp}),
delete(InputFig);
%cfg_message('Default Answer must be a cell array of strings.');
cfg_message('MATLAB:inputdlg:InvalidInput', 'Default Answer must be a cell array of strings.');
end
EditHandle(lp)=uicontrol(InputFig , ...
EdInfo , ...
'Max' ,NumLines(lp,1) , ...
'Position' ,[ TxtXOffset EditYOffset(lp) TxtWidth EditHeight(lp) ], ...
'String' ,DefAns{lp} , ...
'Tag' ,'Edit' , ...
lfont{:});
QuestHandle(lp)=text('Parent' ,AxesHandle, ...
TextInfo , ...
'Position' ,[ TxtXOffset QuestYOffset(lp)], ...
'String' ,WrapQuest{lp} , ...
'Interpreter',Interpreter , ...
'Tag' ,'Quest' ...
);
MinWidth = max(QuestWidth(:));
if (size(NumLines,2) == 2)
% input field width has been specified.
inputWidthSpecified = true;
EditWidth = setcolumnwidth(EditHandle(lp), NumLines(lp,1), NumLines(lp,2));
MinWidth = max(MinWidth, EditWidth);
end
FigWidth=max(FigWidth, MinWidth+2*DefOffset);
end % for lp
% fig width may have changed, update the edit fields if they dont have user specified widths.
if ~inputWidthSpecified
TxtWidth=FigWidth-2*DefOffset;
for lp=1:NumQuest
set(EditHandle(lp), 'Position', [TxtXOffset EditYOffset(lp) TxtWidth EditHeight(lp)]);
end
end
FigPos=get(InputFig,'Position');
FigWidth=max(FigWidth,2*(BtnWidth+DefOffset)+DefOffset);
FigPos(1)=0;
FigPos(2)=0;
FigPos(3)=FigWidth;
FigPos(4)=FigHeight;
set(InputFig,'Position',getnicedialoglocation(FigPos,get(InputFig,'Units')));
OKHandle=uicontrol(InputFig , ...
BtnInfo , ...
'Position' ,[ FigWidth-2*BtnWidth-2*DefOffset DefOffset BtnWidth BtnHeight ] , ...
'KeyPressFcn',@doControlKeyPress , ...
'String' ,'OK' , ...
'Callback' ,@doCallback , ...
'Tag' ,'OK' , ...
'UserData' ,'OK' ...
);
setdefaultbutton(InputFig, OKHandle);
CancelHandle=uicontrol(InputFig , ...
BtnInfo , ...
'Position' ,[ FigWidth-BtnWidth-DefOffset DefOffset BtnWidth BtnHeight ] , ...
'KeyPressFcn',@doControlKeyPress , ...
'String' ,'Cancel' , ...
'Callback' ,@doCallback , ...
'Tag' ,'Cancel' , ...
'UserData' ,'Cancel' ...
); %#ok
handles = guihandles(InputFig);
handles.MinFigWidth = FigWidth;
handles.FigHeight = FigHeight;
handles.TextMargin = 2*DefOffset;
guidata(InputFig,handles);
set(InputFig,'ResizeFcn', {@doResize, inputWidthSpecified});
% make sure we are on screen
movegui(InputFig)
% if there is a figure out there and it's modal, we need to be modal too
if ~isempty(gcbf) && strcmp(get(gcbf,'WindowStyle'),'modal')
set(InputFig,'WindowStyle','modal');
end
set(InputFig,'Visible','on');
drawnow;
if ~isempty(EditHandle)
uicontrol(EditHandle(1));
end
if ishandle(InputFig)
% Go into uiwait if the figure handle is still valid.
% This is mostly the case during regular use.
uiwait(InputFig);
end
% Check handle validity again since we may be out of uiwait because the
% figure was deleted.
if ishandle(InputFig)
Answer={};
if strcmp(get(InputFig,'UserData'),'OK'),
Answer=cell(NumQuest,1);
for lp=1:NumQuest,
Answer(lp)=get(EditHandle(lp),{'String'});
end
end
delete(InputFig);
else
Answer={};
end
function doFigureKeyPress(obj, evd) %#ok
switch(evd.Key)
case {'return','space'}
set(gcbf,'UserData','OK');
uiresume(gcbf);
case {'escape'}
delete(gcbf);
end
function doControlKeyPress(obj, evd) %#ok
switch(evd.Key)
case {'return'}
if ~strcmp(get(obj,'UserData'),'Cancel')
set(gcbf,'UserData','OK');
uiresume(gcbf);
else
delete(gcbf)
end
case 'escape'
delete(gcbf)
end
function doCallback(obj, evd) %#ok
if ~strcmp(get(obj,'UserData'),'Cancel')
set(gcbf,'UserData','OK');
uiresume(gcbf);
else
delete(gcbf)
end
function doResize(FigHandle, evd, multicolumn) %#ok
% TBD: Check difference in behavior w/ R13. May need to implement
% additional resize behavior/clean up.
Data=guidata(FigHandle);
resetPos = false;
FigPos = get(FigHandle,'Position');
FigWidth = FigPos(3);
FigHeight = FigPos(4);
if FigWidth < Data.MinFigWidth
FigWidth = Data.MinFigWidth;
FigPos(3) = Data.MinFigWidth;
resetPos = true;
end
% make sure edit fields use all available space if
% number of columns is not specified in dialog creation.
if ~multicolumn
for lp = 1:length(Data.Edit)
EditPos = get(Data.Edit(lp),'Position');
EditPos(3) = FigWidth - Data.TextMargin;
set(Data.Edit(lp),'Position',EditPos);
end
end
if FigHeight ~= Data.FigHeight
FigPos(4) = Data.FigHeight;
resetPos = true;
end
if resetPos
set(FigHandle,'Position',FigPos);
end
% set pixel width given the number of columns
function EditWidth = setcolumnwidth(object, rows, cols)
% Save current Units and String.
old_units = get(object, 'Units');
old_string = get(object, 'String');
old_position = get(object, 'Position');
set(object, 'Units', 'pixels')
set(object, 'String', char(ones(1,cols)*'x'));
new_extent = get(object,'Extent');
if (rows > 1)
% For multiple rows, allow space for the scrollbar
new_extent = new_extent + 19; % Width of the scrollbar
end
new_position = old_position;
new_position(3) = new_extent(3) + 1;
set(object, 'Position', new_position);
% reset string and units
set(object, 'String', old_string, 'Units', old_units);
EditWidth = new_extent(3);
|
github
|
philippboehmsturm/antx-master
|
cfg_justify.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/matlabbatch/private/cfg_justify.m
| 4,780 |
utf_8
|
e63deba1ef91c37883c9de58f6f99344
|
function out = cfg_justify(varargin)
% CFG_JUSTIFY Justifies a text string
% OUT = CFG_JUSTIFY(N,TXT) justifies text string TXT to
% the length specified by N.
%
% OUT = CFG_JUSTIFY(OBJ,TXT), where OBJ is a handle to a 'listbox' style
% uicontrol, justifies text string TXT to the width of the OBJ in
% characters - 1.
%
% If TXT is a cell array, then each element is treated
% as a paragraph and justified, otherwise the string is
% treated as a paragraph and is justified.
% Non a-z or A-Z characters at the start of a paragraph
% are used to define any indentation required (such as
% for enumeration, bullets etc. If less than one line
% of text is returned, then no formatting is done.
%
% Example:
% out = cfg_justify(40,{['Statistical Parametric ',...
% 'Mapping refers to the construction and ',...
% 'assessment of spatially extended ',...
% 'statistical process used to test hypotheses ',...
% 'about [neuro]imaging data from SPECT/PET & ',...
% 'fMRI. These ideas have been instantiated ',...
% 'in software that is called SPM']});
% strvcat(out{:})
%
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: cfg_justify.m 484 2010-06-23 08:51:04Z glauche $
out = {};
if nargin < 2
cfg_message('matlabbatch:usage','Incorrect usage of cfg_justify.')
end
n = varargin{1};
if ishandle(n)
% estimate extent of a space char and scrollbar width
TempObj=copyobj(n,get(n,'Parent'));
set(TempObj,'Visible','off','Max',100);
spext = cfg_maxextent(TempObj,{repmat(' ',1,100)})/100;
% try to work out slider size
pos = get(TempObj,'Position');
oldun = get(TempObj,'units');
set(TempObj,'units','points');
ppos = get(TempObj,'Position');
set(TempObj,'units',oldun);
sc = pos(3)/ppos(3);
% assume slider width of 15 points
swidth=15*sc;
else
% dummy constants
spext = 1;
swidth = 0;
TempObj = n;
end
for i=2:nargin,
if iscell(varargin{i}),
for j=1:numel(varargin{i}),
para = justify_paragraph(TempObj,spext,swidth,varargin{i}{j});
out = [out(:);para(:)]';
end
else
para = justify_paragraph(TempObj,spext,swidth,varargin{i});
out = [out(:);para(:)]';
end
end
if ishandle(TempObj)
delete(TempObj);
end
function out = justify_paragraph(n,spext,swidth,txt)
if numel(txt)>1 && txt(1)=='%',
txt = txt(2:end);
end;
%txt = regexprep(txt,'/\*([^(/\*)]*)\*/','');
st1 = strfind(txt,'/*');
en1 = strfind(txt,'*/');
st = [];
en = [];
for i=1:numel(st1),
en1 = en1(en1>st1(i));
if ~isempty(en1),
st = [st st1(i)];
en = [en en1(1)];
en1 = en1(2:end);
end;
end;
str = [];
pen = 1;
for i=1:numel(st),
str = [str txt(pen:st(i)-1)];
pen = en(i)+2;
end;
str = [str txt(pen:numel(txt))];
txt = str;
off = find((txt'>='a' & txt'<='z') | (txt'>='A' & txt'<='Z'));
if isempty(off),
out{1} = txt;
else
off = off(1);
para = justify_para(n,off,spext,swidth,txt(off:end));
out = cell(numel(para),1);
if numel(para)>1,
out{1} = [txt(1:(off-1)) para{1}];
for j=2:numel(para),
out{j} = [repmat(' ',1,off-1) para{j}];
end;
else
out{1} = txt;
end;
end;
return;
function out = justify_para(n,off,spext,swidth,varargin)
% Collect varargs into a single string
str = varargin{1};
for i=2:length(varargin),
str = [str ' ' varargin{i}];
end;
if isempty(str), out = {''}; return; end;
if ishandle(n)
% new size: at least 20 spaces wide, max widget width less offset
% space and scrollbar width
pos = get(n,'position');
opos = pos;
pos(3) = max(pos(3)-off*spext-swidth,20*spext);
set(n,'position',pos);
% wrap text
out = textwrap(n,{str});
cext = cfg_maxextent(n,out);
% fill with spaces to produce (roughly) block output
for k = 1:numel(out)-1
out{k} = justify_line(out{k}, pos(3), cext(k), spext);
end;
% reset position
set(n,'Position',opos);
else
cols = max(n-off,20);
out = textwrap({str},cols);
for k = 1:numel(out)-1
out{k} = justify_line(out{k}, cols, length(out{k}), 1);
end;
end;
function out = justify_line(str, width, cext, spext)
ind = strfind(str,' ');
if isempty(ind)
out = str;
else
% #spaces to insert
nsp = floor((width-cext)/spext);
% #spaces per existing space
ins(1:numel(ind)) = floor(nsp/numel(ind));
ins(1:mod(nsp,numel(ind))) = floor(nsp/numel(ind))+1;
% insert spaces beginning at the end of the string
for k = numel(ind):-1:1
str = [str(1:ind(k)) repmat(' ',1,ins(k)) str(ind(k)+1:end)];
end;
out = str;
end;
|
github
|
philippboehmsturm/antx-master
|
listdlg.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/matlabbatch/private/listdlg.m
| 8,510 |
utf_8
|
1f4fe8c262a7bb4801e0b8abe2014870
|
function [selection,value] = listdlg(varargin)
%LISTDLG List selection dialog box.
% [SELECTION,OK] = LISTDLG('ListString',S) creates a modal dialog box
% which allows you to select a string or multiple strings from a list.
% SELECTION is a vector of indices of the selected strings (length 1 in
% the single selection mode). This will be [] when OK is 0. OK is 1 if
% you push the OK button, or 0 if you push the Cancel button or close the
% figure.
%
% Double-clicking on an item or pressing <CR> when multiple items are
% selected has the same effect as clicking the OK button. Pressing <CR>
% is the same as clicking the OK button. Pressing <ESC> is the same as
% clicking the Cancel button.
%
% Inputs are in parameter,value pairs:
%
% Parameter Description
% 'ListString' cell array of strings for the list box.
% 'SelectionMode' string; can be 'single' or 'multiple'; defaults to
% 'multiple'.
% 'ListSize' minimum [width height] of listbox in pixels; defaults
% to [160 300]. The maximum [width height] is fixed to
% [800 600].
% 'InitialValue' vector of indices of which items of the list box
% are initially selected; defaults to the first item.
% 'Name' String for the figure's title; defaults to ''.
% 'PromptString' string matrix or cell array of strings which appears
% as text above the list box; defaults to {}.
% 'OKString' string for the OK button; defaults to 'OK'.
% 'CancelString' string for the Cancel button; defaults to 'Cancel'.
%
% A 'Select all' button is provided in the multiple selection case.
%
% Example:
% d = dir;
% str = {d.name};
% [s,v] = listdlg('PromptString','Select a file:',...
% 'SelectionMode','single',...
% 'ListString',str)
%
% See also DIALOG, ERRORDLG, HELPDLG, INPUTDLG,
% MSGBOX, QUESTDLG, WARNDLG.
% Copyright 1984-2005 The MathWorks, Inc.
% $Revision: 328 $ $Date: 2005/10/28 15:54:55 $
% 'uh' uicontrol button height, in pixels; default = 22.
% 'fus' frame/uicontrol spacing, in pixels; default = 8.
% 'ffs' frame/figure spacing, in pixels; default = 8.
% simple test:
%
% d = dir; [s,v] = listdlg('PromptString','Select a file:','ListString',{d.name});
%
cfg_message(nargchk(1,inf,nargin,'struct'))
figname = '';
smode = 2; % (multiple)
promptstring = {};
liststring = [];
listsize = [160 300];
initialvalue = [];
okstring = 'OK';
cancelstring = 'Cancel';
fus = 8;
ffs = 8;
uh = 22;
if mod(length(varargin),2) ~= 0
% input args have not com in pairs, woe is me
cfg_message('MATLAB:listdlg:InvalidArgument', 'Arguments to LISTDLG must come param/value in pairs.')
end
for i=1:2:length(varargin)
switch lower(varargin{i})
case 'name'
figname = varargin{i+1};
case 'promptstring'
promptstring = varargin{i+1};
case 'selectionmode'
switch lower(varargin{i+1})
case 'single'
smode = 1;
case 'multiple'
smode = 2;
end
case 'listsize'
listsize = varargin{i+1};
case 'liststring'
liststring = varargin{i+1};
case 'initialvalue'
initialvalue = varargin{i+1};
case 'uh'
uh = varargin{i+1};
case 'fus'
fus = varargin{i+1};
case 'ffs'
ffs = varargin{i+1};
case 'okstring'
okstring = varargin{i+1};
case 'cancelstring'
cancelstring = varargin{i+1};
otherwise
cfg_message('MATLAB:listdlg:UnknownParameter', ['Unknown parameter name passed to LISTDLG. Name was ' varargin{i}])
end
end
if ischar(promptstring)
promptstring = cellstr(promptstring);
end
if isempty(initialvalue)
initialvalue = 1;
end
if isempty(liststring)
cfg_message('MATLAB:listdlg:NeedParameter', 'ListString parameter is required.')
end
liststring=cellstr(liststring);
lfont = cfg_get_defaults('cfg_ui.lfont');
bfont = cfg_get_defaults('cfg_ui.bfont');
tmpObj = uicontrol('style','listbox',...
'max',100,...
'Visible','off',...
lfont);
lext = cfg_maxextent(tmpObj, liststring);
ex = get(tmpObj,'Extent');
ex = ex(4);
delete(tmpObj);
listsize = min([800 600],max(listsize, [max(lext)+16, ex*numel(liststring)]));
fp = get(0,'defaultfigureposition');
w = 2*(fus+ffs)+listsize(1);
h = 2*ffs+6*fus+ex*length(promptstring)+listsize(2)+uh+(smode==2)*(fus+uh);
fp = [fp(1) fp(2)+fp(4)-h w h]; % keep upper left corner fixed
fig_props = { ...
'name' figname ...
'color' get(0,'defaultUicontrolBackgroundColor') ...
'resize' 'off' ...
'numbertitle' 'off' ...
'menubar' 'none' ...
'windowstyle' 'modal' ...
'visible' 'off' ...
'createfcn' '' ...
'position' fp ...
'closerequestfcn' 'delete(gcbf)' ...
};
fig = figure(fig_props{:});
if ~isempty(promptstring)
prompt_text = uicontrol('style','text','string',promptstring,...
'horizontalalignment','left',...
'position',[ffs+fus fp(4)-(ffs+fus+ex*length(promptstring)) ...
listsize(1) ex*length(promptstring)]); %#ok
end
btn_wid = (fp(3)-2*(ffs+fus)-fus)/2;
listbox = uicontrol('style','listbox',...
'position',[ffs+fus ffs+uh+4*fus+(smode==2)*(fus+uh) listsize],...
'string',liststring,...
'backgroundcolor','w',...
'max',smode,...
'tag','listbox',...
'value',initialvalue, ...
'callback', {@doListboxClick}, ...
lfont);
ok_btn = uicontrol('style','pushbutton',...
'string',okstring,...
'position',[ffs+fus ffs+fus btn_wid uh],...
'callback',{@doOK,listbox},...
bfont);
cancel_btn = uicontrol('style','pushbutton',...
'string',cancelstring,...
'position',[ffs+2*fus+btn_wid ffs+fus btn_wid uh],...
'callback',{@doCancel,listbox},...
bfont);
if smode == 2
selectall_btn = uicontrol('style','pushbutton',...
'string','Select all',...
'position',[ffs+fus 4*fus+ffs+uh listsize(1) uh],...
'tag','selectall_btn',...
'callback',{@doSelectAll, listbox});
if length(initialvalue) == length(liststring)
set(selectall_btn,'enable','off')
end
set(listbox,'callback',{@doListboxClick, selectall_btn})
end
set([fig, ok_btn, cancel_btn, listbox], 'keypressfcn', {@doKeypress, listbox});
set(fig,'position',getnicedialoglocation(fp, get(fig,'Units')));
% Make ok_btn the default button.
setdefaultbutton(fig, ok_btn);
% make sure we are on screen
movegui(fig)
set(fig, 'visible','on'); drawnow;
try
% Give default focus to the listbox *after* the figure is made visible
uicontrol(listbox);
uiwait(fig);
catch
if ishandle(fig)
delete(fig)
end
end
if isappdata(0,'ListDialogAppData__')
ad = getappdata(0,'ListDialogAppData__');
selection = ad.selection;
value = ad.value;
rmappdata(0,'ListDialogAppData__')
else
% figure was deleted
selection = [];
value = 0;
end
%% figure, OK and Cancel KeyPressFcn
function doKeypress(src, evd, listbox) %#ok
switch evd.Key
case 'escape'
doCancel([],[],listbox);
end
%% OK callback
function doOK(ok_btn, evd, listbox) %#ok
if (~isappdata(0, 'ListDialogAppData__'))
ad.value = 1;
ad.selection = get(listbox,'value');
setappdata(0,'ListDialogAppData__',ad);
delete(gcbf);
end
%% Cancel callback
function doCancel(cancel_btn, evd, listbox) %#ok
ad.value = 0;
ad.selection = [];
setappdata(0,'ListDialogAppData__',ad)
delete(gcbf);
%% SelectAll callback
function doSelectAll(selectall_btn, evd, listbox) %#ok
set(selectall_btn,'enable','off')
set(listbox,'value',1:length(get(listbox,'string')));
%% Listbox callback
function doListboxClick(listbox, evd, selectall_btn) %#ok
% if this is a doubleclick, doOK
if strcmp(get(gcbf,'SelectionType'),'open')
doOK([],[],listbox);
elseif nargin == 3
if length(get(listbox,'string'))==length(get(listbox,'value'))
set(selectall_btn,'enable','off')
else
set(selectall_btn,'enable','on')
end
end
|
github
|
philippboehmsturm/antx-master
|
initialise.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/matlabbatch/@cfg_mchoice/initialise.m
| 3,150 |
utf_8
|
0f2df3f6db6f05985b97b4c89357cb92
|
function item = initialise(item, val, dflag)
% function item = initialise(item, val, dflag)
% Initialise a configuration tree with values. If val is a job
% struct/cell, only the parts of the configuration that are present in
% this job will be initialised. If dflag is true, then matching items
% from item.values will be initialised. If dflag is false, the matching
% item from item.values will be added to item.val and initialised after
% copying.
% If val has the special value '<DEFAULTS>', the entire configuration
% will be updated with values from .def fields. If a .def field is
% present in a cfg_leaf item, the current default value will be inserted,
% possibly replacing a previously entered (default) value. If dflag is
% true, defaults will only be set in item.values. If dflag is false,
% defaults will be set for both item.val and item.values.
%
% This code is part of a batch job configuration system for MATLAB. See
% help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging
% Volkmar Glauche
% $Id: initialise.m 574 2012-06-20 13:39:53Z glauche $
rev = '$Rev: 574 $'; %#ok
if strcmp(val,'<UNDEFINED>')
val = struct([]);
end
if strcmp(val,'<DEFAULTS>')
item = initialise_def(item, val, dflag);
elseif isstruct(val)
item = initialise_job(item, val, dflag);
elseif iscell(val) && numel(val) == 1 && isstruct(val{1})
item = initialise_job(item, val{1}, dflag);
else
cfg_message('matlabbatch:initialise', ...
'Can not initialise %s: job is not a struct.', ...
gettag(item));
end;
function item = initialise_def(item, val, dflag)
if ~dflag
% initialise defaults both in current job and in defaults
citem = subsref(item, substruct('.','val'));
for k = 1:numel(citem)
citem{k} = initialise(citem{k}, val, dflag);
end;
item = subsasgn(item, substruct('.','val'), citem);
end;
for k = 1:numel(item.values)
item.values{k} = initialise(item.values{k}, val, dflag);
end;
function item = initialise_job(item, val, dflag)
vtags = fieldnames(val);
if dflag % set defaults
for k = 1:numel(item.values)
% find field in values that corresponds to one of the branch vals
vi = strcmp(gettag(item.values{k}), vtags);
if any(vi) % field names are unique, so there will be at most one match
item.values{k} = initialise(item.values{k}, ...
val.(vtags{vi}), dflag);
end;
end;
else
% select matching values struct, initialise and assign it to val
% field
item.cfg_item.val = {};
if ~isempty(vtags)
for k = 1:numel(item.values)
% find fields in values that corresponds to one of the branch vals
vi = strcmp(gettag(item.values{k}), vtags);
if any(vi) % field names are unique, so there will be at most one match
item.cfg_item.val{end+1} = initialise(item.values{k}, ...
val.(vtags{vi}), dflag);
end;
end;
end;
end;
|
github
|
philippboehmsturm/antx-master
|
cfg_confgui.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/matlabbatch/cfg_confgui/cfg_confgui.m
| 31,063 |
utf_8
|
c3ac1e274d0982450821448a622318a6
|
function menu_cfg = cfg_confgui
% This function describes the user defined fields for each kind of
% cfg_item and their layout in terms of cfg_items. Thus, the
% configuration system can be used to generate code for new configuration
% files itself.
%
% This code is part of a batch job configuration system for MATLAB. See
% help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging
% Volkmar Glauche
% $Id: cfg_confgui.m 483 2010-06-17 13:20:16Z glauche $
rev = '$Rev: 483 $'; %#ok
%% Declaration of fields
% Name
%-----------------------------------------------------------------------
conf_name = cfg_entry;
conf_name.name = 'Name';
conf_name.tag = 'name';
conf_name.strtype = 's';
conf_name.num = [1 Inf];
conf_name.help = {'Display name of configuration item.'};
% Tag
%-----------------------------------------------------------------------
conf_tag = cfg_entry;
conf_tag.name = 'Tag';
conf_tag.tag = 'tag';
conf_tag.strtype = 's';
conf_tag.num = [1 Inf];
conf_tag.help = {['Tag of configuration item.', 'This will be used as tag' ...
' of the generated output and (depending on item class)' ...
' appear in the input structure to the computation' ...
' function.']};
% Val Item
%-----------------------------------------------------------------------
conf_val_item = cfg_entry;
conf_val_item.name = 'Val Item';
conf_val_item.tag = 'val';
conf_val_item.strtype = 'e';
conf_val_item.num = [1 1];
conf_val_item.help = {'Val of configuration item.', 'This should be a dependency to another cfg_item object.'};
% Val
%-----------------------------------------------------------------------
conf_val = cfg_repeat;
conf_val.name = 'Val';
conf_val.tag = 'val';
conf_val.values = {conf_val_item};
conf_val.num = [1 Inf];
conf_val.help = {'Val of configuration item.', 'A collection of cfg_item objects to be assembled in a cfg_(ex)branch. Each item in this list needs to have a unique tag.'};
% Val with exactly one element
%-----------------------------------------------------------------------
conf_val_single = conf_val;
conf_val_single.val = {conf_val_item};
conf_val_single.num = [1 1];
% Check
%-----------------------------------------------------------------------
conf_check = cfg_entry;
conf_check.name = 'Check';
conf_check.tag = 'check';
conf_check.strtype = 'f';
conf_check.num = [0 Inf];
conf_check.help = {'Check function (handle).', ...
['This function will be called during all_set, before a job can be run. ', ...
'It receives the harvested configuration tree rooted at the current item as input. ', ...
'If the input is ok, it should return an empty string. Otherwise, ', ...
'its output should be a string that describes why input is not correct or consistent.'], ...
['Note that the check function will be called only if all dependencies are resolved. ', ...
'This will usually be at the time just before the job is actually run.']};
% Help paragraph
%-----------------------------------------------------------------------
conf_help_par = cfg_entry;
conf_help_par.name = 'Paragraph';
conf_help_par.val = {''};
conf_help_par.tag = 'help';
conf_help_par.strtype = 's';
conf_help_par.num = [0 Inf];
conf_help_par.help = {'Help paragraph.', 'Enter a string which will be formatted as a separate paragraph.'};
% Help
%-----------------------------------------------------------------------
conf_help = cfg_repeat;
conf_help.name = 'Help';
conf_help.tag = 'help';
conf_help.values = {conf_help_par};
conf_help.num = [0 Inf];
conf_help.help = {'Help text.', 'Each help text consists of a number of paragraphs.'};
% Def
%-----------------------------------------------------------------------
conf_def = cfg_entry;
conf_def.name = 'Def';
conf_def.tag = 'def';
conf_def.strtype = 'f';
conf_def.num = [0 1];
conf_def.help = {'Default settings for configuration item.', ...
['This should be a function handle to a function accepting '...
'both zero and one free argument. It will be called by setval ' ...
'with zero free arguments to retrieve a default value and with ' ...
'one argument to set a default.'], ...
['If the default function has a registry like call ' ...
'syntax '], ...
'defval = get_defaults(''some.key'')', ...
'get_defaults(''some.key'', defval)', ...
'then the function handle should look like this', ...
'@(defval)get_defaults(''some.key'', defval{:})', ...
['Matlabbatch will wrap the second argument in a cell ' ...
'when calling this handle, thereby effectively passing ' ...
'no second argument to retrieve a value and passing ' ...
'the default value when setting it.']};
% Hidden
%-----------------------------------------------------------------------
conf_hidden = cfg_menu;
conf_hidden.name = 'Hidden';
conf_hidden.tag = 'hidden';
conf_hidden.labels = {'False', 'True'};
conf_hidden.values = {false, true};
conf_hidden.help = {'''Hidden'' status of configuration item.', 'If you want to hide an item to the user, set this to true. However, the item will be harvested, and a job can only run if this item is all_set. To hide an item is mostly useful for constants, that do not need to be changed by the user.'};
% Forcestruct
%-----------------------------------------------------------------------
conf_forcestruct = cfg_menu;
conf_forcestruct.name = 'Forcestruct';
conf_forcestruct.tag = 'forcestruct';
conf_forcestruct.labels = {'False', 'True'};
conf_forcestruct.values = {false, true};
conf_forcestruct.help = {'Forcestruct flag.', 'Sometimes the default harvest behaviour of a cfg_repeat object is not what one wants to have: if there is only one repeatable item, it returns a cell and discards its own tag. If one adds a new configuration to this repeat, then suddenly the harvested cfg_repeat has the tag of the repeat item and a cell with struct arrays as members. If you want to force this latter behaviour also if there is only one item in the ''values'' field, then set this flag to ''true''.'};
% Values Item
%-----------------------------------------------------------------------
conf_values_item = cfg_entry;
conf_values_item.name = 'Values Item';
conf_values_item.tag = 'values';
conf_values_item.strtype = 'e';
conf_values_item.num = [1 Inf];
conf_values_item.help = {'Value of configuration item.', 'For cfg_menus, this is an arbitrary value, for cfg_repeat/cfg_choice items, this should be a dependency to another cfg_item object.'};
% Values
%-----------------------------------------------------------------------
conf_values = cfg_repeat;
conf_values.name = 'Values';
conf_values.tag = 'values';
conf_values.values = {conf_values_item};
conf_values.num = [1 Inf];
conf_values.help = {'Values of configuration item. If this is a cfg_repeat/cfg_choice and there is more than one item in this list, each item needs to have a unique tag.'};
% Label Item
%-----------------------------------------------------------------------
conf_labels_item = cfg_entry;
conf_labels_item.name = 'Label';
conf_labels_item.tag = 'labels';
conf_labels_item.strtype = 's';
conf_labels_item.num = [1 Inf];
conf_labels_item.help = {'Label of menu item.', 'This is a string which will become a label entry.'};
% Labels
%-----------------------------------------------------------------------
conf_labels = cfg_repeat;
conf_labels.name = 'Labels';
conf_labels.tag = 'labels';
conf_labels.values = {conf_labels_item};
conf_labels.num = [1 Inf];
conf_labels.help = {'Labels of configuration item.', 'This is a collection of strings - each string will become a label entry.'};
% Filter
%-----------------------------------------------------------------------
conf_filter = cfg_entry;
conf_filter.name = 'Filter';
conf_filter.tag = 'filter';
conf_filter.strtype = 's';
conf_filter.num = [0 Inf];
conf_filter.help = {'Filter for files.', ...
['This filter will not display in the file selector filter field, '...
'it will be used prior to displaying files. The following special '...
'types are supported:'], ...
'* ''any''', ...
'* ''batch''', ...
'* ''dir''', ...
'* ''image''', ...
'* ''mat''', ...
'* ''mesh''', ...
'* ''nifti''', ...
'* ''xml''', ...
'* any regular expression filter.'};
% Ufilter
%-----------------------------------------------------------------------
conf_ufilter = cfg_entry;
conf_ufilter.name = 'Ufilter';
conf_ufilter.tag = 'ufilter';
conf_ufilter.strtype = 's';
conf_ufilter.num = [0 Inf];
conf_ufilter.help = {'Filter for files.', 'This filter is a regexp to filter filenames that survive .filter field.'};
% Dir
%-----------------------------------------------------------------------
conf_dir = cfg_entry;
conf_dir.name = 'Dir';
conf_dir.tag = 'dir';
conf_dir.strtype = 'e'; % TODO: This should really be a cell string type
conf_dir.num = [0 Inf];
conf_dir.help = {'Dir field.', 'Initial directory for file selector.'};
% Num
%-----------------------------------------------------------------------
conf_num_any = cfg_entry;
conf_num_any.name = 'Num';
conf_num_any.tag = 'num';
conf_num_any.strtype = 'w';
conf_num_any.num = [0 Inf];
conf_num_any.help = {'Num field.', ...
['Specify how many dimensions this ' ...
'item must have and the size of each dimension. An ' ...
'empty num field means no restriction on number of ' ...
'dimensions. Inf in any dimension means no upper limit ' ...
'on size of this dimension.'], ...
['Note that for strtype ''s'' inputs, num is interpreted ' ...
'as a 2-vector [min max], allowing for a 1-by-min...max ' ...
'string to be entered.']};
% Num
%-----------------------------------------------------------------------
conf_num = cfg_entry;
conf_num.name = 'Num';
conf_num.tag = 'num';
conf_num.strtype = 'w';
conf_num.num = [1 2];
conf_num.help = {'Num field.', 'Specify how many items (min and max) must be entered to yield a valid input. min = 0 means zero or more, max = Inf means no upper limit on number.'};
% Strtype
%-----------------------------------------------------------------------
conf_strtype = cfg_menu;
conf_strtype.name = 'Strtype';
conf_strtype.tag = 'strtype';
conf_strtype.labels = {'String (s)', ...
'Evaluated (e)', ...
'Natural number (1..n) (n)', ...
'Whole number (0..n) (w)', ...
'Integer (i)', ...
'Real number (r)', ...
'Function handle (f)', ...
'Condition vector (c)', ...
'Contrast matrix (x)', ...
'Permutation (p)'};
conf_strtype.values = {'s','e','n','w','i','r','f','c','x','p'};
conf_strtype.help = {'Strtype field.', 'This type describes how an evaluated input should be treated. Type checking against this type will be performed during subscript assignment.'};
% Extras
%-----------------------------------------------------------------------
conf_extras = cfg_entry;
conf_extras.name = 'Extras';
conf_extras.tag = 'extras';
conf_extras.strtype = 'e';
conf_extras.num = [0 Inf];
conf_extras.help = {'Extras field.', 'Extra information that may be used to evaluate ''strtype''.'};
% Prog
%-----------------------------------------------------------------------
conf_prog = cfg_entry;
conf_prog.name = 'Prog';
conf_prog.tag = 'prog';
conf_prog.strtype = 'f';
conf_prog.num = [1 Inf];
conf_prog.help = {'Prog function (handle).', 'This function will be called to run a job. It receives the harvested configuration tree rooted at the current item as input. If it produces output, this should be a single variable. This variable can be a struct, cell or whatever is appropriate. To pass references to it a ''vout'' function has to be implemented that describes the virtual outputs.'};
% Vout
%-----------------------------------------------------------------------
conf_vout = cfg_entry;
conf_vout.name = 'Vout';
conf_vout.tag = 'vout';
conf_vout.strtype = 'f';
conf_vout.num = [0 Inf];
conf_vout.help = {'Vout function (handle).', 'This function will be called during harvest, if all inputs to a job are set. It receives the harvested configuration tree rooted at the current item as input. Its output should be an array of cfg_dep objects, containing subscript indices into the output variable that would result when running this job. Note that no dependencies are resolved here.'};
%% Declaration of item classes
% Branch
%-----------------------------------------------------------------------
conf_class_branch = cfg_const;
conf_class_branch.name = 'Branch';
conf_class_branch.tag = 'type';
conf_class_branch.val = {'cfg_branch'};
conf_class_branch.hidden = true;
conf_class_branch.help = {'Hidden field that gives the hint to cfg_struct2cfg which class to create.'};
% Choice
%-----------------------------------------------------------------------
conf_class_choice = cfg_const;
conf_class_choice.name = 'Choice';
conf_class_choice.tag = 'type';
conf_class_choice.val = {'cfg_choice'};
conf_class_choice.hidden = true;
conf_class_choice.help = {'Hidden field that gives the hint to cfg_struct2cfg which class to create.'};
% Const
%-----------------------------------------------------------------------
conf_class_const = cfg_const;
conf_class_const.name = 'Const';
conf_class_const.tag = 'type';
conf_class_const.val = {'cfg_const'};
conf_class_const.hidden = true;
conf_class_const.help = {'Hidden field that gives the hint to cfg_struct2cfg which class to create.'};
% Entry
%-----------------------------------------------------------------------
conf_class_entry = cfg_const;
conf_class_entry.name = 'Entry';
conf_class_entry.tag = 'type';
conf_class_entry.val = {'cfg_entry'};
conf_class_entry.hidden = true;
conf_class_entry.help = {'Hidden field that gives the hint to cfg_struct2cfg which class to create.'};
% Exbranch
%-----------------------------------------------------------------------
conf_class_exbranch = cfg_const;
conf_class_exbranch.name = 'Exbranch';
conf_class_exbranch.tag = 'type';
conf_class_exbranch.val = {'cfg_exbranch'};
conf_class_exbranch.hidden = true;
conf_class_exbranch.help = {'Hidden field that gives the hint to cfg_struct2cfg which class to create.'};
% Files
%-----------------------------------------------------------------------
conf_class_files = cfg_const;
conf_class_files.name = 'Files';
conf_class_files.tag = 'type';
conf_class_files.val = {'cfg_files'};
conf_class_files.hidden = true;
conf_class_files.help = {'Hidden field that gives the hint to cfg_struct2cfg which class to create.'};
% Menu
%-----------------------------------------------------------------------
conf_class_menu = cfg_const;
conf_class_menu.name = 'Menu';
conf_class_menu.tag = 'type';
conf_class_menu.val = {'cfg_menu'};
conf_class_menu.hidden = true;
conf_class_menu.help = {'Hidden field that gives the hint to cfg_struct2cfg which class to create.'};
% Repeat
%-----------------------------------------------------------------------
conf_class_repeat = cfg_const;
conf_class_repeat.name = 'Repeat';
conf_class_repeat.tag = 'type';
conf_class_repeat.val = {'cfg_repeat'};
conf_class_repeat.hidden = true;
conf_class_repeat.help = {'Hidden field that gives the hint to cfg_struct2cfg which class to create.'};
%% Item generators
% Branch
%-----------------------------------------------------------------------
conf_branch = cfg_exbranch;
conf_branch.name = 'Branch';
conf_branch.tag = 'conf_branch';
conf_branch.val = {conf_class_branch, conf_name, conf_tag, conf_val, conf_check, conf_help};
conf_branch.help = help2cell('cfg_branch');
conf_branch.prog = @cfg_cfg_pass;
conf_branch.vout = @cfg_cfg_vout;
% Choice
%-----------------------------------------------------------------------
conf_choice = cfg_exbranch;
conf_choice.name = 'Choice';
conf_choice.tag = 'conf_choice';
conf_choice.val = {conf_class_choice, conf_name, conf_tag, conf_values, conf_check, conf_help};
conf_choice.help = help2cell('cfg_choice');
conf_choice.prog = @cfg_cfg_pass;
conf_choice.vout = @cfg_cfg_vout;
% Const
%-----------------------------------------------------------------------
conf_const = cfg_exbranch;
conf_const.name = 'Const';
conf_const.tag = 'conf_const';
conf_const.val = {conf_class_const, conf_name, conf_tag, conf_val_single, ...
conf_check, conf_help, conf_def};
conf_const.help = help2cell('cfg_const');
conf_const.prog = @cfg_cfg_pass;
conf_const.vout = @cfg_cfg_vout;
% Entry
%-----------------------------------------------------------------------
conf_entry = cfg_exbranch;
conf_entry.name = 'Entry';
conf_entry.tag = 'conf_entry';
conf_entry.val = {conf_class_entry, conf_name, conf_tag, conf_strtype, ...
conf_extras, conf_num_any, conf_check, conf_help, conf_def};
conf_entry.help = help2cell('cfg_entry');
conf_entry.prog = @cfg_cfg_pass;
conf_entry.vout = @cfg_cfg_vout;
% Exbranch
%-----------------------------------------------------------------------
conf_exbranch = cfg_exbranch;
conf_exbranch.name = 'Exbranch';
conf_exbranch.tag = 'conf_exbranch';
conf_exbranch.val = {conf_class_exbranch, conf_name, conf_tag, conf_val, ...
conf_prog, conf_vout, conf_check, conf_help};
conf_exbranch.help = help2cell('cfg_exbranch');
conf_exbranch.prog = @cfg_cfg_pass;
conf_exbranch.vout = @cfg_cfg_vout;
% Files
%-----------------------------------------------------------------------
conf_files = cfg_exbranch;
conf_files.name = 'Files';
conf_files.tag = 'conf_files';
conf_files.val = {conf_class_files, conf_name, conf_tag, conf_filter, ...
conf_ufilter, conf_dir, conf_num, conf_check, conf_help, conf_def};
conf_files.help = help2cell('cfg_files');
conf_files.prog = @cfg_cfg_pass;
conf_files.vout = @cfg_cfg_vout;
% Menu
%-----------------------------------------------------------------------
conf_menu = cfg_exbranch;
conf_menu.name = 'Menu';
conf_menu.tag = 'conf_menu';
conf_menu.val = {conf_class_menu, conf_name, conf_tag, conf_labels, ...
conf_values, conf_check, conf_help, conf_def};
conf_menu.help = help2cell('cfg_menu');
conf_menu.prog = @cfg_cfg_pass;
conf_menu.vout = @cfg_cfg_vout;
conf_menu.check = @cfg_cfg_labels_values;
% repeat
%-----------------------------------------------------------------------
conf_repeat = cfg_exbranch;
conf_repeat.name = 'Repeat';
conf_repeat.tag = 'conf_repeat';
conf_repeat.val = {conf_class_repeat, conf_name, conf_tag, conf_values, ...
conf_num, conf_forcestruct, conf_check, conf_help};
conf_repeat.help = help2cell('cfg_repeat');
conf_repeat.prog = @cfg_cfg_pass;
conf_repeat.vout = @cfg_cfg_vout;
%% Output nodes
% Generate code
%-----------------------------------------------------------------------
gencode_fname = cfg_entry;
gencode_fname.name = 'Output filename';
gencode_fname.tag = 'gencode_fname';
gencode_fname.strtype = 's';
gencode_fname.num = [1 Inf];
gencode_fname.help = {'Filename for generated .m File.'};
gencode_dir = cfg_files;
gencode_dir.name = 'Output directory';
gencode_dir.tag = 'gencode_dir';
gencode_dir.filter = 'dir';
gencode_dir.num = [1 1];
gencode_dir.help = {'Output directory for generated .m File.'};
gencode_var = cfg_entry;
gencode_var.name = 'Root node of config';
gencode_var.tag = 'gencode_var';
gencode_var.strtype = 'e';
gencode_var.num = [1 1];
gencode_var.help = {['This should be a dependency input from the root ' ...
'node of the application''s configuration tree. Use ' ...
'the output of the root configuration item directly, ' ...
'it is not necessary to run "Generate object tree" first.']};
gencode_o_def = cfg_menu;
gencode_o_def.name = 'Create Defaults File';
gencode_o_def.tag = 'gencode_o_def';
gencode_o_def.labels= {'No', 'Yes'};
gencode_o_def.values= {false, true};
gencode_o_def.help = {'The defaults file can be used to document all possible job structures. Its use to set all defaults is deprecated, .def function handles should be used instead.'};
gencode_o_mlb = cfg_menu;
gencode_o_mlb.name = 'Create mlbatch_appcfg File';
gencode_o_mlb.tag = 'gencode_o_mlb';
gencode_o_mlb.labels= {'No', 'Yes'};
gencode_o_mlb.values= {false, true};
gencode_o_mlb.help = {'The cfg_mlbatch_appcfg file can be used if the toolbox should be found by MATLABBATCH automatically.'};
gencode_o_path = cfg_menu;
gencode_o_path.name = 'Create Code for addpath()';
gencode_o_path.tag = 'gencode_o_path';
gencode_o_path.labels= {'No', 'Yes'};
gencode_o_path.values= {false, true};
gencode_o_path.help = {'If the toolbox resides in a non-MATLAB path, code can be generated to automatically add the configuration file to MATLAB path.'};
gencode_opts = cfg_branch;
gencode_opts.name = 'Options';
gencode_opts.tag = 'gencode_opts';
gencode_opts.val = {gencode_o_def gencode_o_mlb gencode_o_path};
gencode_opts.help = {'Code generation options.'};
gencode_gen = cfg_exbranch;
gencode_gen.name = 'Generate code';
gencode_gen.tag = 'gencode_gen';
gencode_gen.val = {gencode_fname, gencode_dir, gencode_var, gencode_opts};
gencode_gen.help = {['Generate code from a cfg_item tree. This tree can ' ...
'be either a struct (as returned from the ConfGUI ' ...
'modules) or a cfg_item object tree.']};
gencode_gen.prog = @cfg_cfg_gencode;
gencode_gen.vout = @vout_cfg_gencode;
% Generate object tree without code generation
%-----------------------------------------------------------------------
genobj_var = cfg_entry;
genobj_var.name = 'Root node of config';
genobj_var.tag = 'genobj_var';
genobj_var.strtype = 'e';
genobj_var.num = [1 1];
genobj_var.help = {'This should be a dependency input from the root node of the application''s configuration tree.'};
genobj_gen = cfg_exbranch;
genobj_gen.name = 'Generate object tree';
genobj_gen.tag = 'genobj_gen';
genobj_gen.val = {genobj_var};
genobj_gen.help = {['Generate a cfg_item tree as a variable. This can ' ...
'be useful to test a configuration before it is saved ' ...
'into files.']};
genobj_gen.prog = @cfg_cfg_genobj;
genobj_gen.vout = @vout_cfg_genobj;
%% Assemble Menu
% Data entry nodes
%-----------------------------------------------------------------------
menu_entry = cfg_choice;
menu_entry.name = 'Data entry items';
menu_entry.tag = 'menu_entry';
menu_entry.values = {conf_entry, conf_files, conf_menu, conf_const};
menu_entry.help = {'These items are used to enter data that will be passed to the computation code.'};
% Tree structuring nodes
%-----------------------------------------------------------------------
menu_struct = cfg_choice;
menu_struct.name = 'Tree structuring items';
menu_struct.tag = 'menu_struct';
menu_struct.values = {conf_branch, conf_exbranch, conf_choice, conf_repeat};
menu_struct.help = {'These items collect data entry items and build a menu structure.'};
% Root node
%-----------------------------------------------------------------------
menu_cfg = cfg_choice;
menu_cfg.name = 'ConfGUI';
menu_cfg.tag = 'menu_cfg';
menu_cfg.values = {menu_entry, menu_struct, gencode_gen, genobj_gen};
menu_cfg.help = help2cell(mfilename);
%% Helper functions
function out = cfg_cfg_genobj(varargin)
if isa(varargin{1}.genobj_var, 'cfg_item')
% use object tree "as is"
out.c0 = varargin{1}.gencode_var;
else
% Transform struct into class based tree
out.c0 = cfg_struct2cfg(varargin{1}.genobj_var);
end
[u1 out.djob] = harvest(out.c0, out.c0, true, true);
function out = cfg_cfg_gencode(varargin)
if isa(varargin{1}.gencode_var, 'cfg_item')
% use object tree "as is"
out.c0 = varargin{1}.gencode_var;
else
% Transform struct into class based tree
out.c0 = cfg_struct2cfg(varargin{1}.gencode_var);
end
% Generate code
[str tag] = gencode(out.c0,'',{});
[p n e] = fileparts(varargin{1}.gencode_fname);
out.cfg_file{1} = fullfile(varargin{1}.gencode_dir{1}, [n '.m']);
fid = fopen(out.cfg_file{1}, 'wt');
fprintf(fid, 'function %s = %s\n', tag, n);
fprintf(fid, ...
['%% ''%s'' - MATLABBATCH configuration\n' ...
'%% This MATLABBATCH configuration file has been generated automatically\n' ...
'%% by MATLABBATCH using ConfGUI. It describes menu structure, validity\n' ...
'%% constraints and links to run time code.\n' ...
'%% Changes to this file will be overwritten if the ConfGUI batch is executed again.\n' ...
'%% Created at %s.\n'], out.c0.name, datestr(now, 31));
fprintf(fid, '%s\n', str{:});
if varargin{1}.gencode_opts.gencode_o_path
fprintf(fid, '%% ---------------------------------------------------------------------\n');
fprintf(fid, '%% add path to this mfile\n');
fprintf(fid, '%% ---------------------------------------------------------------------\n');
fprintf(fid, 'addpath(fileparts(mfilename(''fullpath'')));\n');
end
fclose(fid);
if varargin{1}.gencode_opts.gencode_o_def
% Generate defaults file
[u1 out.djob] = harvest(out.c0, out.c0, true, true);
[str dtag] = gencode(out.djob, sprintf('%s_def', tag));
dn = sprintf('%s_def', n);
out.def_file{1} = fullfile(varargin{1}.gencode_dir{1}, sprintf('%s.m', dn));
fid = fopen(out.def_file{1}, 'wt');
fprintf(fid, 'function %s = %s\n', dtag, dn);
fprintf(fid, ...
['%% ''%s'' - MATLABBATCH defaults\n' ...
'%% This MATLABBATCH defaults file has been generated automatically\n' ...
'%% by MATLABBATCH using ConfGUI. It contains all pre-defined values for\n' ...
'%% menu items and provides a full documentation of all fields that may\n' ...
'%% be present in a job variable for this application.\n' ...
'%% Changes to this file will be overwritten if the ConfGUI batch is executed again.\n' ...
'%% Created at %s.\n'], out.c0.name, datestr(now, 31));
fprintf(fid, '%s\n', str{:});
fclose(fid);
end
if varargin{1}.gencode_opts.gencode_o_mlb
% Generate cfg_util initialisation file
out.mlb_file{1} = fullfile(varargin{1}.gencode_dir{1}, 'cfg_mlbatch_appcfg.m');
fid = fopen(out.mlb_file{1}, 'wt');
fprintf(fid, 'function [cfg, def] = cfg_mlbatch_appcfg(varargin)\n');
fprintf(fid, ...
['%% ''%s'' - MATLABBATCH cfg_util initialisation\n' ...
'%% This MATLABBATCH initialisation file can be used to load application\n' ...
'%% ''%s''\n' ...
'%% into cfg_util. This can be done manually by running this file from\n' ...
'%% MATLAB command line or automatically when cfg_util is initialised.\n' ...
'%% The directory containing this file and the configuration file\n' ...
'%% ''%s''\n' ...
'%% must be in MATLAB''s path variable.\n' ...
'%% Created at %s.\n\n'], ...
out.c0.name, out.c0.name, n, datestr(now, 31));
fprintf(fid, 'if ~isdeployed\n');
fprintf(fid, ' %% Get path to this file and add it to MATLAB path.\n');
fprintf(fid, [' %% If the configuration file is stored in another place, the ' ...
'path must be adjusted here.\n']);
fprintf(fid, ' p = fileparts(mfilename(''fullpath''));\n');
fprintf(fid, ' addpath(p);\n');
fprintf(fid, 'end\n');
fprintf(fid, '%% run configuration main & def function, return output\n');
fprintf(fid, 'cfg = %s;\n', n);
if varargin{1}.gencode_opts.gencode_o_def
fprintf(fid, 'def = %s;\n', dn);
else
fprintf(fid, 'def = [];\n');
end
fclose(fid);
end
function out = cfg_cfg_pass(varargin)
% just pass input to output
out = varargin{1};
function str = cfg_cfg_labels_values(varargin)
% Check whether a menu has the same number of labels and values items
if numel(varargin{1}.labels) == numel(varargin{1}.values)
str = '';
else
str = 'Number of labels must match number of values.';
end
function vout = cfg_cfg_vout(varargin)
% cfg_struct2cfg returns its output immediately, so a subscript '(1)' is
% appropriate.
vout = cfg_dep;
vout.sname = sprintf('%s (%s)', varargin{1}.name, varargin{1}.type);
vout.src_output = substruct('()', {1});
function vout = vout_cfg_genobj(varargin)
vout(1) = cfg_dep;
vout(1).sname = 'Configuration Object Tree';
vout(1).src_output = substruct('.','c0');
vout(1).tgt_spec = cfg_findspec({{'strtype','e'}});
vout(2) = cfg_dep;
vout(2).sname = 'Configuration Defaults Variable';
vout(2).src_output = substruct('.','djob');
vout(2).tgt_spec = cfg_findspec({{'strtype','e'}});
function vout = vout_cfg_gencode(varargin)
vout(1) = cfg_dep;
vout(1).sname = 'Generated Configuration File';
vout(1).src_output = substruct('.', 'cfg_file');
vout(1).tgt_spec = cfg_findspec({{'class','cfg_files','strtype','e'}});
vout(2) = cfg_dep;
vout(2).sname = 'Configuration Object Tree';
vout(2).src_output = substruct('.','c0');
vout(2).tgt_spec = cfg_findspec({{'strtype','e'}});
if islogical(varargin{1}.gencode_opts.gencode_o_def) && varargin{1}.gencode_opts.gencode_o_def
vout(3) = cfg_dep;
vout(3).sname = 'Generated Defaults File';
vout(3).src_output = substruct('.', 'def_file');
vout(3).tgt_spec = cfg_findspec({{'class','cfg_files','strtype','e'}});
vout(4) = cfg_dep;
vout(4).sname = 'Configuration Defaults Variable';
vout(4).src_output = substruct('.','djob');
vout(4).tgt_spec = cfg_findspec({{'strtype','e'}});
end
if islogical(varargin{1}.gencode_opts.gencode_o_mlb) && varargin{1}.gencode_opts.gencode_o_mlb
vout(end+1) = cfg_dep;
vout(end).sname = 'Generated Initialisation File';
vout(end).src_output = substruct('.', 'mlb_file');
vout(end).tgt_spec = cfg_findspec({{'class','cfg_files','strtype','e'}});
end
|
github
|
philippboehmsturm/antx-master
|
cfg_run_template.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/matlabbatch/cfg_confgui/cfg_run_template.m
| 4,820 |
utf_8
|
6b3abdb5d1a9cfd4401faaf597385d30
|
function varargout = cfg_run_template(cmd, varargin)
% Template function to implement callbacks for an cfg_exbranch. The calling
% syntax is
% varargout = cfg_run_template(cmd, varargin)
% where cmd is one of
% 'run' - out = cfg_run_template('run', job)
% Run a job, and return its output argument
% 'vout' - dep = cfg_run_template('vout', job)
% Examine a job structure with all leafs present and return an
% array of cfg_dep objects.
% 'check' - str = cfg_run_template('check', subcmd, subjob)
% Examine a part of a fully filled job structure. Return an empty
% string if everything is ok, or a string describing the check
% error. subcmd should be a string that identifies the part of
% the configuration to be checked.
% 'defaults' - defval = cfg_run_template('defaults', key)
% Retrieve defaults value. key must be a sequence of dot
% delimited field names into the internal def struct which is
% kept in function local_def. An error is returned if no
% matching field is found.
% cfg_run_template('defaults', key, newval)
% Set the specified field in the internal def struct to a new
% value.
% Application specific code needs to be inserted at the following places:
% 'run' - main switch statement: code to compute the results, based on
% a filled job
% 'vout' - main switch statement: code to compute cfg_dep array, based
% on a job structure that has all leafs, but not necessarily
% any values filled in
% 'check' - create and populate switch subcmd switchyard
% 'defaults' - modify initialisation of defaults in subfunction local_defs
% Callbacks can be constructed using anonymous function handles like this:
% 'run' - @(job)cfg_run_template('run', job)
% 'vout' - @(job)cfg_run_template('vout', job)
% 'check' - @(job)cfg_run_template('check', 'subcmd', job)
% 'defaults' - @(val)cfg_run_template('defaults', 'defstr', val{:})
% Note the list expansion val{:} - this is used to emulate a
% varargin call in this function handle.
%
% This code is part of a batch job configuration system for MATLAB. See
% help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging
% Volkmar Glauche
% $Id: cfg_run_template.m 466 2010-01-28 11:26:47Z glauche $
rev = '$Rev: 466 $'; %#ok
if ischar(cmd)
switch lower(cmd)
case 'run'
job = local_getjob(varargin{1});
% do computation, return results in variable out
if nargout > 0
varargout{1} = out;
end
case 'vout'
job = local_getjob(varargin{1});
% initialise empty cfg_dep array
dep = cfg_dep;
dep = dep(false);
% determine outputs, return cfg_dep array in variable dep
varargout{1} = dep;
case 'check'
if ischar(varargin{1})
subcmd = lower(varargin{1});
subjob = varargin{2};
str = '';
switch subcmd
% implement checks, return status string in variable str
otherwise
cfg_message('unknown:check', ...
'Unknown check subcmd ''%s''.', subcmd);
end
varargout{1} = str;
else
cfg_message('ischar:check', 'Subcmd must be a string.');
end
case 'defaults'
if nargin == 2
varargout{1} = local_defs(varargin{1});
else
local_defs(varargin{1:2});
end
otherwise
cfg_message('unknown:cmd', 'Unknown command ''%s''.', cmd);
end
else
cfg_message('ischar:cmd', 'Cmd must be a string.');
end
function varargout = local_defs(defstr, defval)
persistent defs;
if isempty(defs)
% initialise defaults
end
if ischar(defstr)
% construct subscript reference struct from dot delimited tag string
tags = textscan(defstr,'%s', 'delimiter','.');
subs = struct('type','.','subs',tags{1}');
try
cdefval = subsref(defs, subs);
catch
cdefval = [];
cfg_message('defaults:noval', ...
'No matching defaults value ''%s'' found.', defstr);
end
if nargin == 1
varargout{1} = cdefval;
else
defs = subsasgn(defs, subs, defval);
end
else
cfg_message('ischar:defstr', 'Defaults key must be a string.');
end
function job = local_getjob(job)
if ~isstruct(job)
cfg_message('isstruct:job', 'Job must be a struct.');
end
|
github
|
philippboehmsturm/antx-master
|
subsasgn_check.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/matlabbatch/@cfg_entry/subsasgn_check.m
| 8,352 |
utf_8
|
c0c07054289df61d4ca469b59de16097
|
function [sts, val] = subsasgn_check(item,subs,val)
% function [sts, val] = subsasgn_check(item,subs,val)
% Perform validity checks for cfg_entry inputs. Does not yet support
% evaluation of inputs.
%
% This code is part of a batch job configuration system for MATLAB. See
% help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging
% Volkmar Glauche
% $Id: subsasgn_check.m 560 2012-06-20 11:49:38Z glauche $
rev = '$Rev: 560 $'; %#ok
sts = true;
switch subs(1).subs
case {'num'}
% special num treatment - num does describe the dimensions of
% input in cfg_entry items, not a min/max number
sts = isnumeric(val) && (isempty(val) || numel(val)>=2 && all(val(:) >= 0));
if ~sts
cfg_message('matlabbatch:check:num', ...
'%s: Value must be empty or a vector of non-negative numbers with at least 2 elements', ...
subsasgn_checkstr(item,subs));
end
case {'val'}
% perform validity checks - subsasgn_check should be called with
% a cell containing one item
if ~iscell(val)
cfg_message('matlabbatch:checkval', ...
'%s: Value must be a cell.', subsasgn_checkstr(item,subs));
sts = false;
return;
end
if isempty(val)
val = {};
else
% check whether val{1} is a valid element
[sts vtmp] = valcheck(item,val{1});
val = {vtmp};
end
case {'strtype'}
strtypes = {'s','e','f','n','w','i','r','c','x','p'};
sts = isempty(val) || (ischar(val) && ...
any(strcmp(val, strtypes)));
if ~sts
cfg_message('matlabbatch:check:strtype', ...
'%s: Value must be a valid strtype.', subsasgn_checkstr(item,subs));
end
end
function [sts, val] = valcheck(item,val)
% taken from spm_jobman/stringval
% spm_eeval goes into GUI
sts = true;
% check for reserved words
if ischar(val) && any(strcmp(val, {'<UNDEFINED>','<DEFAULTS>'}))
cfg_message('matlabbatch:checkval', ...
['%s: Item must not be one of the reserved words ''<UNDEFINED>'' ' ...
'or ''<DEFAULTS>''.'], subsasgn_checkstr(item,substruct('.','val')));
sts = false;
return;
end
if isa(val,'cfg_dep')
% Check dependency match
sts2 = cellfun(@(cspec)match(item,cspec),{val.tgt_spec});
if ~all(sts2)
cfg_message('matlabbatch:checkval', ...
'%s: Dependency does not match.', subsasgn_checkstr(item,subs));
end
val = val(sts2);
sts = any(sts2);
else
switch item.strtype
case {'s'}
if ~ischar(val)
cfg_message('matlabbatch:checkval:strtype', ...
'%s: Item must be a string.', subsasgn_checkstr(item,substruct('.','val')));
sts = false;
else
[sts val] = numcheck(item,val);
if sts && ~isempty(item.extras) && (ischar(item.extras) || iscellstr(item.extras))
pats = cellstr(item.extras);
mch = regexp(val, pats);
sts = any(~cellfun(@isempty, mch));
if ~sts
cfg_message('matlabbatch:checkval:strtype', ...
'%s: Item must match one of these patterns:\n%s', subsasgn_checkstr(item,substruct('.','val')), sprintf('%s\n', pats{:}));
sts = false;
end
end
end
case {'s+'}
cfg_message('matlabbatch:checkval:strtype', ...
'%s: FAILURE: Cant do s+ yet', subsasgn_checkstr(item,substruct('.','val')));
case {'f'}
% test whether val is a function handle or a name of an
% existing function
sts = subsasgn_check_funhandle(val);
if ~sts
cfg_message('matlabbatch:checkval:strtype', ...
'%s: Item must be a function handle or function name.', ...
subsasgn_checkstr(item,substruct('.','val')));
end
case {'n'}
tol = 4*eps;
sts = isempty(val) || (isnumeric(val) && all(val(:) >= 1) && ...
all(abs(round(val(isfinite(val(:))))-val(isfinite(val(:)))) <= tol));
if ~sts
cfg_message('matlabbatch:checkval:strtype', ...
'%s: Item must be an array of natural numbers.', subsasgn_checkstr(item,substruct('.','val')));
return;
end
[sts val] = numcheck(item,val);
case {'i'}
tol = 4*eps;
sts = isempty(val) || (isnumeric(val) && ...
all(abs(round(val(isfinite(val(:))))-val(isfinite(val(:)))) <= tol));
if ~sts
cfg_message('matlabbatch:checkval:strtype', ...
'%s: Item must be an array of integers.', subsasgn_checkstr(item,substruct('.','val')));
return;
end
[sts val] = numcheck(item,val);
case {'r'}
sts = isempty(val) || (isnumeric(val) && all(isreal(val(:))));
if ~sts
cfg_message('matlabbatch:checkval:strtype', ...
'%s: Item must be an array of real numbers.', subsasgn_checkstr(item,substruct('.','val')));
return;
end
[sts val] = numcheck(item,val);
case {'w'}
tol = 4*eps;
sts = isempty(val) || (isnumeric(val) && all(val(:) >= 0) && ...
all(abs(round(val(isfinite(val(:))))-val(isfinite(val(:)))) <= tol));
if ~sts
cfg_message('matlabbatch:checkval:strtype', ...
'%s: Item must be an array of whole numbers.', subsasgn_checkstr(item,substruct('.','val')));
return;
end
[sts val] = numcheck(item,val);
case {'e'}
if ~isempty(item.extras) && subsasgn_check_funhandle(item.extras)
[sts val] = feval(item.extras, val, item.num);
else
[sts val] = numcheck(item,val);
end
otherwise
% only do size check for other strtypes
[sts val] = numcheck(item,val);
end
end
function [sts, val] = numcheck(item,val)
% allow arbitrary size, if num field is empty
sts = true;
csz = size(val);
if ~isempty(item.num)
if item.strtype == 's' && numel(item.num) == 2
% interpret num field as [min max] # elements
sts = item.num(1) <= numel(val) && numel(val) <= item.num(2);
if ~sts
cfg_message('matlabbatch:checkval:numcheck:mismatch', ...
'%s: Size mismatch (required [%s], present [%s]).', ...
subsasgn_checkstr(item,substruct('.','val')), num2str(item.num), num2str(csz));
end
else
ind = item.num>0 & isfinite(item.num);
if numel(csz) == 2
% also try transpose for 2D arrays
cszt = size(val');
else
cszt = csz;
end
if numel(item.num) ~= numel(csz)
cfg_message('matlabbatch:checkval:numcheck:mismatch', ...
'%s: Dimension mismatch (required %d, present %d).', subsasgn_checkstr(item,substruct('.','val')), numel(item.num), numel(csz));
sts = false;
return;
end
if any(item.num(ind)-csz(ind))
if any(item.num(ind)-cszt(ind))
cfg_message('matlabbatch:checkval:numcheck:mismatch', ...
'%s: Size mismatch (required [%s], present [%s]).', ...
subsasgn_checkstr(item,substruct('.','val')), num2str(item.num), num2str(csz));
sts = false;
return
else
val = val';
cfg_message('matlabbatch:checkval:numcheck:transposed', ...
'%s: Value transposed to match required size [%s].', ...
subsasgn_checkstr(item,substruct('.','val')), num2str(item.num));
end
end
end
end
|
github
|
philippboehmsturm/antx-master
|
showdoc.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/matlabbatch/@cfg_entry/showdoc.m
| 1,961 |
utf_8
|
4470b2abb40c7db525283b910ac13664
|
function str = showdoc(item, indent)
% function str = showdoc(item, indent)
% Display help text for a cfg_entry item.
%
% This code is part of a batch job configuration system for MATLAB. See
% help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging
% Volkmar Glauche
% $Id: showdoc.m 269 2008-05-23 07:15:10Z glauche $
rev = '$Rev: 269 $'; %#ok
str = showdoc(item.cfg_item, indent);
switch item.strtype
case {'e'},
str{end+1} = 'Evaluated statements are entered.';
str{end+1} = shownum(item.num);
case {'n'},
str{end+1} = 'Natural numbers are entered.';
str{end+1} = shownum(item.num);
case {'r'},
str{end+1} = 'Real numbers are entered.';
str{end+1} = shownum(item.num);
case {'w'},
str{end+1} = 'Whole numbers are entered.';
str{end+1} = shownum(item.num);
case {'s'},
str{end+1} = 'A String is entered.';
if isempty(item.num)
str{end+1} = 'The character array may have arbitrary size.';
elseif isfinite(item.num(2))
str{end+1} = sprintf(['The string must have between %d and %d ' ...
'characters.'], item.num(1), ...
item.num(2));
else
str{end+1} = sprintf(['The string must have at least %d ' ...
'characters.'], item.num(1));
end;
end;
function numstr = shownum(num)
if isempty(num)
numstr = ['The entered data may have an arbitrary number of dimensions ' ...
'and elements.'];
else
for k=1:numel(num)
if isfinite(num(k))
numstr1{k} = sprintf('%d',num(k));
else
numstr1{k} = 'X';
end;
end;
numstr = sprintf('%s-by-', numstr1{:});
numstr = sprintf('An %s array must be entered.', numstr(1:end-4));
end;
|
github
|
philippboehmsturm/antx-master
|
resolve_deps.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/matlabbatch/@cfg_item/resolve_deps.m
| 3,620 |
utf_8
|
3ed76ebe16ad02f135f4a83f428654f3
|
function [val, sts] = resolve_deps(item, cj)
% function [val, sts] = resolve_deps(item, cj)
% Resolve dependencies for an cfg item. This is a generic function that
% returns the contents of item.val{1} if it is an array of cfg_deps. If
% there is more than one dependency, they will be resolved in order of
% appearance. The returned val will be the concatenation of the values of
% all dependencies. A warning will be issued if this concatenation fails
% (which would happen if resolved dependencies contain incompatible
% values).
% If any of the dependencies cannot be resolved, val will be empty and sts
% false.
%
% This code is part of a batch job configuration system for MATLAB. See
% help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging
% Volkmar Glauche
% $Id: resolve_deps.m 484 2010-06-23 08:51:04Z glauche $
rev = '$Rev: 484 $'; %#ok
val1 = cell(size(item.val{1}));
for k = 1:numel(item.val{1})
% Outputs are stored in .jout field of cfg_exbranch, which is
% not included in .src_exbranch substruct
out = subsref(cj, [item.val{1}(k).src_exbranch, ...
substruct('.','jout')]);
sts = ~isa(out,'cfg_inv_out');
if ~sts
% dependency not yet computed, fail silently
val = [];
return;
end
try
val1{k} = subsref(out, item.val{1}(k).src_output);
catch %#ok
% dependency can't be resolved, even though it should be there
l = lasterror; %#ok
% display source output to diagnose problems
val1{k} = out;
dstr = disp_deps(item, val1);
cfg_message('matlabbatch:resolve_deps:missing', ...
'Dependency source available, but is missing required output.\n%s',...
l.message);
cfg_message('matlabbatch:resolve_deps:missing', '%s\n', dstr{:});
val = [];
sts = false;
return;
end
end
if sts
% All items resolved, try concatenation
try
% try concatenation along 1st dim
val = cat(1, val1{:});
catch %#ok
% try concatenation along 2nd dim
try
val = cat(2, val1{:});
catch %#ok
% all concatenations failed, display warning
l = lasterror; %#ok
dstr = disp_deps(item, val1);
cfg_message('matlabbatch:resolve_deps:incompatible',...
'Dependencies resolved, but incompatible values.\n%s', ...
l.message);
cfg_message('matlabbatch:resolve_deps:incompatible', '%s\n', dstr{:});
% reset val and sts
val = [];
sts = false;
return;
end
end
end
% all collected, check subsasgn validity
if sts
% subsasgn_check only accepts single subscripts
[sts val] = subsasgn_check(item, substruct('.','val'), {val});
end;
if sts
% dereference val after subsasgn_check
val = val{1};
else
dstr = disp_deps(item, val1);
dstr = [{'Dependencies resolved, but not suitable for this item.'}, ...
dstr(:)'];
cfg_message('matlabbatch:subsasgn:val',...
'%s\n', dstr{:});
return;
end
function dstr = disp_deps(item, val1) %#ok
dstr = cell(numel(item.val{1})+1,1);
dstr{1} = sprintf('In item %s:', subsref(item, substruct('.','name')));
for k = 1:numel(item.val{1})
substr = gencode_substruct(item.val{1}(k).src_output);
dstr{k+1} = sprintf('Dependency %d: %s (out%s)\n%s', ...
k, item.val{1}(k).sname, substr{1}, evalc('disp(val1{k})'));
end
|
github
|
philippboehmsturm/antx-master
|
initialise.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/matlabbatch/@cfg_repeat/initialise.m
| 4,833 |
utf_8
|
318adce123a9102e6369cf2d4f428e3f
|
function item = initialise(item, val, dflag)
% function item = initialise(item, val, dflag)
% Initialise a configuration tree with values. If val is a job
% struct/cell, only the parts of the configuration that are present in
% this job will be initialised. If dflag is true, then matching items
% from item.values will be initialised. If dflag is false, matching items
% from item.values will be added to item.val and initialised after
% copying.
% If val has the special value '<DEFAULTS>', the entire configuration
% will be updated with values from .def fields. If a .def field is
% present in a cfg_leaf item, the current default value will be inserted,
% possibly replacing a previously entered (default) value. If dflag is
% true, defaults will only be set in item.values. If dflag is false,
% defaults will be set for both item.val and item.values.
%
% This code is part of a batch job configuration system for MATLAB. See
% help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging
% Volkmar Glauche
% $Id: initialise.m 490 2010-09-20 13:14:03Z glauche $
rev = '$Rev: 490 $'; %#ok
if strcmp(val,'<DEFAULTS>')
item = initialise_def(item, val, dflag);
else
item = initialise_job(item, val, dflag);
end;
function item = initialise_def(item, val, dflag)
if ~dflag
% initialise defaults both in current job and in defaults
citem = subsref(item, substruct('.','val'));
for k = 1:numel(citem)
citem{k} = initialise(citem{k}, val, dflag);
end;
item = subsasgn(item, substruct('.','val'), citem);
end;
for k = 1:numel(item.values)
item.values{k} = initialise(item.values{k}, val, dflag);
end;
function item = initialise_job(item, val, dflag)
if numel(item.values)==1 && isa(item.values{1},'cfg_branch') ...
&& ~item.forcestruct,
if isstruct(val)
if dflag
item.values{1} = initialise(item.values{1}, val, dflag);
else
citem = cell(1,numel(val));
for k = 1:numel(val)
citem{k} = initialise(item.values{1}, val(k), dflag);
end;
item.cfg_item.val = citem;
end;
else
cfg_message('matlabbatch:initialise', ...
'Can not initialise %s value(s): job is not a struct.', ...
gettag(item));
return;
end;
else
if dflag
if numel(item.values) > 1 || item.forcestruct
% val should be either a cell array containing structs with a
% single field (a harvested job), or a struct with multiple
% fields (a harvested defaults tree). In the latter case,
% convert val to a cell array before proceeding.
if isstruct(val)
vtag = fieldnames(val);
val1 = cell(size(vtag));
for k = 1:numel(vtag)
val1{k} = struct(vtag{k}, {val.(vtag{k})});
end;
val = val1;
elseif iscell(val) && all(cellfun(@isstruct,val))
vtag = cell(size(val));
for k = 1:numel(val)
vtag(k) = fieldnames(val{k});
end;
else
cfg_message('matlabbatch:initialise', ...
'Can not initialise %s value(s): job is not a cell array of struct items.', ...
gettag(item));
return;
end;
for k = 1:numel(item.values)
% use first match for defaults initialisation
sel = find(strcmp(gettag(item.values{k}), vtag));
if ~isempty(sel)
item.values{k} = initialise(item.values{k}, ...
val{sel(1)}.(vtag{sel(1)}), ...
dflag);
end;
end;
else
item.values{1} = initialise(item.values{1}, val{1}, dflag);
end;
else
citem = cell(1,numel(val));
if numel(item.values) > 1 || item.forcestruct
for l = 1:numel(val)
% val{l} should be a struct with a single field
vtag = fieldnames(val{l});
for k = 1:numel(item.values)
if strcmp(gettag(item.values{k}), vtag{1})
citem{l} = initialise(item.values{k}, ...
val{l}.(vtag{1}), ...
dflag);
end;
end;
end;
else
for l = 1:numel(val)
citem{l} = initialise(item.values{1}, ...
val{l}, dflag);
end;
end;
item.cfg_item.val = citem;
end;
end;
|
github
|
philippboehmsturm/antx-master
|
spm_hrf_timeshift_demo.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/demo/spm_hrf_timeshift_demo.m
| 7,324 |
utf_8
|
f198b9d5ad85ad5f98540f291c660b4f
|
function spm_hrf_timeshift_demo
%% Modelling time shifts in hemodynamic responses
% In some situations, the time course of the canonical hrf might not fit
% the observed time course. In particular, the observed time-to-peak might
% vary between different areas of the brain (or different event types in
% the same brain area).
%
% This demo shows the strengths and limitations of the commonly used basis
% function sets in capturing time-shifted responses.
%% General timing constants
% dt is the time resolution (in seconds) of the generated hrf.
dt = .05;
%% Create response
% A canonical HRF response is created and shifted in time.
xBFr.name = 'hrf';
xBFr.dt = dt;
xBFr = spm_get_bf(xBFr);
%% Create shifted responses
% maximum shift (in +/- sec)
mxshift = 5;
ts = -mxshift:dt:mxshift;
npad = mxshift/dt;
lresp = npad+size(xBFr.bf,1);
sresp = zeros(lresp,2*npad+1);
for k = 1:(2*npad+1)
bflen = min(size(xBFr.bf,1), lresp-k);
sresp(k:(k-1+bflen),k) = xBFr.bf(1:bflen,1);
end
%% Get basis function set
% SPM uses spm_get_bf to obtain a basis function set for a single, zero
% length event. This basis function set is then used to create the expected
% response time courses. In this demo, we assume a single, zero length
% event at t = 0. We want to model faster and slower responses, therefore
% internal demo time is running from -2 sec to 32 sec (the length of the
% canonical hrf). Plots always start at t = 0, however.
SPM.xBF.dt = dt;
SPM.xBF = spm_get_bf(SPM.xBF);
% pad canonical basis function with zeros for time before event
pbf = zeros(lresp, size(SPM.xBF.bf,2));
pbf(npad+(1:size(SPM.xBF.bf,1)),:) = SPM.xBF.bf;
% truncate to length of shifted response
pbf = pbf(1:lresp,:);
ishrftime = ~isempty(regexpi(SPM.xBF.name, '^hrf.*time'));
% post-event time
t = 0:SPM.xBF.dt:(lresp-npad-1)*SPM.xBF.dt;
%% Solve
% solve for regression weights wrt basis set - in real SPM, this would be
% done in spm_spm.
betas = pbf\sresp;
% fitted response and error of full model
fresp = pbf*betas;
err = fresp - sresp;
ssq = sum(err.^2);
if ishrftime
% fitted response of HRF only
fresp1 = pbf(:,1)*betas(1,:);
end
%% Time to peak and amplitude
% For the shifted response, this is a the same as the time shift
% introduced. For the fitted response, it depends on the basis set used.
% For hrf+derivative, it is similar to the real time shift only in a small
% interval around zero time shift.
[samp stmx] = max(sresp);
[famp ftmx] = max(fresp);
if ishrftime
[famp1 tmp] = max(fresp1);
end
sttp = t(stmx-npad);
fttp = t(ftmx-npad);
%% Interpretation of parameters for hrf+derivative
% The parameters of the hrf basis set can be interpreted as \Delta t and be
% used to fit a time shift function.
if ishrftime
%% dt
% This is the ratio between beta2 and beta1.
dt = betas(2,:)./betas(1,:);
%% Fit parameters for function fttp = f(dt)
% To be able to estimate ttp from the fitted betas, a sigmoid function is
% fitted to the simulated ttp of the fitted responses.
l = fminsearch(@(x)ttpfit(x,dt,fttp),[1 1 1]);
fttpfit=l(1)./(1+exp(l(2)*ts))+l(3);
end
%% Set up figure
figname = sprintf('%s - %s', mfilename, SPM.xBF.name);
f = findobj(0,'tag',figname);
if isempty(f)
f = figure('tag',figname,'name',figname,'Numbertitle','off');
end
clf(f);
set(f,'position',get(0,'ScreenSize'));
% current time step
cs = 100;
% legend handles and legends
hleg = [];
hlstr = {};
%% Plot betas
axbetas = axes('parent',f, 'position',[.01 .05 .23 .26]);
bar(betas(:,cs),'parent',axbetas)
set(axbetas,'tag','axbetas');
%% Plot time to peak over timeshift
axttp = axes('parent',f, 'position',[.26 .05 .23 .26]);
plot(axttp,ts,[sttp;fttp]);
if ishrftime
hold(axttp, 'on');
hleg(end+1) = plot(axttp,dt,fttpfit,'r');
hlstr{end+1} = sprintf('%0.2f./exp(%0.2f*ts))+%0.2f',l(1),l(2),l(3));
end
axlim = axis(axttp);
line([ts(cs) ts(cs)],axlim([3 4]),'parent',axttp,'color','k','tag','tsline');
xlabel(axttp,'Real response - time shift');
ylabel(axttp,'Time to peak');
% set update function, hit test
set(axttp,'ButtonDownFcn',@update_lines);
set(allchild(axttp),'HitTest','off');
%% Plot dt over timeshift
if ishrftime
axdt = axes('parent',f, 'position',[.51 .05 .23 .26]);
plot(axdt,ts, [-ts; dt]);
axlim = axis(axdt);
line([ts(cs) ts(cs)],axlim([3 4]),'parent',axdt,'color','k','tag','tsline');
xlabel(axdt,'Real response - time shift');
ylabel(axdt,'\Delta t');
% set update function, hit test
set(axdt,'ButtonDownFcn',@update_lines);
set(allchild(axdt),'HitTest','off');
else
axdt = [];
end
%% Plot fitted amplitudes over timeshift
axamp = axes('parent',f,'position',[.76 .05 .23 .26]);
if ishrftime
set(axamp,'colororder',[0 0 1; 0 .5 0;0 .5 0]);
hold(axamp, 'on');
tmp = plot(axamp,ts,samp,'-',ts,famp,'-',ts,famp1,'--');
hold(axamp, 'off');
hleg(end+1) = tmp(3);
hlstr{end+1} = 'Fitted response HRF only';
else
plot(axamp,ts,[samp;famp]);
end
axlim = axis(axamp);
line([ts(cs) ts(cs)],axlim([3 4]),'parent',axamp,'color','k','tag','tsline');
xlabel(axamp,'Real response - Time shift');
ylabel(axamp,'Peak amplitude');
% set update function, hit test
set(axamp,'ButtonDownFcn',@update_lines);
set(allchild(axamp),'HitTest','off');
%% plot fitted response - coloured with error
axfit = axes('parent',f,'position',[.05 .4 .47 .47]);
hfresp = surf(axfit,t,ts,fresp(npad+1:end,:)',abs(err(npad+1:end,:)'),'linestyle','none');
colormap(axfit,'gray')
xlabel(axfit,'Post-event time')
ylabel(axfit,'Time shift')
zlabel(axfit,'Response')
title(axfit,'Fitted response')
% add canonical response
hold(axfit, 'on');
hleg(end+1) = line(t,ts(cs)*ones(size(t)),sresp(npad+1:end,cs),'parent',axfit,'color','b','linewidth',5,'tag','lsresp');
hlstr{end+1} = 'Real HRF';
%% plot real response - coloured with error
axreal = axes('parent',f,'position',[.53 .4 .47 .47]);
hsresp = surf(axreal,t,ts,sresp(npad+1:end,:)',abs(err(npad+1:end,:)'),'linestyle','none');
colormap(axreal,'gray')
xlabel(axreal,'Post-event time')
ylabel(axreal,'Time shift')
zlabel(axreal,'Response')
title(axreal,'Real response')
% add fitted response
hold(axreal, 'on');
hleg(end+1) = line(t,ts(cs)*ones(size(t)),fresp(npad+1:end,cs),'parent',axreal,'color',[0 .5 0],'linewidth',5,'tag','lfresp');
hlstr{end+1} = 'Fitted HRF';
% set legend, let MATLAB figure out its size
legend(hleg(end:-1:1),hlstr(end:-1:1),'position', [0.5 0.9 0 0])
hl=linkprop([axfit axreal],'View');
set(f,'userdata',struct('links',hl,'t',t,'npad',npad,'ts',ts,'fresp',fresp,'sresp',sresp,'betas',betas))
function update_lines(ob,ev)
ud = get(gcbf, 'userdata');
cp = get(ob, 'CurrentPoint');
[tmp cs] = min(abs(ud.ts-cp(1,1)));
tslines = findobj(gcbf, 'tag','tsline');
set(tslines,'xdata',[ud.ts(cs),ud.ts(cs)]);
lfresp = findobj(gcbf, 'tag','lfresp');
set(lfresp,'ydata',ud.ts(cs)*ones(size(ud.t)),'zdata',ud.fresp(ud.npad+1:end,cs));
lsresp = findobj(gcbf, 'tag','lsresp');
set(lsresp,'ydata',ud.ts(cs)*ones(size(ud.t)),'zdata',ud.sresp(ud.npad+1:end,cs));
axbetas = findobj(gcbf,'tag','axbetas');
bar(ud.betas(:,cs),'parent',axbetas)
set(axbetas,'tag','axbetas');
function err = ttpfit(l,t,y)
% This function computes the error between data y and a sigmoid function
% parameterised by l(1:3).
y1 = l(1)./(1+exp(l(2)*t))+l(3);
err = norm(y1-y);
|
github
|
philippboehmsturm/antx-master
|
spm_conv_demo.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/demo/spm_conv_demo.m
| 804 |
utf_8
|
dc62d248d1d683bf767fa551bf708054
|
function spm_conv_demo
global defaults;
defaults.stats.fmri.t=16;
RT=.1;
[hrf phrf]=spm_hrf(RT);
hrf=hrf/max(hrf);
t=0:1/defaults.stats.fmri.t:500;
scans=zeros(size(t));
scans(1:defaults.stats.fmri.t:end)=1;
f=figure(2);
clf;
axscans=axes('position',[.3 .1 .6 .2]);
axons=axes('position',[.3 .4 .6 .2]);
axconv=axes('position',[.3 .7 .6 .2]);
plot_sticks(axscans,t,scans);
title('Scan time points');
for k=200:-2:40
ons=zeros(size(t));
ons(50+(1:k:20*k))=1;
plot_sticks(axons,t,ons);
chrf=conv(ons,hrf);
chrf=chrf(1:numel(t));
chrf=chrf/max(chrf);
plot(axconv,t,chrf);
pause(.1);
end
function h=plot_sticks(ax,t,x)
x1=find(x);
tn=kron(t(x1),[1 1 1]);
xn=kron(x(x1),[0 1 0]);
h=plot(ax,tn,xn);
axis(ax,[min(t) max(t) min(x) max(x)]);
|
github
|
philippboehmsturm/antx-master
|
spm_ovhelper_3Dreg.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_orthviews/spm_ovhelper_3Dreg.m
| 3,534 |
utf_8
|
1820adca26f6de47595faa8162381cda
|
function spm_ovhelper_3Dreg(cmd, varargin)
% Helper function to register spm_orthviews plugins via spm_XYZreg
% FORMAT spm_ovhelper_3Dreg('register', h, V)
% Register a (3D) graphics with the main spm_orthviews display. This will
% draw 3D crosshairs at the current spm_orthviews position and update
% them whenever the spm_orthviews cursor moves.
% h - a graphics handle or a tag of graphics handle to register
% V - a volume handle (or equivalent) containing dimensions and
% voxel-to-world mapping information
% FORMAT spm_ovhelper_3Dreg('unregister', h)
% h - a graphics handle or a tag of graphics handle to unregister
% FORMAT spm_ovhelper_3Dreg('setcoords', xyz, h)
% Update position of crosshairs in 3D display
% xyz - new crosshair coordinates (in mm)
% h - a graphics handle or a tag of graphics handle to update
% FORMAT spm_ovhelper_3Dreg('xhairson', h)
% FORMAT spm_ovhelper_3Dreg('xhairsoff', h)
% Toggle display of crosshairs in 3D display.
% h - a graphics handle or a tag of graphics handle
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Volkmar Glauche
% $Id: spm_ovhelper_3Dreg.m 3756 2010-03-05 18:43:37Z guillaume $
if ishandle(varargin{1})
h = varargin{1};
elseif ischar(varargin{1})
h = findobj(0, 'Tag',varargin{1});
if ~ishandle(h)
warning([mfilename ':InvalidHandle'], ...
'No valid graphics handle found');
return;
else
h = get(h(ishandle(h)),'parent');
end;
end;
switch lower(cmd)
case 'register'
register(h,varargin{2:end});
return;
case 'setcoords'
setcoords(varargin{1:end});
return;
case 'unregister',
unregister(h,varargin{2:end});
return;
case 'xhairson'
xhairs(h,'on',varargin{2:end});
return;
case 'xhairsoff'
xhairs(h,'off',varargin{2:end});
return;
end;
function register(h,V,varargin)
try
global st;
if isstruct(st)
xyz=spm_orthviews('pos');
if isfield(st,'registry')
hreg = st.registry.hReg;
else
[hreg xyz]=spm_XYZreg('InitReg', h, V.mat, ...
V.dim(1:3)',xyz);
spm_orthviews('register',hreg);
end;
spm_XYZreg('Add2Reg',hreg,h,mfilename);
feval(mfilename,'setcoords',xyz,h);
set(h, 'DeleteFcn', ...
sprintf('%s(''unregister'',%f);', mfilename, h));
end;
catch
warning([mfilename ':XYZreg'],...
'Unable to register to spm_orthviews display');
disp(lasterror);
end;
return;
function setcoords(xyz,h,varargin)
spm('pointer','watch');
Xh = findobj(h,'Tag', 'Xhairs');
if ishandle(Xh)
vis = get(Xh(1),'Visible');
delete(Xh);
else
vis = 'on';
end;
axes(findobj(h,'Type','axes'));
lim = axis;
Xh = line([xyz(1), xyz(1), lim(1);...
xyz(1), xyz(1), lim(2)],...
[lim(3), xyz(2), xyz(2);...
lim(4), xyz(2), xyz(2)],...
[xyz(3), lim(5), xyz(3);...
xyz(3), lim(6), xyz(3)],...
'Color','b', 'Tag','Xhairs', 'Visible',vis,...
'Linewidth',2, 'HitTest','off');
spm('pointer','arrow');
return;
function xhairs(h,val,varargin)
Xh = findobj(h, 'Tag', 'Xhairs');
if ~isempty(Xh)
set(Xh,'Visible',val);
end;
function unregister(h,varargin)
try
global st;
if isfield(st,'registry')
hreg = st.registry.hReg;
else
hreg = findobj(0,'Tag','hReg');
end;
if h == hreg
spm_XYZreg('UnInitReg',hreg);
st = rmfield(st, 'registry');
else
spm_XYZreg('Del2Reg',hreg,h);
end;
catch
warning([mfilename ':XYZreg'],...
'Unable to unregister');
disp(lasterror);
end;
return;
|
github
|
philippboehmsturm/antx-master
|
spm_ov_title.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_orthviews/spm_ov_title.m
| 2,474 |
utf_8
|
dbb8c641fb8dfe619909aac75fa7deb5
|
function spm_ov_title(varargin)
global st;
if isempty(st)
error(sprintf('spm:%s', mfilename), '%s: This routine can only be called as a plugin for spm_orthviews!', mfilename);
end;
if nargin < 2
error(sprintf('spm:%s', mfilename), '%: Wrong number of arguments. Usage: spm_orthviews(''title'', cmd, volhandle, varargin)', mfilename);
end;
cmd = lower(varargin{1});
volhandle = varargin{2};
switch cmd
%----------------------------------------------------------------------
% Context menu and callbacks
case 'context_menu'
item0 = uimenu(varargin{3}, 'Label', 'Add title', 'Callback', ...
sprintf('%s(''context_init'', %d);', mfilename, volhandle), ...
'Tag',['TITLE_0_', num2str(volhandle)]);
case 'context_init'
Finter = spm_figure('FindWin', 'Interactive');
spm_input('!DeleteInputObj', Finter);
if isfield(st.vols{volhandle}, 'title')
titlestr = st.vols{volhandle}.title.str;
else
titlestr = '';
end
st.vols{volhandle}.title.str = spm_input('Title', '!+1', 's', titlestr);
set_title;
case 'addtitle'
st.vols{volhandle}.title.str = varargin{3};
set_title(volhandle);
case 'rmtitle'
st.vols{volhandle}.title.str = '';
set_title(volhandle);
case 'redraw'
% Do nothing
otherwise
fprintf('spm_orthviews(''rgb'', ...): Unknown action %s', cmd);
end
function set_title(volhandle)
global st
if isempty(st.vols{volhandle}.title.str)
if isfield(st.vols{volhandle}.title, 'ax')
delete(st.vols{volhandle}.title.ax);
end
st.vols{volhandle} = rmfield(st.vols{volhandle}, 'title');
else
if isfield(st.vols{volhandle}.title, 't')
set(st.vols{volhandle}.title.t, 'String', st.vols{volhandle}.title.str);
else
axpos = zeros(3,4);
for k = 1:3
axpos(k,:) = get(st.vols{volhandle}.ax{k}.ax, 'Position');
end
axul = [min(axpos(:,1)), max(axpos(:,2)+axpos(:,4))+.1*(st.vols{volhandle}.area(2)+st.vols{volhandle}.area(4)-max(axpos(:,2)+axpos(:,4)))];
axsz = [st.vols{volhandle}.area(3) st.vols{volhandle}.area(2)+st.vols{volhandle}.area(4) - axul(2)];
st.vols{volhandle}.title.ax = axes('Position', [axul axsz], 'Visible', 'off');
st.vols{volhandle}.title.t = text(.5, 0, st.vols{volhandle}.title.str, 'HorizontalAlignment', 'Center');
end
end
|
github
|
philippboehmsturm/antx-master
|
spm_ov_roi.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_orthviews/spm_ov_roi.m
| 36,776 |
utf_8
|
aeb54afe2f51c5c9e637c2e3b31f8e18
|
function ret = spm_ov_roi(varargin)
% ROI tool - plugin for spm_orthviews
%
% With ROI tool it is possible to create new or modify existing mask images
% interactively. ROI tool can be launched via the spm_orthviews image
% context menu.
% While ROI tool is active, mouse buttons have the following functions:
% left Reposition crosshairs
% middle Perform ROI tool box selection according to selected edit mode at
% crosshair position
% right context menu
%
% Menu options and prompts explained:
% Launch Initialise ROI tool in current image
% 'Load existing ROI image? (yes/no)'
% If you want to modify an existing mask image (e.g. mask.img from
% a fMRI analysis), press 'yes'. You will then be prompted to
% 'Select ROI image'
% This is the image that will be loaded as initial ROI.
% If you want to create a new ROI image, you will first be
% prompted to
% 'Select image defining ROI space'
% The image dimensions, voxel sizes and slice orientation will
% be read from this image. Thus you can edit a ROI based on a
% image with a resolution and slice orientation different from
% the underlying displayed image.
%
% Once ROI tool is active, the menu consists of three parts: settings,
% edit operations and load/save operations.
% Settings
% --------
% Selection Operation performed when pressing the middle mouse button or
% mode by clustering operations.
% 'Set selection'
% The selection made with the following commands will
% be included in your ROI.
% 'Clear selection'
% The selection made with the following commands will
% be excluded from your ROI.
% Box size Set size of box to be (de)selected when pressing the
% middle mouse button.
% Polygon Set number of adjacent slices selected by one polygon
% slices drawing.
% Cluster Set minimum cluster size for "Cleanup clusters" and
% size "Connected cluster" operations.
% Erosion/ During erosion/dilation operations, the binary mask will be
% dilation smoothed. At boundaries, this will result in mask values
% threshold that are not exactly zero or one, but somewhere in
% between. Whether a mask will be eroded (i.e. be smaller than
% the original) or dilated (i.e. grow) depends on this
% threshold. A threshold below 0.5 dilates, above 0.5 erodes a
% mask.
% Edit actions
% ------------
% Polygon Draw an outline on one of the 3 section images. Voxels
% within the outline will be added to the ROI. The same
% outline can be applied to a user-defined number of
% consecutive slices around the current crosshair position.
% Threshold You will be prompted to enter a [min max] threshold. Only
% those voxels in the ROI image where the intensities of the
% underlying image are within the [min max] range will survive
% this operation.
% Connected Select only voxels that are connected to the voxel at
% cluster current crosshair position through the ROI.
% Cleanup Keep only clusters that are larger than a specified cluster
% clusters size.
% Erode/ Erode or dilate a mask, using the current erosion/dilation
% Dilate threshold.
% Invert Invert currently defined ROI
% Clear Clear ROI, but keep ROI space information
% Add ROI from file(s)
% Add ROIs from file(s) into current ROI set. According to the
% current edit mode voxels unequal zero will be set or
% cleared. The image files will be resampled and thus do not
% need to have the same orientation or voxel size as the
% original ROI.
% Save actions
% ------------
% Save Save ROI image
% Save As Save ROI image under a new file name
% The images will be rescaled to 0 (out of mask) and 1 (in
% mask).
% Quit Quit ROI tool
%
% This routine is a plugin to spm_orthviews for SPM8. For general help about
% spm_orthviews and plugins type
% help spm_orthviews
% at the matlab prompt.
%_____________________________________________________________________________
% $Id: spm_ov_roi.m 3920 2010-06-11 12:08:13Z volkmar $
% Note: This plugin depends on the blobs set by spm_orthviews('addblobs',...)
% They should not be removed while ROI tool is active and no other blobs be
% added. This restriction may be removed when using the 'alpha' property
% to overlay blobs onto images.
rev = '$Revision: 3920 $';
global st;
if isempty(st)
error('roi: This routine can only be called as a plugin for spm_orthviews!');
end;
if nargin < 2
error('roi: Wrong number of arguments. Usage: spm_orthviews(''roi'', cmd, volhandle, varargin)');
end;
cmd = lower(varargin{1});
volhandle = varargin{2};
toset = [];
toclear = [];
tochange = [];
update_roi = false;
switch cmd
case 'init'
% spm_ov_roi('init', volhandle, Vroi, loadasroi, xyz)
spm('pointer','watch');
Vroi = spm_vol(varargin{3});
switch varargin{4} % loadasroi
case 1,
roi = spm_read_vols(Vroi)>0;
[x y z] = ndgrid(1:Vroi.dim(1),1:Vroi.dim(2),1:Vroi.dim(3));
xyz = [x(roi(:))'; y(roi(:))'; z(roi(:))'];
case {0,2} % ROI space image or SPM mat
Vroi = rmfield(Vroi,'private');
roi = false(Vroi.dim(1:3));
Vroi.fname = fileparts(Vroi.fname); % save path
xyz = varargin{5};
if ~isempty(xyz)
ind = sub2ind(Vroi.dim(1:3),xyz(1,:),xyz(2,:),xyz(3,:));
roi(ind) = true;
end;
end;
% reset data type to save disk space
Vroi.dt(1) = spm_type('uint8');
% reset scaling factor of Vroi handle
Vroi.pinfo(1:2) = Inf;
clear x y z
% draw a frame only if ROI volume different from underlying GM volume
if any(Vroi.dim(1:3)-st.vols{volhandle}.dim(1:3))|| ...
any(Vroi.mat(:)-st.vols{volhandle}.mat(:))
[xx1 yx1 zx1] = ndgrid(1 , 1:Vroi.dim(2), 1:Vroi.dim(3));
[xx2 yx2 zx2] = ndgrid(Vroi.dim(1) , 1:Vroi.dim(2), 1:Vroi.dim(3));
[xy1 yy1 zy1] = ndgrid(1:Vroi.dim(1), 1 , 1:Vroi.dim(3));
[xy2 yy2 zy2] = ndgrid(1:Vroi.dim(1), Vroi.dim(2) , 1:Vroi.dim(3));
[xz1 yz1 zz1] = ndgrid(1:Vroi.dim(1), 1:Vroi.dim(2), 1);
[xz2 yz2 zz2] = ndgrid(1:Vroi.dim(1), 1:Vroi.dim(2), Vroi.dim(3));
fxyz = [xx1(:)' xx2(:)' xy1(:)' xy2(:)' xz1(:)' xz2(:)'; ...
yx1(:)' yx2(:)' yy1(:)' yy2(:)' yz1(:)' yz2(:)'; ...
zx1(:)' zx2(:)' zy1(:)' zy2(:)' zz1(:)' zz2(:)'];
clear xx1 yx1 zx1 xx2 yx2 zx2 xy1 yy1 zy1 xy2 yy2 zy2 xz1 yz1 zz1 xz2 yz2 zz2
hframe = 1;
else
hframe = [];
fxyz = [];
end;
cb = cell(1,3);
for k=1:3
cb{k}=get(st.vols{volhandle}.ax{k}.ax,'ButtonDownFcn');
set(st.vols{volhandle}.ax{k}.ax,...
'ButtonDownFcn',...
@(ob,ev)spm_ov_roi('bdfcn',volhandle,ob,ev));
end;
st.vols{volhandle}.roi = struct('Vroi',Vroi, 'xyz',xyz, 'roi',roi,...
'hroi',1, 'fxyz',fxyz,...
'hframe',hframe, 'mode','set',...
'tool', 'box', ...
'thresh',[60 140], 'box',[4 4 4],...
'cb',[], 'polyslices',1, 'csize',5,...
'erothresh',.5);
st.vols{volhandle}.roi.cb = cb;
if ~isempty(st.vols{volhandle}.roi.fxyz)
if isfield(st.vols{volhandle}, 'blobs')
st.vols{volhandle}.roi.hframe = numel(st.vols{volhandle}.blobs)+1;
end;
spm_orthviews('addcolouredblobs',volhandle, ...
st.vols{volhandle}.roi.fxyz,...
ones(size(st.vols{volhandle}.roi.fxyz,2),1), ...
st.vols{volhandle}.roi.Vroi.mat,[1 .5 .5]);
st.vols{volhandle}.blobs{st.vols{volhandle}.roi.hframe}.max=1.3;
end;
update_roi=1;
obj = findobj(0, 'Tag', sprintf('ROI_1_%d', volhandle));
set(obj, 'Visible', 'on');
obj = findobj(0, 'Tag', sprintf('ROI_0_%d', volhandle));
set(obj, 'Visible', 'off');
case 'edit'
switch st.vols{volhandle}.roi.tool
case 'box'
spm('pointer','watch');
pos = round(inv(st.vols{volhandle}.roi.Vroi.mat)* ...
[spm_orthviews('pos'); 1]);
tmp = round((st.vols{volhandle}.roi.box-1)/2);
[sx sy sz] = meshgrid(-tmp(1):tmp(1), -tmp(2):tmp(2), -tmp(3):tmp(3));
sel = [sx(:)';sy(:)';sz(:)']+repmat(pos(1:3), 1,prod(2*tmp+1));
tochange = sel(:, (all(sel>0) &...
sel(1,:)<=st.vols{volhandle}.roi.Vroi.dim(1) & ...
sel(2,:)<=st.vols{volhandle}.roi.Vroi.dim(2) & ...
sel(3,:)<=st.vols{volhandle}.roi.Vroi.dim(3)));
update_roi = 1;
case 'connect'
spm_ov_roi('connect', volhandle)
case 'poly'
% @COPYRIGHT :
% Copyright 1993,1994 Mark Wolforth and Greg Ward, McConnell
% Brain Imaging Centre, Montreal Neurological Institute, McGill
% University.
% Permission to use, copy, modify, and distribute this software
% and its documentation for any purpose and without fee is
% hereby granted, provided that the above copyright notice
% appear in all copies. The authors and McGill University make
% no representations about the suitability of this software for
% any purpose. It is provided "as is" without express or
% implied warranty.
for k = 1:3
if st.vols{volhandle}.ax{k}.ax == gca
axhandle = k;
break;
end;
end;
line_color = [1 1 0];
axes(st.vols{volhandle}.ax{axhandle}.ax);
hold on;
Xlimits = get (st.vols{volhandle}.ax{axhandle}.ax,'XLim');
Ylimits = get (st.vols{volhandle}.ax{axhandle}.ax,'YLim');
XLimMode = get(st.vols{volhandle}.ax{axhandle}.ax,'XLimMode');
set(st.vols{volhandle}.ax{axhandle}.ax,'XLimMode','manual');
YLimMode = get(st.vols{volhandle}.ax{axhandle}.ax,'YLimMode');
set(st.vols{volhandle}.ax{axhandle}.ax,'YLimMode','manual');
ButtonDownFcn = get(st.vols{volhandle}.ax{axhandle}.ax,'ButtonDownFcn');
set(st.vols{volhandle}.ax{axhandle}.ax,'ButtonDownFcn','');
UIContextMenu = get(st.vols{volhandle}.ax{axhandle}.ax,'UIContextMenu');
set(st.vols{volhandle}.ax{axhandle}.ax,'UIContextMenu',[]);
set(st.vols{volhandle}.ax{axhandle}.ax,'Selected','on');
disp (['Please mark the ROI outline in the highlighted image' ...
' display.']);
disp ('Points outside the ROI image area will be clipped to');
disp ('the image boundaries.');
disp ('Left-Click on the vertices of the ROI...');
disp ('Middle-Click to finish ROI selection...');
disp ('Right-Click to cancel...');
x=Xlimits(1);
y=Ylimits(1);
i=1;
lineHandle = [];
xc = 0; yc = 0; bc = 0;
while ~isempty(bc)
[xc,yc,bc] = ginput(1);
if isempty(xc) || bc > 1
if bc == 3
x = []; y=[];
end;
if bc == 2 || bc == 3
bc = [];
break;
end;
else
if xc > Xlimits(2)
xc = Xlimits(2);
elseif xc < Xlimits(1)
xc = Xlimits(1);
end;
if yc > Ylimits(2)
yc = Ylimits(2);
elseif yc < Ylimits(1)
yc = Ylimits(1);
end;
x(i) = xc;
y(i) = yc;
i=i+1;
if ishandle(lineHandle)
delete(lineHandle);
end;
lineHandle = line (x,y,ones(1,length(x)), ...
'Color',line_color,...
'parent',st.vols{volhandle}.ax{axhandle}.ax,...
'HitTest','off');
end;
end
if ishandle(lineHandle)
delete(lineHandle);
end;
if ~isempty(x)
spm('pointer','watch');
x(i)=x(1);
y(i)=y(1);
prms=spm_imatrix(st.vols{volhandle}.roi.Vroi.mat);
% Code from spm_orthviews('redraw') for determining image
% positions
is = inv(st.Space);
cent = is(1:3,1:3)*st.centre(:) + is(1:3,4);
polyoff = [0 0 0];
switch axhandle
case 1,
M0 = [ 1 0 0 -st.bb(1,1)+1
0 1 0 -st.bb(1,2)+1
0 0 1 -cent(3)
0 0 0 1];
polyoff(3) = st.vols{volhandle}.roi.polyslices/2;
polythick = prms(9);
case 2,
M0 = [ 1 0 0 -st.bb(1,1)+1
0 0 1 -st.bb(1,3)+1
0 1 0 -cent(2)
0 0 0 1];
polyoff(2) = st.vols{volhandle}.roi.polyslices/2;
polythick = prms(8);
case 3,
if st.mode ==0,
M0 = [ 0 0 1 -st.bb(1,3)+1
0 1 0 -st.bb(1,2)+1
1 0 0 -cent(1)
0 0 0 1];
else
M0 = [ 0 -1 0 +st.bb(2,2)+1
0 0 1 -st.bb(1,3)+1
1 0 0 -cent(1)
0 0 0 1];
end;
polyoff(1) = st.vols{volhandle}.roi.polyslices/2;
polythick = abs(prms(7));
end;
polvx = inv(st.vols{volhandle}.roi.Vroi.mat)*st.Space*inv(M0)*...
[x(:)';y(:)'; zeros(size(x(:)')); ones(size(x(:)'))];
% Bounding volume for polygon in ROI voxel space
[xbox ybox zbox] = ndgrid(max(min(floor(polvx(1,:)-polyoff(1))),1):...
min(max(ceil(polvx(1,:)+polyoff(1))),...
st.vols{volhandle}.roi.Vroi.dim(1)),...
max(min(floor(polvx(2,:)-polyoff(2))),1):...
min(max(ceil(polvx(2,:)+polyoff(2))),...
st.vols{volhandle}.roi.Vroi.dim(2)),...
max(min(floor(polvx(3,:)-polyoff(3))),1):...
min(max(ceil(polvx(3,:)+polyoff(3))),...
st.vols{volhandle}.roi.Vroi.dim(3)));
% re-transform in polygon plane
xyzbox = M0*is*st.vols{volhandle}.roi.Vroi.mat*[xbox(:)';ybox(:)';zbox(:)';...
ones(size(xbox(:)'))];
xyzbox = xyzbox(:,abs(xyzbox(3,:))<=.6*polythick*...
st.vols{volhandle}.roi.polyslices); % nearest neighbour to polygon
sel = logical(inpolygon(xyzbox(1,:),xyzbox(2,:),x,y));
xyz = inv(st.vols{volhandle}.roi.Vroi.mat)*st.Space*inv(M0)*xyzbox(:,sel);
if ~isempty(xyz)
tochange = round(xyz(1:3,:));
update_roi = 1;
end;
end;
set(st.vols{volhandle}.ax{axhandle}.ax,...
'Selected','off', 'XLimMode',XLimMode, 'YLimMode',YLimMode,...
'ButtonDownFcn',ButtonDownFcn, 'UIContextMenu',UIContextMenu);
end;
case 'thresh'
spm('pointer','watch');
rind = find(st.vols{volhandle}.roi.roi);
[x y z]=ind2sub(st.vols{volhandle}.roi.Vroi.dim(1:3),rind);
tmp = round(inv(st.vols{volhandle}.mat) * ...
st.vols{volhandle}.roi.Vroi.mat*[x'; y'; z'; ones(size(x'))]);
dat = spm_sample_vol(st.vols{volhandle}, ...
tmp(1,:), tmp(2,:), tmp(3,:), 0);
sel = ~((st.vols{volhandle}.roi.thresh(1) < dat) & ...
(dat < st.vols{volhandle}.roi.thresh(2)));
if strcmp(st.vols{volhandle}.roi.mode,'set')
toclear = [x(sel)'; y(sel)'; z(sel)'];
else
toset = [x(sel)'; y(sel)'; z(sel)'];
toclear = st.vols{volhandle}.roi.xyz;
end;
update_roi = 1;
case 'erodilate'
spm('pointer','watch');
V = zeros(size(st.vols{volhandle}.roi.roi));
spm_smooth(double(st.vols{volhandle}.roi.roi), V, 2);
[ero(1,:) ero(2,:) ero(3,:)] = ind2sub(st.vols{volhandle}.roi.Vroi.dim(1:3),...
find(V(:)>st.vols{volhandle}.roi.erothresh));
if strcmp(st.vols{volhandle}.roi.mode,'set')
toset = ero;
toclear = st.vols{volhandle}.roi.xyz;
else
toclear = ero;
end;
update_roi = 1;
case {'connect', 'cleanup'}
spm('pointer','watch');
[V L] = spm_bwlabel(double(st.vols{volhandle}.roi.roi),6);
sel = [];
switch cmd
case 'connect'
pos = round(inv(st.vols{volhandle}.roi.Vroi.mat)* ...
[spm_orthviews('pos'); 1]);
sel = V(pos(1),pos(2),pos(3));
if sel == 0
sel = [];
end;
case 'cleanup'
numV = zeros(1,L);
for k = 1:L
numV(k) = sum(V(:)==k);
end;
sel = find(numV>st.vols{volhandle}.roi.csize);
end;
if ~isempty(sel)
ind1 = cell(1,numel(sel));
for k=1:numel(sel)
ind1{k} = find(V(:) == sel(k));
end;
ind = cat(1,ind1{:});
conn = zeros(3,numel(ind));
[conn(1,:) conn(2,:) conn(3,:)] = ...
ind2sub(st.vols{volhandle}.roi.Vroi.dim(1:3),ind);
if strcmp(st.vols{volhandle}.roi.mode,'set')
toset = conn;
toclear = st.vols{volhandle}.roi.xyz;
else
toclear = conn;
end;
end;
update_roi = 1;
case 'invert'
spm('pointer','watch');
st.vols{volhandle}.roi.roi = ~st.vols{volhandle}.roi.roi;
ind = find(st.vols{volhandle}.roi.roi);
st.vols{volhandle}.roi.xyz = zeros(3,numel(ind));
[st.vols{volhandle}.roi.xyz(1,:), ...
st.vols{volhandle}.roi.xyz(2,:), ...
st.vols{volhandle}.roi.xyz(3,:)] = ind2sub(st.vols{volhandle}.roi.Vroi.dim(1:3),ind);
update_roi = 1;
case 'clear'
spm('pointer','watch');
st.vols{volhandle}.roi.roi = false(size(st.vols{volhandle}.roi.roi));
st.vols{volhandle}.roi.xyz=[];
update_roi = 1;
case 'addfile'
V = spm_vol(spm_select([1 Inf],'image','Image(s) to add'));
[x y z] = ndgrid(1:st.vols{volhandle}.roi.Vroi.dim(1),...
1:st.vols{volhandle}.roi.Vroi.dim(2),...
1:st.vols{volhandle}.roi.Vroi.dim(3));
xyzmm = st.vols{volhandle}.roi.Vroi.mat*[x(:)';y(:)';z(:)'; ...
ones(1, prod(st.vols{volhandle}.roi.Vroi.dim(1:3)))];
msk = false(1,prod(st.vols{volhandle}.roi.Vroi.dim(1:3)));
for k = 1:numel(V)
xyzvx = inv(V(k).mat)*xyzmm;
dat = spm_sample_vol(V(k), xyzvx(1,:), xyzvx(2,:), xyzvx(3,:), 0);
dat(~isfinite(dat)) = 0;
msk = msk | logical(dat);
end;
[tochange(1,:) tochange(2,:) tochange(3,:)] = ind2sub(st.vols{volhandle}.roi.Vroi.dim(1:3),find(msk));
clear xyzmm xyzvx msk
update_roi = 1;
case {'save','saveas'}
if strcmp(cmd,'saveas') || ...
exist(st.vols{volhandle}.roi.Vroi.fname, 'dir')
flt = {'*.nii','NIfTI (1 file)';'*.img','NIfTI (2 files)'};
[name pth idx] = uiputfile(flt, 'Output image');
if ~ischar(pth)
warning('spm:spm_ov_roi','Save cancelled');
return;
end;
[p n e v] = spm_fileparts(fullfile(pth,name));
if isempty(e)
e = flt{idx,1}(2:end);
end;
st.vols{volhandle}.roi.Vroi.fname = fullfile(p, [n e v]);
end;
spm('pointer','watch');
spm_write_vol(st.vols{volhandle}.roi.Vroi, ...
st.vols{volhandle}.roi.roi);
spm('pointer','arrow');
return;
case 'redraw'
% do nothing
return;
%-------------------------------------------------------------------------
% Context menu and callbacks
case 'context_menu'
item0 = uimenu(varargin{3}, 'Label', 'ROI tool');
item1 = uimenu(item0, 'Label', 'Launch', 'Callback', ...
sprintf('%s(''context_init'', %d);', mfilename, volhandle), ...
'Tag',sprintf('ROI_0_%d', volhandle));
item2 = uimenu(item0, 'Label', 'Selection mode', ...
'Visible', 'off', 'Tag', ['ROI_1_', num2str(volhandle)]);
item2_1a = uimenu(item2, 'Label', 'Set selection', 'Callback', ...
sprintf('%s(''context_selection'', %d, ''set'');', ...
mfilename, volhandle), ...
'Tag',sprintf('ROI_SELECTION_%d', volhandle), ...
'Checked','on');
item2_1b = uimenu(item2, 'Label', 'Clear selection', 'Callback', ...
sprintf('%s(''context_selection'', %d,''clear'');', ...
mfilename, volhandle), ...
'Tag', sprintf('ROI_SELECTION_%d', volhandle));
item3 = uimenu(item0, 'Label', 'Box size', 'Callback', ...
sprintf('%s(''context_box'', %d);', mfilename, volhandle), ...
'Visible', 'off', 'Tag',sprintf('ROI_1_%d', volhandle));
item4 = uimenu(item0, 'Label', 'Polygon slices', 'Callback', ...
sprintf('%s(''context_polyslices'', %d);', mfilename, volhandle), ...
'Visible','off', 'Tag', sprintf('ROI_1_%d', volhandle));
item5 = uimenu(item0, 'Label', 'Cluster size', 'Callback', ...
sprintf('%s(''context_csize'', %d);', mfilename, volhandle), ...
'Visible','off', 'Tag',sprintf('ROI_1_%d', volhandle));
item6 = uimenu(item0, 'Label', 'Erosion/Dilation threshold', 'Callback', ...
sprintf('%s(''context_erothresh'', %d);', mfilename, volhandle), ...
'Visible', 'off', 'Tag', sprintf('ROI_1_%d', volhandle));
item7 = uimenu(item0, 'Label', 'Edit tool', ...
'Visible','off', 'Tag',sprintf('ROI_1_%d', volhandle), ...
'Separator','on');
item7_1a = uimenu(item7, 'Label', 'Box tool', 'Callback', ...
sprintf('%s(''context_edit'', %d,''box'');', mfilename, volhandle), ...
'Tag',sprintf('ROI_EDIT_%d', volhandle), 'Checked','on');
item7_1b = uimenu(item7, 'Label', 'Polygon tool', 'Callback', ...
sprintf('%s(''context_edit'', %d,''poly'');', mfilename, volhandle), ...
'Tag',sprintf('ROI_EDIT_%d', volhandle));
item7_1c = uimenu(item7, 'Label', 'Connected cluster', 'Callback', ...
sprintf('%s(''context_edit'', %d,''connect'');', mfilename, volhandle), ...
'Tag',sprintf('ROI_EDIT_%d', volhandle));
item8 = uimenu(item0, 'Label', 'Threshold', 'Callback', ...
sprintf('%s(''context_thresh'', %d);', mfilename, volhandle), ...
'Visible','off', 'Tag',sprintf('ROI_1_%d', volhandle));
item10 = uimenu(item0, 'Label', 'Cleanup clusters', 'Callback', ...
sprintf('%s(''cleanup'', %d);', mfilename, volhandle), ...
'Visible','off', 'Tag',sprintf('ROI_1_%d', volhandle));
item11 = uimenu(item0, 'Label', 'Erode/Dilate', 'Callback', ...
sprintf('%s(''erodilate'', %d);', mfilename, volhandle), ...
'Visible','off', 'Tag',sprintf('ROI_1_%d', volhandle));
item12 = uimenu(item0, 'Label', 'Invert', 'Callback', ...
sprintf('%s(''invert'', %d);', mfilename, volhandle), ...
'Visible','off', 'Tag',sprintf('ROI_1_%d', volhandle));
item13 = uimenu(item0, 'Label', 'Clear', 'Callback', ...
sprintf('%s(''clear'', %d);', mfilename, volhandle), ...
'Visible','off', 'Tag',sprintf('ROI_1_%d', volhandle));
item14 = uimenu(item0, 'Label', 'Add ROI from file(s)', 'Callback', ...
sprintf('%s(''addfile'', %d);', mfilename, volhandle), ...
'Visible','off', 'Tag',sprintf('ROI_1_%d', volhandle));
item15 = uimenu(item0, 'Label', 'Save', 'Callback', ...
sprintf('%s(''save'', %d);', mfilename, volhandle), ...
'Visible','off', 'Tag',sprintf('ROI_1_%d', volhandle),...
'Separator','on');
item16 = uimenu(item0, 'Label', 'Save As', 'Callback', ...
sprintf('%s(''saveas'', %d);', mfilename, volhandle), ...
'Visible','off', 'Tag',sprintf('ROI_1_%d', volhandle));
item17 = uimenu(item0, 'Label', 'Quit', 'Callback', ...
sprintf('%s(''context_quit'', %d);', mfilename, volhandle), ...
'Visible','off', 'Tag',sprintf('ROI_1_%d', volhandle));
item18 = uimenu(item0, 'Label', 'Help', 'Callback', ...
sprintf('spm_help(''%s'');', mfilename));
% add some stuff outside ROI tool menu
iorient = findobj(st.vols{volhandle}.ax{1}.cm, 'Label', 'Orientation');
item19 = uimenu(iorient, 'Label', 'ROI Space', 'Callback', ...
sprintf('%s(''context_space'', %d);', mfilename, volhandle), ...
'Visible','off', 'Tag',sprintf('ROI_1_%d', volhandle));
return;
case 'context_init'
Finter = spm_figure('FindWin', 'Interactive');
spm_input('!DeleteInputObj',Finter);
loadasroi = spm_input('Initial ROI','!+1','m',{'ROI image',...
'ROI space definition', 'SPM result'},[1 0 2],1);
xyz = [];
switch loadasroi
case 1,
imfname = spm_select(1, 'image', 'Select ROI image');
case 0,
imfname = spm_select(1, 'image', 'Select image defining ROI space');
case 2,
[SPM, xSPM] = spm_getSPM;
xyz = xSPM.XYZ;
imfname = SPM.Vbeta(1).fname;
end;
spm_input('!DeleteInputObj',Finter);
feval('spm_ov_roi','init',volhandle,imfname,loadasroi,xyz);
return;
case 'context_selection'
st.vols{volhandle}.roi.mode = varargin{3};
obj = findobj(0, 'Tag', ['ROI_SELECTION_', num2str(volhandle)]);
set(obj, 'Checked', 'off');
set(gcbo, 'Checked', 'on');
return;
case 'context_edit'
st.vols{volhandle}.roi.tool = varargin{3};
obj = findobj(0, 'Tag', ['ROI_EDIT_', num2str(volhandle)]);
set(obj, 'Checked', 'off');
set(gcbo, 'Checked', 'on');
return;
case 'context_box'
Finter = spm_figure('FindWin', 'Interactive');
spm_input('!DeleteInputObj',Finter);
box = spm_input('Selection size {vx vy vz}','!+1','e', ...
num2str(st.vols{volhandle}.roi.box), [1 3]);
spm_input('!DeleteInputObj',Finter);
st.vols{volhandle}.roi.box = box;
return;
case 'context_polyslices'
Finter = spm_figure('FindWin', 'Interactive');
spm_input('!DeleteInputObj',Finter);
polyslices = spm_input('Polygon: slices around current slice','!+1','e', ...
num2str(st.vols{volhandle}.roi.polyslices), [1 1]);
spm_input('!DeleteInputObj',Finter);
st.vols{volhandle}.roi.polyslices = polyslices;
return;
case 'context_csize'
Finter = spm_figure('FindWin', 'Interactive');
spm_input('!DeleteInputObj',Finter);
csize = spm_input('Minimum cluster size (#vx)','!+1','e', ...
num2str(st.vols{volhandle}.roi.csize), [1 1]);
spm_input('!DeleteInputObj',Finter);
st.vols{volhandle}.roi.csize = csize;
return;
case 'context_erothresh'
Finter = spm_figure('FindWin', 'Interactive');
spm_input('!DeleteInputObj',Finter);
erothresh = spm_input('Erosion/Dilation threshold','!+1','e', ...
num2str(st.vols{volhandle}.roi.erothresh), [1 1]);
spm_input('!DeleteInputObj',Finter);
st.vols{volhandle}.roi.erothresh = erothresh;
return;
case 'context_space'
spm_orthviews('space', volhandle, ...
st.vols{volhandle}.roi.Vroi.mat, ...
st.vols{volhandle}.roi.Vroi.dim(1:3));
iorient = get(findobj(0,'Label','Orientation'),'children');
if iscell(iorient)
iorient = cell2mat(iorient);
end;
set(iorient, 'Checked', 'Off');
ioroi = findobj(iorient, 'Label','ROI space');
set(ioroi, 'Checked', 'On');
return;
case 'context_thresh'
Finter = spm_figure('FindWin', 'Interactive');
spm_input('!DeleteInputObj',Finter);
thresh = spm_input('Threshold {min max}','!+1','e', ...
num2str(st.vols{volhandle}.roi.thresh), [1 2]);
spm_input('!DeleteInputObj',Finter);
st.vols{volhandle}.roi.thresh = thresh;
feval('spm_ov_roi', 'thresh', volhandle);
return;
case 'context_quit'
obj = findobj(0, 'Tag', sprintf('ROI_1_%d', volhandle));
set(obj, 'Visible', 'off');
obj = findobj(0, 'Tag', sprintf('ROI_0_%d', volhandle));
set(obj, 'Visible', 'on');
spm_orthviews('rmblobs', volhandle);
for k=1:3
set(st.vols{volhandle}.ax{k}.ax,'ButtonDownFcn', st.vols{volhandle}.roi.cb{k});
end;
st.vols{volhandle} = rmfield(st.vols{volhandle}, 'roi');
spm_orthviews('redraw');
return;
case 'bdfcn'
if strcmpi(get(gcf,'SelectionType'), 'extend')
spm_orthviews('roi','edit',volhandle);
else
for k=1:3
if isequal(st.vols{volhandle}.ax{k}.ax, gca)
break;
end
end
feval(st.vols{volhandle}.roi.cb{k});
end
otherwise
fprintf('spm_orthviews(''roi'', ...): Unknown action %s', cmd);
return;
end;
if update_roi
if ~isempty(tochange) % change state according to mode
if strcmp(st.vols{volhandle}.roi.mode,'set')
toset = tochange;
else
toclear = tochange;
end;
end;
% clear first, then set (needed for connect operation)
if ~isempty(toclear)
itoclear = sub2ind(st.vols{volhandle}.roi.Vroi.dim(1:3), ...
toclear(1,:), toclear(2,:), toclear(3,:));
st.vols{volhandle}.roi.roi(itoclear) = false;
if ~isempty(st.vols{volhandle}.roi.xyz)
st.vols{volhandle}.roi.xyz = setdiff(st.vols{volhandle}.roi.xyz',toclear','rows')';
else
st.vols{volhandle}.roi.xyz = [];
end;
end;
if ~isempty(toset)
% why do we need this round()?? I don't know, but Matlab thinks
% it is necessary
itoset = round(sub2ind(st.vols{volhandle}.roi.Vroi.dim(1:3), ...
toset(1,:), toset(2,:), toset(3,:)));
st.vols{volhandle}.roi.roi(itoset) = true;
if ~isempty(st.vols{volhandle}.roi.xyz)
st.vols{volhandle}.roi.xyz = union(st.vols{volhandle}.roi.xyz',toset','rows')';
else
st.vols{volhandle}.roi.xyz = toset;
end;
end;
if isfield(st.vols{volhandle}, 'blobs')
nblobs=length(st.vols{volhandle}.blobs);
if nblobs>1
blobstmp(1:st.vols{volhandle}.roi.hroi-1) = st.vols{volhandle}.blobs(1:st.vols{volhandle}.roi.hroi-1);
blobstmp(st.vols{volhandle}.roi.hroi:nblobs-1) = st.vols{volhandle}.blobs(st.vols{volhandle}.roi.hroi+1:nblobs);
st.vols{volhandle}.blobs=blobstmp;
else
if isempty(st.vols{volhandle}.roi.hframe) % save frame
st.vols{volhandle}=rmfield(st.vols{volhandle},'blobs');
end;
end;
end;
if isfield(st.vols{volhandle}, 'blobs')
st.vols{volhandle}.roi.hroi = numel(st.vols{volhandle}.blobs)+1;
else
st.vols{volhandle}.roi.hroi = 1;
end;
if isempty(st.vols{volhandle}.roi.xyz) % initialised with empty roi
spm_orthviews('addcolouredblobs', volhandle, ...
[1; 1; 1], 0, st.vols{volhandle}.roi.Vroi.mat,[1 3 1]);
else
spm_orthviews('addcolouredblobs', volhandle, ...
st.vols{volhandle}.roi.xyz, ones(size(st.vols{volhandle}.roi.xyz,2),1), ...
st.vols{volhandle}.roi.Vroi.mat,[1 3 1]); % use color that is more intense than standard rgb range
end;
st.vols{volhandle}.blobs{st.vols{volhandle}.roi.hroi}.max=2;
spm_orthviews('redraw');
end;
spm('pointer','arrow');
function varargout = stack(cmd, varargin)
switch cmd
case 'init'
varargout{1}.st = cell(varargin{1},1);
varargout{1}.top= 0;
case 'isempty'
varargout{1} = (varargin{1}.top==0);
case 'push'
stck = varargin{1};
if (stck.top < size(stck.st,1))
stck.top = stck.top + 1;
stck.st{stck.top} = varargin{2};
varargout{1}=stck;
else
error('Stack overflow\n');
end;
case 'pop'
if stack('isempty',varargin{1})
error('Stack underflow\n');
else
varargout{2} = varargin{1}.st{varargin{1}.top};
varargin{1}.top = varargin{1}.top - 1;
varargout{1} = varargin{1};
end;
end;
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_sendmail.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/spm_cfg_sendmail.m
| 5,377 |
utf_8
|
202a73a362717243076b2289fd67484c
|
function sendmail = spm_cfg_sendmail
% SPM Configuration file for sendmail
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% $Id: spm_cfg_sendmail.m 2923 2009-03-23 18:34:51Z guillaume $
% ---------------------------------------------------------------------
% Recipient
% ---------------------------------------------------------------------
recipient = cfg_entry;
recipient.tag = 'recipient';
recipient.name = 'Recipient';
recipient.help = {'User to receive mail.'};
recipient.strtype = 's';
recipient.num = [1 Inf];
% ---------------------------------------------------------------------
% Subject
% ---------------------------------------------------------------------
subject = cfg_entry;
subject.tag = 'subject';
subject.name = 'Subject';
subject.val = {['[SPM] [%DATE%] On behalf of ' spm('Ver')]};
subject.help = {'The subject line of the message. %DATE% will be replaced by a string containing the time and date when the email is sent.'};
subject.strtype = 's';
subject.num = [1 Inf];
% ---------------------------------------------------------------------
% Message
% ---------------------------------------------------------------------
message = cfg_entry;
message.tag = 'message';
message.name = 'Message';
message.val = {'Hello from SPM!'};
message.help = {'A string containing the message to send.'};
message.strtype = 's';
message.num = [1 Inf];
% ---------------------------------------------------------------------
% Attachments
% ---------------------------------------------------------------------
attachments = cfg_files;
attachments.tag = 'attachments';
attachments.name = 'Attachments';
attachments.val{1} = {};
attachments.help = {'List of files to attach and send along with the message.'};
attachments.filter = '.*';
attachments.ufilter = '.*';
attachments.num = [0 Inf];
% ---------------------------------------------------------------------
% SMTP Server
% ---------------------------------------------------------------------
smtp = cfg_entry;
smtp.tag = 'smtp';
smtp.name = 'SMTP Server';
smtp.help = {'Your SMTP server. If not specified, look for sendmail help.'};
smtp.strtype = 's';
try
smtp.val = {getpref('Internet','SMTP_Server')};
end
smtp.num = [1 Inf];
% ---------------------------------------------------------------------
% E-mail
% ---------------------------------------------------------------------
email = cfg_entry;
email.tag = 'email';
email.name = 'E-mail';
email.help = {'Your e-mail address. Look in sendmail help how to store it.'};
email.strtype = 's';
try
email.val = {getpref('Internet','E_mail')};
end
email.num = [1 Inf];
% ---------------------------------------------------------------------
% Zip attachments
% ---------------------------------------------------------------------
zip = cfg_menu;
zip.tag = 'zip';
zip.name = 'Zip attachments';
zip.val = {'No'};
zip.help = {'Zip attachments before being sent along with the message.'};
zip.labels = {'Yes' 'No'}';
zip.values = {'Yes' 'No'}';
% ---------------------------------------------------------------------
% Parameters
% ---------------------------------------------------------------------
params = cfg_branch;
params.tag = 'params';
params.name = 'Parameters';
params.val = { smtp email zip};
params.help = {'Preferences for your e-mail server (Internet SMTP server) and your e-mail address. MATLAB tries to read the SMTP mail server from your system registry. This should work flawlessly. If you encounter any error, identify the outgoing mail server for your electronic mail application, which is usually listed in the application''s preferences, or, consult your e-mail system administrator, and update the parameters. Note that this function does not support e-mail servers that require authentication.'};
% ---------------------------------------------------------------------
% Sendmail
% ---------------------------------------------------------------------
sendmail = cfg_exbranch;
sendmail.tag = 'sendmail';
sendmail.name = 'Sendmail';
sendmail.val = { recipient subject message attachments params};
sendmail.help = {'Send a mail message (attachments optionals) to an address.'};
sendmail.prog = @spm_sendmail;
%_______________________________________________________________________
%_______________________________________________________________________
function spm_sendmail(job)
try
setpref('Internet','SMTP_Server',job.params.smtp);
setpref('Internet','E_mail',job.params.email);
subj = strrep(job.subject,'%DATE%',datestr(now));
mesg = strrep(job.message,'%DATE%',datestr(now));
mesg = [mesg 10 10 '-- ' 10 10 'Statistical Parametric Mapping'];
if ~isempty(job.attachments)
if strcmpi(job.params.zip,'Yes')
zipfile = fullfile(tempdir,'spm_sendmail.zip');
zip(zipfile,job.attachments);
job.attachments = {zipfile};
end
sendmail(job.recipient,subj,mesg,job.attachments);
else
sendmail(job.recipient,subj,mesg);
end
catch
%- not an error to prevent an analysis to crash because of just that...
fprintf('Sendmail failed...\n');
end
|
github
|
philippboehmsturm/antx-master
|
Neural_demo.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/Neural_Models/Neural_demo.m
| 4,316 |
utf_8
|
1266d6ca90e707c689e0ad1c471d8909
|
function varargout = Neural_demo(varargin)
% NEURAL_DEMO M-file for Neural_demo.fig
% NEURAL_DEMO, by itself, creates a new NEURAL_DEMO or raises the existing
% singleton*.
%
% H = NEURAL_DEMO returns the handle to a new NEURAL_DEMO or the handle to
% the existing singleton*.
%
% NEURAL_DEMO('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in NEURAL_DEMO.M with the given input arguments.
%
% NEURAL_DEMO('Property','Value',...) creates a new NEURAL_DEMO or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before Neural_demo_OpeningFunction gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to Neural_demo_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help Neural_demo
% Last Modified by GUIDE v2.5 09-Apr-2008 14:15:32
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @Neural_demo_OpeningFcn, ...
'gui_OutputFcn', @Neural_demo_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before Neural_demo is made visible.
function Neural_demo_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to Neural_demo (see VARARGIN)
% Choose default command line output for Neural_demo
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes Neural_demo wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = Neural_demo_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
function run_demo_Callback(hObject, handles, file)
h = help(file);
str{1} = [file ':'];
str{2} = '______________________________________________________________ ';
str{2} = ' ';
str{3} = h;
set(handles.help,'String',str);
drawnow
% get graphics handle
spm_figure('GetWin','MFM');
clf
eval(file)
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
run_demo_Callback(hObject, handles, 'spm_lfp_demo')
% --- Executes on button press in pushbutton15.
function pushbutton15_Callback(hObject, eventdata, handles)
run_demo_Callback(hObject, handles, 'spm_ind_demo')
% --- Executes on button press in pushbutton16.
function pushbutton16_Callback(hObject, eventdata, handles)
run_demo_Callback(hObject, handles, 'spm_mtf_demo')
% --- Executes on button press in pushbutton17.
function pushbutton17_Callback(hObject, eventdata, handles)
run_demo_Callback(hObject, handles, 'spm_csd_demo')
% --- Executes on button press in pushbutton18.
function pushbutton18_Callback(hObject, eventdata, handles)
run_demo_Callback(hObject, handles, 'spm_sigmoid_demo')
% --- Executes on button press in pushbutton19.
function pushbutton19_Callback(hObject, eventdata, handles)
run_demo_Callback(hObject, handles, 'spm_mfm_demo')
% --- Executes on button press in pushbutton20.
function pushbutton20_Callback(hObject, eventdata, handles)
run_demo_Callback(hObject, handles, 'spm_nested_oscillations_demo')
|
github
|
philippboehmsturm/antx-master
|
spm_freqs.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/Neural_Models/spm_freqs.m
| 3,737 |
utf_8
|
62139edd7cd9d8687d5af3ac86f25027
|
function [h,ww] = freqs(b,a,w)
%FREQS Laplace-transform (s-domain) frequency response.
% H = FREQS(B,A,W) returns the complex frequency response vector H
% of the filter B/A:
% nb-1 nb-2
% B(s) b(1)s + b(2)s + ... + b(nb)
% H(s) = ---- = -------------------------------------
% na-1 na-2
% A(s) a(1)s + a(2)s + ... + a(na)
%
% given the numerator and denominator coefficients in vectors B and A.
% The frequency response is evaluated at the points specified in
% vector W (in rad/s). The magnitude and phase can be graphed by
% calling FREQS(B,A,W) with no output arguments.
%
% [H,W] = FREQS(B,A) automatically picks a set of 200 frequencies W on
% which the frequency response is computed. FREQS(B,A,N) picks N
% frequencies.
%
% See also LOGSPACE, POLYVAL, INVFREQS, and FREQZ.
% Author(s): J.N. Little, 6-26-86
% T. Krauss, 3-19-93, default plots and frequency vector
% Copyright 1988-2004 The MathWorks, Inc.
% $Revision: 1.12.4.2 $ $Date: 2004/12/26 22:15:54 $
error(nargchk(2,3,nargin));
error(nargoutchk(0,2,nargout));
if ~any(size(b)<=1) || ~any(size(a)<=1),
error('The numerator and denominator must be vectors.');
end
if nargin == 2,
w = 200;
end
if length(w) == 1,
wlen = w;
w_long = freqint(b,a,wlen);
% need to interpolate long frequency vector:
xi = linspace(1,length(w_long),wlen).';
w = 10.^interp1(1:length(w_long),log10(w_long),xi,'linear');
end
s = j*w;
hh = polyval(b,s) ./ polyval(a,s);
if nargout == 0,
newplot;
mag = abs(hh); phase = angle(hh)*180/pi;
subplot(211),loglog(w,mag),set(gca,'xgrid','on','ygrid','on')
set(gca,'xlim',[w(1) w(length(w))])
xlabel('Frequency (rad/s)')
ylabel('Magnitude')
ax = gca;
subplot(212), semilogx(w,phase),set(gca,'xgrid','on','ygrid','on')
set(gca,'xlim',[w(1) w(length(w))])
xlabel('Frequency (rad/s)')
ylabel('Phase (degrees)')
axes(ax)
elseif nargout == 1,
h = hh;
elseif nargout == 2,
h = hh;
ww = w;
end
% end freqs
function w=freqint(a,b,c,d,npts)
%FREQINT Auto-ranging algorithm for Bode frequency response
% W=FREQINT(A,B,C,D,Npts)
% W=FREQINT(NUM,DEN,Npts)
% Andy Grace 7-6-90
% Was Revision: 1.9, Date: 1996/07/25 16:43:37
% Generate more points where graph is changing rapidly.
% Calculate points based on eigenvalues and transmission zeros.
na = size(a, 1);
if (nargin==3) && (na==1), % Transfer function form.
npts=c;
ep=roots(b);
tz=roots(a);
else % State space form
if nargin==3, npts=c; [a,b,c,d] = spm_tf2ss(a,b); end
ep=eig(a);
tz=tzero(a,b,c,d);
end
if isempty(ep), ep=-1000; end
% Note: this algorithm does not handle zeros greater than 1e5
ez=[ep(find(imag(ep)>=0));tz(find(abs(tz)<1e5&imag(tz)>=0))];
% Round first and last frequencies to nearest decade
integ = abs(ez)<1e-10; % Cater for systems with pure integrators
highfreq=round(log10(max(3*abs(real(ez)+integ)+1.5*imag(ez)))+0.5);
lowfreq=round(log10(0.1*min(abs(real(ez+integ))+2*imag(ez)))-0.5);
% Define a base range of frequencies
diffzp=length(ep)-length(tz);
w=logspace(lowfreq,highfreq,npts+diffzp+10*(sum(abs(imag(tz))<abs(real(tz)))>0));
ez=ez(imag(ez)>abs(real(ez)));
% Oscillatory poles and zeros
if ~isempty(ez)
f=w;
npts2=2+8/ceil(abs((diffzp+eps)/10));
[dum,ind]=sort(-abs(real(ez))); %#ok
z=[];
for i=ind'
r1=max([0.8*imag(ez(i))-3*abs(real(ez(i))),10^lowfreq]);
r2=1.2*imag(ez(i))+4*abs(real(ez(i)));
z=z(z>r2|z<r1);
f=f(f>r2|f<r1);
z=[z,logspace(log10(r1),log10(r2),sum(w<=r2&w>=r1)+npts2)];
end
w=sort([f,z]);
end
w = w(:);
% end freqint
|
github
|
philippboehmsturm/antx-master
|
spm_shoot_update.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/Shoot/spm_shoot_update.m
| 4,384 |
utf_8
|
effbd61be58eeeacba046cd940be6612
|
function [u0,ll1, ll2,grad_norm] = spm_shoot_update(g,f,u0,phi,dt,prm,int_args, bs_args,scale)
% Shooting Of Diffeomorphisms (Spawn Of Dartel).
% FORMAT u0 = spm_shoot_update(g,f,u0,phi,dt,prm,int_args, bs_args)
% g - template
% f - individual
% u0 - initial velocity
% phi - deformation
% dt - Jacobian determinants
% prm - Parameters of differential operator
% int_args - integration settings
% bs_args - interpolation settings
% scale - scaling of the update step
%
% u0 - updated initial velocity
% ll1 - matching part of objective function
% ll2 - regularisation part of objective function
% grad_norm - Norm of the 1st derivatives
%
% The easiest way to figure out what this function does is to read the code.
%________________________________________________________
% (c) Wellcome Trust Centre for NeuroImaging (2009)
% John Ashburner
% $Id: spm_shoot_update.m 4103 2010-10-28 15:43:16Z john $
if nargin<9, scale = 1.0; end
scale = max(min(scale,1.0),0.0);
d = [size(g{1}),1,1];
d = d(1:3);
if isempty(u0)
u0 = zeros([d,3],'single');
end
[ll1,b,A] = mnom_derivs(g,f,phi,dt, bs_args);
m0 = dartel3('vel2mom',u0,prm);
ll2 = 0.5*sum(sum(sum(sum(m0.*u0))));
var1 = sum(sum(sum(sum(b.^2))));
b = b + m0;
var2 = sum(sum(sum(sum(b.^2))));
grad_norm = sqrt(var2/prod(d));
fprintf('%-10.5g %-10.5g %-10.5g %-10.5g %-10.5g\n',...
ll1/prod(d), ll2/prod(d), (ll1+ll2)/prod(d),...
var2/(var1+eps), grad_norm);
u0 = u0 - scale*dartel3('fmg',A, b, [prm 3 2]);
clear A b
%=======================================================================
%=======================================================================
function [ll,b,A] = mnom_derivs(g,f,phi,dt, bs_args)
% Compute log-likelihood, first and second derivatives for multi-nomial matching
% FORMAT [ll,b,A] = mnom_derivs(g,f,phi,dt,bs_args)
% g - cell array of template B-spline coefficients
% f - cell array of individual subject data
% phi - deformation field
% dt - Jacobian determinants
% bs_args - B-spline arguments for sampling g. Defaults to [2 2 2 1 1 1] if
% not supplied.
%
% ll - log-likelihood
% b - first derivatives
% A - (approx) second derivatives (Fisher information)
%
%_______________________________________________________________________
% Copyright (C) 2009 Wellcome Trust Centre for Neuroimaging
if nargin<4,
bs_args = [2 2 2 1 1 1];
end
d = [size(g{1}),1,1];
d = d(1:3);
ll = 0;
b = zeros([d,3],'single');
A = zeros([d,6],'single');
[id{1},id{2},id{3}] = ndgrid(1:d(1),1:d(2),ceil(bs_args(3)/2)+1);
for z=1:d(3),
ind = z+(-ceil(bs_args(3)/2):ceil(bs_args(3)/2));
if bs_args(6), ind = rem(ind-1+d(3),d(3))+1; end
f1 = cell(size(f));
for k=1:numel(g),
% Note the fudge with the indexing because spm_bsplins only works for double.
[g1,d1,d2,d3] = spm_bsplins(double(g{k}(:,:,ind)),id{:},bs_args);
slice(k) = struct('mu',exp(g1),'d1',d1,'d2',d2,'d3',d3);
if isempty(phi)
f1{k} = f{k}(:,:,z);
else
f1{k} = dartel3('samp',f{k},phi(:,:,z,:));
end
end
s = zeros(d(1:2));
for k=1:numel(g), s = s + slice(k).mu; end
for k=1:numel(g), slice(k).mu = slice(k).mu./s; end
b(:,:,z,:) = 0;
A(:,:,z,:) = 0;
for k=1:numel(g),
tmp = f1{k}.*log(slice(k).mu);
ll = ll - sum(tmp(:));
tmp = f1{k} - slice(k).mu.*dt(:,:,z);
b(:,:,z,1) = b(:,:,z,1) + tmp.*slice(k).d1;
b(:,:,z,2) = b(:,:,z,2) + tmp.*slice(k).d2;
b(:,:,z,3) = b(:,:,z,3) + tmp.*slice(k).d3;
for k1=1:numel(g),
if k1~=k,
tmp = -slice(k).mu.*slice(k1).mu.*dt(:,:,z);
else
tmp = max(slice(k).mu.*(1-slice(k1).mu),0).*dt(:,:,z);
end
A(:,:,z,1) = A(:,:,z,1) + tmp.*slice(k).d1.*slice(k1).d1;
A(:,:,z,2) = A(:,:,z,2) + tmp.*slice(k).d2.*slice(k1).d2;
A(:,:,z,3) = A(:,:,z,3) + tmp.*slice(k).d3.*slice(k1).d3;
A(:,:,z,4) = A(:,:,z,4) + tmp.*slice(k).d1.*slice(k1).d2;
A(:,:,z,5) = A(:,:,z,5) + tmp.*slice(k).d1.*slice(k1).d3;
A(:,:,z,6) = A(:,:,z,6) + tmp.*slice(k).d2.*slice(k1).d3;
end
end
end
|
github
|
philippboehmsturm/antx-master
|
spm_shoot3di.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/Shoot/spm_shoot3di.m
| 6,901 |
utf_8
|
4db8d50018ee6679cfb375dc8e01c81c
|
function varargout = spm_shoot3di(v0,prm,args)
% Geodesic shooting
% FORMAT [theta,Jtheta,v1,phi,Jphi] = spm_shoot3di(v0,prm,args)
% v0 - Initial velocity field n1*n2*n3*3 (single prec. float)
% prm - 7 Differential operator parameter settings
% - [1] Regularisation type (ie the form of the differential
% operator), can take values of
% - 0 Linear elasticity
% - 1 Membrane energy
% - 2 Bending energy
% - [2][3][4] Voxel sizes
% - [5][6][7] Regularisation parameters
% - For "membrane energy", the parameters are
% lambda, unused and id.
% - For "linear elasticity", the parameters are
% mu, lambda, and id
% - For "bending energy", the parameters are
% lambda, id1 and id2.
% args - Integration parameters
% - [1] Num time steps
% - [2][3] Multigrid parameters (cycles and iterations)
% for generating velocities from momentum
%
% theta - Inverse deformation field n1*n2*n3*3 (single prec. float)
% Jtheta - Inverse Jacobian tensors n1*n2*n3 (single prec. float)
% v1 - Final velocity field n1*n2*n3*3 (single prec. float)
% phi - Forward deformation field n1*n2*n3*3 (single prec. float)
% Jphi - Forward Jacobian tensors n1*n2*n3 (single prec. float)
%
% This code generates deformations and their Jacobian determinans from
% initial velocity fields by gedesic shooting. See the work of Miller,
% Younes and others.
%
% LDDMM (Beg et al) uses the following evolution equation:
% d\phi/dt = v_t(\phi_t)
% where a variational procedure is used to find the stationary solution
% for the time varying velocity field.
% In principle though, once the initial velocity is known, then the
% velocity at subsequent time points can be computed. This requires
% initial momentum (m_0), computed (using differential operator L) by:
% m_0 = L v_0
% Then (Ad_{\phi_t})^* m_0 is computed:
% m_t = |d \phi_t| (d\phi_t)^T m_0(\phi_t)
% The velocity field at this time point is then obtained by using
% multigrid to solve:
% v_t = L^{-1} m_t
%
% These equations can be found in:
% Younes (2007). "Jacobi fields in groups of diffeomorphisms and
% applications". Quarterly of Applied Mathematics, vol LXV,
% number 1, pages 113-134 (2007).
%
% Multigrid is currently used to obtain v_t = L^{-1} m_t, but
% this could also be done by convolution with the Greens function
% N = L^{-1} (see e.g. Bro-Nielson).
%
%________________________________________________________
% (c) Wellcome Trust Centre for NeuroImaging (2009)
% John Ashburner
% $Id: spm_shoot3di.m 4026 2010-07-29 13:45:50Z john $
args0 = [8 4 4];
if nargin<3,
args = args0;
else
if numel(args)<numel(args0),
args = [args args0((numel(args)+1):end)];
end
end
verb = false;
N = args(1); % # Time steps
fmg_args = args(2:3); % Multigrid params
d = size(v0);
d = d(1:3);
vt = v0;
if ~isfinite(N),
% Number of time steps from an educated guess about how far to move
N = double(floor(sqrt(max(max(max(v0(:,:,:,1).^2+v0(:,:,:,2).^2+v0(:,:,:,3).^2)))))+1);
end
if verb, fprintf('N=%g:', N); end
m0 = dartel3('vel2mom',v0,prm); % Initial momentum (m_0 = L v_0)
if verb, fprintf('\t%g', 0.5*sum(v0(:).*m0(:))/prod(d)); end
% Compute initial small deformation and Jacobian matrices from the velocity.
% The overall deformation and its Jacobian tensor field is generated by
% composing a series of small deformations.
[theta,Jtheta] = dartel3('smalldef', vt,-1/N);
% If required, also compute the forward and possibly also its Jacobian
% tensor field. Note that the order of the compositions will be the
% reverse of those for building the forward deformation.
if nargout>=5,
[ phi, Jphi] = dartel3('smalldef', vt,1/N);
elseif nargout>=4,
phi = dartel3('smalldef', vt,1/N);
end
for t=2:abs(N),
mt = pullg(m0,theta,Jtheta);
vt = mom2vel(mt,prm,fmg_args,vt);
if verb, fprintf('\t%g', 0.5*sum(vt(:).*mt(:))/prod(d)); end
[ dp, dJ] = dartel3('smalldef', vt,-1/N); % Small deformation
[theta,Jtheta] = dartel3('comp', theta,dp, Jtheta,dJ); % Build up large def. from small defs
clear dp dJ
% If required, build up forward deformation and its Jacobian tensor field from
% small deformations
if nargout>=5,
[ dp,dJ] = dartel3('smalldef', vt,1/N); % Small deformation
[phi, Jphi] = dartel3('comp', dp, phi, dJ, Jphi); % Build up large def. from small defs
clear dp dJ
elseif nargout>=4,
dp = dartel3('smalldef', vt,1/N); % Small deformation
phi = dartel3('comp', dp, phi); % Build up large def. from small defs
clear dp
end
drawnow
end
if verb, fprintf('\n'); end
varargout{1} = theta;
varargout{2} = Jtheta;
if nargout>=3,
mt = pullg(m0,theta,Jtheta);
varargout{3} = mom2vel(mt,prm,fmg_args,vt);
end
if nargout>=4, varargout{4} = phi; end
if nargout>=5, varargout{5} = Jphi; end
%__________________________________________________________________________________
%__________________________________________________________________________________
function vt = mom2vel(mt,prm,fmg_args,vt)
% L^{-1} m_t
r = dartel3('vel2mom',vt,prm);
vt = dartel3('mom2vel', mt-r, [prm fmg_args])+vt;
if false,
% Go for machine precision
r = dartel3('vel2mom',vt,prm);
ss = sum(sum(sum(sum((mt-r).^2))));
for i=1:8,
oss = ss;
vt = dartel3('mom2vel', mt-r, [prm fmg_args])+vt;
r = dartel3('vel2mom',vt,prm);
ss = sum(sum(sum(sum((mt-r).^2))));
if ss/oss>0.9, break; end
end
end
%__________________________________________________________________________________
%__________________________________________________________________________________
function mt = pullg(m0,phi,J)
% The Ad* operation
mt = zeros(size(m0),'single');
for i=1:size(m0,3),
phii = phi(:,:,i,:);
mr1 = dartel3('samp',m0(:,:,:,1), phii);
mr2 = dartel3('samp',m0(:,:,:,2), phii);
mr3 = dartel3('samp',m0(:,:,:,3), phii);
dj = J(:,:,i,1,1).*(J(:,:,i,2,2).*J(:,:,i,3,3)-J(:,:,i,2,3).*J(:,:,i,3,2))...
+J(:,:,i,2,1).*(J(:,:,i,1,3).*J(:,:,i,3,2)-J(:,:,i,1,2).*J(:,:,i,3,3))...
+J(:,:,i,3,1).*(J(:,:,i,1,2).*J(:,:,i,2,3)-J(:,:,i,1,3).*J(:,:,i,2,2));
mt(:,:,i,1) = (J(:,:,i,1,1).*mr1 + J(:,:,i,2,1).*mr2 + J(:,:,i,3,1).*mr3).*dj;
mt(:,:,i,2) = (J(:,:,i,1,2).*mr1 + J(:,:,i,2,2).*mr2 + J(:,:,i,3,2).*mr3).*dj;
mt(:,:,i,3) = (J(:,:,i,1,3).*mr1 + J(:,:,i,2,3).*mr2 + J(:,:,i,3,3).*mr3).*dj;
end
%__________________________________________________________________________________
%__________________________________________________________________________________
|
github
|
philippboehmsturm/antx-master
|
spm_shoot_template.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/Shoot/spm_shoot_template.m
| 11,515 |
utf_8
|
a1f2b9608195d776adafa0fdb535d298
|
function out = spm_shoot_template(job)
% Iteratively compute a template with mean shape and intensities
% format spm_shoot_template(job)
% Fields of job:
% job.images{1} first set of images (eg rc1*.nii)
% job.images{2} second set of images (eg rc2*.nii)
% etc
%
% Other settings are defined in spm_shoot_defaults.m
%
% The outputs are flow fields (v*.nii), deformation fields (y*.nii)
% and a series of Template images.
%_______________________________________________________________________
% Copyright (C) Wellcome Trust Centre for Neuroimaging (2009)
% John Ashburner
% $Id: spm_shoot_template.m 4324 2011-05-06 11:29:30Z john $
%_______________________________________________________________________
d = spm_shoot_defaults;
tname = d.tname; % Base file name for templates
issym = d.issym; % Use a symmetric template
cyc_its = d.cyc_its; % No. multigrid cycles and inerations
smits = d.smits; % No. smoothing iterations
sched = d.sched; % Schedule for coarse to fine
nits = numel(sched)-1;
rparam = d.rparam; % Regularisation parameters for deformation
sparam = d.sparam; % Regularisation parameters for blurring
eul_its = d.eul_its; % Start with fewer steps
bs_args = d.bs_args; % B-spline settings for interpolation
%_______________________________________________________________________
% Sort out handles to images
n1 = numel(job.images);
n2 = numel(job.images{1});
NF = struct('NI',[],'vn',[1 1]);
NF(n1,n2) = struct('NI',[],'vn',[1 1]);
% Pick out individual volumes within NIfTI files
for i=1:n1,
if numel(job.images{i}) ~= n2,
error('Incompatible number of images');
end;
for j=1:n2,
[pth,nam,ext,num] = spm_fileparts(job.images{i}{j});
NF(i,j).NI = nifti(fullfile(pth,[nam ext]));
num = [str2num(num) 1 1];
NF(i,j).vn = num(1:2);
end;
end;
spm_progress_bar('Init',n2,'Initial mean','Subjects done');
dm = [size(NF(1,1).NI.dat) 1];
dm = dm(1:3);
NU = nifti;
NU(n2) = nifti;
NY = nifti;
NY(n2) = nifti;
NJ = nifti;
NJ(n2) = nifti;
t = zeros([dm n1+1],'single');
for i=1:n2,
% Generate files for flow fields, deformations and Jacobian determinants.
[pth,nam,ext] = fileparts(NF(1,i).NI.dat.fname);
NU(i) = nifti;
NY(i) = nifti;
NJ(i) = nifti;
offs = 352;
if ~isempty(tname),
NU(i).dat = file_array(fullfile(pth,['v_' nam '_' tname '.nii']),...
[dm 1 3], 'float32-le', 352, 1, 0);
NY(i).dat = file_array(fullfile(pth,['y_' nam '_' tname '.nii']),...
[dm 1 3], 'float32-le', 352, 1, 0);
NJ(i).dat = file_array(fullfile(pth,['j_' nam '_' tname '.nii']),...
[dm 1 1], 'float32-le', 352, 1, 0);
else
NU(i).dat = file_array(fullfile(pth,['v_' nam '.nii']),...
[dm 1 3], 'float32-le', 352, 1, 0);
NY(i).dat = file_array(fullfile(pth,['y_' nam '.nii']),...
[dm 1 3], 'float32-le', 352, 1, 0);
NJ(i).dat = file_array(fullfile(pth,['y_' nam '.nii']),...
[dm 1 1], 'float32-le', 352, 1, 0);
end
NU(i).descrip = sprintf('Velocity (%d %.4g %.4g %.4g)', rparam(1), rparam(2), rparam(3), rparam(4));
NU(i).mat = NF(1,i).NI.mat;
NU(i).mat0 = NF(1,i).NI.mat0;
NY(i).descrip = 'Deformation (templ. to. ind.)';
NY(i).mat = NF(1,i).NI.mat;
NJ(i).descrip = 'Jacobian det (templ. to. ind.)';
NJ(i).mat = NF(1,i).NI.mat;
create(NU(i)); NU(i).dat(:,:,:,:,:) = 0;
create(NY(i)); NY(i).dat(:,:,:,:,:) = reshape(affind(dartel3('Exp',zeros([dm,3],'single'),[0 1]),NU(i).mat0),[dm,1,3]);
create(NJ(i)); NJ(i).dat(:,:,:) = 1;
% Add to sufficient statistics for generating initial template
for j=1:n1,
vn = NF(j,i).vn;
dat = NF(j,i).NI.dat(:,:,:,vn(1),vn(2));
msk = isfinite(dat);
dat(~msk) = 0;
t(:,:,:,j) = t(:,:,:,j) + dat;
end;
t(:,:,:,end) = t(:,:,:,end) + msk;
clear tmp msk
spm_progress_bar('Set',i);
end;
spm_progress_bar('Clear');
% Make symmetric (if necessary)
if issym, t = t + t(end:-1:1,:,:,:); end
% Generate template from sufficient statistics
tmp = t(:,:,:,end);
msk = tmp<=0;
for j=1:n1,
tmp = tmp - t(:,:,:,j);
end
tmp(msk) = 0.01; % Most NaNs are likely to be background
t(:,:,:,end) = tmp;
clear tmp msk
M = NF(1,1).NI.mat;
vx = sqrt(sum(M(1:3,1:3).^2));
t = max(t,0);
g = cell(n1+1,1);
%%%%%%%%%%%%%%%
% save SuffStats0.mat t sparam vx sched smits
%%%%%%%%%%%%%%%
if ~isempty(sparam),
g0 = spm_shoot_blur(t,[sparam(1), vx, sched(1)*sparam(2) sparam(3:4)],smits);
for j=1:n1+1,
g{j} = max(g0(:,:,:,j),1e-4);
end
clear g0
else
sumt = max(sum(t,4),0)+eps;
for j=1:n1+1,
g{j} = (t(:,:,:,j)+0.1)./(sumt+0.1*(n1+1));
end
clear sumt
end
if ~isempty(tname),
% Write template
NG = NF(1,1).NI;
NG.descrip = sprintf('Avg of %d', n2);
[tdir,nam,ext] = fileparts(job.images{1}{1});
NG.dat.fname = fullfile(tdir,[tname, '_0.nii']);
NG.dat.dim = [dm n1+1];
NG.dat.dtype = 'float32-le';
NG.dat.scl_slope = 1;
NG.dat.scl_inter = 0;
NG.mat0 = NG.mat;
create(NG);
for j=1:n1+1,
NG.dat(:,:,:,j) = g{j};
end
end
for j=1:n1+1, g{j} = spm_bsplinc(log(g{j}), bs_args); end
vx = sqrt(sum(NG.mat(1:3,1:3).^2));
ok = true(n2,1);
% The actual work
for it=1:nits,
% More regularisation in the early iterations, as well as a
% a less accurate approximation in the integration.
prm = [rparam(1), vx, rparam(2:3)*sched(it+1), rparam(4)];
int_args = [eul_its(it), cyc_its];
drawnow
t = zeros([dm n1+1],'single');
su = zeros([dm 3]);
% Update velocities
spm_progress_bar('Init',n2,sprintf('Update velocities (%d)',it),'Subjects done');
for i=1:n2, % Loop over subjects
if ok(i)
fprintf(' %-3d %-5d\t| ',it,i);
% Load image data for this subject
f = loadimage(NF(:,i));
% Load this subject's flow field and deformation
u = squeeze(single(NU(i).dat(:,:,:,:,:)));
y = affind(squeeze(single(NY(i).dat(:,:,:,:,:))),inv(NU(i).mat0));
dt = squeeze(single(NJ(i).dat(:,:,:)));
drawnow
% Gauss-Newton iteration to re-estimate deformations for this subject
u = spm_shoot_update(g,f,u,y,dt,prm,int_args,bs_args);
clear f y
drawnow
NU(i).dat(:,:,:,:,:) = reshape(u,[dm 1 3]);
su = su + u;
clear u
spm_progress_bar('Set',i);
end
end
spm_progress_bar('Clear');
if issym
su(:,:,:,1) = (su(:,:,:,1) - su(end:-1:1,:,:,1) )/(sum(ok)*2);
su(:,:,:,2:3) = (su(:,:,:,2:3) + su(end:-1:1,:,:,2:3))/(sum(ok)*2);
else
su = su/sum(ok);
end
% Update template sufficient statistics
spm_progress_bar('Init',n2,sprintf('Update deformations and template (%d)',it),'Subjects done');
for i=1:n2, % Loop over subjects
if ok(i)
% Load velocity, mean adjust and re-save
u = squeeze(single(NU(i).dat(:,:,:,:,:)));
u = u - su; % Subtract mean
NU(i).dat(:,:,:,:,:) = reshape(u,[dm 1 3]);
% Generate inverse deformation and save
[y,J] = spm_shoot3d(u,prm,int_args);
clear u
dt = dartel3('det',J); clear J
if any(~isfinite(dt(:)) | dt(:)>100 | dt(:)<1/100)
ok(i) = false;
fprintf('Problem with %s (dets: %g .. %g)\n', NU(i).dat.fname, min(dt(:)), max(dt(:)));
clear dt
end
end
if ok(i)
NY(i).dat(:,:,:,:,:) = reshape(affind(y,NU(i).mat0),[dm 1 3]);
NJ(i).dat(:,:,:) = dt;
drawnow;
% Load image data for this subject
f = loadimage(NF(:,i));
% Increment sufficient statistic for template
for j=1:n1+1,
tmp = dartel3('samp',f{j},y);
t(:,:,:,j) = t(:,:,:,j) + tmp.*dt;
drawnow
end;
clear f y dt
fprintf('.');
spm_progress_bar('Set',i);
end
end
clear su
fprintf('\n');
spm_progress_bar('Clear');
% Make symmetric (if necessary)
if issym, t = t + t(end:-1:1,:,:,:); end
%%%%%%%%%%%%%%%
% save(['SuffStats' num2str(it) '.mat'],'t', 'sparam', 'vx', 'sched', 'smits', 'g');
%%%%%%%%%%%%%%%
% Re-generate template data from sufficient statistics
if ~isempty(sparam),
g0 = reconv(g,bs_args);
g0 = spm_shoot_blur(t,[sparam(1), vx, sched(it+1)*sparam(2) sparam(3:4)],smits,g0);
g = cell(n1+1,1);
for j=1:n1+1,
g{j} = max(g0(:,:,:,j),1e-4);
end
clear g0
else
sumt = max(sum(t,4),0)+eps;
for j=1:n1+1,
g{j} = (t(:,:,:,j)+0.1)./(sumt+0.1*(n1+1));
end
clear sumt
end
clear t
% Write template
if ~isempty(tname),
NG.dat.fname = fullfile(tdir,[tname '_' num2str(ceil(it/6)) '.nii']);
create(NG);
for j=1:n1+1,
NG.dat(:,:,:,j) = g{j};
end
end
% Compute template's B-spline coefficients
for j=1:n1+1, g{j} = spm_bsplinc(log(g{j}), bs_args); end
drawnow
end
if any(~ok)
fprintf('Problems with:\n');
for i=find(~ok)',
fprintf('\t%s\n', NU(i).dat.fname);
end
end
% Finish off
[tdir,nam,ext] = fileparts(job.images{1}{1});
out.template = cell(floor(nits/3)+1,1);
if ~isempty(tname),
for it=0:floor(nits/3),
fname = fullfile(tdir,[tname '_' num2str(it) '.nii']);
out.template{it+1} = fname;
end
end
out.vel = cell(n2,1);
out.def = cell(n2,1);
out.jac = cell(n2,1);
for i=1:n2,
out.vel{i} = NU(i).dat.fname;
out.def{i} = NY(i).dat.fname;
out.jac{i} = NJ(i).dat.fname;
end
%=======================================================================
%=======================================================================
function y1 = affind(y0,M)
% Affine transform of deformation
y1 = zeros(size(y0),'single');
for d=1:3,
y1(:,:,:,d) = y0(:,:,:,1)*M(d,1) + y0(:,:,:,2)*M(d,2) + y0(:,:,:,3)*M(d,3) + M(d,4);
end
%=======================================================================
%=======================================================================
function g0 = reconv(g,bs_args)
d = [size(g{1}), 1];
[i1,i2,i3]=ndgrid(1:d(1),1:d(2),1:d(3));
g0 = zeros([d,numel(g)],'single');
for k=1:numel(g),
g0(:,:,:,k) = max(exp(spm_bsplins(g{k},i1,i2,i3,bs_args)),1e-4);
end
%=======================================================================
%=======================================================================
function f = loadimage(NF)
n1 = size(NF,1);
f = cell(n1+1,1);
dm = [NF(1).NI.dat.dim 1 1 1];
dm = dm(1:3);
f{n1+1} = ones(dm,'single');
for j=1:n1,
vn = NF(j,1).vn;
f{j} = single(NF(j,1).NI.dat(:,:,:,vn(1),vn(2)));
msk = ~isfinite(f{j});
f{j}(msk) = 0;
f{n1+1} = f{n1+1} - f{j};
drawnow
end
f{n1+1}(msk) = 0.00001;
%=======================================================================
%=======================================================================
|
github
|
philippboehmsturm/antx-master
|
spm_shoot_blur.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/Shoot/spm_shoot_blur.m
| 6,581 |
utf_8
|
44fc0c3ca2a43f6ffcd3af5a35660c45
|
function [sig,a] = spm_shoot_blur(t,prm,its,sig)
% A function for blurring ("smoothing") tissue probability maps
% FORMAT [sig,a_new] = spm_shoot_blur(t,prm,its,sig)
% t - sufficient statistics
% prm - regularisation parameters (2, 1,1,1, 1,0.01,0.01)
% its - max no. iterations (12)
% sig - optional starting estimates
%
% sig - "smoothed" average
% a - parameters
%
% The core of this procedure is described in:
% John Ashburner & Karl J. Friston.
% "Computing Average Shaped Tissue Probability Templates"
% NeuroImage, In Press, Accepted Manuscript, Available online 24 December 2008
%
% However, there is an additional modification such that the the null space
% of the parameters is rotated out.
%________________________________________________________
% (c) Wellcome Trust Centre for NeuroImaging (2009)
% John Ashburner
% $Id: spm_shoot_blur.m 4174 2011-01-26 13:33:13Z john $
d = [size(t),1,1,1];
if nargin<3, its = 16; end; % Maximum no. iterations
if nargin<2, prm = [2, 1,1,1, 1,0.01,0.01]; end; % Default regularisation
rits = [1 1]; % No. cycles and no. relaxation iterations
W = zeros([d(1:3) round(((d(4)-1)*d(4))/2)],'single'); % 2nd derivatives
gr = zeros([d(1:3),d(4)-1],'single'); % 1st derivatives
% Re-organise sufficient statistics to a form that is easier to work with
t = max(t,eps('single')*1000);
s = sum(t,4);
for k=1:d(4),
t(:,:,:,k) = t(:,:,:,k)./s;
end
maxs = max(s(:)); % Used for scaling the regularisation
prm(end) = prm(end)+maxs*d(4)*1e-3;
% Only d(4)-1 fields need to be estimated because sum(a,4) = 0. This matrix
% is used to rotate out the null space
R = null(ones(1,d(4)));
% Initial starting estimates (if sig is passed)
a = zeros([d(1:3),d(4)-1],'single');
if nargin>=4,
for z=1:d(3), % Loop over planes
sz = sig(:,:,z,:);
sz = min(max(sig,0),1);
sz(~isfinite(sz)) = 1/d(4);
sz = squeeze(log(double(sz*(1-d(4)*1e-3)+1e-3)));
for j1=1:(d(4)-1),
az = zeros(d(1:2));
for j2=1:d(4),
az = az + R(j2,j1)*sz(:,:,j2); % Note the rotation
end
a(:,:,z,j1) = az;
end
clear sz az
end
end
for i=1:its,
ll = 0;
for z=1:d(3), % Loop over planes
% Compute softmax for this plane
sig = double(reshape(sftmax(a(:,:,z,:),R),[d(1:2),d(4)]));
% -ve log likelihood of the likelihood
ll = ll - sum(sum(sum(log(sig).*reshape(t(:,:,z,:),[d(1:2),d(4)]),3).*s(:,:,z)));
% Compute first derivatives (d(4)-1) x 1
grz = sig - double(reshape(t(:,:,z,:),[d(1:2),d(4)]));
for j1=1:(d(4)-1),
gr(:,:,z,j1) = 0;
for j2=1:d(4),
gr(:,:,z,j1) = gr(:,:,z,j1) + R(j2,j1)*grz(:,:,j2); % Note the rotation
end
gr(:,:,z,j1) = gr(:,:,z,j1).*s(:,:,z);
end
% Compute d(4) x d(4) matrix of second derivatives at each voxel.
% These should be positive definate, but rounding errors may prevent this.
% Regularisation is included to enforce +ve definateness.
wz = zeros([d(1:2),d(4),d(4)]);
for j1=1:d(4),
wz(:,:,j1,j1) = (1-sig(:,:,j1)).*sig(:,:,j1).*s(:,:,z);
for j2=1:(j1-1),
wz(:,:,j1,j2) = -sig(:,:,j1) .*sig(:,:,j2).*s(:,:,z);
wz(:,:,j2,j1) = wz(:,:,j1,j2);
end
end
% First step of rotating 2nd derivatives to (d(4)-1) x (d(4)-1)
% by R'*W*R
wz1 = zeros([d(1:2),d(4),d(4)-1]);
for j1=1:d(4),
for j2=1:(d(4)-1),
tmp = zeros(d(1:2));
for j3=1:d(4),
tmp = tmp + wz(:,:,j1,j3)*R(j3,j2);
end
wz1(:,:,j1,j2) = tmp;
end
end
% Second step of rotating 2nd derivatives to (d(4)-1) x (d(4)-1)
% by R'*W*R
wz = zeros([d(1:2),d(4)-1,d(4)-1]);
for j1=1:(d(4)-1),
for j2=1:(d(4)-1),
tmp = zeros(d(1:2));
for j3=1:d(4),
tmp = tmp + R(j3,j1)*wz1(:,:,j3,j2);
end
wz(:,:,j1,j2) = tmp;
end
end
% First pull out the diagonal of the 2nd derivs
for j1=1:d(4)-1,
W(:,:,z,j1) = wz(:,:,j1,j1);% + maxs*sqrt(eps('single'))*d(4)^2;
end
% Then pull out the off diagonal parts (note that matrices are symmetric)
jj = d(4);
for j1=1:d(4)-1,
for j2=(j1+1):(d(4)-1),
W(:,:,z,jj) = wz(:,:,j2,j1);
jj = jj+1;
end
end
end
% ss1 and ss2 are for examining how close the 1st derivatives are to zero.
% At convergence, the derivatives from the likelihood term should match those
% from the prior (regularisation) term.
ss1 = sum(sum(sum(sum(gr.^2))));
gr1 = optimN('vel2mom',a,prm); % 1st derivative of the prior term
ll1 = 0.5*sum(sum(sum(sum(gr1.*a)))); % -ve log probability of the prior term
gr = gr + gr1; % Combine the derivatives of the two terms
ss2 = sum(sum(sum(sum(gr.^2)))); % This should approach zero at convergence
mx = max(max(max(sum(gr.^2,4))));
fprintf('%d\t%g\t%g\t%g\t%g\t%g\t%g\n', i, ll/prod(d(1:3)),ll1/prod(d(1:3)), (ll+ll1)/prod(d(1:3)), ss2/ss1, mx, ss2/prod(d(1:3)));
reg = double(0.1*sqrt(mx)*d(4));
%reg = double(0.1*sqrt(ss2/prod(d(1:3))));
a = a - optimN(W,gr,[prm(1:6) prm(7)+reg rits]); % Gauss-Newton update
if ss2/ss1<1e-4, break; end % Converged?
end
sig = sftmax(a,R);
%________________________________________________________
%________________________________________________________
function sig = sftmax(a,R)
% Softmax function
d = [size(a) 1 1 1];
sig = zeros([d(1:3),d(4)+1],'single');
trunc = log(realmax('single')*(1-eps('single'))/(d(4)+1));
for j=1:size(a,3), % Loop over planes
% Rotate the null-space back in to the data
aj = double(reshape(a(:,:,j,:),[d(1:2),d(4)]));
sj = zeros([d(1:2),d(4)+1]);
for j1=1:d(4)+1,
sj(:,:,j1) = 0;
for j2=1:d(4),
sj(:,:,j1) = sj(:,:,j1) + R(j1,j2)*aj(:,:,j2);
end
end
% Compute softmax
sj = min(max(sj,-trunc),trunc);
sj = exp(sj)+eps('single')*(d(4)+1);
s = sum(sj,3);
for i=1:d(4)+1,
sig(:,:,j,i) = single(sj(:,:,i)./s);
end
end
%________________________________________________________
|
github
|
philippboehmsturm/antx-master
|
spm_shoot3d.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/Shoot/spm_shoot3d.m
| 6,488 |
utf_8
|
7f1ca5842f35b820190834c523353944
|
function varargout = spm_shoot3d(v0,prm,args)
% Geodesic shooting
% FORMAT [phi,Jphi,v1,theta,Jtheta] = spm_shoot3d(v0,prm,args)
% v0 - Initial velocity field n1*n2*n3*3 (single prec. float)
% prm - Differential operator parameters
% prm - 7 parameters (settings)
% - [1] Regularisation type (ie the form of the differential
% operator), can take values of
% - 0 Linear elasticity
% - 1 Membrane energy
% - 2 Bending energy
% - [2][3][4] Voxel sizes
% - [5][6][7] Regularisation parameters
% - For "membrane energy", the parameters are
% lambda, unused and id.
% - For "linear elasticity", the parameters are
% mu, lambda, and id
% - For "bending energy", the parameters are
% lambda, id1 and id2.
% args - Integration parameters
% - [1] Num time steps
% - [2][3] Multigrid parameters (cycles and iterations)
% for generating velocities from momentum
%
% phi - Forward deformation field n1*n2*n3*3 (single prec. float)
% Jphi - Forward Jacobian tensors n1*n2*n3 (single prec. float)
% v1 - Final velocity field n1*n2*n3*3 (single prec. float)
% theta - Inverse deformation field n1*n2*n3*3 (single prec. float)
% Jtheta - Inverse Jacobian tensors n1*n2*n3 (single prec. float)
%
% This code generates deformations and their Jacobian determinans from
% initial velocity fields by gedesic shooting. See the work of Miller,
% Younes and others.
%
% LDDMM (Beg et al) uses the following evolution equation:
% d\phi/dt = v_t(\phi_t)
% where a variational procedure is used to find the stationary solution
% for the time varying velocity field.
% In principle though, once the initial velocity is known, then the
% velocity at subsequent time points can be computed. This requires
% initial momentum (m_0), computed (using differential operator L) by:
% m_0 = L v_0
% Then (Ad_{\phi_t})^* m_0 is computed:
% m_t = |d \phi_t| (d\phi_t)^T m_0(\phi_t)
% The velocity field at this time point is then obtained by using
% multigrid to solve:
% v_t = L^{-1} m_t
%
% These equations can be found in:
% Younes (2007). "Jacobi fields in groups of diffeomorphisms and
% applications". Quarterly of Applied Mathematics, vol LXV,
% number 1, pages 113-134 (2007).
%
% Note that in practice, (Ad_{\phi_t})^* m_0 is computed differently,
% by multiplying the initial momentum by the inverse of the Jacobian
% matrices of the inverse warp, and pushing the values to their new
% location by the inverse warp (see the "pushg" code of dartel3).
% Multigrid is currently used to obtain v_t = L^{-1} m_t, but
% this could also be done by convolution with the Greens function
% K = L^{-1} (see e.g. Bro-Nielson).
%
%________________________________________________________
% (c) Wellcome Trust Centre for NeuroImaging (2009)
% John Ashburner
% $Id: spm_shoot3d.m 4026 2010-07-29 13:45:50Z john $
args0 = [8 4 4];
if nargin<3,
args = args0;
else
if numel(args)<numel(args0),
args = [args args0((numel(args)+1):end)];
end
end
verb = false;
N = args(1); % # Time steps
fmg_args = args(2:3); % Multigrid params
d = size(v0);
d = d(1:3);
vt = v0;
if ~isfinite(N),
% Number of time steps from an educated guess about how far to move
N = double(floor(sqrt(max(max(max(v0(:,:,:,1).^2+v0(:,:,:,2).^2+v0(:,:,:,3).^2)))))+1);
end
if verb, fprintf('N=%g:', N); end
m0 = dartel3('vel2mom',v0,prm); % Initial momentum (m_0 = L v_0)
if verb, fprintf('\t%g', 0.5*sum(v0(:).*m0(:))/prod(d)); end
% Compute initial small deformation and Jacobian matrices from the velocity.
% The overall deformation and its Jacobian tensor field is generated by
% composing a series of small deformations.
[ phi, Jphi] = dartel3('smalldef', vt,1/N);
% If required, also compute the forward and possibly also its Jacobian
% tensor field. Note that the order of the compositions will be the
% reverse of those for building the forward deformation.
if nargout>=5,
[theta,Jtheta] = dartel3('smalldef', vt,-1/N);
elseif nargout>=4,
theta = dartel3('smalldef', vt,-1/N);
end
for t=2:abs(N),
mt = dartel3('pushg',m0,phi,Jphi);
vt = mom2vel(mt,prm,fmg_args,vt);
if verb, fprintf('\t%g', 0.5*sum(vt(:).*mt(:))/prod(d)); end
[ dp, dJ] = dartel3('smalldef', vt,1/N); % Small deformation
[ phi, Jphi] = dartel3('comp', dp, phi, dJ, Jphi); % Build up large def. from small defs
clear dp dJ
% If required, build up forward deformation and its Jacobian tensor field from
% small deformations
if nargout>=5,
[ dp, dJ] = dartel3('smalldef', vt,-1/N); % Small deformation
[theta,Jtheta] = dartel3('comp', theta,dp, Jtheta,dJ); % Build up large def. from small defs
clear dp dJ
elseif nargout>=4,
dp = dartel3('smalldef', vt,-1/N); % Small deformation
theta = dartel3('comp', theta, dp); % Build up large def. from small defs
clear dp
end
drawnow
end
if verb, fprintf('\n'); end
varargout{1} = phi;
varargout{2} = Jphi;
if nargout>=3,
mt = dartel3('pushg',m0,phi,Jphi);
varargout{3} = mom2vel(mt,prm,fmg_args,vt);
end
if nargout>=4, varargout{4} = theta; end
if nargout>=5, varargout{5} = Jtheta; end
%__________________________________________________________________________________
%__________________________________________________________________________________
function vt = mom2vel(mt,prm,fmg_args,vt)
% L^{-1} m_t
r = dartel3('vel2mom',vt,prm);
if prm(1) == 0,
% This option has been coded up in C
vt = dartel3('mom2vel', mt-r, [prm fmg_args])+vt;
else
% This option has not been coded in C yet, so needs to be
% done in a less efficient way
dm = size(mt);
H = zeros([dm(1:3),6],'single');
vt = dartel3('fmg',H,mt-r, [prm fmg_args])+vt;
end
if false,
% Go for machine precision
r = dartel3('vel2mom',vt,prm);
ss = sum(sum(sum(sum((mt-r).^2))));
for i=1:8,
oss = ss;
vt = dartel3('mom2vel', mt-r, [prm fmg_args])+vt;
r = dartel3('vel2mom',vt,prm);
ss = sum(sum(sum(sum((mt-r).^2))));
if ss/oss>0.9, break; end
end
end
%__________________________________________________________________________________
%__________________________________________________________________________________
|
github
|
philippboehmsturm/antx-master
|
tbx_cfg_shoot.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/Shoot/tbx_cfg_shoot.m
| 38,664 |
utf_8
|
0fd083d5d34a604dfcaeb7f4cd3568d1
|
function shoot = tbx_cfg_shoot
% MATLABBATCH Configuration file for toolbox 'Shoot Tools'
% $Id: tbx_cfg_shoot.m 4136 2010-12-09 22:22:28Z guillaume $
addpath(fullfile(spm('dir'),'toolbox','DARTEL'));
addpath(fullfile(spm('dir'),'toolbox','Shoot'));
% ---------------------------------------------------------------------
% images Images
% ---------------------------------------------------------------------
images1 = cfg_files;
images1.tag = 'images';
images1.name = 'Images';
images1.help = {'Select a set of imported images of the same type to be registered by minimising a measure of difference from the template.'};
images1.filter = 'image';
images1.ufilter = '^r.*';
images1.num = [1 Inf];
% ---------------------------------------------------------------------
% images Images
% ---------------------------------------------------------------------
images = cfg_repeat;
images.tag = 'images';
images.name = 'Images';
images.help = {'Select the images to be warped together. Multiple sets of images can be simultaneously registered. For example, the first set may be a bunch of grey matter images, and the second set may be the white matter images of the same subjects.'};
images.values = {images1};
images.val = {images1};
images.num = [1 Inf];
% ---------------------------------------------------------------------
% warp Run Shoot (create Templates)
% ---------------------------------------------------------------------
warp = cfg_exbranch;
warp.tag = 'warp';
warp.name = 'Run Shooting (create Templates)';
warp.val = {images };
warp.help = {'Run the geodesic shooting nonlinear image registration procedure. This involves iteratively matching all the selected images to a template generated from their own mean. A series of Template*.nii files are generated, which become increasingly crisp as the registration proceeds.'};
warp.prog = @spm_shoot_template;
% ---------------------------------------------------------------------
% images Images
% ---------------------------------------------------------------------
images1 = cfg_files;
images1.tag = 'images';
images1.name = 'Images';
images1.help = {'Select a set of imported images of the same type to be registered by minimising a measure of difference from the template.'};
images1.filter = 'image';
images1.ufilter = '^r.*';
images1.num = [1 Inf];
% ---------------------------------------------------------------------
% images Images
% ---------------------------------------------------------------------
images = cfg_repeat;
images.tag = 'images';
images.name = 'Images';
images.help = {'Select the images to be warped together. Multiple sets of images can be simultaneously registered. For example, the first set may be a bunch of grey matter images, and the second set may be the white matter images of the same subjects.'};
images.values = {images1 };
images.num = [1 Inf];
% ---------------------------------------------------------------------
% rform Regularisation Form
% ---------------------------------------------------------------------
rform = cfg_menu;
rform.tag = 'rform';
rform.name = 'Regularisation Form';
rform.val = {0};
rform.help = {'The registration is penalised by some ``energy'''' term. Here, the form of this energy term is specified. Three different forms of regularisation can currently be used.'};
rform.labels = {
'Linear Elastic Energy'
'Membrane Energy'
'Bending Energy'
}';
rform.values = {0 1 2};
% ---------------------------------------------------------------------
% template Template
% ---------------------------------------------------------------------
template = cfg_files;
template.tag = 'templates';
template.name = 'Templates';
template.help = {'Select templates. Smoother templates should be used for the early iterations. Note that the template should be a 4D file, with the 4th dimension equal to the number of sets of images.'};
template.filter = 'nifti';
template.ufilter = '.*';
template.num = [1 Inf];
% ---------------------------------------------------------------------
% warp1 Run Shooting (existing Templates)
% ---------------------------------------------------------------------
warp1 = cfg_exbranch;
warp1.tag = 'warp1';
warp1.name = 'Run Shoot (existing Templates)';
warp1.val = {images template };
warp1.check = @check_shoot_template;
warp1.help = {'Run the Shoot nonlinear image registration procedure to match individual images to pre-existing template data. Start out with smooth templates, and select crisp templates for the later iterations.'};
%warp1.prog = @spm_shoot_warp;
%warp1.vout = @vout_shoot_warp;
% ---------------------------------------------------------------------
% velocities Velocity fields
% ---------------------------------------------------------------------
velocities = cfg_files;
velocities.tag = 'velocities';
velocities.name = 'Velocity fields';
velocities.help = {'The velocity fields store the deformation information. The same fields can be used for both forward or backward deformations (or even, in principle, half way or exaggerated deformations).'};
velocities.filter = 'nifti';
velocities.ufilter = '^v_.*';
velocities.num = [1 Inf];
% ---------------------------------------------------------------------
% images Images
% ---------------------------------------------------------------------
images1 = cfg_files;
images1.tag = 'images';
images1.name = 'Images';
images1.help = {'Select images to be warped. Note that there should be the same number of images as there are velocity fields, such that each velocity field warps one image.'};
images1.filter = 'nifti';
images1.ufilter = '.*';
images1.num = [1 Inf];
% ---------------------------------------------------------------------
% images Images
% ---------------------------------------------------------------------
images = cfg_repeat;
images.tag = 'images';
images.name = 'Images';
images.help = {'The velocity field deformations can be applied to multiple images. At this point, you are choosing how many images each velocity field should be applied to.'};
images.values = {images1 };
images.num = [1 Inf];
% ---------------------------------------------------------------------
% See later
% ---------------------------------------------------------------------
many_subj = cfg_branch;
many_subj.tag = 'subjs';
many_subj.name = 'Many Subjects';
many_subj.val = {velocities,images};
many_subj.help = {[...
'Select this option if you have many subjects to spatially normalise, ',...
'but there are a small and fixed number of scans for each subject.']};
% ---------------------------------------------------------------------
% jactransf Modulation
% ---------------------------------------------------------------------
jactransf = cfg_menu;
jactransf.tag = 'jactransf';
jactransf.name = 'Modulation';
jactransf.val = {0};
jactransf.help = {'This allows the spatially normalised images to be rescaled by the Jacobian determinants of the deformations. Note that the rescaling is only approximate for deformations generated using smaller numbers of time steps.'};
jactransf.labels = {
'Pres. Concentration (No "modulation")'
'Pres. Amount ("Modulation")'
}';
jactransf.values = {0 1};
% ---------------------------------------------------------------------
% interp Interpolation
% ---------------------------------------------------------------------
interp = cfg_menu;
interp.tag = 'interp';
interp.name = 'Interpolation';
interp.val = {1};
interp.help = {
'The method by which the images are sampled when being written in a different space.'
' Nearest Neighbour: - Fastest, but not normally recommended.'
' Bilinear Interpolation: - OK for PET, or realigned fMRI.'
' B-spline Interpolation: - Better quality (but slower) interpolation/* \cite{thevenaz00a}*/, especially with higher degree splines. Do not use B-splines when there is any region of NaN or Inf in the images. '
}';
interp.labels = {
'Nearest neighbour'
'Trilinear'
'2nd Degree B-spline'
'3rd Degree B-Spline '
'4th Degree B-Spline '
'5th Degree B-Spline'
'6th Degree B-Spline'
'7th Degree B-Spline'
}';
interp.values = {0 1 2 3 4 5 6 7};
% ---------------------------------------------------------------------
% crt_warped Create Warped
% ---------------------------------------------------------------------
crt_warped = cfg_exbranch;
crt_warped.tag = 'crt_warped';
crt_warped.name = 'Create Warped';
crt_warped.val = {velocities images jactransf interp };
crt_warped.check = @check_norm;
crt_warped.help = {'This allows spatially normalised images to be generated. Note that voxel sizes and bounding boxes can not be adjusted, and that there may be strange effects due to the boundary conditions used by the warping. Also note that the warped images are not in Talairach or MNI space. The coordinate system is that of the average shape and size of the subjects to which Shoot was applied. In order to have MNI-space normalised images, then the Deformations Utility can be used to compose the individual Shoot warps, with a deformation field that matches (e.g.) the Template grey matter generated by Shoot, with one of the grey matter volumes released with SPM.'};
%crt_warped.prog = @spm_shoot_norm;
%crt_warped.vout = @vout_norm;
% ---------------------------------------------------------------------
% velocities Velocity fields
% ---------------------------------------------------------------------
velocities = cfg_files;
velocities.tag = 'velocities';
velocities.name = 'Velocity fields';
velocities.help = {'The velocity fields store the deformation information. The same fields can be used for both forward or backward deformations (or even, in principle, half way or exaggerated deformations).'};
velocities.filter = 'nifti';
velocities.ufilter = '^v_.*';
velocities.num = [1 Inf];
% ---------------------------------------------------------------------
% jacdet Jacobian determinants
% ---------------------------------------------------------------------
jacdet = cfg_exbranch;
jacdet.tag = 'jacdet';
jacdet.name = 'Jacobian determinants';
jacdet.val = {velocities};
jacdet.help = {'Create Jacobian determinant fields from velocities.'};
%jacdet.prog = @spm_shoot_jacobian;
%jacdet.vout = @vout_jacdet;
% ---------------------------------------------------------------------
% velocities Velocity fields
% ---------------------------------------------------------------------
velocities = cfg_files;
velocities.tag = 'velocities';
velocities.name = 'Velocity fields';
velocities.help = {'The velocity fields store the deformation information. The same fields can be used for both forward or backward deformations (or even, in principle, half way or exaggerated deformations).'};
velocities.filter = 'nifti';
velocities.ufilter = '^v_.*';
velocities.num = [1 Inf];
% ---------------------------------------------------------------------
% images Images
% ---------------------------------------------------------------------
images = cfg_files;
images.tag = 'images';
images.name = 'Images';
images.help = {'Select the image(s) to be inverse normalised. These should be in alignment with the template image generated by the warping procedure.'};
images.filter = 'nifti';
images.ufilter = '.*';
images.num = [1 Inf];
% ---------------------------------------------------------------------
% interp Interpolation
% ---------------------------------------------------------------------
interp = cfg_menu;
interp.tag = 'interp';
interp.name = 'Interpolation';
interp.val{1} = double(1);
interp.help = {
'The method by which the images are sampled when being written in a different space.'
' Nearest Neighbour: - Fastest, but not normally recommended.'
' Bilinear Interpolation: - OK for PET, or realigned fMRI.'
' B-spline Interpolation: - Better quality (but slower) interpolation/* \cite{thevenaz00a}*/, especially with higher degree splines. Do not use B-splines when there is any region of NaN or Inf in the images. '
}';
interp.labels = {
'Nearest neighbour'
'Trilinear'
'2nd Degree B-spline'
'3rd Degree B-Spline '
'4th Degree B-Spline '
'5th Degree B-Spline'
'6th Degree B-Spline'
'7th Degree B-Spline'
}';
interp.values = {0 1 2 3 4 5 6 7};
% ---------------------------------------------------------------------
% crt_iwarped Create Inverse Warped
% ---------------------------------------------------------------------
crt_iwarped = cfg_exbranch;
crt_iwarped.tag = 'crt_iwarped';
crt_iwarped.name = 'Create Inverse Warped';
crt_iwarped.val = {velocities images interp };
crt_iwarped.help = {'Create inverse normalised versions of some image(s). The image that is inverse-normalised should be in alignment with the template (generated during the warping procedure). Note that the results have the same dimensions as the ``velocity fields'''', but are mapped to the original images via the affine transformations in their headers.'};
%crt_iwarped.prog = @spm_shoot_invnorm;
%crt_iwarped.vout = @vout_invnorm;
% ---------------------------------------------------------------------
%
% ---------------------------------------------------------------------
velocityfield = cfg_files;
velocityfield.tag = 'velocityfield';
velocityfield.name = 'Flow Field';
velocityfield.filter = 'nifti';
velocityfield.ufilter = '^v_.*\.nii$';
velocityfield.num = [1 1];
velocityfield.help = {'Shoot velocity field for this subject.'};
% ---------------------------------------------------------------------
%
% ---------------------------------------------------------------------
images = cfg_files;
images.tag = 'images';
images.name = 'Images';
images.filter = 'nifti';
images.num = [1 Inf];
images.help = {'Images for this subject to spatially normalise.'};
% ---------------------------------------------------------------------
%
% ---------------------------------------------------------------------
subj = cfg_branch;
subj.tag = 'subj';
subj.name = 'Subject';
subj.val = {velocityfield,images};
subj.help = {'Subject to be spatially normalized.'};
% ---------------------------------------------------------------------
%
% ---------------------------------------------------------------------
few_subj = cfg_repeat;
few_subj.tag = 'few_subj';
few_subj.name = 'Few Subjects';
few_subj.values = {subj};
few_subj.help = {[...
'Select this option if there are only a few subjects, each with many or ',...
'a variable number of scans each. You will then need to specify a series of subjects, and the velocity field and images of each of them.']};
% ---------------------------------------------------------------------
%
% ---------------------------------------------------------------------
way = cfg_choice;
way.tag = 'data';
way.name = 'Select according to';
way.values = {few_subj,many_subj};
way.help = {...
['You may wish to spatially normalise only a few subjects, '...
'but have many scans per subject (eg for fMRI), '...
'or you may have lots of subjects, but with a small and fixed number '...
'of scans for each of them (eg for VBM). The idea is to chose the way of '...
'selecting files that is easier.']};
% ---------------------------------------------------------------------
%
% ---------------------------------------------------------------------
template = cfg_files;
template.tag = 'template';
template.name = 'Shoot Template';
template.filter = 'nifti';
template.num = [0 1];
template.help = {...
['Select the final Template file generated by Shoot. This will be affine '...
'registered with a TPM file, such that the resulting spatially normalised '...
'images are closer aligned to MNI space. Leave empty if you do not wish to '...
'incorporate a transform to MNI space '...
'(ie just click ``done'' on the file selector, without selecting any images).']};
% ---------------------------------------------------------------------
%
% ---------------------------------------------------------------------
fwhm = cfg_entry;
fwhm.tag = 'fwhm';
fwhm.name = 'Gaussian FWHM';
fwhm.val = {[8 8 8]};
fwhm.strtype = 'e';
fwhm.num = [1 3];
fwhm.help = {'Specify the full-width at half maximum (FWHM) of the Gaussian blurring kernel in mm. Three values should be entered, denoting the FWHM in the x, y and z directions. Note that you can also specify [0 0 0], but any ``modulated'' data will show aliasing (see eg Wikipedia), which occurs because of the way the warped images are generated.'};
% ---------------------------------------------------------------------
%
% ---------------------------------------------------------------------
preserve = cfg_menu;
preserve.tag = 'preserve';
preserve.name = 'Preserve';
preserve.help = {
'Preserve Concentrations: Smoothed spatially normalised images (sw*) represent weighted averages of the signal under the smoothing kernel, approximately preserving the intensities of the original images. This option is currently suggested for eg fMRI.'
''
'Preserve Total: Smoothed and spatially normalised images preserve the total amount of signal from each region in the images (smw*). Areas that are expanded during warping are correspondingly reduced in intensity. This option is suggested for VBM.'
}';
preserve.labels = {
'Preserve Concentrations (no "modulation")'
'Preserve Amount ("modulation")'
}';
preserve.values = {0 1};
preserve.val = {0};
% ---------------------------------------------------------------------
%
% ---------------------------------------------------------------------
vox = cfg_entry;
vox.tag = 'vox';
vox.name = 'Voxel sizes';
vox.num = [1 3];
vox.strtype = 'e';
vox.def = @(val)spm_get_defaults('defs.vox',val{:});
vox.help = {[...
'Specify the voxel sizes of the deformation field to be produced. ',...
'Non-finite values will default to the voxel sizes of the template image',...
'that was originally used to estimate the deformation.']};
% ---------------------------------------------------------------------
%
% ---------------------------------------------------------------------
bb = cfg_entry;
bb.tag = 'bb';
bb.name = 'Bounding box';
bb.strtype = 'e';
bb.num = [2 3];
bb.def = @(val)spm_get_defaults('defs.bb',val{:});
bb.help = {[...
'Specify the bounding box of the deformation field to be produced. ',...
'Non-finite values will default to the bounding box of the template image',...
'that was originally used to estimate the deformation.']};
% ---------------------------------------------------------------------
%
% ---------------------------------------------------------------------
nrm = cfg_exbranch;
nrm.tag = 'mni_norm';
nrm.name = 'Normalise to MNI Space';
nrm.val = {template,way,vox,bb,preserve,fwhm};
%nrm.prog = @spm_shoot_norm_fun;
%nrm.vout = @vout_norm_fun;
%nrm.check = @check_norm_fun;
nrm.help = {[...
'Normally, Shoot generates warped images that align with the average-shaped template. ',...
'This routine includes an initial affine regisration of the template (the final one ',...
'generated by Shoot), with the TPM data released with SPM.'],[...
'``Smoothed'''' (blurred) spatially normalised images are generated in such a ',...
'way that the original signal is preserved. Normalised images are ',...
'generated by a ``pushing'''' rather than a ``pulling'''' (the usual) procedure. ',...
'Note that trilinear interpolation is used, and no masking is done. It ',...
'is therefore essential that the images are realigned and resliced ',...
'before they are spatially normalised. Alternatively, contrast images ',...
'generated from unsmoothed native-space fMRI/PET data can be spatially ',...
'normalised for a 2nd level analysis.'],[...
'Two ``preserve'''' options are provided. One of them should do the ',...
'equavalent of generating smoothed ``modulated'''' spatially normalised ',...
'images. The other does the equivalent of smoothing the modulated ',...
'normalised fMRI/PET, and dividing by the smoothed Jacobian determinants.']};
% ---------------------------------------------------------------------
% images Images
% ---------------------------------------------------------------------
images1 = cfg_files;
images1.tag = 'images';
images1.name = 'Images';
images1.help = {'Select tissue class images (one per subject).'};
images1.filter = 'nifti';
images1.ufilter = '^r.*c';
images1.num = [1 Inf];
% ---------------------------------------------------------------------
% images Images
% ---------------------------------------------------------------------
images = cfg_repeat;
images.tag = 'images';
images.name = 'Images';
images.help = {'Multiple sets of images are used here. For example, the first set may be a bunch of grey matter images, and the second set may be the white matter images of the same subjects. The number of sets of images must be the same as was used to generate the template.'};
images.values = {images1 };
images.num = [1 Inf];
% ---------------------------------------------------------------------
% velocities Velocity fields
% ---------------------------------------------------------------------
velocities = cfg_files;
velocities.tag = 'velocities';
velocities.name = 'Velocity fields';
velocities.help = {'Select the velocity fields for each subject.'};
velocities.filter = 'nifti';
velocities.ufilter = '^v_.*';
velocities.num = [1 Inf];
% ---------------------------------------------------------------------
% template Template
% ---------------------------------------------------------------------
template = cfg_files;
template.tag = 'template';
template.name = 'Template';
template.help = {'Residual differences are computed between the warped images and template.'};
template.filter = 'nifti';
template.ufilter = '^Template.*';
template.num = [0 1];
% ---------------------------------------------------------------------
% fwhm Smoothing
% ---------------------------------------------------------------------
fwhm = cfg_menu;
fwhm.tag = 'fwhm';
fwhm.name = 'Smoothing';
fwhm.val = {4};
fwhm.help = {'The residuals can be smoothed with a Gaussian to reduce dimensionality. More smoothing is recommended if there are fewer training images.'};
fwhm.labels = {
'None'
' 2mm'
' 4mm'
' 6mm'
' 8mm'
'10mm'
'12mm'
'14mm'
'16mm'
}';
fwhm.values = {0 2 4 6 8 10 12 14 16};
% ---------------------------------------------------------------------
% resids Generate Residuals
% ---------------------------------------------------------------------
resids = cfg_exbranch;
resids.tag = 'resids';
resids.name = 'Generate Residuals';
resids.val = {images velocities template fwhm };
resids.check = @check_resids;
resids.help = {'Generate residual images in a form suitable for computing a Fisher kernel. In principle, a Gaussian Process model can be used to determine the optimal (positive) linear combination of kernel matrices. The idea would be to combine the kernel from the residuals, with a kernel derived from the velocity-fields. Such a combined kernel should then encode more relevant information than the individual kernels alone.'};
%resids.prog = @spm_shoot_resids;
%resids.vout = @vout_resids;
% ---------------------------------------------------------------------
% images Data
% ---------------------------------------------------------------------
images = cfg_files;
images.tag = 'images';
images.name = 'Data';
images.help = {'Select images to generate dot-products from.'};
images.filter = 'nifti';
images.ufilter = '.*';
images.num = [1 Inf];
% ---------------------------------------------------------------------
% weight Weighting image
% ---------------------------------------------------------------------
weight = cfg_files;
weight.tag = 'weight';
weight.name = 'Weighting image';
weight.val = {{}};
weight.help = {'The kernel can be generated so that some voxels contribute to the similarity measures more than others. This is achieved by supplying a weighting image, which each of the component images are multiplied before the dot-products are computed. This image needs to have the same dimensions as the component images, but orientation information (encoded by matrices in the headers) is ignored. If left empty, then all voxels are weighted equally.'};
weight.filter = 'image';
weight.ufilter = '.*';
weight.num = [0 1];
% ---------------------------------------------------------------------
% dotprod Dot-product Filename
% ---------------------------------------------------------------------
dotprod = cfg_entry;
dotprod.tag = 'dotprod';
dotprod.name = 'Dot-product Filename';
dotprod.help = {'Enter a filename for results (it will be prefixed by ``dp_'''' and saved in the current directory).'};
dotprod.strtype = 's';
dotprod.num = [1 Inf];
% ---------------------------------------------------------------------
% reskern Kernel from Resids
% ---------------------------------------------------------------------
reskern = cfg_exbranch;
reskern.tag = 'reskern';
reskern.name = 'Kernel from Images';
reskern.val = {images weight dotprod };
reskern.help = {'Generate a kernel matrix from images. In principle, this same function could be used for generating kernels from any image data (e.g. ``modulated'''' grey matter). If there is prior knowledge about some region providing more predictive information (e.g. the hippocampi for AD), then it is possible to weight the generation of the kernel accordingly. The matrix of dot-products is saved in a variable ``Phi'''', which can be loaded from the dp_*.mat file. The ``kernel trick'''' can be used to convert these dot-products into distance measures for e.g. radial basis-function approaches.'};
%reskern.prog = @spm_shoot_dotprods;
% ---------------------------------------------------------------------
% velocities Velocity fields
% ---------------------------------------------------------------------
velocities = cfg_files;
velocities.tag = 'velocities';
velocities.name = 'Velocity fields';
velocities.help = {'Select the velocity fields for each subject.'};
velocities.filter = 'nifti';
velocities.ufilter = '^v_.*';
velocities.num = [1 Inf];
% ---------------------------------------------------------------------
% dotprod Dot-product Filename
% ---------------------------------------------------------------------
dotprod = cfg_entry;
dotprod.tag = 'dotprod';
dotprod.name = 'Dot-product Filename';
dotprod.help = {'Enter a filename for results (it will be prefixed by ``dp_'''' and saved in the current directory.'};
dotprod.strtype = 's';
dotprod.num = [1 Inf];
% ---------------------------------------------------------------------
% velkern Kernel from Flows
% ---------------------------------------------------------------------
velkern = cfg_exbranch;
velkern.tag = 'velkern';
velkern.name = 'Kernel from velocities';
velkern.val = {velocities dotprod};
velkern.help = {'Generate a kernel from velocity fields. The dot-products are saved in a variable ``Phi'''' in the resulting dp_*.mat file.'};
velkern.prog = @spm_shoot_kernel;
% ---------------------------------------------------------------------
% kernfun Kernel Utilities
% ---------------------------------------------------------------------
kernfun = cfg_choice;
kernfun.tag = 'kernfun';
kernfun.name = 'Kernel Utilities';
kernfun.help = {
'Shoot can be used for generating matrices of dot-products for various kernel pattern-recognition procedures.'
'The idea of applying pattern-recognition procedures is to obtain a multi-variate characterisation of the anatomical differences among groups of subjects. These characterisations can then be used to separate (eg) healthy individuals from particular patient populations. There is still a great deal of methodological work to be done, so the types of kernel that can be generated here are unlikely to be the definitive ways of proceeding. They are only just a few ideas that may be worth trying out. The idea is simply to attempt a vaguely principled way to combine generative models with discriminative models (see the ``Pattern Recognition and Machine Learning'''' book by Chris Bishop for more ideas). Better ways (higher predictive accuracy) will eventually emerge.'
'Various pattern recognition algorithms are available freely over the Internet. Possible approaches include Support-Vector Machines, Relevance-Vector machines and Gaussian Process Models. Gaussian Process Models probably give the most accurate probabilistic predictions, and allow kernels generated from different pieces of data to be most easily combined.'
}';
kernfun.values = {velkern};
% ---------------------------------------------------------------------
% shoot Shoot Tools
% ---------------------------------------------------------------------
shoot = cfg_choice;
shoot.tag = 'shoot';
shoot.name = 'Shoot Tools';
shoot.help = {
'This toolbox is based around the ``Diffeomorphic Registration using Geodesic Shooting and Gauss-Newton Optimisation'''' paper, which has been submitted to NeuroImage. The idea is to register images by estimating an initial velocity field, which can then be integrated to generate both forward and backward deformations. Currently, the software only works with images that have isotropic voxels, identical dimensions and which are in approximate alignment with each other. One of the reasons for this is that the approach assumes circulant boundary conditions, which makes modelling global rotations impossible. Because of these limitations, the registration should be based on images that have first been ``imported'''' via the New Segment toolbox.'
'The next step is the registration itself, which involves the simultaneous registration of e.g. GM with GM, WM with WM and 1-(GM+WM) with 1-(GM+WM) (when needed, the 1-(GM+WM) class is generated implicitly, so there is no need to include this class yourself). This procedure begins by creating a mean of all the images, which is used as an initial template. Deformations from this template to each of the individual images are computed, and the template is then re-generated by applying the inverses of the deformations to the images and averaging. This procedure is repeated a number of times.'
''
'This toolbox should be considered as only a beta (trial) version, and will include a number of (as yet unspecified) extensions in future updates. Please report any bugs or problems to the SPM mailing list.'
}';
shoot.values = {warp kernfun};
%_______________________________________________________________________
%
%_______________________________________________________________________
function dep = vout_initial_import(job)
cls = {'GM', 'WM', 'CSF'};
kk = 1;
for k=1:3,
if isnumeric(job.(cls{k})) && job.(cls{k})
dep(kk) = cfg_dep;
dep(kk).sname = sprintf('Imported Tissue (%s)', cls{k});
dep(kk).src_output = substruct('.','cfiles','()',{':',k});
dep(kk).tgt_spec = cfg_findspec({{'filter','nifti'}});
kk = kk + 1;
end
end
if isnumeric(job.image) && job.image
dep(kk) = cfg_dep;
dep(kk).sname = sprintf('Resliced Original Images');
dep(kk).src_output = substruct('.','files');
dep(kk).tgt_spec = cfg_findspec({{'filter','nifti'}});
end
%_______________________________________________________________________
%_______________________________________________________________________
function chk = check_shoot_template(job)
n1 = numel(job.images);
n2 = numel(job.images{1});
chk = '';
for i=1:n1,
if numel(job.images{i}) ~= n2,
chk = 'Incompatible number of images';
break;
end;
end;
%_______________________________________________________________________
%_______________________________________________________________________
function dep = vout_shoot_template(job)
if isa(job.template,'cfg_dep') || ~ ...
isempty(deblank(job.template))
for it=0:numel(job.param),
tdep(it+1) = cfg_dep;
tdep(it+1).sname = sprintf('Template (Iteration %d)', it);
tdep(it+1).src_output = substruct('.','template','()',{it+1});
tdep(it+1).tgt_spec = cfg_findspec({{'filter','nifti'}});
end
else
tdep = cfg_dep;
tdep = tdep(false);
end
fdep = cfg_dep;
fdep.sname = 'Flow Fields';
fdep.src_output = substruct('.','files','()',{':'});
fdep.tgt_spec = cfg_findspec({{'filter','nifti'}});
dep = [tdep fdep];
%_______________________________________________________________________
%_______________________________________________________________________
function dep = vout_shoot_warp(job)
dep = cfg_dep;
dep.sname = 'Flow Fields';
dep.src_output = substruct('.','files','()',{':'});
dep.tgt_spec = cfg_findspec({{'filter','nifti'}});
%_______________________________________________________________________
%_______________________________________________________________________
function chk = check_norm(job)
chk = '';
PU = job.velocities;
PI = job.images;
n1 = numel(PU);
for i=1:numel(PI),
if numel(PI{i}) ~= n1,
chk = 'Incompatible number of images';
break;
end
end
%_______________________________________________________________________
%_______________________________________________________________________
function chk = check_norm_fun(job)
chk = '';
if isfield(job.data,'subjs')
PU = job.data.subjs.velocities;
PI = job.data.subjs.images;
n1 = numel(PU);
for i=1:numel(PI),
if numel(PI{i}) ~= n1,
chk = 'Incompatible number of images';
break;
end
end
end
%_______________________________________________________________________
%_______________________________________________________________________
function dep = vout_norm(job)
if job.jactransf,
sname = 'Warped Images - Jacobian Transformed';
else
sname = 'Warped Images';
end
PU = job.velocities;
PI = job.images;
for m=1:numel(PI),
dep(m) = cfg_dep;
dep(m).sname = sprintf('%s (Image %d)',sname,m);
dep(m).src_output = substruct('.','files','()',{':',m});
dep(m).tgt_spec = cfg_findspec({{'filter','nifti'}});
end
n = numel(PI);
for m=1:numel(PU),
dep(m+n) = cfg_dep;
dep(m+n).sname = sprintf('%s (Deformation %d)',sname,m);
dep(m+n).src_output = substruct('.','files','()',{m,':'});
dep(m+n).tgt_spec = cfg_findspec({{'filter','nifti'}});
end
%_______________________________________________________________________
%_______________________________________________________________________
function dep = vout_invnorm(job)
PU = job.velocities;
PI = job.images;
for m=1:numel(PI),
dep(m) = cfg_dep;
dep(m).sname = sprintf('Inverse Warped Images (Image %d)',m);
dep(m).src_output = substruct('.','files','()',{':',m});
dep(m).tgt_spec = cfg_findspec({{'filter','nifti'}});
end
n = numel(PI);
for m=1:numel(PU),
dep(m+n) = cfg_dep;
dep(m+n).sname = sprintf('Inverse Warped Images (Deformation %d)',m);
dep(m+n).src_output = substruct('.','files','()',{m,':'});
dep(m+n).tgt_spec = cfg_findspec({{'filter','nifti'}});
end
%_______________________________________________________________________
%_______________________________________________________________________
function dep = vout_jacdet(job)
dep = cfg_dep;
dep.sname = 'Jacobian Determinant Fields';
dep.src_output = substruct('.','files','()',{':'});
dep.tgt_spec = cfg_findspec({{'filter','nifti'}});
%_______________________________________________________________________
%_______________________________________________________________________
function dep = vout_norm_fun(job)
if job.preserve,
sname = 'MNI Smo. Warped - Amount';
else
sname = 'MNI Smo. Warped - Concentrations';
end
dep = cfg_dep;
if isfield(job.data,'subj')
for m=1:numel(job.data.subj)
dep(m) = cfg_dep;
dep(m).sname = sprintf('%s (Deformation %d)',sname,m);
dep(m).src_output = substruct('{}',{m},'()',{':'});
dep(m).tgt_spec = cfg_findspec({{'filter','nifti'}});
end
end
if isfield(job.data,'subjs')
for m=1:numel(job.data.subjs.images),
dep(m) = cfg_dep;
dep(m).sname = sprintf('%s (Image %d)',sname,m);
dep(m).src_output = substruct('()',{':',m});
dep(m).tgt_spec = cfg_findspec({{'filter','nifti'}});
end
end
%_______________________________________________________________________
%_______________________________________________________________________
function chk = check_resids(job)
chk = '';
PU = job.velocities;
PI = job.images;
n1 = numel(PU);
for i=1:numel(PI),
if numel(PI{i}) ~= n1,
chk = 'Incompatible number of images';
break;
end
end
%_______________________________________________________________________
%_______________________________________________________________________
function dep = vout_resids(job)
dep = cfg_dep;
dep.sname = 'Residual Files';
dep.src_output = substruct('.','files','()',{':'});
dep.tgt_spec = cfg_findspec({{'filter','nifti'}});
%_______________________________________________________________________
|
github
|
philippboehmsturm/antx-master
|
ArtRepair.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/ArtRepair/ArtRepair.m
| 4,284 |
utf_8
|
30332ef73082be065bb6166cb5330bd2
|
function varargout = spm_artifactrepair(varargin)
% SPM_ARTIFACTREPAIR M-file for spm_artifactrepair.fig
% SPM_ARTIFACTREPAIR, by itself, creates a new SPM_ARTIFACTREPAIR or raises the existing
% singleton*.
%
% H = SPM_ARTIFACTREPAIR returns the handle to a new SPM_ARTIFACTREPAIR or the handle to
% the existing singleton*.
%
% SPM_ARTIFACTREPAIR('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in SPM_ARTIFACTREPAIR.M with the given input arguments.
%
% SPM_ARTIFACTREPAIR('Property','Value',...) creates a new SPM_ARTIFACTREPAIR or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before spm_artifactrepair_OpeningFunction gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to spm_artifactrepair_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Copyright 2002-2003 The MathWorks, Inc.
% Edit the above text to modify the response to help spm_artifactrepair
% Last Modified by GUIDE v2.5 26-Mar-2009 10:52:25
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @spm_artifactrepair_OpeningFcn, ...
'gui_OutputFcn', @spm_artifactrepair_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before spm_artifactrepair is made visible.
function spm_artifactrepair_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to spm_artifactrepair (see VARARGIN)
% Choose default command line output for spm_artifactrepair
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes spm_artifactrepair wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = spm_artifactrepair_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on button press in pushbutton6.
function pushbutton6_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton6 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton7.
function pushbutton7_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton7 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton8.
function pushbutton8_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton8 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton9.
function pushbutton9_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton9 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
|
github
|
philippboehmsturm/antx-master
|
art_summary.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/ArtRepair/art_summary.m
| 13,264 |
utf_8
|
f92ca4faeb9ae93562b3fd58332e3ccd
|
function [GQout,GQmean,Resout] = art_summary(ImageFullName,MaskFullName,OutputFolder,Figname,Fignum,AutoParams);
% FUNCTION art_summary (v3) FEB 2009
% For manual GUI:
% >>art_summary will use GUI to ask for images
%
% SUMMARY
% Summarizes the overall quality of estimates produced during GLM
% estimation for a single subject. Finds a histogram of all the
% estimates over the whole head measured in percent signal change,
% and calculates the model residual averaged over the whole head.
%
% Accurate estimates of percent signal change require that the user
% know specific design information on the peak of the design regressor
% and definition of the contrast. The program suggests a peak value
% and user may override it. The suggestion is pretty reliable.
%
% GUI INPUTS if no arguments are supplied
% User chooses con (or beta) results image(s) from an SPM Results folder.
% User enters peak value of design regressor (a value will be suggested)
% The peak value can be found by SPM->Review Design->Explore.
% Observe the peak value in the upper left graphics image. For ER designs
% where events overlap, select the value that matches a single event.
% User chooses a mask image (usually in the same Results folder)
% IMPORTANT: To compare accuracies between different Results folders,
% be sure to use the same mask for all cases.
% Program assumes the SPM.mat, ResMS and constant-term beta image are in
% the same Results folder.
% OutputFolder is for GlobalMeasure text summary is set
% automatically to the SPM Results folder.
% OUTPUTS
% [ GQout, GQmean, Resout ] are the Global Quality scores and the mean
% of sqrt(ResMS) over all the voxels in the brain,
% in units of percent signal change.
% For multiple con image inputs, GQout is for the last one.
% Writes an output text file 'GlobalMeasure.txt' in the OutputFolder,
% with mean, std, and RMS value of each image.
% Plots a histogram of estimated results (in percent signal change)
% for each input image.
% If the Matlab/Statistics toolbox is installed, and the code
% at the end of this program is uncommented:
% Plots a cumulative distribution of estimate/residual for all
% the voxels in the image.
%
% ARGUMENT INPUTS for calling from another function
% [GQout,GQmean,Resout] = art_summary(ImageFullName, MaskFullName, OutputFolder,Figname,Fignum,AutoParams);
% Program is called by art_redo and art_groupoutlier
% Additional inputs are required when called from another function.
% Figname specifies name of histogram image
% In GUI mode, set to the name of Results folder.
% Fignum specifies the first figure number to be plotted.
% In GUI mode, it is set to 50.
% AutoParams: a 1x3 array,
% peak_value: peak value of the design regressor
% contrast_value: sum of positive parts of contrast definition.
% bmean: mean of constant term image from last beta
%
% FUNCTIONS
% Program normalizes to percent, by using the average value of
% the last beta image within the specified mask.This value is scaled by
% P/C, where P is the peak value of the design regressor, and C is the
% sum of positive coefficients in the contrast definition.
% Makes an inner mask, and outer mask from head mask by finding
% a shell at the boundary of the mask, approx. 10 mm thick
% (1 voxel thick when voxel size is > 2.5 mm, 2 voxels thick
% when voxel size is < 2.5 mm.).
%
% Paul Mazaika, Sept. 2006.
% v2.1 added GQout and Resout function outputs. pkm Jan 2007
% small read changes for SPM5
% v2.2 added scaling by peak value and contrast RMS,
% added those parameters as inputs for automatic mode..
% removed dependency on Matlab Statistics Toolbox. pkm july07
% v2.3 scale GQ for nargin > 0. Constrain peak to be positive.
% v3 call art_percentscale for scaling, pkm feb09
spm('defaults','fmri');
spmv = spm('Ver'); spm_ver = 'spm2';
if (strcmp(spmv,'SPM5') | strcmp(spmv,'SPM8b') | strcmp(spmv,'SPM8') )
spm_ver = 'spm5'; end
if nargin > 0
% Assumed to handle one image at a time.
Rimages = ImageFullName;
imgmask = MaskFullName;
[ResultsFolder, temp ] = fileparts(Rimages(1,:));
% Art_redo and art_groupoutlier only send one contrast image to check.
elseif nargin == 0 % GUI interface if no arguments
if strcmp(spm_ver,'spm5')
Rimages = spm_select(Inf,'image','select con image(s)');
%Rimages = spm_get(Inf,'.img','select con image(s)'); spm2
[ResultsFolder, temp ] = fileparts(Rimages(1,:));
imgmask = spm_select(Inf,'image','select Mask image',[],ResultsFolder,'^mask.*');
else % spm2
Rimages = spm_get(Inf,'.img','select con image(s)'); spm2
[ResultsFolder, temp ] = fileparts(Rimages(1,:));
imgmask = spm_get(Inf,'mask.img','select Mask image');
end
OutputFolder = ResultsFolder;
[temp, ResultsName ] = fileparts(ResultsFolder);
Fignum = 50;
Figname = ResultsName;
%imgmask = spm_select(Inf,'image','select Mask image',[],ResultsFolder,'^mask.*');
end
Maska = spm_vol(imgmask);
Mask = spm_read_vols(Maska);
Mask = round(Mask); % sometimes computed masks have roundoff error
if nargin == 0 % find the scale factors automatically
for jj = 1:size(Rimages,1)
ScaleFactors = art_percentscale(Rimages(1,:),imgmask);
contrast_value(jj) = ScaleFactors(2);
end
jpeakmode = ScaleFactors(1);
bmean = ScaleFactors(3);
% User can override peak value.
peak_value = spm_input('Enter peak value of design regressor',1,'e',num2str(jpeakmode,3),1);
spm_input('!DeleteInputObj');
else % AutoParams were passed in as arguments
ScaleFactors = AutoParams;
peak_value = AutoParams(1); contrast_value(1) = AutoParams(2); bmean = AutoParams(3);
end
% Find the ResMS and last beta image in Results folder with the Images
R = spm_vol(Rimages);
nimages = size(R,1);
Resimage = fullfile(ResultsFolder,'ResMS.img');
% Find inner region (imask) and shell region (smask) of Mask.
% Want the shell to be about 10mm, so erode the mask by a step
% or two depending on the voxel size
if Maska.mat(2,2) < 2.5
SHELL = 2;
else
SHELL = 1;
end
% Shell is the number of voxels thickness in the shell.
% Shell = 1 seems to produce a two voxel thick shell.
if SHELL == 1
imask = floor(smooth3(Mask)+0.02);
smask = Mask & (1-imask);
else % case SHELL = 2
iimask = floor(smooth3(Mask)+0.02);
imask = floor(smooth3(iimask)+0.02);
smask = Mask & (1-imask);
end
ilisti = find(imask==1);
ilists = find(smask==1);
ilista = find(Mask==1);
clear Mask smask imask
% Find the estimated residual stdev on each voxel
% Undo the MeanSquare for ResMS
PRes = spm_vol(Resimage);
Yres = spm_read_vols(PRes);
Yres = 100*sqrt(Yres)/bmean;
% Compute stats on the images
for i = 1:nimages+1
if (i < nimages+1)
% Scale the images into percentage.
P = spm_vol(Rimages(i,:));
X = spm_read_vols(P);
X = 100*X/bmean;
X = (peak_value/contrast_value(i))*X; % v2.2 change
%X = (peak_value/contrast_value)*X; % v2.2 change
disp(Rimages(i,:));
else % (i == nimages+1)
X = Yres;
disp(Resimage);
end
% Find mean and standard deviation of inner, shell, and total regions.
%ilist = find(imask==1);
isize = length(ilisti);
imean = mean(X(ilisti));
istd = std(X(ilisti));
%itrim = trimmean(X(ilisti),10); % clips high 5% and low 5%
[ itrim, i90 ] = clipstats10(X(ilisti));
imax = max(abs(X(ilisti)));
%i90 = prctile(X(ilisti),90)-itrim; % dist of 90th percentile from mean
ilarge = 100*length(find(abs(X(ilisti)>1)))/length(ilisti); % percent voxels > 1 in size
irms = sqrt(istd*istd + imean*imean);
%ilist = find(smask==1);
ssize = length(ilists);
smean = mean(X(ilists));
sstd = std(X(ilists));
srms = sqrt(sstd*sstd + smean*smean);
%strim = trimmean(X(ilists),10); % clips high 5% and low 5%
[ strim, s90 ] = clipstats10(X(ilists));
smax = max(abs(X(ilists)));
%s90 = prctile(X(ilists),90)-strim; % dist of 90th percentile from mean
slarge = 100*length(find(abs(X(ilists)>1)))/length(ilists); % percent voxels > 1 in size
%ilist = find(Mask==1);
tsize = length(ilista);
tmean = mean(X(ilista));
tstd = std(X(ilista));
trms = sqrt(tstd*tstd + tmean*tmean);
%ttrim = trimmean(X(ilista),10); % clips high 5% and low 5%
[ ttrim, t90 ] = clipstats10(X(ilista));
tmax = max(abs(X(ilista)));
%t90 = prctile(X(ilista),90)-ttrim; % dist of 90th percentile from mean
tlarge = 100*length(find(abs(X(ilista)>1)))/length(ilista); % percent voxels > 1 in size
%totinout = [ tsize/1000 tmean tstd trms;...
% isize/1000 imean istd irms; ssize/1000 smean sstd srms];
%totals2 = [ tlarge ttrim t90 tmax; ilarge itrim i90 imax; slarge strim s90 smax ];
%disp(' %Vox > 1% Trimmean 90%ile AbsMax, for total, inner, and outer regions')
%disp(totals2)
disp(' Statistics for Total, Inner and Outer Regions')
if i < nimages+1
scalewords = [ ' Uses peak value ',num2str(peak_value),', contrast sum of ',num2str(contrast_value(i)),...
' and mean value over mask of ',num2str(bmean,3) ];
elseif i == nimages+1
scalewords = [ ' Calculated for sqrt(ResMS) divided by mean value over mask of ',num2str(bmean,3) ];
end
disp(scalewords)
disp(' Voxels/1000 Mean Std RMS Trimmean 90%ile %Vox > 1% AbsMax')
%disp(' Voxels/1000 Mean Std RMS, for total, inner, and outer regions')
%disp(totinout)
totalstat = [tsize/1000 tmean tstd trms ttrim t90 tlarge tmax;...
isize/1000 imean istd irms itrim i90 ilarge imax;...
ssize/1000 smean sstd srms strim s90 slarge smax];
disp(totalstat)
fid = fopen(fullfile(OutputFolder,'GlobalQuality.txt'),'at');
if i < nimages+1
fprintf(fid,'\n%s\n',Rimages(i,:));
fprintf(fid,'%s\n',scalewords);
else
fprintf(fid,'%s\n',Resimage);
fprintf(fid,'%s\n',scalewords);
end
%fprintf(fid,'%s\n',' %Vox > 1% Trimmean 90ile AbsMax');
%fprintf(fid,'%9.4f %9.4f %9.4f %9.4f\n',totals2');
%fprintf(fid,'%s\n',' Voxels/1000 Mean Std RMS');
%fprintf(fid,'%9.4f %9.4f %9.4f %9.4f\n',totinout');
fprintf(fid,'%s\n',' Voxels/1000 Mean Std RMS Trimmean 90ile %Vox > 1% AbsMax');
fprintf(fid,'%9.4f %9.4f %9.4f %9.4f%9.4f %9.4f %9.4f %9.4f\n',totalstat');
fclose(fid);
% Make histogram and cumulative distribution for image
if i < nimages+1
GQout = tstd;
vec = [ -3:0.05:3 ];
figure(Fignum + 2*(i - 1));
uu = X(ilisti);
uup = hist(uu,vec);
uus = X(ilists);
uups = hist(uus,vec);
vecp2 = [ tmean tmean+0.001 ];
pv(1) = 0; pv(2) = max(uup);
plot(vec,uup,'b-',vec,uups,'b--',vecp2,pv,'r--');
currname = R(i,:);
[ temp1, temp2 ] = fileparts(currname.fname);
xtitle = [ 'Histogram of Estimated Results for ' temp2 ' ' Figname ];
title(xtitle)
widthval = [ 'StDev = ' num2str(tstd,3) ];
xlabela = ['Estimated Result (Pct signal change) ' widthval];
xlabel(xlabela)
ylabel('Number of voxels')
meanval = [ 'Mean ' num2str(tmean,3) ];
legend('Inner region','Outer region', meanval);
hold off;
% % Matlab function normplot is in Statistics Toolbox.
% % To plot distribution relative to normal, use this code.
% figure(Fignum +2*i-1);
% Z = X(ilista)./Yres(ilista);
% normplot(Z);
% xtitle = ['Distribution of Observed Estimate/Residual for ' temp2 ' ' Figname ];
% title(xtitle)
% xlabela = ['Arbitrary Units'];
% xlabel(xlabela)
% ylabel('Cumulative Probability')
% % -----------------------------------
end
if i == nimages % Values to return
GQmean = tmean;
%Exceed = tlarge;
GQout = tstd;
end
end
% Third value to return
Resout = tmean; % Mean of sqrt(ResMS) image, which was last one processed.
function [ trim10, dist90 ] = clipstats10(YY);
% Finds trimmean and 90th percentile of data without Statistics toolbox.
% Likely slower and less robust, but this is a simple application.
% Hard-coded for 10% clip. Not worrying about roundoff for large datasets.
zz = sort(YY);
lz = length(zz);
lz90 = zz(round(lz*0.9)); % 90th percentile point
lim5 = round(lz*0.05); % 5th percentile point
lim95 = lz -lim5 +1; % symmetric clipping for 95%ile point
trim10 = mean(zz(lim5:lim95)); % trimmed mean
dist90 = lz90 - trim10; % distance between 90%ile and trimmean.
|
github
|
philippboehmsturm/antx-master
|
art_groupcheck.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/ArtRepair/art_groupcheck.m
| 30,844 |
utf_8
|
9668b36f736e66de0d687cde18c8b60c
|
function art_groupcheck(Action)
% FUNCTION art_groupcheck - v4
%
% FUNCTIONS:
% Allows a user to perform visual quality checks on contrast images
% associated with a user-supplied group level SPM.mat file. These checks
% can compare con and ResMS values for all subjects on a voxel, or
% view contrast estimates over all voxels for every subject, or
% run Global Quality scores to help detect outlier subjects.
%
% INPUTS
% Choose group level SPM.mat file
% If files at the full path name no longer exist, program prompts for the
% current location of the con file of the first image. Program assumes
% this same path change applies to all files in the group design.
% These con files will be used for the analysis.
% Input the scale factor to percent signal change if you wish to override
% the program suggestion. (See below for the method.) The suggestion
% is pretty reliable.
% Choose method of viewing:
% 1. All subjects on one voxel of interest
% 2. Contrast image for every subject, same format as art_movie,
% but with scale range from -2% to +2%.
% 3. Identify subject outliers with the art_groupoutlier program.
% If viewing by images:
% Choose Orientation: Transverse, Sagittal, or Coronal
% Select All slices (Recommended), or 25 close-up slices
% In close-up mode, about 20-25 consecutive slices are shown in a
% montage at twice the image size per slice. Select the desired
% center slice of the montage.
% Select ResMS weighting option: Yes or No.
% No: Shows contrast images for each subject. Helpful to
% see if a normalization were peculiar for a subject.
% Yes: Each contrast image is masked by the group ResMS, and
% each voxel is weighted according to both the
% single subject and group ResMS values at the voxel,
% This highlights voxel areas more likely to have high
% group activations because of low variance.
% If viewing by voxel:
% Input voxel coordinates (in mm) in the format: X Y Z
%
% PERCENT SIGNAL CHANGE CONVERSION
% The contrast image itself would be in percent signal change, IF
% 1.the mean image over the mask were 100, and
% 2.the peak of the design regressor were 1, and.
% 3.there were only one session included.(contrast sum = 1)
% The user can find these values from the result for a single
% subject using art_percentscale. Use the same con image as will be used
% in the group analysis. The peak and contrast sum are the same for
% all subjects. The mean value varies a bit from subject to subject,
% and is often 145-160 for Lucas Center scans. An average value will do here.
% The scale factor to convert the con images to percent is:
% percentscale = (peak/(constrast sum))*(100/(meanvalue))
% Then
% con (in percent sig change) = percentscale*con(image)
% This scales the groupcheck results for con images into percent signal change.
%
% OUTPUTS
% If viewed by images:
% - An interactive slider display with all frames of the montage movie,
% where each frame shows the contrast image from one subject.
% If viewed by voxel:
% Overlayed bar graphs of the contrast and sqrt(ResMS) values for each
% subject at the user-specified voxel, with the contrast values in the
% top 3/4 of the graph and the resMS values in the bottom 1/4. There is
% also an editable text field from which the user can select new
% mm coordinates.
% If viewed by Global Quality scores, type >>help art_groupoutlier
% for more information.
%
% Jenny Drexler, August 2007.
% pkm, v.4, Mar 2009 adds scaling, and option for art_groupoutlier
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SIZE LIMIT - This parameter can be adjusted for a particular computer.
% Matlab data is read as type double, then compressed to 8 bits.
% 400 volumes of (64x64x30) is 50 MB stored as type uint8.
% An experiment session may contain 300-600 volumes.
% The number of volumes affects the loading speed.
MAXSIZE = 510340; % About 50 MB is allowed into program storage.
spm('defaults','fmri');
% IMAGE GRAPH LIMIT. - Max and min of contrast image display is 2%.
GRAPHSCALE = 75;
% Identify spm version
spmv = spm('Ver'); spm_ver = 'spm2';
if (strcmp(spmv,'SPM5') | strcmp(spmv,'SPM8b') | strcmp(spmv,'SPM8') )
spm_ver = 'spm5'; end
% GET THE USER'S INPUTS
if (nargin==0) % For calling in line with arguments
% prompt user to select SPM design
if strcmp(spm_ver,'spm5')
origSPM = spm_select(1,'SPM.mat','Select SPM group design');
else % spm2 version
origSPM = spm_get(1,'SPM.mat','Select SPM group design');
end
dirSPM = fileparts(origSPM);
cd(dirSPM);
load SPM;
% load contrast image names
for(i=1:SPM.nscan(1))
F{i} = SPM.xY.P{i};
end
nFsize = size(F,2);
% STORE DESIGN MATRIX
groupdesign = SPM.xX.X;
if ~exist(F{1},'file')
% if contrast images cannot be found, they have been moved
disp('Image file paths have changed since SPM.mat was created.')
disp(['Please select replacement image for ' F{1}])
% prompt user to select new path of first scan
askstring = ['Path has changed. Select con file to replace the one displayed.'];
if strcmp(spm_ver,'spm5')
Pnew = spm_select(1, 'image', askstring);
else % spm2 version
Pnew = spm_get(1,'*img', askstring );
end
Pold = F{1};
% Remove comma in names (sometimes occurs in SPM5)
Pnew = strtok(Pnew,',');
Pold = strtok(Pold,',');
S = char(Pnew, Pold);
S(1,:) = strjust(S(1,:), 'right');
S(2,:) = strjust(S(2,:), 'right');
% compare paths to find new path prefix
for(i=1:size(S,2))
if strcmp(S(1, i:size(S, 2)), S(2, i:size(S, 2)))
PnewPrefix = strtrim(S(1, 1:i));
PoldPrefix = strtrim(S(2, 1:i));
break;
end
end
% find new paths for all images
for(j=1:nFsize)
F{j} = strrep(F{j}, PoldPrefix, PnewPrefix);
end
end
for(i=1:nFsize)
% if path updates didn't work, prompt user for each image that
% could not be found
if ~exist(F{i})
disp([F{i} ' does not exist. Please select new image path.']);
askstring = ['Select replacement image'];
if strcmp(spm_ver,'spm5')
F = cellstr(spm_select(1, 'image', askstring));
else % spm2 version
F = cellstr(spm_get(1, '*img', askstring));
end
end
end
% Find the percent scaling factors automatically.
% Set the mask by the group level 'mask.img,1' image
GroupMaskName = fullfile(dirSPM,'mask.img');
ScaleFactors1 = art_percentscale(char(F{1}),GroupMaskName);
ScaleFactors2 = art_percentscale(char(F{2}),GroupMaskName);
bmeanavg = 0.5*(ScaleFactors1(3) + ScaleFactors2(3));
suggestscale = (ScaleFactors1(1)/ScaleFactors1(2))*100/bmeanavg;
% Give user a chance to fix it.
disp(' ')
disp('A suggested scaling into percent signal change is shown.')
disp('User may change the value to override the suggestion.');
percentscale = 1;
percentscale = spm_input('Enter (peak/constrast)*100/bmean',1,'e',num2str(suggestscale),1);
% prompt user for viewing option
View = spm_input('View by:', ...
1, 'm', ' Con and ResMS values for all subjects at one voxel location | Image of contrast result for every subject | Global Quality scores and suggested subject outliers', [1, 0, 2]);
if (View == 1) % voxel of interest
% load single subject resMS image names
for(i=1:nFsize)
[Path, ConImg] = fileparts(F{i});
subjResMS{i} = spm_vol([Path '/ResMS.img']);
end
% get image dimensions
Q = spm_vol(F{1});
Q1 = spm_read_vols(Q);
[ NX, NY, NZ ] = size(Q1);
dim(1) = NX; dim(2) =NY; dim(3) = NZ;
% prompt user for voxel coordinates in mm
xyz = spm_input('Enter X Y Z coords in mm',1,'e',[],3);
x_mm=xyz(1);
y_mm=xyz(2);
z_mm=xyz(3);
% Read the images and extract the information on a voxel
intensity=zeros(nFsize,1);
intensityRes=zeros(nFsize,1);
for filenumber=1:nFsize
Q2 = spm_vol(F{filenumber});
Q1 = spm_read_vols(Q2);
% find transformation for converting to voxel coordinates
transformation(1, :) = Q2.mat(1, 1:3);
transformation(2, :) = Q2.mat(2, 1:3);
transformation(3, :) = Q2.mat(3, 1:3);
translation = [Q2.mat(1, 4);
Q2.mat(2, 4);
Q2.mat(3, 4);];
% convert user input from mm to voxel coordinates
mmcoord = [x_mm; y_mm; z_mm;] - translation;
voxcoord = transformation\mmcoord;
x = round(voxcoord(1));
y = round(voxcoord(2));
z = round(voxcoord(3));
% get contrast and ResMS values
intensity(filenumber) = Q1(x,y,z);
if isnan(Q1(x,y,z))
disp('WARNING: NaN voxel in Contrast image')
words = [ F{filenumber} ];
disp(words);
end
QRes1 = spm_read_vols(spm_vol(subjResMS{filenumber}));
intensityRes(filenumber) = sqrt(QRes1(x,y,z));
if isnan(QRes1(x,y,z))
disp('WARNING: NaN voxel in ResMS image')
words = [ F{filenumber} ];
disp(words);
end
end
% Scale information to percent signal change
intensity = percentscale*intensity;
intensityRes = percentscale*intensityRes;
% HAVE INFORMATION WE NEED. intensity and groupdesign.
dummy = 1;
%Display Figure
contrastplot = figure('Position', [360,500,650,400]);
subplot('Position', [.1, .3, .8, .6]);
xx = [1:nFsize];
K = 0.75; % variable for bar sizing
% produce ResMS bar graph
barResMS = bar(xx, intensityRes, 'FaceColor', [.6 .9 1], 'EdgeColor', [.2 .5 .6]);
set(barResMS, 'BarWidth', K/4);
axesResMS = gca;
set(axesResMS, 'YAxisLocation', 'right', 'YColor', [.2 .5 .6], 'TickDir', 'out', 'TickLength', [0 1]);
ylabel('Subject sqrt(ResMS) (% signal change)');
xlabel('Subject Number');
%title('Contrast and ResMS Values by Subject');
titlewords = ['Contrast and sqrt(ResMS) Values by Subject, Location ',num2str(x_mm,2),' ',num2str(y_mm,2),' ',num2str(z_mm,2) ];
title(titlewords)
% produce Contrast bar graph
axesContrast = axes('Position', get(axesResMS, 'Position'));
barContrast = bar(xx, intensity, 'FaceColor', [.4 .8 .6], 'EdgeColor', [.2 .6 .4]);
set(barContrast, 'BarWidth', K);
set(axesContrast, 'Color', 'none', 'XTickLabel',[], 'YColor', [.2 .6 .4]);
ylabel('Contrast Value (% signal change)');
set(axesContrast, 'XLim', get(axesResMS, 'XLim'));
% expand Contrast Y-axis by 1/3 on the bottom (so that the bottom
% 1/4 of the contrast graph is empty space)
axesContrastLims = get(axesContrast, 'YLim');
axesContrastrange = axesContrastLims(2) - axesContrastLims(1);
newLims = [(axesContrastLims(1) - axesContrastrange/3) axesContrastLims(2)];
set(axesContrast, 'YLim', newLims);
% expland ResMS Y-axis by a factor of 4, so that the bars are all
% contained in the bottom 1/4 of the figure
set(axesResMS, 'YLim', (4.2*get(axesResMS, 'YLim')))
% create editable text box
hnewvoxel = uicontrol('Units', 'normalized',...
'Style','edit',...
'Max', 1, 'Min', 1,...
'String', 'Select New Coordinates',...
'Position', [.3,.05,.4,.1],...
'Callback', {@newvoxel_Callback, F, subjResMS,percentscale});
Action = 'voxel';
elseif View == 0 % view by image for each subject
f = deblank(F{1});
V = spm_vol(f);
Y = spm_read_vols(V);
sdims = size(Y);
% Get the image dimensions. Set bounds on the number of scans allowed.
[ sy, si ] = sort(sdims); % si(1) is the minimum dimension
sor = 1; % default preference for axial.
if ( sy(2)==sy(3) & (sy(2) == 64 | sy(2) == 128 ))
disp('Looks like a raw image!')
if ( si(1) == 1 ) disp(' Sagittal slices'); sor = 2; end
if ( si(1) == 2 ) disp(' Coronal slices'); sor = 3; end
if ( si(1) == 3 ) disp(' Axial slices'); sor = 1; end
end
Orient= spm_input('Select slice orientation',...
1,'m','axial|sagittal|coronal',[ 1 2 3], sor); % Orient=1 for transverse, etc.
if ( Orient == 1 ) slnum = sdims(3); end
if ( Orient == 2 ) slnum = sdims(1); end
if ( Orient == 3 ) slnum = sdims(2); end
mdims = prod(sdims);
mxscans = round(MAXSIZE/mdims) * 100;
MAXSCAN = mxscans;
% Get the images and define the viewing montage.
CloseUp = 0; % Usually want all slices for results.
% if slnum > 9 % 9 is for the HiResolution case.
% CloseUp = spm_input('All Slices or ~20 close-up slices',1, ' All | Close-up', [ 0 1 ], 1 );
% else % No need to ask if there are fewer than 25 slices total.
% CloseUp = 1;
% end
if CloseUp == 1
centerslice = round(slnum/2);
slicesel = spm_input([num2str(slnum) ' slices. Pick montage center' ],1,'n',num2str(centerslice)); % array of integers
slicesel = max(1,slicesel - 12); % slicesel is now the first slice.
else
slicesel = 1; % Start at first slice for All slice case
end
%resMSweighting= spm_input('ResMS weighting?',1, ' No | Yes ', [ 0 1 ] );
resMSweighting = 0; % residual weighted images are not helpful yet.
if(resMSweighting)
%load group ResMS image
ResMS_img = spm_read_vols(spm_vol(SPM.VResMS.fname));
%load single subject ResMS images
for(i=1:nFsize)
[Path, ConImg] = fileparts(F{i});
img1 = spm_vol([Path '/ResMS.img']);
subjResMS{i} = spm_read_vols(img1);
end
end
mode = 1;
export = 0;
f = deblank(F{1});
V = spm_vol(f);
nFsize = size(F,2);
Action = 'Load'; nnnn = 6;
elseif View == 2 % Global Quality scores
% Note user override scaling is NOT available here.
Groupscale(1) = ScaleFactors1(1); % peak
Groupscale(2) = ScaleFactors1(2);
Groupscale(3) = bmeanavg;
OutputDir = dirSPM; % write output diagnostics to group results folder
disp('Output diagnostics will be written to folder with SPM.mat.')
art_groupoutlier(F, GroupMaskName, Groupscale, OutputDir);
%groupoutlier5(sjDirX, ResultsFolder,ConImageName, dirSPM,Groupscale, OutputDir);
% F is cell array of contrast images
% ResultsFolder is folder in subject path with con image and mask image.
% GroupMaskNameMask is the conjunction group mask
% OutputDir specifies where output images and files will be written.
Action = 'groupoutlier';
end
end
spm_input('!DeleteInputObj');
switch lower(Action)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
case('load')
if(View==0) % view by scan
% INITIALIZE ARRAYS, REFERENCE IMAGE, AND COLORMAP
% Adjust for number of scans and size limit
% Last scan is minimum of size limited or end of group.
firstscan = 1;
lastscanM = firstscan + MAXSCAN - 1; % Size limit for memory and program speed
lastscanF = nFsize; % Size limit by end of available files.
lastscan = min( [ lastscanM lastscanF ] );
Slimit = lastscan - firstscan + 1; % Number of scans that will be processed.
% Display the ResMS images
% Use second contrast image as reference for sizing and scaling
% purposes
nbase = round(firstscan + 1);
fref = deblank(F{nbase});
V = spm_vol(fref);
gap = 0; % No space allowed between image slices in the montage.
% Read and draw the preview image.
Yref = spm_read_vols(V); % Y is type double, size 4MB for (79,95,68);
Yref = percentscale*Yref; % Scale reference to percent signal change.
n = isnan(Yref);
Yref(n)=0;
if(resMSweighting)
% replace NaNs with zeroes in group ResMS image
n = isnan(ResMS_img);
ResMS_img(n)=0;
% replace NaNs with zeroes in single subject ResMS images
for(i=1:nFsize)
x = isnan(subjResMS{i});
subjResMS{i}(x) = 0;
end
% Calculate average (i.e. RMS) single subject ResMS on a voxel
% by voxel basis
for(i=1:size(subjResMS{1}, 3))
for(j=1:size(subjResMS{1}, 2))
for(k=1:size(subjResMS{1},1))
x=[];
for(n=size(subjResMS, 2))
x=[x; subjResMS{n}(k,j,i)];
end
avgsubjResMS(k, j, i) = norm(x)/sqrt(nFsize);
end
end
end
% ResMask is the combination of the group ResMS and average
% single subject ResMS
ResMask = sqrt(ResMS_img + avgsubjResMS);
% Divide the reference image by the ResMask
for(i=1:size(Yref, 3))
for(j=1:size(Yref, 2))
for(k=1:size(Yref,1))
if(ResMask(k,j,i)==0) Yref(k,j,i) = 0;
else Yref(k,j,i)=Yref(k,j,i)/ResMask(k,j,i); end
end
end
end
% set up montage displays for ResMS image
[layoutrms, nil] = art_montage(ResMask, Orient, slicesel, CloseUp);
Resmax = max(max(layoutrms));
Resmin = min(min(layoutrms));
% replace zeroes in the display of the ResMask with high values
% so that the image displayed shows the effect of the ResMS
% weighting (darker voxels in the ResMask are emphasized in the
% weighted contrasts)
for(i=1:size(layoutrms, 1))
for(j=1:size(layoutrms, 2))
if(layoutrms(i,j) == 0) layoutrms(i,j) = Resmax; end
end
end
%figure 1 is the ResMask
figure(1);
clf;
imagesc(layoutrms,[ Resmin Resmax]); colormap(gray)
drawnow;
disp('Total ResMS image has been read and displayed.')
end
% set up display of reference image in order to determine max and
% min values for scaling purposes.
[layout,nil] = art_montage(Yref,Orient,slicesel,CloseUp);
Yrmax=max(max(layout));
Yrmin=min(min(layout));
% Set up the arrays. Size of the image was determined in function art_montage.
[ xs, ys ] = size(layout);
% Dimension imageblock on the fly, else "zeros" command makes type double.
imageblock = uint8(zeros(xs,ys,Slimit)); % Size is 50MB for 100 scans of uint8 data.
temp = uint16(zeros(xs,ys));
temp1 = zeros(xs,ys);
layout8 = uint8(zeros(xs,ys));
history = zeros(lastscan,4); % Track some global properties
% Set the colormap
cmap = colormap(gray); % Size cmap is 64, so must map imageblock values to 0-63.
if(resMSweighting) cmap = art_activationmap3(1);
%else cmap = art_blue2yellowmap(1); end % cmap = colormap(cool) is also pretty good.
%else cmap = art_activationmap2(1); end % cmap = colormap(cool) is also pretty good.
else cmap = art_activationmap3(1); end % cmap = colormap(cool) is also pretty good.
% LOAD A SINGLE VOLUME AT A TIME AND CONVERT TO UINT8 FOR STORAGE
% Reads a scan at a time, and sets up a uint8 image, or a movie frame, for it.
disp('Loading data - this may take a few minutes for a lot of scans')
scale = 510/(Yrmax-Yrmin + 1);
scale = GRAPHSCALE; %75; % DISABLED AUTO SCALING. EXTREMES OF GRAPH ARE 2%.
scale_str = sprintf('Colormap display range is [-2,+2] using scale factor of %3g', scale);
disp(scale_str);
% Scale the reference image to baseline intensities [ 0 510 ].
for iscan = firstscan:lastscan
nscan = iscan - firstscan + 1;
% load contrast image
f =deblank(F{iscan});
V = spm_vol(f);
Y = spm_read_vols(V);
% Replace all NaNs in contrast image with zeroes
n = isnan(Y);
Y(n)=0;
% Divide contrast image by the ResMask. Ignore (i.e. set to
% zero) the contrast image where the ResMask is zero
if(resMSweighting)
for(i=1:size(Y, 3))
for(j=1:size(Y, 2))
for(k=1:size(Y,1))
if(ResMask(k,j,i)==0) Y(k,j,i) = 0;
else Y(k,j,i)=Y(k,j,i)/ResMask(k,j,i); end
end
end
end
end
%scale contrast image and convert to 2D montage
% Scale in percent signal change.
Y=Y*scale*percentscale;
history(iscan,1:4) = art_centroid(Y); % Collect time histories
[temp1,nil] = art_montage(Y,Orient,slicesel,CloseUp); % temp is double
%temp1 = round(tempz);
% convert values to fit 0-64 colormap scale
% Range [ -150, +150 ] -> [ 1, 63 ]
temp = uint16(max(1.6*(temp1)+254,0)); % clips the bottom
temp = min(temp,510); % clips the top
imageblock(:,:,nscan) = uint8( bitshift(temp,-3)); % Range -150 to +150 -> 1-63.
if export == 1 % Write out contrast volumes in AnalyzeFormat
Y = Y - Yref + 512;
Y = max(1,Y);
% Prepare the header for the filtered volume.
%V = spm_vol(P(i-1).fname);
v = V;
[dirname, sname, sext ] = fileparts(V.fname);
sfname = [ 'c', sname ]; % c pre-pended for contrast.
filtname = fullfile(dirname,[sfname sext]);
v.fname = filtname;
spm_write_vol(v,Y);
end
end
% Display slider figure
ha =figure('Position',[100 100 830 830]); % Create the slider figure.
figure(ha);
colormap(cmap);
if Slimit == 1 % Slimit is number of scans processed.
min_step=0.5;
max_step=1;
min_slide=0;
max_slide=0.5;
elseif Slimit == 2
min_step=0.5;
max_step=1;
min_slide=0;
max_slide = Slimit - 1;
elseif Slimit < 10
min_step=1/(Slimit-1);
max_step=1;
min_slide=0;
max_slide = Slimit - 1;
else
min_step=1/(Slimit-1);
max_step=10/(Slimit-1);
min_slide = 0;
max_slide = Slimit - 1;
end
h=findobj('Tag','ToDelete');
if ~isempty(h)
delete(h);
end;
figwin = ha;
% set up fields for slider callback
m_struct=struct('movie',imageblock,'filename',struct('names',F),'first',firstscan,...
'orient',Orient);
s=uicontrol('Style','slider','Parent',figwin,...
'Position',[245 80 338 30],...
'Min',min_slide,'Max',max_slide,...
'SliderStep',[min_step max_step],...
'Callback','art_groupcheck(''Scroll'');',...
'Userdata',m_struct,'String','Frame number');
figbar = axes('position',[ 0.93 0.3 0.03 0.4]);
darray = [63:-1:0];
image(darray');
%set(figbar,'Ytick',[1 17 33 48 64],'YTickLabel',[+160 +80 0 -80 -160],'XTickLabel',[]);
set(figbar,'Ytick',[1 17 33 48 64],'YTickLabel',[+2 +1 0 -1 -2],'Xtick',1,'XTickLabel','PERCENT');
set(0,'CurrentFigure',figwin);
set(0,'ShowHiddenHandles','on')
fig = axes('position',[0.07 0.15 0.8 0.8],'Parent',figwin);
I = imageblock(:,:,1);
image(I,'Parent',fig,'Tag','ToDelete');
axis image;
axis off;
frame=sprintf('%s',deblank(F{firstscan})); % Gets the path and file name
t=title('x','FontSize',14,'Interpreter','none','Tag','ToDelete'); %sets Interpreter
t=title(frame,'FontSize',14,'Interpreter','none','Tag','ToDelete');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
case('scroll') % if user clicks on slider
global PRINTSTR
if isempty(PRINTSTR)
PRINTSTR='print -dpsc2 -append spm.ps';
end;
g=get(gcbo,'Value');
m_struct=get(gcbo,'Userdata');
imageblock = m_struct.movie;
Or=m_struct.orient;
firstscan=m_struct.first;
F = m_struct.filename;
[ htemp, currfig ] = gcbo;
figwin= figure(currfig); % spm_figure('FindWin','Graphics');
figbar = axes('position',[ 0.93 0.3 0.03 0.4]);
darray = [63:-1:0];
image(darray');
%set(figbar,'Ytick',[1 17 33 48 64],'YTickLabel',[+160 +80 0 -80 -160],'XTickLabel',[]);
set(figbar,'Ytick',[1 17 33 48 64],'YTickLabel',[+2 +1 0 -1 -2],'XTickLabel',[]);
fig = axes('position',[0.07 0.15 0.8 0.8],'Parent',figwin);
h=findobj('Tag','ToDelete');
if ~isempty(h)
delete(h);
end;
figure(currfig);
nscan = size(imageblock,3);
gscan = 1 + floor(g+0.5);
if (gscan > nscan) gscan = nscan; end
I=imageblock(:,:,gscan);
image(I,'Tag','ToDelete');
axis image;
g2scan = gscan + firstscan - 1;
framename = deblank(F(g2scan).names);
t=title('y','FontSize',14,'Interpreter','none','Tag','ToDelete'); %sets Interpreter
t=title(framename,'FontSize',14,'Interpreter','none','Tag','ToDelete');
axis off;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
case('voxel') % if in voxel mode, callback doesn't need to do anything
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
case('groupoutlier') % callback doesn't need to do anything
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
otherwise
warning('Unknown action string')
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% function newvoxel_Callback is called when the user inputs new coordinates
% in the voxel display
function newvoxel_Callback(hObject,eventdata,F, subjResMS,percentscale)
user_input = get(hObject,'String');
Q1 = spm_read_vols(spm_vol(F{1}));
nFsize = size(F, 2);
% convert user input to coordinates
[ NX, NY, NZ ] = size(Q1);
dim(1) = NX; dim(2) =NY; dim(3) = NZ;
[xstr, remain]=strtok(user_input, ' ');
x_mm=str2double(xstr);
[ystr, remain]=strtok(remain, ' ');
y_mm=str2double(ystr);
z_mm=str2double(strtok(remain, ' '));
% Read the images and extract the information on a voxel
intensity=zeros(nFsize,1); %length(SPM.xY.P));
intensityRes=zeros(nFsize,1);
for filenumber=1:nFsize %length(SPM.xY.P)
Q2 = spm_vol(F{filenumber});
Q1 = spm_read_vols(Q2);
%get transformation to convert mm input to voxel coordinates
transformation(1, :) = Q2.mat(1, 1:3);
transformation(2, :) = Q2.mat(2, 1:3);
transformation(3, :) = Q2.mat(3, 1:3);
translation = [Q2.mat(1, 4);
Q2.mat(2, 4);
Q2.mat(3, 4);];
% convert user input to voxel coordinates
mmcoord = [x_mm; y_mm; z_mm;] - translation;
voxcoord = transformation\mmcoord;
x = round(voxcoord(1));
y = round(voxcoord(2));
z = round(voxcoord(3));
intensity(filenumber) = Q1(x,y,z);
if isnan(Q1(x,y,z))
disp('WARNING: NaN voxel in Contrast image')
words = [ F{filenumber} ];
disp(words);
end
QRes1 = spm_read_vols(spm_vol(subjResMS{filenumber}));
intensityRes(filenumber) = sqrt(QRes1(x,y,z));
if isnan(QRes1(x,y,z))
disp('WARNING: NaN voxel in ResMS image')
words = [ F{filenumber} ];
disp(words);
end
end
% HAVE THE VALUES WE NEED in intensity(1:nFsize).and groupdesign.
% Scale information to percent signal change
intensity = percentscale*intensity;
intensityRes = percentscale*intensityRes;
dummy = 1;
% Display figure
clf;
subplot('Position', [.1, .3, .8, .6]);
title(['Voxel coordinates ' user_input]);
xx = [1:nFsize];
K = 0.75;
barResMS = bar(xx, intensityRes, 'FaceColor', [.6 .9 1], 'EdgeColor', [.2 .5 .6]);
set(barResMS, 'BarWidth', K/4);
axesResMS = gca;
set(axesResMS, 'YAxisLocation', 'right', 'YColor', [.2 .5 .6], 'TickDir', 'out', 'TickLength', [0 1]);
ylabel('Subject ResMS StdDev');
xlabel('Subject Number');
titlewords = ['Contrast and ResMS Values by Subject, Location ',num2str(x_mm,2),' ',num2str(y_mm,2),' ',num2str(z_mm,2) ];
title(titlewords)
%title('Contrast and ResMS Values by Subject');
axesContrast = axes('Position', get(axesResMS, 'Position'));
barContrast = bar(xx, intensity, 'FaceColor', [.4 .8 .6], 'EdgeColor', [.2 .6 .4]);
set(barContrast, 'BarWidth', K);
set(axesContrast, 'Color', 'none', 'XTickLabel',[], 'YColor', [.2 .6 .4]);
ylabel('Contrast Value (% signal change)');
set(axesContrast, 'XLim', get(axesResMS, 'XLim'));
axesContrastLims = get(axesContrast, 'YLim');
axesContrastrange = axesContrastLims(2) - axesContrastLims(1);
newLims = [(axesContrastLims(1) - axesContrastrange/3) axesContrastLims(2)];
set(axesContrast, 'YLim', newLims);
set(axesResMS, 'YLim', (4.2*get(axesResMS, 'YLim')));
hnewvoxel = uicontrol('Units', 'normalized',...
'Style','edit',...
'Max', 1, 'Min', 1,...
'String', 'Select New Coordinates',...
'Position', [.3,.05,.4,.1],...
'Callback', {@newvoxel_Callback, F, subjResMS,percentscale});
Action = 'voxel';
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
github
|
philippboehmsturm/antx-master
|
art_groupsummary.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/ArtRepair/art_groupsummary.m
| 13,707 |
utf_8
|
7f3f9b92ccadf33ed0ed88767af8aab2
|
function [GQout,GQmean, Resout] = art_groupsummary(ImageFullName,MaskFullName,OutputFolder,Figname,Fignum,AutoParams);
% FUNCTION art_groupsummary (v1)
% For manual GUI:
% >>art_groupsummary will use GUI to ask for images
%
% SUMMARY
% Summarizes the overall quality of estimates produced during group level
% GLM. Finds a histogram over all the voxels in the brain of the group mean
% estimates on each voxel. Finds the mean and standard deviation of the
% histogram (the Global Quality scores). Calculates the mean of sqrt(ResMS)
% averaged over all the voxels in the brain. Results
% are expressed in percent signal change,
%
% This program is similar to art_summary for single subjects, except
% it must ask for a scale factor including a mean since there is no
% constant term in a group study. Another difference is that
% residuals at the group level are scaled into percent signal change
% with the same conversion as the con images themselves, since these
% group level residuals represent variance between subject estimates
% that were produced with that scaling.
%
% GUI INPUTS if no arguments are supplied
% User chooses con results image(s) from an SPM Group Results folder.
% User enters scale factor: peak/contrastsum)*100/bmean
% Find this using art_percentscale on a single subject.
% User chooses a mask image (usually in the same Results folder)
% Program assumes the SPM.mat, ResMS and constant-term beta image are in
% the same Results folder.
% OutputFolder is for GlobalMeasure text summary is set
% automatically to the SPM Results folder.
%
% OUTPUTS
% [ GQout, GQmean, Resout ] are Global Quality standard deviation and
% mean, and the mean of sqrt(ResMS) over the brain.,
% For multiple con image inputs, GQout is for the last one.
% Writes an output text file 'GlobalGroupQuality.txt' in OutputFolder,
% with mean, std, and RMS value of each image.
% Plots a histogram of estimated results (in percent signal change)
% for each input image.
% If the Matlab/Statistics toolbox is installed, and the code
% at the end of this program is uncommented:
% Plots a cumulative distribution of estimate/residual for all
% the voxels in the image.
%
% FUNCTIONS
% Program normalizes to percent, by using the average value of
% the last beta image within the specified mask.This value is scaled by
% P/C, where P is the peak value of the design regressor, and C is the
% RMS of nonzero coefficients in the contrast definition.
% Makes an inner mask, and outer mask from head mask by finding
% a shell at the boundary of the mask, approx. 10 mm thick
% (1 voxel thick when voxel size is > 2.5 mm, 2 voxels thick
% when voxel size is < 2.5 mm.).
%
% Paul Mazaika, Jan. 2009. adapted from art_summary.
% For calling from another function (not currently used)
% [GQout,GQmean,Resout]=art_groupsummary(ImageFullName, MaskFullName, OutputFolder,Figname,Fignum,AutoParams);
% Required inputs
% Figname specifies name of histogram image
% In GUI mode, set to the name of Results folder.
% Fignum specifies the first figure number to be plotted.
% In GUI mode, set to 50.
% AutoParams: a 1x2 array,
% Hopefully, set correctly from SPM.mat using art_redo.
% peak_value: peak value of the design regressor
% contrast_value: sum of positive parts of contrast definition.
% Identify spm version
spmv = spm('Ver'); spm_ver = 'spm2';
%if (spmv == 'SPM5' | spmv == 'SPM8b' | spmv == 'SPM8') spm_ver = 'spm5'; end
if (strcmp(spmv,'SPM5') | strcmp(spmv,'SPM8b') | strcmp(spmv,'SPM8') )
spm_ver = 'spm5'; end
spm('defaults','fmri');
if nargin > 0
Rimages = ImageFullName;
imgmask = MaskFullName;
[ResultsFolder, temp ] = fileparts(Rimages(1,:));
% Art_redo only sends one contrast image to check.
% But this is not relevant for group case.
peak_value = 1; contrast_value(1) = 1;
if exist('AutoParams')
peak_value = AutoParams(1); contrast_value(1) = AutoParams(2);
end
elseif nargin == 0 % GUI interface if no arguments
if strcmp(spm_ver,'spm5')
Rimages = spm_select(Inf,'image','select group level con image(s)');
else % spm2
Rimages = spm_get(Inf,'.img','select group level con image(s)');
end
[ResultsFolder, temp ] = fileparts(Rimages(1,:));
% Mask may be the SPM generated mask, or could be a user mask.
if strcmp(spm_ver,'spm5')
imgmask = spm_select(Inf,'image','select Mask image'); % ' ',ResultsFolder);
else % spm2
imgmask = spm_get(Inf,'mask.img','select Mask image');
end
peak_value = spm_input('Enter peak/constrast*100/bmean ',1);
[ResultsFolder, temp ] = fileparts(Rimages(1,:));
OutputFolder = ResultsFolder;
[temp, ResultsName ] = fileparts(ResultsFolder);
Fignum = 50;
Figname = ResultsName;
spm_input('!DeleteInputObj');
end
% Find the ResMS and last beta image in Results folder with the Images
R = spm_vol(Rimages);
nimages = size(R,1);
Resimage = fullfile(ResultsFolder,'ResMS.img');
% betaimages = spm_get('files',ResultsFolder,'beta*.img');
% lastbeta = size(betaimages,1);
% Normimage = betaimages(lastbeta,:);
%words = [' Normalizing by ', Normimage]; disp(words);
% Group case does not scale by last beta, so this is irrelevant.
% The last beta image in the Results folder is the SPM-estimated
% constant term. Scale all images by the average value of the last
% beta image with the head mask to get percentage.
% Find the normalization coefficient
% Pb = spm_vol(Normimage);
Maska = spm_vol(imgmask);
% Xb = spm_read_vols(Pb);
Mask = spm_read_vols(Maska);
Mask = round(Mask); % sometimes computed masks have roundoff error
% Find the global mean within the mask
% bmean = sum(Xb(find(Mask==1)));
bvox = length(find(Mask==1)); % number of voxels in mask
% bmean = bmean/bvox; % mean of beta in the mask
%words = ['Mean value of last beta: ', num2str(bmean,3) ];
%disp(words);
% clear Xb
% Find inner region (imask) and shell region (smask) of Mask.
% Want the shell to be about 10mm, so erode the mask by a step
% or two depending on the voxel size
if Maska.mat(2,2) < 2.5
SHELL = 2;
else
SHELL = 1;
end
% Shell is the number of voxels thickness in the shell.
% Shell = 1 seems to produce a two voxel thick shell.
if SHELL == 1
imask = floor(smooth3(Mask)+0.02);
imask = Mask & imask; % in case a hole was filled
smask = Mask & (1-imask);
else % case SHELL = 2
iimask = floor(smooth3(Mask)+0.02);
imask = floor(smooth3(iimask)+0.02);
imask = Mask & imask; % in case a hole was filled
smask = Mask & (1-imask);
end
ilisti = find(imask==1);
ilists = find(smask==1);
ilista = find(Mask==1);
clear Mask smask imask
% Find the estimated residual stdev on each voxel
% Undo the MeanSquare for ResMS
PRes = spm_vol(Resimage);
Yres = spm_read_vols(PRes);
Yres = sqrt(Yres)*peak_value; % was 100/bmean for single subject;
% Compute stats on the images
for i = 1:nimages+1
if (i < nimages+1)
% Scale the images into percentage.
P = spm_vol(Rimages(i,:));
X = spm_read_vols(P);
X = peak_value*X; %100*X/bmean;
%X = (peak_value/contrast_value(i))*X; % v2.2 change
disp(Rimages(i,:));
else % (i == nimages+1)
X = Yres;
disp(Resimage);
end
% Find mean and standard deviation of inner, shell, and total regions.
%ilist = find(imask==1);
isize = length(ilisti);
imean = mean(X(ilisti));
istd = std(X(ilisti));
%itrim = trimmean(X(ilisti),10); % clips high 5% and low 5%
[ itrim, i90 ] = clipstats10(X(ilisti));
imax = max(abs(X(ilisti)));
%i90 = prctile(X(ilisti),90)-itrim; % dist of 90th percentile from mean
ilarge = 100*length(find(abs(X(ilisti)>1)))/length(ilisti); % percent voxels > 1 in size
irms = sqrt(istd*istd + imean*imean);
%ilist = find(smask==1);
ssize = length(ilists);
smean = mean(X(ilists));
sstd = std(X(ilists));
srms = sqrt(sstd*sstd + smean*smean);
%strim = trimmean(X(ilists),10); % clips high 5% and low 5%
[ strim, s90 ] = clipstats10(X(ilists));
smax = max(abs(X(ilists)));
%s90 = prctile(X(ilists),90)-strim; % dist of 90th percentile from mean
slarge = 100*length(find(abs(X(ilists)>1)))/length(ilists); % percent voxels > 1 in size
%ilist = find(Mask==1);
tsize = length(ilista);
tmean = mean(X(ilista));
tstd = std(X(ilista));
trms = sqrt(tstd*tstd + tmean*tmean);
%ttrim = trimmean(X(ilista),10); % clips high 5% and low 5%
[ ttrim, t90 ] = clipstats10(X(ilista));
tmax = max(abs(X(ilista)));
%t90 = prctile(X(ilista),90)-ttrim; % dist of 90th percentile from mean
tlarge = 100*length(find(abs(X(ilista)>1)))/length(ilista); % percent voxels > 1 in size
%totinout = [ tsize/1000 tmean tstd trms;...
% isize/1000 imean istd irms; ssize/1000 smean sstd srms];
%totals2 = [ tlarge ttrim t90 tmax; ilarge itrim i90 imax; slarge strim s90 smax ];
%disp(' %Vox > 1% Trimmean 90%ile AbsMax, for total, inner, and outer regions')
%disp(totals2)
disp(' Statistics for Total, Inner and Outer Regions')
%if i < nimages+1
scalewords = [ ' Uses scale value of (peak value/contrast_sum)*100/bmean = ',num2str(peak_value) ];
disp(scalewords)
if i == nimages + 1
disp(' Statistics of sqrt(ResMS)/(scale value) averaged over the image.')
end
disp(' Voxels/1000 Mean Std RMS Trimmean 90%ile %Vox > 1% AbsMax')
%disp(' Voxels/1000 Mean Std RMS, for total, inner, and outer regions')
%disp(totinout)
totalstat = [tsize/1000 tmean tstd trms ttrim t90 tlarge tmax;...
isize/1000 imean istd irms itrim i90 ilarge imax;...
ssize/1000 smean sstd srms strim s90 slarge smax];
disp(totalstat)
fid = fopen(fullfile(OutputFolder,'GlobalGroupQuality.txt'),'at');
if i < nimages+1
fprintf(fid,'\n%s\n',Rimages(i,:));
fprintf(fid,'%s\n',scalewords);
else
fprintf(fid,'%s\n',Resimage);
end
%fprintf(fid,'%s\n',' %Vox > 1% Trimmean 90ile AbsMax');
%fprintf(fid,'%9.4f %9.4f %9.4f %9.4f\n',totals2');
%fprintf(fid,'%s\n',' Voxels/1000 Mean Std RMS');
%fprintf(fid,'%9.4f %9.4f %9.4f %9.4f\n',totinout');
fprintf(fid,'%s\n',' Voxels/1000 Mean Std RMS Trimmean 90ile %Vox > 1% AbsMax');
fprintf(fid,'%9.4f %9.4f %9.4f %9.4f%9.4f %9.4f %9.4f %9.4f\n',totalstat');
fclose(fid);
% Make histogram and cumulative distribution for image
if i < nimages+1
GQout = tstd;
vec = [ -3:0.05:3 ];
figure(Fignum + 2*(i - 1));
uu = X(ilisti);
uup = hist(uu,vec);
uus = X(ilists);
uups = hist(uus,vec);
vecp2 = [ tmean tmean+0.001 ];
pv(1) = 0; pv(2) = max(uup);
plot(vec,uup,'b-',vec,uups,'b--',vecp2,pv,'r--');
currname = R(i,:);
[ temp1, temp2 ] = fileparts(currname.fname);
xtitle = [ 'Histogram of Estimated Results for ' temp2 ' ' Figname ];
title(xtitle)
widthval = [ 'StDev = ' num2str(tstd,3) ];
xlabela = ['Estimated Result (Pct signal change) ' widthval];
xlabel(xlabela)
ylabel('Number of voxels')
meanval = [ 'Mean ' num2str(tmean,3) ];
legend('Inner region','Outer region', meanval);
hold off;
% %To draw an image with only the total statistics
% figure(200)
% uua = X(ilista);
% uupa = hist(uua,vec);
% plot(vec,uupa,'b-',vecp2,pv,'r--');
% currname = R(i,:);
% [ temp1, temp2 ] = fileparts(currname.fname);
% xtitle = [ 'Histogram of Estimated Results for ' temp2 ' ' Figname ];
% title(xtitle)
% widthval = [ 'StDev = ' num2str(tstd,3) ];
% xlabela = ['Estimated Result (Pct signal change) ' widthval];
% xlabel(xlabela)
% ylabel('Number of voxels')
% meanval = [ 'Mean ' num2str(tmean,3) ];
% legend('All voxels', meanval);
% % Matlab function normplot is in Statistics Toolbox.
% % To plot distribution relative to normal, use this code.
% figure(Fignum +2*i-1);
% Z = X(ilista)./Yres(ilista);
% normplot(Z);
% xtitle = ['Distribution of Observed Estimate/Residual for ' temp2 ' ' Figname ];
% title(xtitle)
% xlabela = ['Arbitrary Units'];
% xlabel(xlabela)
% ylabel('Cumulative Probability')
% % -----------------------------------
end
if i == nimages
GQmean = tmean;
Exceed = tlarge;
GQout = tstd;
end
end
% For compare_repair script, return two values
% GQout = tstd; % Standard Deviation was saved for last non-Res image.
Resout = tmean; % Mean of Res image, which was last one processed.
function [ trim10, dist90 ] = clipstats10(YY);
% Finds trimmean and 90th percentile of data without Statistics toolbox.
% Likely slower and less robust, but this is a simple application.
% Hard-coded for 10% clip. Not worrying about roundoff for large datasets.
zz = sort(YY);
lz = length(zz);
lz90 = zz(round(lz*0.9)); % 90th percentile point
lim5 = round(lz*0.05); % 5th percentile point
lim95 = lz -lim5 +1; % symmetric clipping for 95%ile point
trim10 = mean(zz(lim5:lim95)); % trimmed mean
dist90 = lz90 - trim10; % distance between 90%ile and trimmean.
|
github
|
philippboehmsturm/antx-master
|
art_addmargin.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/ArtRepair/art_addmargin.m
| 7,400 |
utf_8
|
677f4d80c4296d3358e74d0486c2d1a8
|
function art_addmargin
% Function art_addmargin
%
% Helper function for art_global. For a set of indices to be repaired,
% returns a list of indices to be deweighted. The list is
% returned as outdw_idx. The list will be written to file when the
% art_global REPAIR button is pushed.
% The logic is:
% 1. All repaired scans will be deweighted.
% 2. If a sequence of repaired scans leaves very uneven values
% at each end, then a margin of scans (up to 7) on each side
% is listed for deweighting.
% 3. If a sequence of repair indices has the same motion and global
% intensity values at each end, then no margin is added.
% The function draws deweighting bars in green on the top figure,
% and returns outdw_idx.
% -----------------------------
% Paul Mazaika, Aug. 2006
% v2.3 May 2009. Bug fix if all!! scans repaired.
% -------------------
% Default tolerance level for margins
% -------------------
% Rough analysis: Consider the overlap of dip in HPfilter onto
% the repair region. Its signal contribution is (1/6)*M*d*s*(1-i^2/s^2),
% where M is %signal change on voxel over the repair, d is the depth
% of the whitening function, s is its length (assume s=8), and i is
% margin distance from end of repair. The usual noise contribution is
% d*2*sqrt(s), assuming single voxel noise is 2%. We need to add margin
% when M > 4/(1-i^2/s^2), to keep the repair region from dominating.
%
% Roughly, M varies 8%/mm for transition of grey to white voxel,
% assuming a 4mm voxel and 30% difference in grey and white signals.
% This sets a mm threshold for expected clutter signal on a voxel from
% repair region. Roughly, M varies 10X(??) the global signal variation
% during a physiology event. We'll start with these estimates (i.e.
% equivalet to setting ydiffmove = 1 and ydiffg = 1) for the
% margin tests, and provide two scaling factors to tune them.
ydiffmove = 1.3; % try 1.0 for subjects with intervals of low noise
% try 2.0 for severely noisy subjects
ydiffg = 1.3; % was 1 % scales the global intensity test
% Case 4555 likes 2, while 7910 likes 1.
% -------------------
% Interrogate GUI
% -------------------
handles = guihandles;
g = guidata(gcf);
curr_thresh = str2num(get(handles.threshnum, 'String'));
curr_threshmv = str2num(get(handles.threshnummv, 'String'));
nscans = size(g,1);
delta = squeeze(g(:,2));
mv_data(:,1:6) = g(:,3:8);
gx = squeeze(g(:,1));
%repair1_flag = getappdata(gcbo,'data2');
out_idx = round(str2num(get(handles.indexedit, 'String')));
% Derive the current proposed repairs;
% zscoreA = (gx - mean(gx))./std(gx); % in case Matlab zscore is not available
% glout_idx = (find(abs(zscoreA) > curr_thresh))';
% mvout_idx = (find(delta > curr_threshmv))';
% % Current set of scans to be repaired.
% out_idx = unique([glout_idx mvout_idx]);
% if (repair1_flag == 1) out_idx = unique([1 out_idx]); end
% Find reasonable margins
xout = zeros(1,nscans);
xout(out_idx) = 2;
% Determine whether ends are to be repaired
if xout(1) == 2
repL = 1; else repL = 0; end
if xout(nscans) == 2
repR = 1; else repR = 0; end
% Find sets of consecutive scans to be repaired
j = repL; k = 0; xendL(1) = 0; xendR(1) = 0;
for i = 1:nscans-1
if xout(i) == 0 & xout(i+1) == 2
j = j+1;
xendL(j) = i;
end
if xout(i) == 2 & xout(i+1) == 0
k=k+1;
xendR(k) = i+1;
end
end
% Number of central clusters
nclust = k; % if repR == 0 and repL == 0
nclust = k - repR - repL; % if repR == 1
% For each cluster not at the end, if end values are close,
% then no margins are needed.
for iclust = repL+1:nclust+repL
for imarg = 0:7
if xendL(iclust)-imarg < 1 | xendR(iclust)+imarg > nscans
break
elseif xout(xendL(iclust)-imarg) > 0 | xout(xendR(iclust)+imarg) > 0
break
end
[ ta, tb ] = posdiff(xendL(iclust)-imarg,xendR(iclust)+imarg,mv_data,gx,imarg);
if ta < ydiffmove & tb < ydiffg;
break
else % mark for deweighting
xout(xendL(iclust)-imarg) = 1;
xout(xendR(iclust)+imarg) = 1;
end
end
end
% Case when Left End is repaired
if repL == 1
for imarg = 0:7
if xendR(1)+imarg > nscans
break
elseif xendR(1)+imarg < 1
break
elseif xout(xendR(1)+imarg) > 0
break
end
[ ta, tb ] = posdiff(1,xendR(1)+imarg,mv_data,gx,imarg); % NOT CORRECT
if ta < ydiffmove & tb < ydiffg;
break
else % mark for deweighting
xout(xendR(1)+imarg) = 1;
end
end
end
% Case when Right End is repaired
if repR == 1
for imarg = 0:7
if xendL(length(xendL))-imarg < 0
break
elseif xout(xendL(length(xendL))-imarg) > 0
break
end
[ ta, tb ] = posdiff(xendL(length(xendL))-imarg,nscans,mv_data,gx,imarg); % NOT CORRECT
if ta < ydiffmove & tb < ydiffg;
break
else % mark for deweighting
xout(xendL(iclust)-imarg) = 1;
end
end
end
% Fill in singleton openings
for i = 2:nscans-1
if xout(i-1) > 0 & xout(i+1) > 0
xout(i) = 1;
end
end
% Update deweightlist (which is not shown in a text box)
outdw_idx = find(xout > 0);
set(handles.deweightlist, 'String', int2str(outdw_idx));
% Update top chart for deweighting indices
subplot(5,1,1)
outerase = [1:nscans];
axes_lim = get(gca, 'YLim');
axes_height = [axes_lim(1) axes_lim(2)];
for i = 1:nscans
line((outerase(i)*ones(1, 2)), axes_height, 'Color', 'w');
end
% Refresh the global intensity plot
plot(gx,'b');
ylabel('Global Avg. Signal');
xlabel('Red vertical lines are to repair. Green vertical lines are to deweight.');
title('ArtifactRepair GUI to repair outliers and identify scans to deweight');
% Draw the scans recommended for deweighting
for i = 1:length(outdw_idx)
line((outdw_idx(i)*ones(1, 2)), axes_height, 'Color', 'g');
end
% Draw the scans recommended for repairing
for i = 1:length(out_idx)
line((out_idx(i)*ones(1, 2)), axes_height, 'Color', 'r');
end
%---------------------------------------------------------------
function [ mvpx, gp ] = posdiff(m,n,mv_data,gx,imarg);
% Returns clutter estimates of how the HPfilter interacts with repair region.
% First, finds ~mm displacement and percent global intensity difference
% between the ends of the repair region.
% Then, it estimates the clutter overlap factor of the whitening dip
% onto the strength of the abnormal region that will be repaired.
% Finally, those numbers in mm and global percent are scaled into a
% percent noise value on a voxel, relative to thermal noise.
% Rotational mv_data is in degrees, assumes 65 mm radius.
yd = (mv_data(m,1) - mv_data(n,1))^2 +...
(mv_data(m,2) - mv_data(n,2))^2 +...
(mv_data(m,3) - mv_data(n,3))^2 +...
1.28*(mv_data(m,4) - mv_data(n,4))^2 +...
1.28*(mv_data(m,5) - mv_data(n,5))^2 +...
1.28*(mv_data(m,6) - mv_data(n,6))^2;
yd = sqrt(yd);
% Overlap interaction term (assumed s=9, single voxel noise is 2%)
odiff = ( 1 - imarg^2/80)/4;
mvpx = 8*yd*odiff; % assumes 8% change in intensity/mm.
gpct = abs(gx(m) - gx(n))/(gx(n));
gp = 10*gpct*odiff; % assumes 10% change in voxel/global intensity.
|
github
|
philippboehmsturm/antx-master
|
art_motionregress.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/ArtRepair/art_motionregress.m
| 18,338 |
utf_8
|
239207e5377f255eec3cc544d5b3f778
|
function art_motionregress(ReslicedDir,ReslicedImages,RealignDir,RealignImages)
% function art_motionregress
% >> art_motionregress for use by GUI
% See below for batch.
%
% FUNCTIONS
% Remove residual interpolation errors after the realign and reslice
% operations (see Grootoonk 2000 for theory).
% It is an alternative to adding motion regressors to the design matrix.
% More fractional variation is removed on edge voxels with high variation,
% while little variation is removed on non-edge voxels. The function
% should be applied after realign and reslice, but before normalization.
% WARNING! This function will crash or run very slow on normalized
% images.
%
% INPUT by GUI
% Select realigned and resliced images, eg. 'rI*'.
% Select realigned, unresliced images, e.g. 'I*img' where there
% are associated .mat files. The .mat files describe the realignment
% calculation, and give the x,y,z displacement of every voxel in
% an image from realignment.
% OUTPUT
% Writes new image files with prefix 'm', that are the corrections of
% the input images after motion adjustment.
% Writes maprior image, showing logarithm of regularization value.
% Small values indicate more regression signal is removed, e.g.
% most is removed when log = -5.2, none when log = 2.3.
% Writes six mgamma images files containing motion regressors.
% Writes file art_motion.txt listing files omitted during calculation
% of regression parameters.
%
% BATCH FORM
% art_motionregress( ReslicedDir, ReslicedImages, RealignDir, RealignImages)
% ReslicedDir - folder with resliced images, e.g. '/net/fraX/subj1'
% ReslicedImages - image names, e.g. 'rI*img' or 'sr*img'
% RealignDir - folder with realigned, but not resliced images.
% The .mat files will be used from these images.
% RealignImages - image names, e.g. 'I*img'
%
% This program keeps 63 images in memory, but runs well for fMRI images of
% size 64x64x18 on computers with 512MB of RAM. It may crash for lack of
% memory on normalized images which are usually much larger.
%
% Paul Mazaika, May 2009
% ALGORITHM
% Algorithm finds the x,y,z equivalent translational motion on each voxel,
% assuming that small rotations are broken down into two translations.
% The motion adjustment uses the regressors
% [ sin x 1-cos x sin y 1-cos y sin z 1-cos z 1 ]
% which are different for every voxel. The regressors
% are computed from the .mat data of unresliced images. Images with fast
% variation are omitted from this calculation, although all images will
% be corrected by it.
% Regressors are applied more strongly near edges in the image ( brain
% boundary and ventricles ) where interpolation effects are largest.
% Strength of application is determined using a regularization R that
% depends on an heuristic function of the RMS variation on a voxel.
% Algorithm proceeds in two passes. First pass estimates the six
% regressors for every voxel, and writes these regressors as six images
% named mgamma. Estimation is done b = inv(R+A'A)*A'y, where all values in the
% A' and A'A matrices are accumulated by rolling through all the images.
% Second pass uses the regressors to find the residuals after motion
% correction. The residual images are written out with the prefix 'm'.
% Calls the art_motionadjust function. This pass rolls through the
% input images one more time to apply motion adjustment.
% This program accumulates all cross-products for the matrix inversion,
% storing the equivalent of 63 3D-images. This works only for
% the smaller fMRI images before normalization.
% Identify spm version
spmv = spm('Ver'); spm_ver = 'spm2';
if (strcmp(spmv,'SPM5') | strcmp(spmv,'SPM8b') | strcmp(spmv,'SPM8') )
spm_ver = 'spm5'; end;
% DATA, REALIGNMENT, AND REPAIR LOCATIONS
if nargin == 0
if strcmp(spm_ver,'spm5')
Pimages = spm_select(Inf,'image','Select resliced images to adjust');
Rmats = spm_select(Inf,'image','Select unresliced images (no r in name)');
else % spm2
Pimages = spm_get(Inf,'.img','Select resliced images to adjust');
Rmats = spm_get(Inf,'.img','Select unresliced images (no r in name)');
end
elseif nargin > 0
if strcmp(spm_ver,'spm5')
Pimages = spm_select('FPList',ReslicedDir, ReslicedImages);
Rmats = spm_select('FPList',RealignDir, RealignImages);
else % spm2
Pimages = spm_get('files', ReslicedDir, ReslicedImages);
Rmats = spm_get('files', RealignDir, RealignImages);
end
end
P = spm_vol(Pimages);
R = spm_vol(Rmats);
[imagedir, imagename ] = fileparts(P(1).fname);
motiondir = imagedir;
resdir = imagedir;
% Get image size and voxel size. Flip x-voxel size to positive.
% Imagesize are the images to be motion adjusted.
% Voxelsize is the voxel size of image that was scanned.
nscan = size(P,1);
imagesize = P(1).dim;
dx = imagesize(1); dy = imagesize(2); dz = imagesize(3);
imagedim = [ dx dy dz ];
voxelsize = R(1).mat;
vx = abs(voxelsize(1,1)); vy = voxelsize(2,2); vz = voxelsize(3,3);
Y1 = spm_read_vols(P(1));
%meanY1 = 0.75*max(max(max(Y1))); % a guess!
disp('Generated mask image is written to file ArtifactMask.img.')
%Pnames = P{1};
Automask = art_automask(P(1,:),-1,1);
maskcount = sum(sum(sum(Automask))); % Number of voxels in mask.
voxelcount = prod(size(Automask)); % Number of voxels in 3D volume.
Y1 = Y1.*Automask;
meanY1 = mean(mean(mean(Y1)))*voxelcount/maskcount;
% ------------------------
% Use art_global to find time points with rapid scan-to-scan movement
% Scans with these indices should be removed from motion regression
% calculation because the realignment parameters may have errors.
% One could try to fix these realignment values here, but instead we will
% use art_repair later to smooth the intensities on the same images.
% ------------------------
mv_thresh = 0.5; % perhaps 0.3 for good subjects
disp('Detect scans to remove from motion calculation using art_global');
nsess = 1;
%realname = [ '^' prefix{6} '.*\.img$' ];
mvname = [ '^rp_' '.*\.txt$']; % same prefix as realignment.];
for i = 1:nsess
mvfile = spm_select('FPList',[ imagedir ], mvname);
% Make list of bad scans
%c5_art_global(Pimages, mvfile, 4,0); % fixed, no clipmvmt
art_global(Pimages, mvfile, 4,0); % fixed, no clipmvmt
%b5_art_global(imgFile, mvfile, 4,2);
outnames = textread([ imagedir '/art_suspects.txt']);
mvout_idx = outnames;
end
numberout = length(mvout_idx);
numberst = ['Excluding ' num2str(numberout) ' volumes from motion adjustment estimation.'];
disp(numberst)
delta(1:nscan,1) = 0;
delta(mvout_idx) = 1;
% Save list of scans excluded from estimation of motion
temppwd = pwd;
cd(fileparts(P(1).fname));
save art_motion.txt mvout_idx -ascii
cd(temppwd);
% Initialize accumulation arrays and first image
% This repetitive code uses 3D arrays because
% 4D arrays can be slow depending on subscript order.
disp('Reading image files to solve regression on all voxels.');
mbeta01 = zeros(dx,dy,dz); mbeta02 = zeros(dx,dy,dz); mbeta03 = zeros(dx,dy,dz);
mbeta04 = zeros(dx,dy,dz); mbeta05 = zeros(dx,dy,dz); mbeta06 = zeros(dx,dy,dz);
mbeta07 = zeros(dx,dy,dz); mbeta08 = zeros(dx,dy,dz); mbeta09 = zeros(dx,dy,dz);
mbeta10 = zeros(dx,dy,dz); mbeta11 = zeros(dx,dy,dz); mbeta12 = zeros(dx,dy,dz);
mbetaab = zeros(dx,dy,dz); mbetaac = zeros(dx,dy,dz); mbetaap = zeros(dx,dy,dz);
mbetaaq = zeros(dx,dy,dz); mbetaar = zeros(dx,dy,dz); mbetabc = zeros(dx,dy,dz);
mbetabp = zeros(dx,dy,dz); mbetabq = zeros(dx,dy,dz); mbetabr = zeros(dx,dy,dz);
mbetacp = zeros(dx,dy,dz); mbetacq = zeros(dx,dy,dz); mbetacr = zeros(dx,dy,dz);
mbetapq = zeros(dx,dy,dz); mbetapr = zeros(dx,dy,dz); mbetaqr = zeros(dx,dy,dz);
mbeta00 = zeros(dx,dy,dz); % difference of first from the mean.
mbetac1 = zeros(dx,dy,dz); mbetac2 = zeros(dx,dy,dz); mbetac3 = zeros(dx,dy,dz);
mbetac4 = zeros(dx,dy,dz); mbetac5 = zeros(dx,dy,dz); mbetac6 = zeros(dx,dy,dz);
msumsq = zeros(dx,dy,dz);
%
% Accumulate the correlations
% ------------------------------------------------------------
for i = 1:nscan
if (delta(i) == 1) continue; end
Y = spm_read_vols(P(i));
[ Xp, Yp, Zp ] = rmove(R(i).mat, imagedim, R(1).mat);
Y = Y - Y1; %difference from the baseline.
mbeta00 = Y + mbeta00;
msumsq = Y.*Y + msumsq;
ax = sin(Xp*2*pi/vx); % ax should be a matrix
mbeta01 = Y.*ax + mbeta01;
mbeta07 = ax.*ax + mbeta07;
mbetac1 = ax + mbetac1;
bx = (1-cos(Xp*2*pi/vx));
mbeta02 = Y.*bx + mbeta02;
mbeta08 = bx.*bx + mbeta08;
mbetac2 = bx + mbetac2;
cx = sin(Yp*2*pi/vy);
mbeta03 = Y.*cx + mbeta03;
mbeta09 = cx.*cx + mbeta09;
mbetac3 = cx + mbetac3;
px = (1-cos(Yp*2*pi/vy));
mbeta04 = Y.*px + mbeta04;
mbeta10 = px.*px + mbeta10;
mbetac4 = px + mbetac4;
qx = sin(Zp*2*pi/vz);
mbeta05 = Y.*qx + mbeta05;
mbeta11 = qx.*qx + mbeta11;
mbetac5 = qx + mbetac5;
rx = (1-cos(Zp*2*pi/vz));
mbeta06 = Y.*rx + mbeta06;
mbeta12 = rx.*rx + mbeta12;
mbetac6 = rx + mbetac6;
mbetaab = ax.*bx + mbetaab;
mbetaac = ax.*cx + mbetaac;
mbetaap = ax.*px + mbetaap;
mbetaaq = ax.*qx + mbetaaq;
mbetaar = ax.*rx + mbetaar;
mbetabc = bx.*cx + mbetabc;
mbetabp = bx.*px + mbetabp;
mbetabq = bx.*qx + mbetabq;
mbetabr = bx.*rx + mbetabr;
mbetacp = cx.*px + mbetacp;
mbetacq = cx.*qx + mbetacq;
mbetacr = cx.*rx + mbetacr;
mbetapq = px.*qx + mbetapq;
mbetapr = px.*rx + mbetapr;
mbetaqr = qx.*rx + mbetaqr;
end
% Divide by nscan and save these intermediate results.
disp('Storing variances and cross-correlations')
tempnscan = nscan;
nscan = nscan - numberout;
mbeta01 = mbeta01/nscan; mbeta02 = mbeta02/nscan; mbeta03 = mbeta03/nscan;
mbeta04 = mbeta04/nscan; mbeta05 = mbeta05/nscan; mbeta06 = mbeta06/nscan;
mbeta07 = mbeta07/nscan; mbeta08 = mbeta08/nscan; mbeta09 = mbeta09/nscan;
mbeta10 = mbeta10/nscan; mbeta11 = mbeta11/nscan; mbeta12 = mbeta12/nscan;
mbetaab = mbetaab/nscan;
mbetaac = mbetaac/nscan;
mbetaap = mbetaap/nscan;
mbetaaq = mbetaaq/nscan;
mbetaar = mbetaar/nscan;
mbetabc = mbetabc/nscan;
mbetabp = mbetabp/nscan;
mbetabq = mbetabq/nscan;
mbetabr = mbetabr/nscan;
mbetacp = mbetacp/nscan;
mbetacq = mbetacq/nscan;
mbetacr = mbetacr/nscan;
mbetapq = mbetapq/nscan;
mbetapr = mbetapr/nscan;
mbetaqr = mbetaqr/nscan;
mbeta00 = mbeta00/nscan;
mbetac1 = mbetac1/nscan; mbetac2 = mbetac2/nscan; mbetac3 = mbetac3/nscan;
mbetac4 = mbetac4/nscan; mbetac5 = mbetac5/nscan; mbetac6 = mbetac6/nscan;
nscan = tempnscan; % undo the hack
clear Xp Yp Zp Y Y1 ax bx cx px qx rx;
% % REGULARIZATION FOR MATRIX INVERSION
% % Vary limit on each voxel depending on RMS variation to remove more
% when variation is larger.
% % Find RMS variation on voxel
scansused = nscan-numberout;
msumsq = msumsq/scansused;
msumsq = msumsq - mbeta00.*mbeta00; % estimates variance
msumsq = sqrt(msumsq)/meanY1; % fractional variation on the voxel
msumsq(1,:,:) =1; msumsq(64,:,:) = 1; msumsq(:,1,:)=1; msumsq(:,64,:)=1;
% NOW ASSUME SOME HEURISTIC VALUES FOR INVERSION...
% Best performance used 0.005 and 0.0025 for edges in the Phantom Data
% % Pretty good values for phantom were 0.01 and 0.001
% Smooth this msumsq array? Not in this version.
% SECOND GUESS
% Fractional variation > 0.05, set to less than 0.0037
% Fractional variation < 0.01, set to more than 5 ( a guess)
apriorarray = 50*exp(-200*msumsq);
% NEXT SET MINIMUM LIMIT ON REGULARIZATION TO MAINTAIN STABILITY
% Matlab gives no inversion warnings, even for 0.0001, or 0.001 fixed everywhere.
% Regressors are clipped in a few ventral posterior edge at 0.005 fixed, while
% % clipping also occurs in ventral anterior, and top at 0.0001.
apriorlimit = 0.0025;
apriorhigh = 6;
apriorarray = max(apriorarray, apriorlimit);
apriorarray = min(apriorarray, apriorhigh); % prevents Matlab warning
mbetaones = ones(dx,dy,dz);
% FULL MATRIX INVERSE ON EVERY VOXEL
for in = 1:dx
for jn = 1:dy
for kn = 1:dz
M = [ mbeta07(in,jn,kn) mbetaab(in,jn,kn) mbetaac(in,jn,kn) mbetaap(in,jn,kn) mbetaaq(in,jn,kn) mbetaar(in,jn,kn) mbetac1(in,jn,kn); ...
mbetaab(in,jn,kn) mbeta08(in,jn,kn) mbetabc(in,jn,kn) mbetabp(in,jn,kn) mbetabq(in,jn,kn) mbetabr(in,jn,kn) mbetac2(in,jn,kn); ...
mbetaac(in,jn,kn) mbetabc(in,jn,kn) mbeta09(in,jn,kn) mbetacp(in,jn,kn) mbetacq(in,jn,kn) mbetacr(in,jn,kn) mbetac3(in,jn,kn); ...
mbetaap(in,jn,kn) mbetabp(in,jn,kn) mbetacp(in,jn,kn) mbeta10(in,jn,kn) mbetapq(in,jn,kn) mbetapr(in,jn,kn) mbetac4(in,jn,kn); ...
mbetaaq(in,jn,kn) mbetabq(in,jn,kn) mbetacq(in,jn,kn) mbetapq(in,jn,kn) mbeta11(in,jn,kn) mbetaqr(in,jn,kn) mbetac5(in,jn,kn); ...
mbetaar(in,jn,kn) mbetabr(in,jn,kn) mbetacr(in,jn,kn) mbetapr(in,jn,kn) mbetaqr(in,jn,kn) mbeta12(in,jn,kn) mbetac6(in,jn,kn); ...
mbetac1(in,jn,kn) mbetac2(in,jn,kn) mbetac3(in,jn,kn) mbetac4(in,jn,kn) mbetac5(in,jn,kn) mbetac6(in,jn,kn) mbetaones(in,jn,kn) ];
% aacond(in,jn,kn) = cond(M);
% maximum condition number is 9000000 in phantom data!
% M = M + aprior(in,jn,kn)*eye(7) regularizes everything.
% Only regularize singular locations
aprior = max(apriorlimit,apriorarray(in,jn,kn));
for nn = 1:6
M(nn,nn) = max(M(nn,nn), aprior);
end
% apcond(in,jn,kn) = cond(M);
% With regularization, condition number has range 100000 in
% phantom data. Could use pinv(M) here, but not needed.
MM = inv(M);
bvec = [ mbeta01(in,jn,kn) mbeta02(in,jn,kn) mbeta03(in,jn,kn) mbeta04(in,jn,kn) mbeta05(in,jn,kn) mbeta06(in,jn,kn) mbeta00(in,jn,kn) ]';
mgamma01(in,jn,kn) = MM(1,1:7)*bvec;
mgamma02(in,jn,kn) = MM(2,1:7)*bvec;
mgamma03(in,jn,kn) = MM(3,1:7)*bvec;
mgamma04(in,jn,kn) = MM(4,1:7)*bvec;
mgamma05(in,jn,kn) = MM(5,1:7)*bvec;
mgamma06(in,jn,kn) = MM(6,1:7)*bvec;
% Better to also estimate and write out mgamma00, the difference between mean and baseline value.
end
end
end
% % TEST CODE for ONLY Z COMPONENT MATRIX INVERSE ON EVERY VOXEL
% for in = 1:dx
% for jn = 1:dy
% for kn = 1:dz
% M = [ mbeta11(in,jn,kn) mbetaqr(in,jn,kn) mbetac5(in,jn,kn); ...
% mbetaqr(in,jn,kn) mbeta12(in,jn,kn) mbetac6(in,jn,kn);...
% mbetac5(in,jn,kn) mbetac6(in,jn,kn) 1 ];
% aacond(in,jn,kn) = cond(M);
% % condition numbers are from 2.4 - 3.5 for 1D phantom data!
% %M = M + aprior(in,jn,kn)*eye(2);
% M = M + [ 0.05 0 0; 0 0.05 0; 0 0 0 ]; % *eye(3);
% %apcond(in,jn,kn) = cond(M);
% % No regularization needed in 1D algorithm for phantom.
% % phantom data
% MM = inv(M);
% bvec = [ mbeta05(in,jn,kn) mbeta06(in,jn,kn) mbeta00(in,jn,kn) ]';
% mgamma01(in,jn,kn) = 0;
% mgamma02(in,jn,kn) = 0;
% mgamma03(in,jn,kn) = 0;
% mgamma04(in,jn,kn) = 0;
% mgamma05(in,jn,kn) = MM(1,1:3)*bvec;
% mgamma06(in,jn,kn) = MM(2,1:3)*bvec;
% end
% end
% end
% Prevent runaway large values
clear mbeta*
disp('Clipping regressors that are too large')
acap = 0.21; % correction from any one term < 5% of mean image
% phantom data had max of 21%.
maxgamma = acap*meanY1;
mingamma = - maxgamma;
mgamma01 = min(mgamma01,maxgamma);
mgamma02 = min(mgamma02,maxgamma);
mgamma03 = min(mgamma03,maxgamma);
mgamma04 = min(mgamma04,maxgamma);
mgamma05 = min(mgamma05,maxgamma);
mgamma06 = min(mgamma06,maxgamma);
mgamma01 = max(mgamma01,mingamma);
mgamma02 = max(mgamma02,mingamma);
mgamma03 = max(mgamma03,mingamma);
mgamma04 = max(mgamma04,mingamma);
mgamma05 = max(mgamma05,mingamma);
mgamma06 = max(mgamma06,mingamma);
disp('Writing mgamma images with motion regressors for each voxel.')
%V = spm_vol(P(1).fname);
v = P(1); % was V;
[dirname, sname, sext ] = fileparts(P(1).fname);
v = rmfield(v,'pinfo'); % Allows SPM5 to scale images.
sfname = 'mgamma01';
filtname = fullfile(dirname,[sfname sext]);
v.fname = filtname;
spm_write_vol(v,mgamma01);
sfname = 'mgamma02';
filtname = fullfile(dirname,[sfname sext]);
v.fname = filtname;
spm_write_vol(v,mgamma02);
sfname = 'mgamma03';
filtname = fullfile(dirname,[sfname sext]);
v.fname = filtname;
spm_write_vol(v,mgamma03);
sfname = 'mgamma04';
filtname = fullfile(dirname,[sfname sext]);
v.fname = filtname;
spm_write_vol(v,mgamma04);
sfname = 'mgamma05';
filtname = fullfile(dirname,[sfname sext]);
v.fname = filtname;
spm_write_vol(v,mgamma05);
sfname = 'mgamma06';
filtname = fullfile(dirname,[sfname sext]);
v.fname = filtname;
spm_write_vol(v,mgamma06);
sfname = 'maprior';
logaprior = log(apriorarray); % natural log
% To read the apriorarray later...
% Note log .005 is -5.2, and log 10 is 2.3.
filtname = fullfile(dirname,[sfname sext]);
v.fname = filtname;
spm_write_vol(v,logaprior);
clear mgamma*;
% Estimate motion adjusted images
disp('Write images after motion adjustment');
if strcmp(spm_ver,'spm5')
mgams = spm_select('FPList',imagedir, '^mgamma.*\.img$');
else % spm2
mgams = spm_get('files',imagedir, 'mgamma*img');
end
%cd(motiondir)
art_motionadjust(P, mgams, R);
%b_motionadjust(P, mgams, R);
%--------------------------------------------------------------
function [ Xp, Yp, Zp ] = rmove(New,imagedim,Baseline);
% P.mat transforms voxel coordinates to x,y,z position in mm.
% New is P.mat for image, Baseline is P(1).mat for baseline image
% dim is 3D vector of image size.
% Output is change in (x,y,z) position for every voxel on this image.
Mf = New - Baseline;
for i = 1:imagedim(1)
for j = 1:imagedim(2)
for k = 1:imagedim(3)
Xp(i,j,k) = Mf(1,1)*i+Mf(1,2)*j+Mf(1,3)*k+Mf(1,4);
Yp(i,j,k) = Mf(2,1)*i+Mf(2,2)*j+Mf(2,3)*k+Mf(2,4);
Zp(i,j,k) = Mf(3,1)*i+Mf(3,2)*j+Mf(3,3)*k+Mf(3,4);
end
end
end
|
github
|
philippboehmsturm/antx-master
|
art_motionadjust.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/ArtRepair/art_motionadjust.m
| 2,638 |
utf_8
|
a618fe5bcfdfdec770bc4ef563572143
|
function art_motionadjust(Images, Mgammas, Regressors)
% FORMAT art_motionadjust
% Support function for art_motionregress
% SUMMARY
% Reads a set of images to motion adjust
% Reads six mgamma images to use for regressors.
% Reads a set of images to get their realignment .mat files.
% Writes a set of motion adjusted images, with the letter 'm'
% prepended to the file names.
% No original data is removed- the old images are all preserved.
%
% NOTES
% Use art_movie to compare the input and adjusted images.
% Use art_rms to find RMS voxel variations over time series.
% Compatible with SPM5 and SPM2
% Paul Mazaika, May 2007
% PARAMETERS
spm('defaults','fmri');
P = Images; % spm_vol(Images);
A = spm_vol(Mgammas);
R = Regressors; % may be an alternate way.
% Read in the six motion adjustment images.
A1 = spm_read_vols(A(1));
A2 = spm_read_vols(A(2));
A3 = spm_read_vols(A(3));
A4 = spm_read_vols(A(4));
A5 = spm_read_vols(A(5));
A6 = spm_read_vols(A(6));
% Main Loop - Adjust each image.
nscans = size(P,1);
voxelsize = R(1).mat;
vx = abs(voxelsize(1,1)); vy = voxelsize(2,2); vz = voxelsize(3,3);
imagedim = size(A1);
for k = 1:nscans
Y4 = spm_read_vols(P(k));
% WOULD BE GREAT IF P.MAT HAD THE INFORMATION HERE.
% Get the voxel displacement for every voxel
[ Xp, Yp, Zp ] = rmove(R(k).mat, imagedim, R(1).mat);
% Apply corrections
Y4 = Y4 - sin(Xp*2*pi/vx).*A1 - (1-cos(Xp*2*pi/vx)).*A2;
Y4 = Y4 - sin(Yp*2*pi/vy).*A3 - (1-cos(Yp*2*pi/vy)).*A4;
Y4 = Y4 - sin(Zp*2*pi/vz).*A5 - (1-cos(Zp*2*pi/vz)).*A6;
% Prepare the header for the filtered volume.
prechar ='m';
V = spm_vol(P(k).fname);
v = V;
[dirname, sname, sext ] = fileparts(V.fname);
sfname = [ prechar, sname ];
filtname = fullfile(dirname,[sfname sext]);
v.fname = filtname;
spm_write_vol(v,Y4);
showprog = [' 3D Motion adjusted volume ', sname, sext ];
%disp(showprog);
end
disp('Done with motion adjustment!')
function [ Xp, Yp, Zp ] = rmove(New,imagedim,Baseline);
% P.mat transforms voxel coordinates to x,y,z position in mm.
% New is P.mat for image, Baseline is P(1).mat for baseline image
% dim is 3D vector of image size.
Mf = New - Baseline;
for i = 1:imagedim(1)
for j = 1:imagedim(2)
for k = 1:imagedim(3)
Xp(i,j,k) = Mf(1,1)*i+Mf(1,2)*j+Mf(1,3)*k+Mf(1,4);
Yp(i,j,k) = Mf(2,1)*i+Mf(2,2)*j+Mf(2,3)*k+Mf(2,4);
Zp(i,j,k) = Mf(3,1)*i+Mf(3,2)*j+Mf(3,3)*k+Mf(3,4);
end
end
end
|
github
|
philippboehmsturm/antx-master
|
art_automask.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/ArtRepair/art_automask.m
| 8,663 |
utf_8
|
00761162b94e9340128d2fb96852aab6
|
function Y = art_automask(Image,Threshold,WriteVol);
% Y = art_automask( Image, Threshold, WriteVol ) (v2.2)
% art_automask;
%
% Calculates a pretty good mask image from an input full-head Image
% in order to detect artifacts in the data. The threshold
% is higher than usual for SPM because the spiral scan generates more
% noise outside the head. When called with one
% or no arguments, the mask is adapted for the input image, and the mask is
% written to "ArtifactMask.img" for later user review. The adaptation
% sets a threshold level, removes speckle, and removes corner artifacts.
% The adaptive mask is usually a bit larger than the head.
% The GUI version allows a user to select a threshold,e.g. by looking at
% an SPM display of the image to estimate a value. The program will fill
% in small holes in the mask, so you can pick slightly high values to
% suppress noise and still obtain a mask without gaps.
%
% GUI INPUT
% Image - select the image to use
% Threshold - Select a threshold to use.
% UserMask - Select a name for the derived mask file.
% BATCH INPUT:
% Image - full path name of an image file, e.g. 'C:\test\V002.img'
% Threshold- measured as a FRACTION of the range of Image
% If > 0, applies that threshold. Values from 0.10 to 0.30 are typical.
% e.g. if the Image range is [0,2000] and Threshold = 0.15,
% then a fixed threshold of 300 is applied.
% If not supplied, threshold is set adaptively to a value that is
% 0.2 to 0.4 of the max range of the smoothed image.
% WriteVol = 0 does not write a mask file.
% If not supplied, mask file is written.
%OUTPUT:
% Y 3D mask array, with 1's and 0's.
% ArtifactMask.img, written to the image directory, if WriteVol = 1.
% UserMaskname.img, written to the image directory in GUI maode.
%
% Paul Mazaika April 2004.
% V.2 adapts to different mean image levels. Paul Mazaika Aug. 2006.
% V2.1 write maskvalue=1. get/write changes for SPM5. (2/07)
% v2.2 better GUI for user to set a mask threshold
% Adaptive Threshold Logic depends on estimated error rate outside the head.
% Fraction of points outside the head that pass the threshold must be small.
% For each slice, set the slice to zero if the fraction of mask points on
% the slice is smaller than parameter FMR.
FMR = 0.015; % False Mask Percentage.
spmv = spm('Ver');spm_ver = 'spm2';
if (strcmp(spmv,'SPM5') | strcmp(spmv,'SPM8b') | strcmp(spmv,'SPM8') )
spm_ver = 'spm5'; end
if nargin == 0
if strcmp(spm_ver,'spm5')
Image = spm_select(1,'image','Select image as source for automask.');
else % spm2 version
Image = spm_get(1,'.img','Select image as source for automask.');
end
%Image = spm_select(1,'image','Select image as source for automask.');
%Threshold = -1; % Adaptive mask by default
Threshold = spm_input('Select threshold value' ,1,'r');
MaskName = spm_input('Select name for calculated mask file' ,1,'s','UserMask');
WriteVol = 1; % Writes the mask out for inspection.
elseif nargin == 1
Threshold = -1; % Adaptive mask by default.
WriteVol = 1; % Writes the mask out for inspection.
end
% Get the image data.
V = spm_vol(Image(:,:)); % Input could be a matrix; only need one image.
n = prod(size(V));
Y = spm_read_vols(V);
% Fill in the small holes and reduce the noise spikes.
Y = smooth3(Y); % default 3x3x3 box smoothing.
Yr = max(max(max(Y))) - min(min(min(Y))); % previously used range.
% User defined mask threshold
if Threshold > 0 % Make the mask directly
% Array temp is logical array with 1's and 0's
temp(:,:,:) = (Y(:,:,:)>Threshold);
end
% Adaptive Mask Threshold
if ( Threshold == -1 ) % Find a threshold that discards three outer faces.
% Use gray matter density as lower limit- count is 400.
Tlow = fix(0.2*Yr); Thigh = fix(0.4*Yr); Tskip = max(fix(Tlow/20),1);
for Tbar = Tlow:Tskip:Thigh % 400:20:800
temp(:,:,:) = (Y(:,:,:) > Tbar);
% Count the number of mask points in the far faces of the volume
xdim = size(Y);
count1 = sum(sum(temp(:,:,1)));
count2 = sum(sum(temp(:,:,xdim(3))));
count3 = sum(sum(temp(:,1,:)));
count4 = sum(sum(temp(:,xdim(2),:)));
count5 = sum(sum(temp(1,:,:)));
count6 = sum(sum(temp(xdim(1),:,:)));
% Always have one face with large counts, sometimes have 2 such faces.
countA = count1+count2+count3+count4+count5+count6;
Xbar = [ count1 count2 count3 count4 count5 count6 ];
Ybar = sort(Xbar);
countC = Ybar(1) + Ybar(2); % the two smallest face counts
countB = Ybar(1) + Ybar(2) + Ybar(3); % three smallest face counts
% Number of voxels on 3 faces is approximately:
nvox = xdim(1)*xdim(2) + xdim(2)*xdim(3) + xdim(1)*xdim(3);
if ( countC < FMR*nvox )
break; % Exit the For loop, current Tbar is good enough.
end
% iter = iter + 1;
% ygraph(1,iter) = countA;
% ygraph(2,iter) = countB;
% ygraph(3,iter) = countC;
end
disp('Adaptive Mask Threshold')
disp(Tbar)
%disp(countC)
%disp(ygraph')
end
if Threshold == -1
if Tbar >= Thigh-Tskip
disp('Automask program failed. Try choosing a mean image,')
disp(' or manually set a threshold. Type help art_automask.')
return
end
end
% Clean up the corner alias artifact sometimes evident in the spiral data.
% If the edge of a plane has much more data than the center, delete the
% edge. Then if any plane has too few data points (meaning close to noise level)
% then set the entire plane in the mask image to zero. Note for spiral scans
% a better idea might be to determine the orientation of the spiral, and just
% remove the potential alias effects at those four edges corners.
xdim = size(Y);
iedge = floor(max(5,0.2*xdim(1)));
jedge = floor(max(5,0.2*xdim(2)));
kedge = floor(max(5,0.2*xdim(3)));
% Clear out the edges, and then check the planes.
for i = 1:xdim(1)
% If edges are bigger than center, then delete edges.
fmaski = sum(sum(temp(i,jedge:xdim(2)-jedge,kedge:xdim(3)-kedge)));
mo1 = sum(sum(temp(i,1:jedge,:)));
if ( mo1 > 2*fmaski ) temp(i,1:5,:) = 0; end
mo2 = sum(sum(temp(i,xdim(2)-jedge:xdim(2),:)));
if (mo2 > 2*fmaski) temp(i,xdim(2)-4:xdim(2),:) = 0; end
mo3 = sum(sum(temp(i,:,1:kedge)));
if (mo3 > 2*fmaski) temp(i,:,1:5) = 0; end
mo4 = sum(sum(temp(i,:,xdim(3)-kedge:xdim(3))));
if (mo4 > 2*fmaski) temp(i,:,xdim(3)-4:xdim(3)) = 0; end
% If face is about the noise level, then delete the face.
fmaski = sum(sum(temp(i,:,:)));
if fmaski < 2*FMR*xdim(2)*xdim(3)
temp(i,:,:) = 0;
end
end
for j = 1:xdim(2)
fmaskj = sum(sum(temp(iedge:xdim(1)-iedge,j,kedge:xdim(3)-kedge)));
mo1 = sum(sum(temp(1:iedge,j,:)));
if ( mo1 > 2*fmaskj ) temp(1:5,j,:) = 0; end
mo2 = sum(sum(temp(xdim(1)-iedge:xdim(1),j,:)));
if (mo2 > 2*fmaskj) temp(xdim(1)-4:xdim(1),j,:) = 0; end
mo3 = sum(sum(temp(:,j,1:kedge)));
if (mo3> 2*fmaskj) temp(:,j,1:5) = 0; end
mo4 = sum(sum(temp(:,j,xdim(3)-kedge:xdim(3))));
if (mo4 > 2*fmaskj) temp(:,j,xdim(3)-4:xdim(3)) = 0; end
fmaskj = sum(sum(temp(:,j,:)));
if fmaskj < 2*FMR*xdim(1)*xdim(3)
temp(i,:,:) = 0;
end
end
for k = 1:xdim(3)
fmaskk = sum(sum(temp(:,:,k)));
if fmaskk < 2*FMR*xdim(2)*xdim(1)
temp(i,:,:) = 0;
end
end
% Outputs
Y = temp;
if ( WriteVol == 1 )
v = V; % preserves the header structure
[dirname, xname, xext ] = fileparts(V.fname);
artifname = ['ArtifactMask' xext];
if nargin == 0
artifname = [MaskName xext];
end
artifpath = fullfile(dirname,artifname);
v.fname = artifpath;
noscale_write_vol(v,Y);
end
%---------------------------------------------------------------
% Create and write image without the scale and offset steps
% This function is spm_write_vol without error checking and scaling.
function noscale_write_vol(V,Y);
V = spm_create_vol(V);
for p=1:V.dim(3),
V = spm_write_plane(V,Y(:,:,p),p);
end;
%V = spm_close_vol(V); % not for SPM5
|
github
|
philippboehmsturm/antx-master
|
art_groupoutlier.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/ArtRepair/art_groupoutlier.m
| 18,950 |
utf_8
|
2d22a294e3de9362486a0b535eb4b591
|
function art_groupoutlier(ConImageNames, GroupMaskName,Groupscale, OutputDir)
% FUNCTION art_groupoutlier
% >> art_groupoutlier to run by GUI
%
% Program runs the global quality metrics for a contrast image from all
% subjects. Creates a summary over all subjects of GQ scores per
% per subject, visually displays scores of all subjects, and
% recommends good subgroups for group analyses.
%
% User MUST specify (peak/contrast_sum) to make the scaling correct!
% Find this value by running >>art_percentscale on a single subject.
%
% GUI INPUTS
% Select a set of single subject con images. Use same syntax as making an SPM group study.
% Enter peak/contrast sum. Get this by running art_precentscale on one subject.
% It is usually the same for all regressors, for all subjects.
% OUTPUT is written to current working directory, and displayed.
% This text file and jpg image files summarize all subjects together.
%
% BATCH INPUT (as called from art_groupcheck)
% art_groupoutlier(ConImageNames, GroupMaskName,Groupscale, OutputDir)
% ConImageNames is cell array of contrast images names
% GroupMaskName is full path name of one mask image for all subjects.
% Usually this is the mask image of the group result.
% If GroupMaskName = 0, each subject uses its own mask.
% Groupscale is 3 element vector with peak, contrastsum, and bmean.
% OutputDir specifies where output images and files will be written.
%
% BUG: Sometimes the figure legend will cover a data point.
% Compatible with SPM5 and SPM2.
% paul mazaika - added SPM8, May 2009
% Set some reference guides for assumed single subject values
% Values are in percent signal change
% We'll learn more about these values in the future.
% REFERENCE values are used to draw the reference box
REFW = 0.07; % for block GoNoGo design
REFM = 0.07; % for exec control contrast experiment
REFSTD = 0.25; % for 1% noise, difference of 50 sample estimates.
% Cluster center of data (ROBUSTM, ROBUSTW) is estimated in the code.
% Set high intersubject variability, used only in Figures.
UNIFHIGH = 0.2; % was 0.17
% Identify spm version
spmv = spm('Ver'); spm_ver = 'spm2';
if (strcmp(spmv,'SPM5') | strcmp(spmv,'SPM8b') | strcmp(spmv,'SPM8') )
spm_ver = 'spm5'; end
if nargin == 0
%clear all;
OutputDir = pwd; % Get user's current working directory
if strcmp(spm_ver,'spm5')
Rimages = spm_select(Inf,'image','Select single subject con images' );
else % spm2
Rimages = spm_get(Inf,'.img','Select single subject con images');
end
% pk_con value is the peak/contrast sum for the regressor of interest.
pkcon_value = spm_input('Enter peak/(contrast_sum)',1,'e');%,1.13,1);
[temp1, ConImageName,cext ] = fileparts(Rimages(1,:));
[temp, ResultsFolder ] = fileparts(temp1);
%MaskPath = ResultsFolder;
UseGroupMask = 0;
for i = 1:size(Rimages,1)
temp = fileparts(Rimages(i,:));
sjResults{i} = temp;
temp2 = fileparts(temp);
sjDirX{i}=temp2;
end
%ConImageName = [ ConImageName cext];
ScaleFactor(1) = pkcon_value;
ScaleFactor(2) = 1; % art_summary only needs ratio to be right.
% ScaleFactor(3) =bmean is found for each image
elseif nargin > 0
% inputs for groupoutlier5
%Rimages = char(sjDirX);
%Maskpath = ResultsFolder;
% other variables are passed as arguments
Rimages = char(ConImageNames); % ConImageNames is a cell array
if GroupMaskName == 0
UseGroupMask = 0; % each single subj. contrast uses its own mask
else
UseGroupMask = 1; % group mask is applied to each contrast
disp('Using same group mask for all contrasts.')
end
[temp1, ConImageName,cext ] = fileparts(char(ConImageNames{1}));
[temp, ResultsFolder ] = fileparts(temp1);
%MaskPath = ResultsFolder;
for i = 1:length(ConImageNames)
temp = fileparts(char(ConImageNames{i}));
sjResults{i} = temp;
temp2 = fileparts(temp);
sjDirX{i}=temp2;
end
%ConImageName = [ ConImageName cext];
pkcon_value = Groupscale(1);
ScaleFactor(1) = Groupscale(1);
ScaleFactor(2) = Groupscale(2); % only use is send to art_summary
ScaleFactor(3) = Groupscale(3);
% other variables are passed as arguments
end
X = zeros(length(sjDirX), 5);
NumSubj = length(sjDirX);
% Global Quality of Estimates
for i = 1:length(sjDirX)
%Resultspath = fullfile(sjDirX{i},ResultsFolder);
if UseGroupMask == 0
%Maskpath = fullfile(sjDirX{i},ResultsFolder);
Maskpath = char(sjResults{i});
if strcmp(spm_ver,'spm5')
MaskImage = spm_select('FPList',Maskpath,'^mask.*\.img$');
else % spm2 logic
MaskImage = fullfile(Maskpath,'mask.img');
end
elseif UseGroupMask == 1
MaskImage = GroupMaskName;
end
if nargin == 0
ConImage = Rimages(i,:);% fullfile(Resultspath, ConImageName);
elseif nargin > 0
ConImage = char(ConImageNames{i});
end
if nargin == 0 & i == 1 % Use first one to scale all (approximation).
ScaleFactorX = art_percentscale(ConImage,MaskImage);
ScaleFactor(3) = ScaleFactorX(3);
end
OutputPath = sjDirX{i};
% Last two arguments write Figure 71 with title 'GroupSelect'.
[g,r, s] = art_summary(ConImage,MaskImage,OutputPath,'GroupSelect',71,ScaleFactor);
X(i,2) = g; % width (stdev)
X(i,3) = r; % mean
X(i,4) = s; % Resout, Mean of sqrt(ResMS)number
% for art_redo/art_summary, it is mean of Res image.
X(i,1) = i; % an index number
end
% Get the NAME of the subject
for i = 1:NumSubj
[ a, b, c ] = fileparts(sjDirX{i});
[ a1, b1, c1 ] = fileparts(a);
[ a2, b2, c2 ] = fileparts(a1);
Y{i} = [ b2 '/' b1 '/' b ];
end
% Find two robust measures of GQmean
groupmean = mean(X(:,3));
medianofgroup = median(X(:,3));
trim50 = trimmean(X(:,3),50);
ROBUSTM = 0.5*(medianofgroup + trim50);
% Find a measure of the horizontal location of the main cluster
allwidths = X(:,2);
allsort = sort(allwidths);
ROBUSTW = allsort(round(length(allsort)/4));
% Estimate the standard deviation of confound score. Add variances
% for distance of mean from zero, and the boost in variance relative
% to the variance ROBUSTW for an estimated single subject.
%. ASSUMES SINGLE SUBJECT has true mean of zero.
for i = 1:NumSubj
% Currently, not used. Assumes that zero is correct.
X(i,5) = sqrt(X(i,3)^2 + max(0,(X(i,2)^2 - ROBUSTW^2)));
end
% Estimate the confound score, using an assumed mean from robust estimate.
for i = 1:NumSubj
%X(i,6) = sqrt((X(i,3)-ROBUSTM)^2 + max(0,(X(i,2))^2 - ROBUSTW^2));
% total variance includes intersubject, est, and confound
X(i,6) = sqrt((X(i,3)-ROBUSTM)^2 + max(0,(X(i,2))^2 ));
end
% Print a TABLE of subject results
disp('Output images and text file will be written to this folder:')
disp(OutputDir)
disp(' ')
pkconwords = ['User entered value for peak/contrast_sum: ',num2str(pkcon_value)];
disp(pkconwords)
disp(' ')
disp(' INDIVIDUAL SUBJECT PROPERTIES (ordered as input)')
disp(' Index GQwidth GQmean RESavg GQrms')
%disp(X);
for i = 1:NumSubj
fprintf(1,'\n%5d %8.4f %8.4f %8.4f %8.4f', round(X(i,1)),X(i,2),...
X(i,3),X(i,4),X(i,6));
end
disp(' ')
subj.GQdata = X;
subj.name = Y;
%save subjectsummarystruct subj
% Find and display two robust measures of bias.
disp(' ')
disp(' ESTIMATES OF GQmean averaged over the Group')
disp(' Mean, Median and 50% trimmed mean of subject GQmeans ')
disp(groupmean)
disp(medianofgroup)
disp(trim50)
disp('Robust mean = average of median and trimmed mean')
disp(ROBUSTM)
% Define ideal point and GQmean = 0 line.
cnormm = [ -REFM REFM ];
cnormw = [ REFW REFW ];
didealstdev = [ REFSTD REFW REFW REFSTD ];
didealmean = [ -REFM -REFM REFM REFM ];
% Draw GQ figure for subject
figure(72);
ahcw = X(:,2);
ahcm = X(:,3);
robw = [ 0 max(ahcw+0.1)];
robm = [ ROBUSTM ROBUSTM ];
%plot(ahcm,ahcw,'kd',...
% robm,robw,'k:',cnormm,cnormw,'r--',didealmean,didealstdev,'r-.');
h11=plot(ahcm,ahcw,'kd');
hold on;
plot(robm,robw,'k:',cnormm,cnormw,'r--',didealmean,didealstdev,'r-.');
set(h11,'LineStyle','none');
set(h11,'Marker','o','MarkerFaceColor',[0 0 0],'MarkerEdgeColor',[0 0 0],'MarkerSize',8.0);
legend('Subjects','Robust mean','Ref. subject variability','Ref. lack of power','Location','Best','boxoff');
%plot(ahcm,ahcw,'rd',cnormm,cnormw,'gs',csinglem,csinglew,'bs');
%legend('Subjects','"Ideal"','No confounds','Location','Best');
ylim([ 0 max(ahcw+0.1)]);
%axes_lim = get(gca, 'YLim');
%axes_height = [ axes_lim(1) axes_lim(2)];
axis equal;
%line([0 0], [ROBUSTM max(ahcw+0.1)], 'Color', 'k','LineStyle',':');
title('Global Quality scatterplot, by subject')
xlabel('Global Mean: Mean of histogram (percent signal change)');
ylabel('Global Quality: Stdev of histogram (percent signal change)');
hold off;
% Make a Pretty Figure
fh = figure(82);
ylim([ 0 max(ahcw+0.1)]);
h1 = plot(ahcm,ahcw);
hold on;
h2 = plot(robm,robw);
h4 = plot(cnormm,cnormw);
h3 = plot(didealmean,didealstdev);
% set background white
set(fh,'color','white');
set(h1,'LineStyle','none');
set(h1,'Marker','o','MarkerFaceColor',[0 0 0],'MarkerEdgeColor',[0 0 0],'MarkerSize',8.0);
set(h3,'LineStyle','-.','LineWidth',1.0,'Color','Red');
set(h3,'Marker','none');
set(h2,'LineStyle',':','Color','Black');
set(h2,'Marker','none');
set(h4,'LineStyle','--','LineWidth',1.0,'Color','Red');
set(h4,'Marker','none');
% remove plot box
set(gca,'Box','off');
axis equal;
h5=legend('Subjects','Robust mean','Ref. subject variability','Ref. lack of power','Location','Best');
set(h5,'Location','Best','FontSize',12);
%set(gca,'TickDir','out','XTick',[0:10],'YTick',[1:5]);
set(gca,'TickDir','out');
xlabel('Global Mean (percent signal change)','FontSize',14);
ylabel('Global Standard Deviation of Histogram (pct sig ch)','FontSize',14,'Rotation',90);
title('Global Quality scatterplot, by subject','FontSize',16)
% save for LateX. Mac converts postscript to pdf
% This looks much cleaner than .jpg.
%saveas(fh,'FruitflyPopulation','epsc');
% save for Word
%saveas(fh,'FruitflyPopulationWord','jpg');
hold off
cd(OutputDir); % prints images to this folder
figname = ['SubjectGQScatterplot.jpg'];
saveas(gcf,figname);
% Try two sorts: One by variance alone.
% The second also tries to keep the subgroup bias zero.
% Both sorts use ROBUSTM as the reference mean value.
for sortmethod = 1:2
if sortmethod == 1
% SORT the subjects by GQ magnitude, Assuming ROBUST mean.
sqvar = X(:,6);
[svar, isort ] = sort(sqvar);
elseif sortmethod == 2
% Order subjects by mean square error, Assuming ZERO mean.
% and resort the means along with the variances
sqvar = X(:,6); % 6 is ROBUST MEAN, 5 IS ZERO mean
isort = dualsort(sqvar,X(:,3));
svar = sqvar(isort);
end
cc = X(isort,3); % keep track of biases on sorted subjects
NumSubj = size(X,1);
xax = [ 1: NumSubj ];
% Make a low and high uniform variable, in stdev
unif2 = svar(1)*ones(NumSubj,1); % Starts with GQ scores
unifhi = UNIFHIGH*ones(NumSubj,1);
combo2 = sqrt(svar.*svar+unif2.*unif2);
combohi = sqrt(svar.*svar+unifhi.*unifhi);
limhi = ROBUSTM + REFW*ones(NumSubj,1);
limlo = ROBUSTM - REFW*ones(NumSubj,1);
% Next consider the effects of bias per subject.
% The observed bias from group to group is 0.012 or so.
zeroline = zeros(NumSubj+1,1);
zax = [0:NumSubj];
if sortmethod == 1; figure(73); end
if sortmethod == 2; figure(75); end
clf;
h22 = plot(xax,svar,'ro-');
hold on;
plot( xax,combohi,'k-');
h23 = plot(xax,cc,'bo-');
plot( ...
xax,limlo,'b:',xax,limhi,'b:',zax,zeroline,'k-');
set(h22,'LineStyle','-','Color','Red');
set(h22,'Marker','o','MarkerFaceColor',[0.8 0 0],'MarkerEdgeColor',[0.8 0 0],'MarkerSize',6.0);
set(h23,'LineStyle','-','Color','Blue');
set(h23,'Marker','o','MarkerFaceColor',[0 0 0.8],'MarkerEdgeColor',[0 0 0.8],'MarkerSize',6.0);
title('Each Subjects Global Quality scores, sorted by total variance')
if sortmethod == 2
title('Each Subjects Global Quality scores, sorted keeping bias near zero')
end
xlabel('Subject ID sorted')
legend('GQ Total Stdev','Plus high intersubject','GQMean',...
'2-sigma limit on mean','Location','NorthWest');
figname = ['SubjectsSortedbyGQ.jpg'];
saveas(gcf,figname);
% Find variance of mean, for each subgroup size, N
sumvar(1) = svar(1)^2;
sumbar(1) = cc(1);
sumunif(1) = unif2(1)^2;
sumhi(1) = unifhi(1)^2;
sumchi(1) = sumvar(1)+sumhi(1);
for i = 2:NumSubj
sumvar(i) = sumvar(i-1) + svar(i)^2;
sumbar(i) = sumbar(i-1) + cc(i);
sumunif(i)= sumunif(i-1) + unif2(i)^2;
sumhi(i) = sumhi(i-1) + unifhi(i)^2;
sumchi(i) = sumvar(i) + sumhi(i);
end
for i = 1:NumSubj
stdmean(i) = sqrt(sumvar(i)/(i*i));
subgpmean(i) = sumbar(i)/i;
stdunif2mean(i) = sqrt(sumunif(i)/(i*i));
stdchi(i) = sqrt(sumchi(i)/(i*i));
end
% Find subgroups, over half the group in size,
% with means within 2-sigma of target value ROBUSTM
if sortmethod == 1 | 2 % target value is robust mean
subgpmean1 = subgpmean - ROBUSTM;
bias2mean = sqrt(subgpmean1.*subgpmean1);
end
groupchoice(1:NumSubj) = 0;
for i = round(NumSubj/2):NumSubj
if bias2mean(i) < (REFW)/sqrt(i);
groupchoice(i) = 1;
end
end
gc = find(groupchoice == 1);
lengc = zeros(length(gc),1);
% Draw limits of reasonable values for group mean (within 2-sigma)
biashi(1,2:NumSubj) = ROBUSTM + REFW./sqrt(xax(2:NumSubj));
biaslo(1,2:NumSubj) = ROBUSTM - REFW./sqrt(xax(2:NumSubj));
if sortmethod == 1; figure(74); end
if sortmethod == 2; figure(76); end
clf;
plot(xax(2:NumSubj),stdmean(2:NumSubj),'r',xax(2:NumSubj),stdchi(2:NumSubj),'k-',...
xax(2:NumSubj),stdunif2mean(2:NumSubj),'g--',...
xax,subgpmean,'b-',xax(2:NumSubj),biashi(2:NumSubj),'b:',xax(2:NumSubj),biaslo(2:NumSubj),'b:',zax,zeroline,'k-');
title('Predicted Subgroup Performance: Global StdErr ordered by variance only');
if sortmethod == 2
title('Predicted Subgroup Performance: Global StdErr while forcing zero bias')
end
xlabel('Number of subjects in subgroup');
ylabel('Expected standard error of the mean');
legend('GQ Total','Plus high intersubject',...
'Uniform Only','SubGroup Mean','2-sigma limits on mean');
% Add good subgroup choices and a best choice based on min stdev
[ dummy,index ] = min(stdmean);
gbest = index;
hold on;
if sortmethod == 1 | 2
for i = 1:length(gc)
line((gc(i)*ones(1, 2)), [ subgpmean(gc(i)) stdmean(gc(i)) ], ...
'Color','k','Marker','o','LineStyle',':');
end
line((gbest*ones(1, 2)), [ subgpmean(gbest) stdmean(gbest) ], ...
'Color','k','Marker','o','LineStyle','-');
end
hold off;
figname = ['PredictedGroupAccuracy.jpg'];
saveas(gcf,figname);
% Make a TABLE of sorted subjects, number in group, expected performance
for i = 1:NumSubj
gpsel.id(i) = isort(i);
gpsel.name(i) = Y(isort(i));
gpsel.GQ1(i) = stdmean(i);
gpsel.GQ3(i) = stdchi(i);
gpsel.GQ2(i) = subgpmean(i);
end
gpsel.select(1:NumSubj) = 0;
for i = 1:length(gc)
gpsel.select(gc(i)) = gc(i);
end
gpsel.select(gbest) = gbest;
gptable = [ gpsel.select', gpsel.GQ1' gpsel.GQ3'...
gpsel.GQ2' gpsel.id' ];
disp(' ')
disp(' PREDICTED SUBGROUP PERFORMANCE')
if sortmethod == 1
disp(' SUBGROUP SELECTIONS BASED ON MINIMUM VARIANCE ONLY')
elseif sortmethod == 2
disp(' RECOMMENDED: SUBGROUP SELECTIONS WITH MEAN NEAR ROBUST MEAN')
end
disp(' Group Group Group Group Individual')
disp(' Size StdErr StdEHi Mean Index Subject')
for i = 1:NumSubj
fprintf(1,'\n%5d %8.4f %8.4f %8.4f %5d %s', gptable(i,1),gptable(i,2),...
gptable(i,3),gptable(i,4),gptable(i,5),gpsel.name{i});
end
disp(' ')
% DETECT, COUNT, AND LOG THE ARTIFACTS
if sortmethod == 1
%disp('Writing results file to current directory')
tstamp = clock;
filen = ['OutlierSubjects',date,'Time',num2str(tstamp(4)),num2str(tstamp(5)),'.txt'];
logname = fullfile(OutputDir,filen);
logID = fopen(logname,'wt');
fprintf(logID,'Outlier Subjects Analysis from art_groupoutlier program (feb09): \n %s\n');
% Print a LIST of con images for this analysis
fprintf(logID,'\n LIST OF INPUTS (Single Subject Images)');
for i = 1:size(Rimages,1)
fprintf(logID,'\n%3d %s',i, Rimages(i,:));
end
fprintf(logID,'\n %s',pkconwords)
% Print a TABLE of subject results
fprintf(logID,'\n\n INDIVIDUAL SUBJECT PROPERTIES (ordered as input)');
fprintf(logID,'\n Index GQwidth GQmean RESavg GQrms');
for i = 1:NumSubj
fprintf(logID,'\n%5d %8.4f %8.4f %8.4f %8.4f ', round(X(i,1)),X(i,2),...
X(i,3),X(i,4),X(i,6));
end
% Print the robust estimates of the global mean
fprintf(logID,'\n\n ROBUST ESTIMATES of the GLOBAL MEAN ');
fprintf(logID,'\n Mean Median 50% Trimmean RobustMean');
fprintf(logID,'\n %8.4f %8.4f %8.4f %12.4f', ...
groupmean, medianofgroup, trim50, ROBUSTM);
fprintf(logID,'\n Robust mean is average of median and 50 pct trimmemd mean');
end
% Print a table of recommended subgroups
fprintf(logID,'\n\n PREDICTED SUBGROUP PERFORMANCE');
if sortmethod == 1
fprintf(logID,'\n Subgroups chosen with minimum variance only ');
elseif sortmethod == 2
fprintf(logID,'\n Subgroups chosen to prefer group mean near robust mean ');
end
fprintf(logID,'\n Groups with small group means show the group size.');
fprintf(logID,'\n Group Group Group Group Individual');
fprintf(logID,'\n Size StdErr StdEHi Mean Index Subject') ;
for i = 1:NumSubj
fprintf(logID,'\n%5d %8.4f %8.4f %8.4f %5d %s', gptable(i,1),gptable(i,2),...
gptable(i,3),gptable(i,4),gptable(i,5),gpsel.name{i});
end
if sortmethod == 2
fclose(logID);
end
end % sortmethod loop
%------------------------------------------------------------------
function G = dualsort(A,B)
% Balances choosing smaller variances with maintaining zero mean
% A is vector of variances (always positive)
% B is vector of means.
% G is vector of index numbers for the dualsort order
% Set a balancing parameter
% BAL = 1 means Ordinary sort on variance alone
% BAL = 1000 means just zero bias is considered
BAL = 1.4;
n = length(A);
C = zeros(1,n);
meansum = 0;
for i = 1:n
y = find(C==0);
ymin = min(A(y));
ylim = ymin*BAL + 0.00001;
z = zeros(1,n);
for j = 1:length(y)
z(y(j)) = abs(meansum + B(y(j)));
end
meantemp = 1000;
for j = 1:length(y)
if A(y(j)) < ylim & z(y(j)) < meantemp
jtemp = y(j);
meantemp = z(y(j));
end
end
C(jtemp) = i;
meansum = meansum + B(jtemp);
end
[ gt, G ] = sort(C);
|
github
|
philippboehmsturm/antx-master
|
art_despike.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/ArtRepair/art_despike.m
| 11,589 |
utf_8
|
5e3e7b11e4139268b7cdbae79a22893f
|
function zout = art_despike(Images,FiltType,Despike)
% FUNCTION art_despike(Images,FiltType,Despike)
% >> art_despike to run by GUI
%
% Removes spikes and slow variations using clipping and a high pass filter.
% Generally, these functions remove large noise at the expense of slightly
% reducing the contrast between conditions.
% WARNING! FOR UNNORMALIZED IMAGES ONLY. The large size of normalized
% images may cause this program to crash or go very slow.
%
% The user can choose a despike threshold and the type of filter.
% The DESPIKE function clips all values further than DESPIKE % from a
% rolling mean to exactly a DESPIKE % deviation. For example, if DESPIKE=4,
% a spike of size 6% will be reduced to size 4. Despiking is performed
% voxel-wise, since spikes may occur only on some voxels. Despike can be
% turned off by setting Despike=0.
%
% The high pass filter removes slow variations on each voxel with an AC-coupled
% filter, and adds the mean input image to write the output images. The
% GUI allows two high pass filter choices and a smoothing filter. The ends
% of the dataset are padded by reflection for the filter process. If both
% despike and filtering are chosen, images will be despiked before
% entering the high pass filter.
%
% INPUTS
% Images is a list of images, in a single session.
% Images must all have the same orientation and size.
% FiltType has 4 options:
% 1. 17-tap filter, aggressive high pass filter.
% 2. 37-tap filter, long filter for block designs. SPM high pass
% filter may be better since it preserves gain.
% 3. No high pass filtering is done. Despiking is done based
% on a 17-point moving average of unfiltered data.
% 4. Matched filter for single events using temporal smoothing.
% Perhaps useful for movies of ER fMRI
% Clip Threshold is used to despike the data, in units of percentage
% signal change computed relative to the mean image.
% If Despike = 0, no clipping is done. Despike=4 is the default.
% OUTPUTS
% Images with a prefix "d" (for despike or detrend) in the same directory.
% The filtered images have the same mean as the original series.
% Mean input image, named meenINPUT.img, where INPUT is input image
% name. Misspelling of mean is deliberately different from mean
% image produced by spm realignment.
% All input images are preserved.
%
% Clips and filters about 1 volume per second with default settings.
% SPM high-pass filtering is OK, but not required after this filter.
% Note these filters are applied to only the data, so there is a filter
% gain to try to preserve a quantitative amplitude information. This works
% OK for ER designs, but not as well for block designs. The SPM high pass
% filter applies to the data and design matrix, and is better for blocks.
% Runs through all the images sequentially like a pipeline.
%
% Compatible with SPM5, SPM8 and SPM2.
% Compatible with AnalyzeFormat and Nifti images.
% v.1 July 2008 Paul Mazaika
% v.2 May 2009 pkm despike output works off centered mean.
% Identify spm version
spmv = spm('Ver'); spm_ver = 'spm2';
if (strcmp(spmv,'SPM5') | strcmp(spmv,'SPM8b') | strcmp(spmv,'SPM8') )
spm_ver = 'spm5'; end;
spm('defaults','fmri');
if nargin == 0
CLIP = 1; % 1 to despike, 0 to not despike which is a bit faster.
% DE-SPIKE CLIP PERCENTAGE. Default is 4%.
Despikedef = 4;
Despike = spm_input('Enter clip threshold (pct sig chg)',1,'e',Despikedef);
if Despike == 0; CLIP = 0; end
FiltType = spm_input('Select high pass filter',...
1,'m','17-tap, Robust filter for noisy images |37-tap, Better for block designs in clean images |No high pass filter.|Matched filter for isolated ER designs',[ 1 2 3 4], 1);
if (Despike == 0 & FiltType == 3) disp('Error: Conflict in inputs.'); return; end;
if strcmp(spm_ver,'spm5')
Pimages = spm_select(Inf,'image','Select images to filter');
else % spm2
Pimages = spm_get(Inf,'.img','select images to filter');
end
else
Pimages = Images;
%afilt = HPFilter;
if Despike == 0 & FiltType ~= 3
CLIP = 0
elseif Despike > 0
CLIP = 1;
elseif Despike == 0 & FiltType == 3
disp('Error: Conflict in art_despike inputs.');
return;
end
end
% Set up filter coefficients
% HPFilter is a filter vector (1,N) where N must be ODD in length
% and the sum of the coefficients is zero.
if FiltType == 1
% 17-tap high pass filter with the coefficients sum of zero
afilt = [ -1 -1 -1 -1 -1.5 -1.5 -2 -2 22 -2 -2 -1.5 -1.5 -1 -1 -1 -1];
gain = 1.1/22; % gain is set for small bias for HRF shape
elseif FiltType == 2
% 37-tap high pass filter, Takes about 2 sec per image.
afilt = [ -ones(1,18) 36 -ones(1,18) ];
gain = 1/36; % gain is set for small avg. bias to block length 11.
elseif FiltType == 3
% Skip filtering step. nfilt =17 for clipping baseline.
afilt = [ -ones(1,7) 0 14 0 -ones(1,7) ]; % dummy values used only to set nfilt.
gain = 1/14;
elseif FiltType == 4
% Movie filter, to possibly see single HRFs in art_movie
% Filter is matched to HRF shape, assuming TR=2 sec.
afilt = [ -1 -1 -1.2 -1.2 -1.2 -1.2 -1 -1 2.5 6.3 6.3 2.5 0 -1 -1 -1.2 -1.2 -1.2 -1.2 -1 -1];
gain = 1/14;
end
% Filter characterization
nfilt = length(afilt);
if mod(nfilt,2) == 0 % check that filter length is odd.
disp('Warning from art_despike: Filter length must be odd')
return
end
if abs(mean(afilt)) > 0.000001
disp('Warning from art_despike: Filter coefficients must sum to zero.')
return
end
lag = (nfilt-1)/2; % filtered value at 9 corresponds to a peak at 5.
% Convert despike threshold in percent to fractional mulitplier limits
spikeup = 1 + 0.01*Despike;
spikedn = 1 - 0.01*Despike;
fprintf('\n NEW IMAGE FILES WILL BE CREATED');
fprintf('\n The filtered scan data will be saved in the same directory');
fprintf('\n with "d" (for despike or detrend) pre-pended to their filenames.\n');
prechar = 'd';
if CLIP == 1
disp('Spikes are clipped before high pass filtering')
disp('Spikes beyond this percentage value are clipped.')
disp(Despike)
else
disp('No despiking will be done.');
end
if FiltType ~= 3
disp('The high pass filter is:');
disp(afilt);
wordsgain = [ 'With gain =' num2str(gain) ];
disp(wordsgain);
else
disp('No filtering will be done.');
end
% FILTER AND DESPIKE IMAGES
% Process all the scans sequentially
% Start and End are padded by reflection, e.g. sets data(-1) = data(3).
% Initialize lagged values for filtering with reflected values
% Near the end, create forward values for filtering with reflected values.
% Find mean image
P = spm_vol(Pimages);
startdir = pwd;
cd(fileparts(Pimages(1,:)));
[ xaa, xab, xac ] = fileparts(Pimages(1,:));
xaab = strtok(xab,'_'); % trim off the volume number
%meanimagename = [ 'mean' xaab xac ];
meanimagename = [ 'meen' xaab '.img' ];
local_mean_ui(P,meanimagename);
Pmean = spm_vol(meanimagename);
Vmean = spm_read_vols(Pmean);
nscans = size(Pimages,1);
% Initialize arrays with reflected values.
Y4 = zeros(nfilt,size(Vmean,1),size(Vmean,2),size(Vmean,3));
Y4s = zeros(1,size(Vmean,1),size(Vmean,2),size(Vmean,3));
disp('Initializing filter inputs for starting data')
for i = 1:(nfilt+1)/2
i2 = i + (nfilt-1)/2;
Y4(i2,:,:,:) = spm_read_vols(P(i));
i3 = (nfilt+1) - i2;
if i > 1 % i=1 then i3 = i2.
Y4(i3,:,:,:) = Y4(i2,:,:,:);
end
end
% Start up clipping is done here
if CLIP ==1
movmean = squeeze(mean(Y4,1));
for i = 1:nfilt
Y4s = squeeze(Y4(i,:,:,:));
Y4s = min(Y4s,spikeup*movmean);
Y4s = max(Y4s,spikedn*movmean);
Y4(i,:,:,:) = Y4s;
end
end
% Main Loop
% Speed Note: Use Y4(1,:,:,:) = spm_read_vols(P(1)); % rows vary fastest
disp('Starting Main Loop')
for i = (nfilt+1)/2:nscans+(nfilt-1)/2
if i <= nscans
Y4(nfilt,:,:,:) = spm_read_vols(P(i));
else % Must pad the end data with reflected values.
i2 = i - nscans;
Y4(nfilt,:,:,:) = spm_read_vols(P(nscans-i2)); % Y4(i2,:,:,:);
end
% Incremental clipping is done here
if CLIP == 1 & FiltType == 3 % only despiking
movmean2 = mean(Y4,1);
movmean = squeeze(movmean2); % just a speed thing.
% This lag is from FiltType = 3
Y4s = squeeze(Y4(nfilt-lag,:,:,:)); % centered for despike only
Y4s = min(Y4s,spikeup*movmean);
Y4s = max(Y4s,spikedn*movmean);
Yn2 = squeeze(Y4s);
elseif CLIP == 1 & FiltType ~= 3 % combined despike and filter
movmean2 = mean(Y4,1);
movmean = squeeze(movmean2); % just a speed thing.
Y4s = squeeze(Y4(nfilt,:,:,:)); % predictive despike to use in filter
Y4s = min(Y4s,spikeup*movmean);
Y4s = max(Y4s,spikedn*movmean);
Y4(nfilt,:,:,:) = Y4s;
end
if FiltType ~= 3 % apply filter to original or despiked data
Yn = filter(afilt,1,Y4,[],1);
Yn2 = squeeze(Yn(nfilt,:,:,:));
Yn2 = gain*Yn2 + Vmean;
end
% Prepare the header for the filtered volume, with lag removed.
V = spm_vol(P(i-lag).fname);
v = V;
[dirname, sname, sext ] = fileparts(V.fname);
sfname = [ prechar, sname ];
filtname = fullfile(dirname,[sfname sext]);
v.fname = filtname;
spm_write_vol(v,Yn2);
% Slide the read volumes window up.
showprog = [' Filtered volume ', sname, sext ];
disp(showprog);
for js = 1:nfilt-1
Y4(js,:,:,:) = Y4(js+1,:,:,:);
end
end
zout = 1;
fprintf('\nDone with despike and high pass filter!\n');
cd(startdir)
% Plot a sample voxel
demovoxel = round( size(Vmean)/3 );
xin = art_plottimeseries(Pimages ,demovoxel);
SubjectDir = fileparts(Pimages(1,:));
if strcmp(spm_ver,'spm5')
realname = [ '^d' '.*\.img$' ];
Qimages = spm_select('FPList',[SubjectDir ], realname);
else % spm2
realname = ['d' '*.img'];
Qimages = spm_get('files',[SubjectDir ], realname);
end
xhi = art_plottimeseries( Qimages ,demovoxel);
xscanin = [ 1:nscans];
xscanout = [ 1:size(Qimages,1) ];
figure(99)
plot(xscanin,xin,'r',xscanout,xhi,'b');
titlewords = ['Timeseries before (red) and after (blue) for Voxel ' num2str(demovoxel)];
title(titlewords)
%------------------------------------------------
function local_mean_ui(P,meanimagename)
% Batch adaptation of spm_mean_ui, with image name added.
% meanimagename is a character string, e.g. 'meansr.img'
% FORMAT spm_mean_ui
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% John Ashburner, Andrew Holmes
% $Id: art_despike.m 16 2010-06-07 12:19:40Z volkmar $
Vi = spm_vol(P);
n = prod(size(Vi));
spm_check_orientations(Vi);
%-Compute mean and write headers etc.
%-----------------------------------------------------------------------
fprintf(' ...computing')
Vo = struct( 'fname', meanimagename,...
'dim', Vi(1).dim(1:3),...
'dt', [4, spm_platform('bigend')],...
'mat', Vi(1).mat,...
'pinfo', [1.0,0,0]',...
'descrip', 'spm - mean image');
%-Adjust scalefactors by 1/n to effect mean by summing
for i=1:prod(size(Vi))
Vi(i).pinfo(1:2,:) = Vi(i).pinfo(1:2,:)/n; end;
Vo = spm_create_vol(Vo);
Vo.pinfo(1,1) = spm_add(Vi,Vo);
Vo = spm_create_vol(Vo);
%-End - report back
%-----------------------------------------------------------------------
fprintf(' ...done\n')
fprintf('\tMean image written to file ''%s'' in current directory\n\n',Vo.fname)
|
github
|
philippboehmsturm/antx-master
|
art_slice.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/ArtRepair/art_slice.m
| 14,002 |
utf_8
|
f6d5e310ed66a7afb86a5318abe94963
|
function art_slice
% FORMAT art_slice (v2.3)
%
% SUMMARY
% Reads a set of images and writes a new set of images
% after filtering the data for noise. User is asked to choose the
% repair method or methods. This program is best applied
% to the raw images, so the cleaned output images can be fed into
% slicetiming or realignment algorithms.
%
% V.2 uses the scale factor of input images for the output images
% to improve compatibility when output is used by external programs
%
% To automatically screen an image data set for bad slices, use the
% Detect and Repair Bad Slices option which writes a BadSliceLog
% of all the bad slices detected and repaired.
%
% No original data is removed- the old images are all preserved.
%
% User is asked via GUI to supply:
% - Set of images
% - A repair method
% - If repairing bad slices, user can choose a threshold.
% POSSIBLE REPAIRS
% 1. Filter all the images with a 3-point median filter in time. An
% excellent filter for TR=2 or less. If TR > 2 sec., or for Rapid Event
% experiments where events are separated by 2 TR's or less, this filter
% may clobber activations in event-related experiments.
% Adds a prefix "f" to the cleaned output images.
% 2. Detect and repair bad slices. Derives new values for the bad slice
% using linear interpolation of the before and after volumes.
% Bad slices are detected when the amount of data scattered outside
% the head is at least T above the usual amount for the slice. (The usual
% amount is determined as the average of the best two of the first three
% volumes. It differs for each slice.) The default
% value of T is 5, which the user can adjust. A preview estimate
% of the amount of repaired data at T=5 is shown in the Matlab window.
% This filter removes outliers, but may reduce activations, so it's
% safest when fewer than 5% of the slices are cleaned up.
% Adds a prefix "g" to the cleaned output images.
% Writes a text file BadSliceLog of all bad slices detected.
% 3. Eliminate data outside the head. Generates a head mask automatically,
% and writes it as ArtifactMask.img. Sets voxels outside the head
% to zero. This process may help realignment to be more accurate.
% Adds a prefix "h" to the cleaned output images.
% 4. Combinations of methods 1 and 3, or 2 and 3.
%
% NOTES
% 1. Use art_movie to compare the input and repaired images.
% 2. First and last volumes will not be filtered.
% Paul Mazaika - December 2004. V.2 August 2006,
% v2.2 allows user to specify a head mask instead of automatic. July 2007
% v2.3 compatible with multiple spm versions. Mar09
spmv = spm('Ver'); spm_ver = 'spm2';
if (strcmp(spmv,'SPM5') | strcmp(spmv,'SPM8b') | strcmp(spmv,'SPM8') )
spm_ver = 'spm5'; end
% PARAMETERS
spm('defaults','fmri');
OUTSLICEdef = 5; % Threshold above sample means to filter slices
% 15 is very visible on contrast image. 8 is slightly visible.
% THREEE CONTROL OPTIONS
% Mask the images - Set amask = 1.
% Median filter all the images - Set allfilt = 1.
% Detect and repair bad slices - Set slicefilt = 1.
if strcmp(spm_ver,'spm5')
%mask = spm_select(1, 'image', 'Select mask image in functional space');
Pimages = spm_select(Inf,'image','select images');
else % spm2 version
%mask = spm_get(1, '.img', 'Select mask image in functional space');
Pimages = spm_get(Inf,'image','select images');
end
P = spm_vol(Pimages);
repair_flag = spm_input('Which repair methods to use?', 1, 'm', ...
' Repair Bad Slices and Write BadSliceLog ( repairs only the bad slices ) | Median Filter All Data ( aggressive filter for very noisy data ) | Eliminate data outside head | Repair Bad Slices and Eliminate data outside head | Median Filter All Data and Eliminate data outside head',...
[1 2 3 4 5], 1);
if ( repair_flag == 3 ) amask = 1; allfilt = 0; slicefilt = 0; end
if ( repair_flag == 1 ) amask = 0; allfilt = 0; slicefilt = 1; end
if ( repair_flag == 2 ) amask = 0; allfilt = 1; slicefilt = 0; end
if ( repair_flag == 4 ) amask = 1; allfilt = 0; slicefilt = 1; end
if ( repair_flag == 5 ) amask = 1; allfilt = 1; slicefilt = 0; end
% Set the prefix correctly on the written files
if ( amask ==1 & allfilt == 0 & slicefilt == 0 ) prechar = 'h'; end
if ( amask ==1 & allfilt == 1 & slicefilt == 0 ) prechar = 'fh'; end
if ( amask ==1 & allfilt == 0 & slicefilt == 1 ) prechar = 'gh'; end
if ( amask ==0 & allfilt == 1 & slicefilt == 0 ) prechar = 'f'; end
if ( amask ==0 & allfilt == 0 & slicefilt == 1 ) prechar = 'g'; end
fprintf('\n NEW IMAGE FILES WILL BE CREATED');
fprintf('\n The filtered scan data will be saved in the same directory');
fprintf('\n with %s pre-pended to their filenames.\n',prechar);
if amask == 1 | slicefilt == 1 % Automask options
mask_flag = spm_input('Which mask image to use?', 1, 'm', ...
'Automatic ( will generate ArtifactMask image ) | User specified mask ',...
[1 2], 1);
if mask_flag == 2
if strcmp(spm_ver,'spm5')
maskimg = spm_select(1, '.img', 'Select mask image in functional space');
else % spm2 version
maskimg = spm_get(1, '.img', 'Select mask image in functional space');
end
Automask = spm_read_vols(spm_vol(maskimg));
maskcount = sum(sum(sum(Automask))); % Number of voxels in mask.
voxelcount = prod(size(Automask)); % Number of voxels in 3D volume.
else % mask_flag == 1
fprintf('\n Generated mask image is written to file ArtifactMask.img.\n');
fprintf('\n');
Pnames = P(1).fname;
Automask = art_automask(Pnames(1,:),-1,1);
maskcount = sum(sum(sum(Automask))); % Number of voxels in mask.
voxelcount = prod(size(Automask)); % Number of voxels in 3D volume.
end
end
if amask == 1
fprintf('\n ELIMINATE DATA OUTSIDE HEAD');
fprintf('\n All scans will have voxels outside the head set to zero.\n');
end
if slicefilt == 1 % Prepare some thresholds for slice testing.
fprintf('\n INTERPOLATE THROUGH BAD SLICES\n');
% Find the slice orientation used to collect the data
[ vx, vy, vz ] = size(Automask);
orient = 0;
if ( vx < vy & vx < vz ) orient = 1; disp(' Remove bad Sagittal slices'); end
if ( vy < vx & vy < vz ) orient = 2; disp(' Remove bad Coronal slices'); end
if ( vz < vx & vz < vy ) orient = 3; disp(' Remove bad Axial slices'); end
nslice = min([vx vy vz]);
if ( orient == 0 )
disp('Cannot determine slice orientation for bad slice filtering.')
return;
end
% Find 3 samples of slice baseline activity outside the head.
p = zeros(3,nslice);
for i = 1:3
Y1 = spm_read_vols(P(i));
Y1 = ( 1 - Automask ).*Y1;
% Get the plane sums perpendicular to orient direction
if ( orient == 1 ) p(i,:) = mean(mean(Y1,3),2); end
if ( orient == 2 ) p(i,:) = mean(mean(Y1,1),3); end
if ( orient == 3 ) p(i,:) = mean(mean(Y1,1),2); end
end
% Select a low value for each plane, and set threshold a bit above it.
pq = 0.5*( min(p) + median(p,1));
% Preview estimate of bad slice fraction...
prebad = length(find(p(1,:) > pq + OUTSLICEdef));
prebad = length(find(p(2,:) > pq + OUTSLICEdef)) + prebad;
prebad = length(find(p(3,:) > pq + OUTSLICEdef)) + prebad;
percentbad = round(prebad*100/(3*nslice));
disp('Estimated percent bad slices at default threshold')
disp(percentbad)
% User Input Threshold, and default suggestion.
OUTSLICE = spm_input(['Select threshold (default is shown)' ],1,'n',OUTSLICEdef);
pq = pq + OUTSLICE; % pq array is the threshold test for bad slices.
fprintf('\n Interpolating new values for bad slices when ');
fprintf('\n average value outside head is %3d counts over baseline.\n',OUTSLICE);
fprintf('\n Bad slice log will be written.');
fprintf('\n');
% DETECT, COUNT, AND LOG THE ARTIFACTS
disp('Writing Artifact Log to location of image set')
[ dirname, sname ] = fileparts(P(1).fname); % XXXXXX
tstamp = clock;
filen = ['BadSliceLog',date,'Time',num2str(tstamp(4)),num2str(tstamp(5)),'.txt'];
logname = fullfile(dirname,filen);
logID = fopen(logname,'wt');
fprintf(logID,'Bad Slice Log, Image Set first file is: \n %s\n', sname);
fprintf(logID,'Test Criteria for Artifacts');
fprintf(logID,'\n Outslice (counts) = %4.1f' , OUTSLICE);
fprintf(logID,'\n Slice Artifact List (Vol 1 = First File)\n');
BadError = 0; % Counts bad slices
end
if allfilt == 1
fprintf('\n MEDIAN FILTER ALL THE DATA');
fprintf('\n All scans are being filtered by median 3-point time filter.');
fprintf('\n This is safe to do when TR = 2. Otherwise, use the');
fprintf('\n Remove Bad Slices option instead.\n');
fprintf('\n');
end
spm_input('!DeleteInputObj');
% Main Loop - Filter everything but the first and last volumes.
nscans = size(P,1);
Y4(1,:,:,:) = spm_read_vols(P(1)); % rows vary fastest
Y4(2,:,:,:) = spm_read_vols(P(2));
for i = 3:nscans
Y4(3,:,:,:) = spm_read_vols(P(i));
if allfilt == 1 % Filter all data by median.
Yn = median(Y4,1);
Yn2 = squeeze(Yn);
end
if slicefilt == 1 % Repair bad slices by linear interpolation.
% Check if outside head value is over pq. If so, filter.
Yn2 = squeeze(Y4(2,:,:,:));
Y = ( 1 - Automask).*Yn2;
if ( orient == 1 )
py = mean(mean(Y,3),2);
for j = 1:vx
if py(j) > pq(j) % slice needs to be filtered.
Yn2(j,:,:) = squeeze((Y4(1,j,:,:) + Y4(3,j,:,:))/2.0);
fprintf(' Fixed sagittal. Vol. %d, Slice %d.\n',i-1,j);
fprintf(logID,' Fixed sagittal. Vol %d, Slice %d.\n',i-1,j);
BadError = BadError + 1;
end
end
end
if ( orient == 2 )
py = mean(mean(Y,1),3);
for j = 1:vy
if py(j) > pq(j) % slice needs to be filtered.
Yn2(:,j,:) = squeeze((Y4(1,:,j,:) + Y4(3,:,j,:))/2.0);
fprintf(' Fixed coronal. Vol %d, Slice %d.\n',i-1,j);
fprintf(logID,' Fixed coronal. Vol %d, Slice %d.\n',i-1,j);
BadError = BadError + 1;
end
end
end
if ( orient == 3 )
py = mean(mean(Y,1),2);
for j = 1:vz
if py(j) > pq(j) % slice needs to be filtered.
Yn2(:,:,j) = squeeze((Y4(1,:,:,j) + Y4(3,:,:,j))/2.0);
fprintf(' Fixed axial. Vol %d, Slice %d.\n',i-1,j);
fprintf(logID,' Fixed axial. Vol %d, Slice %d.\n',i-1,j);
BadError = BadError + 1;
end
end
end
end
if ( allfilt == 0 & slicefilt == 0 ) % Head mask only.
Yn2 = squeeze(Y4(2,:,:,:));
end
% Yn is a 4D file including the smoothed Y2 now.
if ( amask ) Yn2 = Yn2.*Automask; end
% Prepare the header for the filtered volume.
V = spm_vol(P(i-1).fname);
v = V;
[dirname, sname, sext ] = fileparts(V.fname);
sfname = [ prechar, sname ];
filtname = fullfile(dirname,[sfname sext]);
v.fname = filtname;
%spm_write_vol(v,Yn2);
noscale_write_vol(v,Yn2);
showprog = [' Corrected volume ', sname, sext ];
disp(showprog);
if i == 3 % Write unfiltered first scan
Yn1 = squeeze(Y4(1,:,:,:));
if ( amask ) Yn1 = Yn1.*Automask; end
[dirname, sname, sext ] = fileparts(P(1).fname);
sfname = [ prechar, sname ];
filtname = fullfile(dirname,[sfname sext]);
v.fname = filtname;
%spm_write_vol(v,Yn1);
noscale_write_vol(v,Yn1);
showprog = [' Corrected volume ', sname, sext ];
disp(showprog);
end
if i == nscans % Write unfiltered last scan.
Yn1 = squeeze(Y4(3,:,:,:));
if ( amask ) Yn1 = Yn1.*Automask; end
Vlast = spm_vol(P(nscans).fname);
[dirname, sname, sext ] = fileparts(P(nscans).fname);
sfname = [ prechar, sname ];
filtname = fullfile(dirname,[sfname sext]);
v.fname = filtname;
%spm_write_vol(v,Yn1);
noscale_write_vol(v,Yn1);
showprog = [' Corrected volume ', sname, sext ];
disp(showprog);
end
% Slide the read volumes window up.
Y4(1,:,:,:) = Y4(2,:,:,:);
Y4(2,:,:,:) = Y4(3,:,:,:);
end
% Summarize the slice errors, in the bad slice case.
if slicefilt == 1
totalslices = nscans*nslice;
ArtifactCount = BadError; % Number of unique bad slices with artifacts
badpercent = BadError*100.0/totalslices;
if ( ArtifactCount == 0 )
disp(' CLEAN DATA! No bad slices detected');
fprintf(logID, '\n\nCLEAN DATA. No bad slices detected.');
end
if ArtifactCount > 0
fprintf(logID,'\n\n Number of slices repaired = %4.0d',ArtifactCount);
fprintf(logID,'\n\n Percentage of slices repaired = %5.1f',badpercent);
end
fclose(logID);
end
disp('Done!')
%---------------------------------------------------------------
% Create and write image without the scale and offset steps
% This function is spm_write_vol without error checking and scaling.
function noscale_write_vol(V,Y);
V = spm_create_vol(V);
for p=1:V.dim(3),
V = spm_write_plane(V,Y(:,:,p),p);
end;
%V = spm_close_vol(V); % not for SPM5
|
github
|
philippboehmsturm/antx-master
|
tbx_cfg_render.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/SRender/tbx_cfg_render.m
| 19,186 |
utf_8
|
52ec82ded599415d96ecaba3b38013d5
|
function render = tbx_cfg_render
% Configuration file for toolbox 'Rendering'
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: tbx_cfg_render.m 3802 2010-03-29 13:07:15Z john $
% ---------------------------------------------------------------------
% images Input Images
% ---------------------------------------------------------------------
images = cfg_files;
images.tag = 'images';
images.name = 'Input Images';
images.help = {'These are the images that are used by the calculator. They are referred to as i1, i2, i3, etc in the order that they are specified.'};
images.filter = 'image';
images.ufilter = '.*';
images.num = [1 Inf];
% ---------------------------------------------------------------------
% expression Expression
% ---------------------------------------------------------------------
expression = cfg_entry;
expression.tag = 'expression';
expression.name = 'Expression';
expression.help = {
'Example expressions (f):'
' * Mean of six images (select six images)'
' f = ''(i1+i2+i3+i4+i5+i6)/6'''
' * Make a binary mask image at threshold of 100'
' f = ''i1>100'''
' * Make a mask from one image and apply to another'
' f = ''i2.*(i1>100)'''
' - here the first image is used to make the mask, which is applied to the second image'
' * Sum of n images'
' f = ''i1 + i2 + i3 + i4 + i5 + ...'''
}';
expression.strtype = 's';
expression.num = [2 Inf];
expression.val = {'i1'};
% ---------------------------------------------------------------------
% thresh Surface isovalue(s)
% ---------------------------------------------------------------------
thresh = cfg_entry;
thresh.tag = 'thresh';
thresh.name = 'Surface isovalue(s)';
thresh.help = {'Enter the value at which isosurfaces through the resulting image is to be computed.'};
thresh.strtype = 'e';
thresh.num = [1 1];
thresh.val = {0.5};
% ---------------------------------------------------------------------
% surface Surface
% ---------------------------------------------------------------------
surface = cfg_branch;
surface.tag = 'surface';
surface.name = 'Surface';
surface.val = {expression thresh };
surface.help = {'An expression and threshold for each of the surfaces to be generated.'};
% ---------------------------------------------------------------------
% Surfaces Surfaces
% ---------------------------------------------------------------------
Surfaces = cfg_repeat;
Surfaces.tag = 'Surfaces';
Surfaces.name = 'Surfaces';
Surfaces.help = {'Multiple surfaces can be created from the same image data.'};
Surfaces.values = {surface };
Surfaces.num = [0 Inf];
% ---------------------------------------------------------------------
% SExtract Surface Extraction
% ---------------------------------------------------------------------
SExtract = cfg_exbranch;
SExtract.tag = 'SExtract';
SExtract.name = 'Surface Extraction';
SExtract.val = {images Surfaces };
SExtract.help = {'User-specified algebraic manipulations are performed on a set of images, with the result being used to generate a surface file. The user is prompted to supply images to work on and a number of expressions to evaluate, along with some thresholds. The expression should be a standard matlab expression, within which the images should be referred to as i1, i2, i3,... etc. An isosurface file is created from the results at the user-specified threshold.'};
SExtract.prog = @spm_local_sextract;
%SExtract.vfiles = @filessurf;
SExtract.vout = @vout_sextract;
% ---------------------------------------------------------------------
% SurfaceFile Surface File
% ---------------------------------------------------------------------
SurfaceFile = cfg_files;
SurfaceFile.tag = 'SurfaceFile';
SurfaceFile.name = 'Surface File';
SurfaceFile.help = {'Filename of the surf_*.gii file containing the rendering information. This can be generated via the surface extraction routine in SPM. Normally, a surface is extracted from grey and white matter tissue class images, but it is also possible to threshold e.g. an spmT image so that activations can be displayed.'};
SurfaceFile.filter = 'mesh';
SurfaceFile.ufilter = '.*';
SurfaceFile.num = [1 1];
% ---------------------------------------------------------------------
% Red Red
% ---------------------------------------------------------------------
Red = cfg_menu;
Red.tag = 'Red';
Red.name = 'Red';
Red.help = {'The intensity of the red colouring (0 to 1).'};
Red.labels = {
'0.0'
'0.2'
'0.4'
'0.6'
'0.8'
'1.0'
}';
Red.values = {
0
0.2
0.4
0.6
0.8
1
}';
Red.val = {1};
% ---------------------------------------------------------------------
% Green Green
% ---------------------------------------------------------------------
Green = cfg_menu;
Green.tag = 'Green';
Green.name = 'Green';
Green.help = {'The intensity of the green colouring (0 to 1).'};
Green.labels = {
'0.0'
'0.2'
'0.4'
'0.6'
'0.8'
'1.0'
}';
Green.values = {
0
0.2
0.4
0.6
0.8
1
}';
Green.val = {1};
% ---------------------------------------------------------------------
% Blue Blue
% ---------------------------------------------------------------------
Blue = cfg_menu;
Blue.tag = 'Blue';
Blue.name = 'Blue';
Blue.help = {'The intensity of the blue colouring (0 to 1).'};
Blue.labels = {
'0.0'
'0.2'
'0.4'
'0.6'
'0.8'
'1.0'
}';
Blue.values = {
0
0.2
0.4
0.6
0.8
1
}';
Blue.val = {1};
% ---------------------------------------------------------------------
% Color Color
% ---------------------------------------------------------------------
Color = cfg_branch;
Color.tag = 'Color';
Color.name = 'Color';
Color.val = {Red Green Blue };
Color.help = {'Specify the colour using a mixture of red, green and blue. For example, white is specified by 1,1,1, black is by 0,0,0 and purple by 1,0,1.'};
% ---------------------------------------------------------------------
% DiffuseStrength Diffuse Strength
% ---------------------------------------------------------------------
DiffuseStrength = cfg_menu;
DiffuseStrength.tag = 'DiffuseStrength';
DiffuseStrength.name = 'Diffuse Strength';
DiffuseStrength.help = {'The strength with which the object diffusely reflects light. Mat surfaces reflect light diffusely, whereas shiny surfaces reflect speculatively.'};
DiffuseStrength.labels = {
'0.0'
'0.2'
'0.4'
'0.6'
'0.8'
'1.0'
}';
DiffuseStrength.values = {
0
0.2
0.4
0.6
0.8
1
}';
DiffuseStrength.val = {0.8};
% ---------------------------------------------------------------------
% AmbientStrength Ambient Strength
% ---------------------------------------------------------------------
AmbientStrength = cfg_menu;
AmbientStrength.tag = 'AmbientStrength';
AmbientStrength.name = 'Ambient Strength';
AmbientStrength.help = {'The strength with which the object reflects ambient (non-directional) lighting.'};
AmbientStrength.labels = {
'0.0'
'0.2'
'0.4'
'0.6'
'0.8'
'1.0'
}';
AmbientStrength.values = {
0
0.2
0.4
0.6
0.8
1
}';
AmbientStrength.val = {0.2};
% ---------------------------------------------------------------------
% SpecularStrength Specular Strength
% ---------------------------------------------------------------------
SpecularStrength = cfg_menu;
SpecularStrength.tag = 'SpecularStrength';
SpecularStrength.name = 'Specular Strength';
SpecularStrength.help = {'The strength with which the object specularly reflects light (i.e. how shiny it is). Mat surfaces reflect light diffusely, whereas shiny surfaces reflect speculatively.'};
SpecularStrength.labels = {
'0.0'
'0.2'
'0.4'
'0.6'
'0.8'
'1.0'
}';
SpecularStrength.values = {
0
0.2
0.4
0.6
0.8
1
}';
SpecularStrength.val = {0.2};
% ---------------------------------------------------------------------
% SpecularExponent Specular Exponent
% ---------------------------------------------------------------------
SpecularExponent = cfg_menu;
SpecularExponent.tag = 'SpecularExponent';
SpecularExponent.name = 'Specular Exponent';
SpecularExponent.help = {'A parameter describing the specular reflectance behaviour. It relates to the size of the high-lights.'};
SpecularExponent.labels = {
'0.01'
'0.1'
'10'
'100'
}';
SpecularExponent.values = {
0.01
0.1
10
100
}';
SpecularExponent.val = {10};
% ---------------------------------------------------------------------
% SpecularColorReflectance Specular Color Reflectance
% ---------------------------------------------------------------------
SpecularColorReflectance = cfg_menu;
SpecularColorReflectance.tag = 'SpecularColorReflectance';
SpecularColorReflectance.name = 'Specular Color Reflectance';
SpecularColorReflectance.help = {'Another parameter describing the specular reflectance behaviour.'};
SpecularColorReflectance.labels = {
'0.0'
'0.2'
'0.4'
'0.6'
'0.8'
'1.0'
}';
SpecularColorReflectance.values = {
0
0.2
0.4
0.6
0.8
1
}';
SpecularColorReflectance.val = {0.8};
% ---------------------------------------------------------------------
% FaceAlpha Face Alpha
% ---------------------------------------------------------------------
FaceAlpha = cfg_menu;
FaceAlpha.tag = 'FaceAlpha';
FaceAlpha.name = 'Face Alpha';
FaceAlpha.help = {'The opaqueness of the surface. A value of 1 means it is opaque, whereas a value of 0 means it is transparent.'};
FaceAlpha.labels = {
'0.0'
'0.2'
'0.4'
'0.6'
'0.8'
'1.0'
}';
FaceAlpha.values = {
0
0.2
0.4
0.6
0.8
1
}';
FaceAlpha.val = {1};
% ---------------------------------------------------------------------
% Object Object
% ---------------------------------------------------------------------
Object = cfg_branch;
Object.tag = 'Object';
Object.name = 'Object';
Object.val = {SurfaceFile Color DiffuseStrength AmbientStrength SpecularStrength SpecularExponent SpecularColorReflectance FaceAlpha };
Object.help = {'Each object is a surface (from a surf_*.gii file), which may have a number of light-reflecting qualities, such as colour and shinyness.'};
% ---------------------------------------------------------------------
% Objects Objects
% ---------------------------------------------------------------------
Objects = cfg_repeat;
Objects.tag = 'Objects';
Objects.name = 'Objects';
Objects.help = {'Several surface objects can be displayed together in different colours and with different reflective properties.'};
Objects.values = {Object };
Objects.num = [0 Inf];
% ---------------------------------------------------------------------
% Position Position
% ---------------------------------------------------------------------
Position = cfg_entry;
Position.tag = 'Position';
Position.name = 'Position';
Position.help = {'The position of the light in 3D.'};
Position.strtype = 'e';
Position.num = [1 3];
Position.val = {[100 100 100]};
% ---------------------------------------------------------------------
% Red Red
% ---------------------------------------------------------------------
Red = cfg_menu;
Red.tag = 'Red';
Red.name = 'Red';
Red.help = {'The intensity of the red colouring (0 to 1).'};
Red.labels = {
'0.0'
'0.2'
'0.4'
'0.6'
'0.8'
'1.0'
}';
Red.values = {
0
0.2
0.4
0.6
0.8
1
}';
Red.val = {1};
% ---------------------------------------------------------------------
% Green Green
% ---------------------------------------------------------------------
Green = cfg_menu;
Green.tag = 'Green';
Green.name = 'Green';
Green.help = {'The intensity of the green colouring (0 to 1).'};
Green.labels = {
'0.0'
'0.2'
'0.4'
'0.6'
'0.8'
'1.0'
}';
Green.values = {
0
0.2
0.4
0.6
0.8
1
}';
Green.val = {1};
% ---------------------------------------------------------------------
% Blue Blue
% ---------------------------------------------------------------------
Blue = cfg_menu;
Blue.tag = 'Blue';
Blue.name = 'Blue';
Blue.help = {'The intensity of the blue colouring (0 to 1).'};
Blue.labels = {
'0.0'
'0.2'
'0.4'
'0.6'
'0.8'
'1.0'
}';
Blue.values = {
0
0.2
0.4
0.6
0.8
1
}';
Blue.val = {1};
% ---------------------------------------------------------------------
% Color Color
% ---------------------------------------------------------------------
Color = cfg_branch;
Color.tag = 'Color';
Color.name = 'Color';
Color.val = {Red Green Blue };
Color.help = {'Specify the colour using a mixture of red, green and blue. For example, white is specified by 1,1,1, black is by 0,0,0 and purple by 1,0,1.'};
% ---------------------------------------------------------------------
% Light Light
% ---------------------------------------------------------------------
Light = cfg_branch;
Light.tag = 'Light';
Light.name = 'Light';
Light.val = {Position Color };
Light.help = {'Specification of a light source in terms of position and colour.'};
% ---------------------------------------------------------------------
% Lights Lights
% ---------------------------------------------------------------------
Lights = cfg_repeat;
Lights.tag = 'Lights';
Lights.name = 'Lights';
Lights.help = {'There should be at least one light specified so that the objects can be clearly seen.'};
Lights.values = {Light };
Lights.num = [0 Inf];
% ---------------------------------------------------------------------
% SRender Surface Rendering
% ---------------------------------------------------------------------
SRender = cfg_exbranch;
SRender.tag = 'SRender';
SRender.name = 'Surface Rendering';
SRender.val = {Objects Lights };
SRender.help = {'This utility is for visualising surfaces. Surfaces first need to be extracted and saved in surf_*.gii files using the surface extraction routine.'};
SRender.prog = @spm_local_srender;
% ---------------------------------------------------------------------
% render Rendering
% ---------------------------------------------------------------------
render = cfg_choice;
render.tag = 'render';
render.name = 'Rendering';
render.help = {'This is a toolbox that provides a limited range of surface rendering options. The idea is to first extract surfaces from image data, which are saved in rend_*.mat files. These can then be loaded and displayed as surfaces. Note that OpenGL rendering is used, which can be problematic on some computers. The tools are limited - and they do what they do.'};
render.values = {SExtract SRender };
%render.num = [0 Inf];
%======================================================================
function spm_local_srender(job)
if ~isdeployed, addpath(fullfile(spm('dir'),'toolbox','SRender')); end
spm_srender(job);
%======================================================================
function out=spm_local_sextract(job)
if ~isdeployed, addpath(fullfile(spm('dir'),'toolbox','SRender')); end
out=spm_sextract(job);
%======================================================================
function dep = vout_sextract(job)
dep = cfg_dep;
for k=1:numel(job.surface),
dep(k) = cfg_dep;
dep(k).sname = ['Surface File ' num2str(k)];
dep(k).src_output = substruct('.','SurfaceFile','()',{k});
% dep(k).tgt_spec = cfg_findspec({{'filter','.*\.gii$'}});
dep(k).tgt_spec = cfg_findspec({{'filter','any'}});
end
|
github
|
philippboehmsturm/antx-master
|
spm_sextract.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/SRender/spm_sextract.m
| 2,032 |
utf_8
|
4a45ee93e484bacd762c3aa2c4cc0003
|
function out = spm_sextract(job)
% Surface extraction
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_sextract.m 2210 2008-09-26 20:14:13Z john $
images = job.images;
Vi = spm_vol(strvcat(images));
n = numel(Vi); %-#images
if n==0, error('no input images specified'), end
[pth,nam,ext] = fileparts(images{1});
for k=1:numel(job.surface),
expression = job.surface(k).expression;
thresh = job.surface(k).thresh;
y = zeros(Vi(1).dim(1:3),'single');
spm_progress_bar('Init',Vi(1).dim(3),expression,'planes completed');
for p = 1:Vi(1).dim(3),
B = spm_matrix([0 0 -p 0 0 0 1 1 1]);
im = cell(1,n);
for i=1:n,
M = inv(B*inv(Vi(1).mat)*Vi(i).mat);
im{i} = spm_slice_vol(Vi(i),M,Vi(1).dim(1:2),[0,NaN]);
end
try
y(:,:,p) = real(single(efun(im,expression)));
catch
error(['Can not evaluate "' expression '".']);
end
spm_progress_bar('Set',p);
end
spm_smooth(y,y,[1.5,1.5,1.5]);
[faces,vertices] = isosurface(y,thresh);
% Swap around x and y because isosurface does for some
% wierd and wonderful reason.
Mat = Vi(1).mat(1:3,:)*[0 1 0 0;1 0 0 0;0 0 1 0; 0 0 0 1];
vertices = (Mat*[vertices' ; ones(1,size(vertices,1))])';
%matname = fullfile(pth,sprintf('surf_%s_%.3d.mat',nam,k));
%save(matname,'-V6','faces','vertices','expression','thresh','images');
matname = fullfile(pth,sprintf('surf_%s_%.3d.gii',nam,k));
save(gifti(struct('faces',faces,'vertices',vertices)),matname);
out.SurfaceFile{k} = matname;
spm_progress_bar('Clear');
end
return
%_______________________________________________________________________
%_______________________________________________________________________
function y = efun(im,f)
for i=1:numel(im),
eval(['i' num2str(i) '= im{i};']);
end
y = eval(f);
return
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_ft_beamformer_cva.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/Beamforming/spm_eeg_ft_beamformer_cva.m
| 40,809 |
utf_8
|
83ce46ca11b2e5c61aa5660790a64ae5
|
function [stats,talpositions,gridpositions,grid,fftnewdata,alllf,allepochdata]=spm_eeg_ft_beamformer_cva(S)
% Computes power-based beamformer image
% FORMAT [outfilenames,ctf_inside,ctf_weights]=spm_eeg_ft_beamformer_cva (S)
%
% S MEEG object where coregistration has been performed.
%
%
% Outputs (1) normalised power, (2) t-stat and (3) multivarariate
% (Hotellings)images. Uses Sekihara eigenval approach to choose optimal
% direction.
%
% outfilenames Output filenames (for 1,2,3)
%
% The following fields are returned if you set
% S.return_weights=1:
%
% ctf_inside CTF locations inside head
% ctf_weights Corresponding beamformer weight matrices
% fftnewdata is fft of data in trial order
% _______________________________________________________________________
% Copyright (C) 2009 Institute of Neurology, UCL
% Gareth Barnes
% $Id: spm_eeg_ft_beamformer_cva.m 4377 2011-06-27 09:54:33Z gareth $
[Finter,Fgraph] = spm('FnUIsetup','Multivariate LCMV beamformer for power', 0);
%%
%% ============ Load SPM EEG file and verify consistency
if nargin == 0
S = [];
end
try
D = S.D;
catch
D = spm_select(1, '\.mat$', 'Select EEG mat file');
S.D = D;
end
if ischar(D)
try
D = spm_eeg_load(D);
catch
error(sprintf('Trouble reading file %s', D));
end
end
[ok, D] = check(D, 'sensfid');
if ~ok
if check(D, 'basic')
errordlg(['The requested file is not ready for source reconstruction.'...
'Use prep to specify sensors and fiducials.']);
else
errordlg('The meeg file is corrupt or incomplete');
end
return
end
modality = spm_eeg_modality_ui(D, 1, 1);
%try
channel_labels = D.chanlabels(strmatch(modality, D.chantype))';
%catch
% warning('ASSUMING ALL CHANNELS ARE MEG CHANNELS');
% channel_labels=D.chanlabels;
%end;
if isfield(S, 'refchan') && ~isempty(S.refchan)
refchan = S.refchan;
else
refchan = [];
end
if ~isfield(S,'CorrectPvals'),
S.CorrectPvals=[];
end;
if isempty(S.CorrectPvals),
S.CorrectPvals=1;
disp('outputing whole volume corrected p vals by default');
end;
%% ============ Find or prepare head model
if ~isfield(D, 'val')
D.val = 1;
end
if ~isfield(S,'filenamestr'),
S.filenamestr=[];
end;%
%D.inv{1}.forward(1).voltype
try
vol = D.inv{D.val}.forward.vol;
datareg = D.inv{D.val}.datareg;
catch
D = spm_eeg_inv_mesh_ui(D, D.val, [], 1);
D = spm_eeg_inv_datareg_ui(D, D.val);
datareg = D.inv{D.val}.datareg;
end
for m = 1:numel(D.inv{D.val}.forward)
if strncmp(modality, D.inv{D.val}.forward(m).modality, 3)
vol = D.inv{D.val}.forward(m).vol;
if isa(vol, 'char')
vol = fileio_read_vol(vol);
end
datareg = D.inv{D.val}.datareg(m); %% NEED TO KNOW HOW TO HANDLE DATAREG
disp('USING LAST FORWARD MODEL !');
end
end
% Return beamformer weights
if ~isfield(S,'return_weights')
ctf_weights=[];
S.return_weights=0;
alllf=[];
end
if ~isfield(S,'compUV')
S.compUV=[];
end; % if
if isempty(S.compUV),
S.compUV=0;
end;
if ~isfield(S,'Niter')
S.Niter=[];
end; % if
if isempty(S.Niter),
S.Niter=1;
end; % if
if ~isfield(S,'design'),
error('Design matrix required');
end; % if
X=S.design.X;
c=S.design.contrast; %% c is contrast eg [ 0 1 -1] compare columns 2,3 of X
if ~isfield(S,'ttest'),
S.ttest=[];
end; % if
if S.ttest,
TWOSAMPLETEST=1
else
TWOSAMPLETEST=0
end;
if size(S.design.X(:,1),1)~=size(S.design.Xtrials,1)
error('Design windows missepcified');
end;
if size(S.design.X(:,1),1)~=size(S.design.Xstartlatencies,1)
error('Design windows missepcified');
end;
X0 = X - X*c*pinv(c); %% make sure X0 is orthogonal to X
Xdesign = full(X*c);
X0 = spm_svd(X0); %% X0 is null space i.e. everything that is happening in other columns of X
outfilenames='';
freqbands=[];
if ~isfield(S, 'freqbands')
for i = 1:spm_input('Number of frequency bands:', '+1', 'r', '1', 1)
outstr=sprintf('Band %d [st end] in Hz ',i);
S.freqbands{i} = spm_input(outstr, '+1', 'r', '', 2);
freqbands =[freqbands;S.freqbands{i}'];
end
else
freqbands=cell2mat(S.freqbands');
end
if ~isfield(S,'testbands'),
S.testbands=[];
end;
if isempty(S.testbands),
S.testbands=S.freqbands; %% bands to do the test on
end; % if
Nbands=numel(S.freqbands);
if ~isfield(S,'weightspect'),
S.weightspect=[];
end;
if ~isfield(S,'weightttest'),
S.weightttest=[];
end;
if ~isfield(S,'gridpos'),
if ~isfield(S,'gridstep');
S.gridstep = spm_input('Grid step (mm):', '+1', 'r', '5');
end;
end; % if
if ~isfield(S,'rankflag'),
S.rankflag=[];
end; % if
if isempty(S.rankflag),
S.rankflag=0;
end; % if
if ~isfield(S,'detrend'),
S.detrend=[];
end;
if isempty(S.detrend),
disp('detrending data by default');
S.detrend=1;
end; %
if ~isfield(S,'hanning'),
S.hanning=[];
end;
if isempty(S.hanning),
disp('windowing data by default');
S.hanning=1;
end; %
if ~isfield(S,'logflag'),
S.logflag=[];
end; % if
if isempty(S.logflag),
S.logflag=0;
end; % if
%
if ~isfield(S,'regpc'),
S.regpc=[];
end; % if
if isempty(S.regpc),
S.regpc=0;
end; % if
%% now read in the first trial of data just to get sizes of variables right
Ntrials=size(S.design.X,1);
Isamples = D.indsample([S.design.Xstartlatencies(1) S.design.Xstartlatencies(1)+S.design.Xwindowduration]);
Nsamples= diff(Isamples)+1;
%channel_labels = D.chanlabels(D.meegchannels(modality));
Nchans=length(channel_labels);
dfe=Ntrials-rank(X);
if S.hanning,
fftwindow=hamming(Nsamples);
else
disp('not windowing');
fftwindow=ones(Nsamples,1);
end;
allfftwindow=repmat(fftwindow,1,Nchans);
NumUniquePts = ceil((Nsamples+1)/2); %% data is real so fft is symmetric
fftnewdata=zeros(Ntrials,NumUniquePts,Nchans);
allepochdata=zeros(Ntrials,Nchans,Nsamples); %% for loading in data quickly
%fftnewdata=zeros(Ntrials,Nsamples,Nchans);
fHz = (0:NumUniquePts-1)*D.fsample/Nsamples;
if ~isfield(S,'Nfeatures'),
S.Nfeatures=[];
end;
if isempty(S.Nfeatures),
Nfeatures=floor(Ntrials/3);
else
Nfeatures=S.Nfeatures;
end;
if ~isfield(S,'write_epochs'),
S.write_epochs=[];
end;
%% now read in all trialtype and hold them as windowed fourier transforms
[uniquewindows]=unique(S.design.Xstartlatencies);
Nwindows=length(uniquewindows);
%% GET DATA- put each trial in allepochdata in same order as design matrix (i.e. remove dependence on Xtrials and Xstartlatencies)
%TtofT=1e15; %% tesla to femto tesla
%disp('rescaling from tesla to fT !!');
TtofT=1; %% tesla to femto tesla - turned off
%disp('rescaling from tesla to fT !!');
for i=1:Nwindows, %% puts trials into epoch data according to order of design.X structures
Isamples = D.indsample([uniquewindows(i) uniquewindows(i)+S.design.Xwindowduration]);
useind=find(uniquewindows(i)==S.design.Xstartlatencies);
Itrials =S.design.Xtrials(useind); %% indices into design.X structures
allepochdata(useind,:,:)=permute(TtofT.*squeeze(D(D.indchannel(channel_labels), Isamples(1):Isamples(2), Itrials)), [3 1 2]); %% get an epoch of data with channels in columns
end; % for i
% Was this- before cfg.latency was removed from ft_timelockanalysis
% TtofT=1e15; %% tesla to femto tesla
% disp('rescaling from tesla to fT !!');
% for i=1:Nwindows, %% puts trials into epoch data according to order of design.X structures
% winstart=uniquewindows(i); %% window start
% cfg=[];
% cfg.keeptrials='yes';
% cfg.channel=channel_labels;
% cfg.feedback='off';
% useind=find(winstart==S.design.Xstartlatencies); %% indices into design.X structures
% cfg.trials=S.design.Xtrials(useind); %% trials starting at these times
% cfg.latency=[winstart winstart+S.design.Xwindowduration];
% subdata=ft_timelockanalysis(cfg,data); % subset of original data
% allepochdata(useind,:,:)=TtofT.*squeeze(subdata.trial); %% get an epoch of data with channels in columns
% end; % for i
for i=1:Ntrials, %% read in all individual trial types
epochdata=squeeze(allepochdata(i,:,:))'; %% get an epoch of data with channels in columns
if S.detrend==1
dtepochdata=detrend(epochdata); %% detrend epoch data, this includes removind dc level. NB. This will have an effect on specific evoked response components !
else
dtepochdata=epochdata; %% no dc removal, no detrend : this will have effect on accuracy of fourier estimate at non dc bins
end; % detrend
wdtepochfft=dtepochdata.*allfftwindow; %% windowed
epochfft=fft(wdtepochfft);
fftnewdata(i,:,:)=epochfft(1:NumUniquePts,:); % .*filtervect';
end;
if size(fftnewdata,3)~=Nchans,
size(fftnewdata)
error('Data dimension mismatch');
end;
%% now have an fft for each channel in each condition
% %%
cfg = [];
if strcmp('EEG', modality)
cfg.elec = D.inv{D.val}.datareg.sensors;
cfg.reducerank=3;
else
cfg.grad = D.sensors('MEG');
cfg.reducerank=2;
disp('Reducing possible source orientations to a tangential plane for MEG');
end
cfg.channel = channel_labels;
cfg.vol = vol;
if ~isfield(S,'gridpos'),
S.gridpos=[];
end;
if ~isfield(S,'gridori'),
S.gridori=[];
end;
if ~isfield(S,'maskgrid'),
S.maskgrid=[];
end;
if ~isfield(S,'dimauto'),
S.dimauto=[];
end;
if ~isfield(S,'maskfile'),
S.maskfile=[];
end;
if ~isfield(S,'randomweight'),
S.randomweight=0;
end;
if ~isfield(S,'fixedweights'),
S.fixedweights=[];
end;
if isempty(S.gridpos),
%cfg.resolution = S.gridstep;
mnigrid.xgrid = -100:S.gridstep:100;
mnigrid.ygrid = -120:S.gridstep:100;
mnigrid.zgrid = -50:S.gridstep:110;
mnigrid.dim = [length(mnigrid.xgrid) length(mnigrid.ygrid) length(mnigrid.zgrid)];
[X, Y, Z] = ndgrid(mnigrid.xgrid, mnigrid.ygrid, mnigrid.zgrid);
mnigrid.pos = [X(:) Y(:) Z(:)];
cfg.grid.dim = mnigrid.dim;
cfg.grid.pos = spm_eeg_inv_transform_points(datareg.fromMNI, mnigrid.pos);
else
disp('USING pre-specified gridpoints');
cfg.grid.pos=S.gridpos; %% predefined grid
cfg.grid.inside=[1:size(S.gridpos,1)]; %% assume all in head
cfg.grid.outside=[];
end;
if ~isfield(S,'bootstrap'),
S.bootstrap=[];
else
Nboot=S.bootstrap;
end;
if isempty(S.bootstrap),
S.bootstrap=0;
Nboot=1;
end;
cfg.feedback='off';
cfg.inwardshift = -S.gridstep; % mm
if ~isfield(S,'grid'),
disp('preparing leadfield');
grid = ft_prepare_leadfield(cfg);
else
disp('Using precomputed leadfield');
grid=S.grid;
end; % if
maskedgrid_inside_ind=[1:length(grid.inside)];
if ~isempty(S.maskgrid),
if length(S.maskgrid)~=length(grid.inside),
error('mask and grid points must be of same size');
end;
maskedgrid_inside_ind=find(S.maskgrid==1); %% indices into grid.inside
end;
if ~isempty(S.maskfile),
if ~isempty(S.maskgrid),
error('cannot have two masks defined');
end;
alltalpositions = spm_eeg_inv_transform_points(datareg.toMNI, grid.pos(grid.inside,:));
V_aal = spm_vol(S.maskfile);
[Y_aal,XYZ]=spm_read_vols(V_aal);
mask_coords=XYZ(:,find(Y_aal>0));
%% now express mni grid and mesh grid at same coarse scale to get
%% intersection
coarse_mm=10;
mask_coarse=unique(round(mask_coords'/coarse_mm)*coarse_mm,'rows');
grid_coarse= round(alltalpositions/coarse_mm)*coarse_mm;
[overlap_pos,maskedgrid_inside_ind]=intersect(grid_coarse,mask_coarse,'rows'); %% mesh_vert_ind are mesh points in this mask
maskedgrid_inside_ind=sort(maskedgrid_inside_ind);
end; % if
if cfg.reducerank, %% follow up rank reduction and remove redundant dimension from lead fields
for i=1:length(maskedgrid_inside_ind), %% 81
lf1=cell2mat(grid.leadfield(grid.inside(maskedgrid_inside_ind(i))));
[u1,s1,v1]=svd(lf1'*lf1);
grid.leadfield(grid.inside(maskedgrid_inside_ind(i)))={lf1*u1(:,1:cfg.reducerank)};
%normlf(i)=std(dot(lfnew',lfnew'));
end;
end; % if reduce rank
if ~isempty(S.fixedweights),
disp('NB USING SUPPLIED FIXED WEIGHTS');
if size(S.fixedweights,1)~=length(maskedgrid_inside_ind),
error('Suppied weights are the wrong size for grid');
end;
end;
%% prepare to write images
talpositions = spm_eeg_inv_transform_points(datareg.toMNI, grid.pos(grid.inside,:)); %% MADE DATAREG STAND ALONE
sMRI = fullfile(spm('dir'), 'canonical', 'single_subj_T1.nii');
if S.write_epochs,
if (S.Nfeatures>1) || (S.Niter>1),
error('cannot write epochs for more than one permutation or one feature');
end;
disp('storing all data in memory');
allY=zeros(length(grid.inside),Ntrials,2);
epochdirname='Epoch_cvaBf_images';
if S.logflag,
epochdirname=[epochdirname '_log'];
end;
res = mkdir(D.path, epochdirname);
end;
%% Now have all lead fields and all data
%% Now do actual beamforming
%% decide on the covariance matrix we need
%% construct covariance matrix within frequency range of interest
disp('now running through freq bands and constructing t stat images');
origfftnewdata=fftnewdata;
for boot=1:Nboot,
bttrials=randi(Ntrials,Ntrials,1);
if boot==1,
bttrials=1:Ntrials;
else
disp(['Bootstrap run' num2str(boot)]);
end; % if boot
fftnewdata=origfftnewdata(bttrials,:,:);
for fband=1:Nbands,
freqrange=freqbands(fband,:);
freq_ind=intersect(find(fHz>=freqrange(1)),find(fHz<freqrange(2)));
freqrangetest=cell2mat(S.testbands(fband));
Ntestbands=length(freqrangetest)/2;
if floor(Ntestbands)~=Ntestbands,
error('Need pairs of values in testband');
end;
freq_indtest=[];
freq_teststr='';
for k=1:Ntestbands
newtestind=intersect(find(fHz>=freqrangetest(k*2-1)),find(fHz<freqrangetest(k*2)));
freq_indtest=[freq_indtest newtestind];
freq_teststr=sprintf('%s %3.2f-%3.2fHz,',freq_teststr,fHz(min(newtestind)),fHz(max(newtestind)));
end; % for k
if length(setdiff(freq_indtest,freq_ind))>0,
error('Bands in test band are not within covariance band')
end;
covtrial=zeros(Nchans,Nchans);
if ~isempty(S.weightspect),
[fweighted,weightspectind]=intersect(fHz,S.weightspect(fband).fHz);
if abs(max(fHz(freq_ind)-S.weightspect(fband).fHz))>0,
error('weight spect vector wrong length');
end; %
filtervect=S.weightspect(fband).fAmp; %% arb filter
else
filtervect=ones(length(freq_ind),1);
end; % weightspect
if ~isempty(S.weightttest),
[fweightedt,weightspectindt]=intersect(fHz,S.weightttest(fband).fHz);
if abs(max(fHz(freq_ind)-S.weightttest(fband).fHz))>0,
error('weight ttest vector wrong length');
end; %
tfiltervect=S.weightttest(fband).vect; %% weighted by previous mv analysis
else
tfiltervect=ones(length(freq_indtest),1);
end; % weightspect
Allfiltervect=repmat(filtervect,1,Nchans);
for i=1:Ntrials, %% read in all individual trial types
ffttrial=squeeze(fftnewdata(i,freq_ind,:)).*Allfiltervect;
covtrial=covtrial+real(cov(ffttrial));
end; % for i
covtrial=covtrial/Ntrials;
allsvd = svd(covtrial);
cumpower=cumsum(allsvd)./sum(allsvd);
nmodes99=min(find(cumpower>0.99));
disp(sprintf('99 percent of the power in this data is in the first %d principal components of the cov matrix',nmodes99));
disp(sprintf('largest/smallest eigenvalue=%3.2f',allsvd(1)/allsvd(end)));
disp(sprintf('\nFrequency resolution %3.2fHz',mean(diff(fHz))));
noise = allsvd(end); %% use smallest eigenvalue
redNfeatures=[Nfeatures*2 Nfeatures]; %% NB major change
if S.dimauto, %% only do this flag set
if nmodes99<redNfeatures,
redNfeatures=nmodes99+1;
disp(sprintf('reducing number of features to those describing 99 percent of data (from %d to %d)',Nfeatures,redNfeatures));
end; %
end; % if S.dimauto
if redNfeatures(2)>length(freq_indtest),
disp(sprintf('reducing number of power features to match bandwidth (from %d to %d) !!',redNfeatures(2),length(freq_indtest)));
redNfeatures(2)=length(freq_indtest);
end;
if redNfeatures(1)>length(freq_indtest)*2, % more features in evoked case
disp(sprintf('reducing number of evoked features to match bandwidth (from %d to %d) !!',redNfeatures(1),2*length(freq_indtest)));
redNfeatures(1)=length(freq_indtest)*2;
end;
if S.compUV
disp('Computing a pseudo stat based on UV estimate of covariance between signals');
end;
disp(sprintf('covariance band from %3.2f to %3.2fHz (%d bins), test band %s (%d bins)',fHz(freq_ind(1)),fHz(freq_ind(end)),length(freq_ind),freq_teststr,length(freq_indtest)))
disp(sprintf('Using %d and %d features for power and amplitude tests respectively',redNfeatures(2),redNfeatures(1)));
lambda = (S.regpc/100) * sum(allsvd)/size(covtrial,1); %% scale lambda relative mean eigenvalue
disp(sprintf('regularisation =%3.2f percent',S.regpc));
cinv=pinv(covtrial+eye(size(covtrial,1))*lambda); %% get inverse - if N features has been reduced should maybe think of sorting this out too.
CVA_maxstat=zeros(length(grid.inside),2,S.Niter);
roymax=zeros(size(CVA_maxstat));
tstat=zeros(length(grid.inside),2,S.Niter);
maxcva=zeros(2,S.Niter);
power_trial=zeros(Ntrials,length(freq_indtest));
evoked_trial=zeros(Ntrials,length(freq_indtest));
TrueIter=1; %% no permutation for this iteration
for j=1:S.Niter, %% set up permutations in advance- so perms across grid points are identical
randind(j,:)=randperm(Ntrials);
if j==TrueIter,
randind(j,:)=1:Ntrials; % don't permute first run
end;
end;
for i=1:length(maskedgrid_inside_ind), %% 81
lf=cell2mat(grid.leadfield(grid.inside(maskedgrid_inside_ind(i))));
%% get optimal orientation- direct copy from Robert's beamformer_lcmv.m
projpower_vect=pinv(lf'*cinv*lf);
if isempty(S.gridori),
[u, s, v] = svd(real(projpower_vect)); %% MAY NOT BE POWER WE NEED TO OPTIMISE
eta = u(:,1);
else
eta=S.gridori(grid.inside(maskedgrid_inside_ind(i)),:)';
end;
lf = lf * eta; %% now have got the lead field at this voxel, compute some contrast
weights=(lf'*cinv*lf)\lf'*cinv; %% no regularisation for now
normweights=sqrt(weights*weights');
if S.fixedweights,
weights=S.fixedweights(i,:);
end;
if S.randomweight,
disp('RANDOM WEIGHT !');
weights=randn(size(weights));
end;
stats(fband).ctf_weights(maskedgrid_inside_ind(i),:)=weights;
alllf(maskedgrid_inside_ind(i),:)=lf;
for j=1:Ntrials, %% this non-linear step (power estimation) has to be done at each location
fdata=squeeze(fftnewdata(j,freq_indtest,:));
if length(freq_indtest)==1,
fdata=fdata';
end; % if length
fdatatrial=fdata*weights';
evoked_trial(j,:)=fdatatrial;
if S.logflag,
power_trial(j,:)=log(fdatatrial.*conj(fdatatrial));
else
power_trial(j,:)=fdatatrial.*conj(fdatatrial); %%
end; % i
end; % for j
for power_flag=0:1,
if power_flag,
Yfull=power_trial;
else
Yfull=[real(evoked_trial), imag(evoked_trial)]; %% split into sin and cos parts
end; % if power_fla
Y = Yfull - X0*(X0'*Yfull); %% eg remove DC level or drift terms from all of Y
%[u s v] = spm_svd(Y,-1,-1); % ,1/4); %% get largest variance in Y -1s make sure nothing is removed
%% reduce dimensions to Nfeatures
[u,s,v]=svd(Y'*Y); %% reduce dimensions of useful signal
U=u(:,1:redNfeatures(power_flag+1));
Y = Y*U;
if S.write_epochs,
nfact=normweights.^(power_flag+1); %% normalise for amplitude or power
allY(i,:,power_flag+1)=Y./nfact; %% normalise the Ys by the depth
end;
%% Now permute the rows of X if necessary
for iter=1:S.Niter,
X=Xdesign(randind(iter,:),:); %% randind(1,:)=1, i.e. unpermuted
if boot>1, %% have to also shuffle design matrix with data in bootstrap
tmp=X;
X=tmp(bttrials,:);
end;
%-Canonical Variates Analysis
% ==========================================================================
% remove null space of contrast
%--------------------------------------------------------------------------
Y = Y - X0*(X0'*Y); %% eg remove DC level or drift terms from all of Y
X = X - X0*(X0'*X);
P = pinv(X);
if TWOSAMPLETEST,
Ym=mean(Y,2);
B = pinv(X)*Ym;
RSS = sum((Ym - X*B).^2);
MRSS = RSS / dfe;
SE = sqrt(MRSS*(pinv(X'*X)));
tstat(maskedgrid_inside_ind(i),power_flag+1,iter)=B./SE;
Ftstat=(B./SE).^2;
end; % if TWOSAMPLETEST
[n,b] = size(X);
[n,m] = size(Y); %% n is number of epochs, m is number of features
b = rank(X);
h = min(b,m); %% either number of features or rank of X
f = n - b - size(X0,2); %% number of epochs- rank(X) - number of confounds
UVTEST=(1-power_flag)*S.compUV;
if UVTEST,
flatX=reshape(X,prod(size(X)),1);
flatY=reshape(X,prod(size(X)),1);
uvB = pinv(flatX)*flatY; %% uv coeff
Tuv=flatX*uvB; %% uv prediction
SSTuv=Tuv'*Tuv;
Ruv=(flatY - Tuv); %% uv error
RSSuv=Ruv'*Ruv;
Tmuv=X*U*uvB;
SSTmuv=Tmuv'*Tmuv;
end;
% generalised eigensolution for treatment and residual sum of squares
%--------------------------------------------------------------------------
T = X*(P*Y); %% predticon of Y based on X (P*Y is the coefficient)
SST = T'*T;
SSR = Y - T; %% residuals in Y (unexplained by X)
SSR = SSR'*SSR;
lastwarn('')
[v,d] = eig(SSR\SST); %% explained/unexplained variance
[lastmsg, LASTID] = lastwarn;
if ~isempty(lastmsg),
disp('rank problem, zeroing eigenvals');
d=zeros(size(d));
end;
[q,r] = sort(-real(diag(d)));
r = r(1:h);
d = real(d(r,r));
v = real(v(:,r));
V = U*v; % canonical vectors (data)
v = Y*v; % canonical variates (data)
W = P*v; % canonical vectors (design)
w = X*W; % canonical variates (design)
C = c*W; % canonical contrast (design)
% inference on dimensionality - p(i) test of D >= i; Wilk's Lambda := p(1)
%--------------------------------------------------------------------------
roymax(maskedgrid_inside_ind(i),power_flag+1,iter)=d(1,1); %% maximum root is the first one
Roy2F=(f+m-max(b,m))/max(b,m); %% conversion from Roy's max root to F
cval = log(diag(d) + 1);
chi=[];df=[];p=[];p05thresh=[];
for i1 = 1:h
chi(i1) = (f - (m - b + 1)/2)*sum(cval(i1:h));
df(i1) = (m - i1 + 1)*(b - i1 + 1); % m is the number of features, b is the rank of the design matrix
p(i1) = 1 - spm_Xcdf(chi(i1),df(i1));
p05thresh(i1) = spm_invXcdf(1-0.05,df(i1));
end
CVA_maxstat(maskedgrid_inside_ind(i),power_flag+1,iter)=chi(1); %% get wilk's lambda stat
CVA_otherdim(maskedgrid_inside_ind(i),power_flag+1,iter,1:h-1)=chi(2:h); %% tests on other dimensions
% if power_flag,
% allw_pw(maskedgrid_inside_ind(i),power_flag+1,iter,:,:)=W;
% else
% allw_ev(maskedgrid_inside_ind(i),power_flag+1,iter,:,:)=W;
% end;
%
if CVA_maxstat(maskedgrid_inside_ind(i),power_flag+1,iter)>maxcva(power_flag+1,iter),
stats(fband).bestchi(power_flag+1,1:h,iter)=chi;
if power_flag,
stats(fband).bestVpw(1:h,iter,:)=V';
stats(fband).bestvpw(1:h,iter,:)=v';
stats(fband).bestUpw=U;
stats(fband).maxw_pw=w;
stats(fband).maxW_pw=W;
else
stats(fband).bestVev(1:h,iter,:)=complex(V(1:size(evoked_trial,2),:),V(size(evoked_trial,2)+1:end,:))';
stats(fband).bestvev(1:h,iter,:)=v';
stats(fband).bestUev=U;
stats(fband).maxw_ev=w;
stats(fband).maxW_ev=W;
end;
stats(fband).pval(power_flag+1,1:h,iter)=p;
stats(fband).df(power_flag+1,1:h,iter)=df;
stats(fband).p05alyt(power_flag+1,1:h)=p05thresh;
stats(fband).maxind(power_flag+1,iter)=maskedgrid_inside_ind(i);
stats(fband).freqHz=fHz(freq_indtest);
stats(fband).freq_indtest=freq_indtest;
stats(fband).freq_ind=freq_ind;
maxcva(power_flag+1,iter)=CVA_maxstat(maskedgrid_inside_ind(i),power_flag+1,iter);
end; % if CVA_Stat
if (iter==TrueIter) && (length(V)>1),
if power_flag,
stats(fband).allVpw(1:h,i,:)=V';
else
stats(fband).allVev(1:h,i,:)=complex(V(1:size(evoked_trial,2),:),V(size(evoked_trial,2)+1:end,:))';
end;
end;% if iter
end; % for Niter
end; % for power_flag
if i/100==floor(i/100)
disp(sprintf('done CVA stats for %3.2f percent of freq band %d of %d, log=%d, rank=%d',100*i/length(maskedgrid_inside_ind),fband,Nbands,S.logflag,S.rankflag));
end; % if
end; % for grid points
%% GET NUMBER OF UNIQUE EXTREMA- ONLY WORKS FOR SPECIFIC GRAD TYPES (mag or axial)
alpha=0.05; %% for display only
%[alyt_thresh_Chi,Nu_extrema,overlap_ind,overlap_pos]=correction_for_ROI(roi_str,talpositions,alllf,alpha,redNfeatures(1)*b)
[maxvals,maxind]=max(alllf');
[minvals,minind]=max(-alllf');
lead_extrema=[maxind' minind'];
lead_extrema=sort(lead_extrema')'; %% doesn't matter if extrema are reversed
u_extrema=unique(lead_extrema,'rows');
Nu_extrema=size(u_extrema,1)
stats(fband).maskedgrid_inside_ind=maskedgrid_inside_ind;
stats(fband).CVAmax=CVA_maxstat;
stats(fband).CVAotherdim=CVA_otherdim;
stats(fband).roymax=roymax;
stats(fband).Roy2F=Roy2F;
%stats(fband).allw=allw;
stats(fband).tstat=tstat.^2;
stats(fband).fHz=fHz;
stats(fband).dfmisc=[b h m];
dispthresh_mv=max(stats(fband).CVAmax)/2; % default display thresholds
max_mv=max(stats(fband).CVAmax); % default display thresholds
if S.Niter>1,
%% get corrected p values for CVA
allglobalmax=squeeze(max(stats(fband).CVAmax(:,:,1:end)));
[sortglobalmax,sortglobalmaxind]=sort(allglobalmax','descend');
allglobalmax_roy=squeeze(max(stats(fband).roymax(:,:,1:end)));
[sortglobalmax_roy,sortglobalmaxind_roy]=sort(allglobalmax_roy','descend');
for k=1:2,
stats(fband).corrpmax_cva(k)=find(sortglobalmaxind(:,k)==TrueIter)/length(sortglobalmaxind);
stats(fband).corrpmax_roy(k)=find(sortglobalmaxind_roy(:,k)==TrueIter)/length(sortglobalmaxind_roy);
end;
stats(fband).thresh05globalmax_cva=sortglobalmax(round(length(sortglobalmaxind)*5/100),:);
stats(fband).thresh05globalmax_roy=sortglobalmax_roy(round(length(sortglobalmaxind)*5/100),:);
dispthresh_mv=stats(fband).thresh05globalmax_cva; % display only significant effects
end; % if
%
csource=grid; %% only plot and write out unpermuted iteration
gridpositions=csource.pos(csource.inside,:);
csource.pow_maxchi(csource.inside) = CVA_maxstat(:,2,TrueIter); %power
log_pvals_corr_pow=log(1-spm_Xcdf(CVA_maxstat(:,2,TrueIter),redNfeatures(2)*b));
if S.CorrectPvals,
log_pvals_corr_pow=log_pvals_corr_pow+log(Nu_extrema); %% multiply by number of comparisons
log_pvals_corr_pow(find(log_pvals_corr_pow>0))=0;
end; % if
csource.logp_power(csource.inside) = -log_pvals_corr_pow; %% write negative log so that largest image values have high significance
%spm_Xcdf(1-alpha/(stats(fband).Nu_extrema),redNfeatures(1)*b)
csource.evoked_maxchi(csource.inside) = CVA_maxstat(:,1,TrueIter); % evoked
log_pvals_corr_evoked=log(1-spm_Xcdf(CVA_maxstat(:,1,TrueIter),redNfeatures(1)*b));
if S.CorrectPvals,
log_pvals_corr_evoked=log_pvals_corr_evoked+log(Nu_extrema); %% multiply by number of comparisons
log_pvals_corr_evoked(find(log_pvals_corr_evoked>0))=0;
end; % if
csource.logp_evoked(csource.inside) = -log_pvals_corr_evoked;
csource.pow_maxchi(csource.outside)=0;
csource.evoked_maxchi(csource.outside)=0;
csource.logp_evoked(csource.outside)=0;
csource.logp_power(csource.outside)=0;
csource.pos = spm_eeg_inv_transform_points(datareg.toMNI, csource.pos);
if isempty(S.gridpos), %% only write images if they use whole volume
cfg1 = [];
cfg1.sourceunits = 'mm';
cfg1.parameter = 'pow_maxchi';
cfg1.downsample = 1;
sourceint_pow_maxchi = ft_sourceinterpolate(cfg1, csource, sMRI);
cfg1 = [];
cfg1.sourceunits = 'mm';
cfg1.parameter = 'evoked_maxchi';
cfg1.downsample = 1;
sourceint_evoked_maxchi = ft_sourceinterpolate(cfg1, csource, sMRI);
cfg1 = [];
cfg1.sourceunits = 'mm';
cfg1.parameter = 'logp_power';
cfg1.downsample = 1;
sourceint_logp_pow = ft_sourceinterpolate(cfg1, csource, sMRI);
cfg1 = [];
cfg1.sourceunits = 'mm';
cfg1.parameter = 'logp_evoked';
cfg1.downsample = 1;
sourceint_logp_evoked = ft_sourceinterpolate(cfg1, csource, sMRI);
stats(fband).Nu_extrema=Nu_extrema;
stats(fband).alyt_thresh_Chi_05(1)=spm_invXcdf(1-alpha/(stats(fband).Nu_extrema),redNfeatures(1)*b); %% estimate of volumetric threshold for evoked
stats(fband).alyt_thresh_Chi_05(2)=spm_invXcdf(1-alpha/(stats(fband).Nu_extrema),redNfeatures(2)*b); %% estimate of volumetric thres for induced
%% else %% write out the data sets
disp('writing images');
cfg = [];
cfg.sourceunits = 'mm';
cfg.parameter = 'pow';
cfg.downsample = 1;
dirname='cvaBf_images';
if S.logflag,
dirname=[dirname '_log'];
end;
res = mkdir(D.path, dirname);
outvol = spm_vol(sMRI);
outvol.dt(1) = spm_type('float32');
featurestr=[S.filenamestr 'Nf' num2str(redNfeatures(2))] ;
if S.bootstrap,
featurestr=sprintf('%s_bt%03d_',featurestr,boot);
end; % if
outvol.fname= fullfile(D.path, dirname, ['chi_pw_' spm_str_manip(D.fname, 'r') '_' num2str(freqbands(fband,1)) '-' num2str(freqbands(fband,2)) 'Hz' featurestr '.nii']);
stats(fband).outfile_chi_pw=outvol.fname;
outvol = spm_create_vol(outvol);
spm_write_vol(outvol, sourceint_pow_maxchi.pow_maxchi);
cmap=colormap;
jetmap=colormap('jet');
if (isfield(S, 'preview') && S.preview)
spm_check_registration(sMRI)
prop=0.4;
colourmap=jetmap;
spm_orthviews('Addtruecolourimage',1,outvol.fname,colourmap,prop,max_mv(2),dispthresh_mv(2));
disp(sprintf('Chi pw image. Est thresh for p<0.05 (corr) is %3.2f. Press any key to continue..',stats(fband).alyt_thresh_Chi_05(2)));
pause;
end; % if preview
colormap(cmap);
featurestr=[S.filenamestr 'Nf' num2str(redNfeatures(1))] ;
outvol.fname= fullfile(D.path, dirname, ['chi_ev_' spm_str_manip(D.fname, 'r') '_' num2str(freqbands(fband,1)) '-' num2str(freqbands(fband,2)) 'Hz' featurestr '.nii']);
stats(fband).outfile_chi_ev=outvol.fname;
outvol = spm_create_vol(outvol);
spm_write_vol(outvol, sourceint_evoked_maxchi.evoked_maxchi);
if (isfield(S, 'preview') && S.preview)
spm_check_registration(sMRI)
prop=0.4;
colourmap=jetmap;
spm_orthviews('Addtruecolourimage',1,outvol.fname,colourmap,prop,max_mv(1),dispthresh_mv(1));
disp(sprintf('Chi ev image. Est thresh for p<0.05 (corr) is %3.2f. Press any key to continue..',stats(fband).alyt_thresh_Chi_05(1)));
pause;
end; % if preview
outvals=CVA_maxstat(:,1,TrueIter);
% prefix='testrun';
%[outvol]=write_trial_image(0,0,talpositions,datareg,sMRI,D,dirname,csource,outvals,prefix,freqbands(fband,:))
colormap(cmap);
featurestr=[S.filenamestr 'Nf' num2str(redNfeatures(2))] ;
outvol.fname= fullfile(D.path, dirname, ['logp_pow_' spm_str_manip(D.fname, 'r') '_' num2str(freqbands(fband,1)) '-' num2str(freqbands(fband,2)) 'Hz' featurestr S.filenamestr '.nii']);
stats(fband).outfile_logp_pow=outvol.fname;
outvol = spm_create_vol(outvol);
spm_write_vol(outvol, sourceint_logp_pow.logp_power);
featurestr=[S.filenamestr 'Nf' num2str(redNfeatures(1))] ;
outvol.fname= fullfile(D.path, dirname, ['logp_evoked_' spm_str_manip(D.fname, 'r') '_' num2str(freqbands(fband,1)) '-' num2str(freqbands(fband,2)) 'Hz' featurestr S.filenamestr '.nii']);
stats(fband).outfile_logp_evoked=outvol.fname;
outvol = spm_create_vol(outvol);
spm_write_vol(outvol, sourceint_logp_evoked.logp_evoked);
% %% now write all trials of data out
if S.write_epochs,
permnum=1;
outfilenames_pw=[];
outfilenames_ev=[];
for trialnum=1:Ntrials,
prefix='ev';outvals=allY(:,trialnum,1); %% evoked first
[outvolev]=write_trial_image(trialnum,permnum,talpositions,datareg,sMRI,D,epochdirname,csource,outvals,prefix,freqbands(fband,:));
outfilenames_ev=strvcat(outfilenames_ev,outvolev.fname);
prefix='pow';outvals=allY(:,trialnum,2); %% then power
[outvolpw]=write_trial_image(trialnum,permnum,talpositions,datareg,sMRI,D,epochdirname,csource,outvals,prefix,freqbands(fband,:));
outfilenames_pw=strvcat(outfilenames_pw,outvolpw.fname);
end; % for trialnum
stats(fband).outfile_pw_epochs=outfilenames_pw;
stats(fband).outfile_ev_epochs=outfilenames_ev;
end;
end; % if ~S.gridpos
end; % for fband=1:Nbands
end; %% bootstrap
bootlist= fullfile(D.path, dirname, ['bootlist_' spm_str_manip(D.fname, 'r') '_' num2str(freqbands(fband,1)) '-' num2str(freqbands(fband,2)) 'Hz' featurestr '.mat']);
save(bootlist,'bttrials');
end % function
function [soutvol]=write_trial_image(trialnum,permnum,talpositions,datareg,sMRI,D,dirname,csource,outvals,prefix,freqband)
%outvals=outvals./1e12;
%outvals=outvals.*0;
%outvals(715)=trialnum;
csource.pow_maxchi(csource.inside) = outvals;
csource.pow_maxchi(csource.outside)=0;
cfg1 = [];
cfg1.sourceunits = 'mm';
cfg1.parameter = 'pow_maxchi';
cfg1.downsample = 1;
sourceint_pow_maxchi = ft_sourceinterpolate(cfg1, csource, sMRI);
cfg = [];
cfg.sourceunits = 'mm';
cfg.parameter = 'pow';
cfg.downsample = 1;
outvol = spm_vol(sMRI);
outvol.dt(1) = spm_type('float32');
featurestr=['Nf1'] ; %% only for 1 feature
outvol.fname= fullfile(D.path, dirname, [sprintf('Trial%04d_Perm%04d_%s',trialnum,permnum,prefix) spm_str_manip(D.fname, 'r') '_' num2str(freqband(1)) '-' num2str(freqband(2)) 'Hz' featurestr '.nii']);
outvol = spm_create_vol(outvol);
spm_write_vol(outvol, sourceint_pow_maxchi.pow_maxchi);
soutvol=outvol;
mmsampling=min(abs(diag(soutvol.mat(1:3,1:3)))); %% get sampling of the output image
Sfwhm=mmsampling*3; %% smooth by 3* this to get sufficiently sampled output image
soutvol.fname= fullfile(D.path, dirname, [sprintf('S%dmmTrial%04d_Perm%04d_%s',Sfwhm,trialnum,permnum,prefix) spm_str_manip(D.fname, 'r') '_' num2str(freqband(1)) '-' num2str(freqband(2)) 'Hz' featurestr '.nii']);
spm_smooth(outvol,soutvol,Sfwhm);
end
|
github
|
philippboehmsturm/antx-master
|
tbx_cfg_tbx_Icc.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/icc/tbx_cfg_tbx_Icc.m
| 3,628 |
utf_8
|
164fe7ffc0377b56b9330df0aae45f34
|
function tbx_Icc = tbx_cfg_tbx_Icc
% Russ Poldrack and Volkmar Glauche
% $Id: tbx_cfg_tbx_Icc.m,v 1.1 2008-04-14 08:53:10 vglauche Exp $
%_______________________________________________________________________
rev='$Revision: 1.1 $';
addpath(fullfile(spm('dir'),'toolbox','icc'));
% see how we are called - if no output argument, then start spm_jobman UI
if nargout == 0
spm_jobman('interactive');
return;
end;
% MATLABBATCH Configuration file for toolbox 'Icc Calculation'
% This code has been automatically generated.
% ---------------------------------------------------------------------
% srcimgs Source Images
% ---------------------------------------------------------------------
srcimgs = cfg_files;
srcimgs.tag = 'srcimgs';
srcimgs.name = 'Source Images';
srcimgs.help = {'Enter all images from the same observation. Subject ordering must be consistent over all observations.'};
srcimgs.filter = 'image';
srcimgs.ufilter = '.*';
srcimgs.num = [1 Inf];
% ---------------------------------------------------------------------
% obs Observations
% ---------------------------------------------------------------------
obs = cfg_repeat;
obs.tag = 'obs';
obs.name = 'Observations';
obs.help = {'Enter images from at least two observations for the same sample of subjects.'};
obs.values = {srcimgs };
obs.num = [2 Inf];
obs.check = @check_obs;
% ---------------------------------------------------------------------
% tbx_Icc Icc Calculation
% ---------------------------------------------------------------------
tbx_Icc = cfg_exbranch;
tbx_Icc.tag = 'tbx_Icc';
tbx_Icc.name = 'Icc Calculation';
tbx_Icc.val = {obs };
tbx_Icc.help = {''};
tbx_Icc.prog = @comp_icc;
tbx_Icc.vout = @vout_icc;
% ---------------------------------------------------------------------
% local functions
% ---------------------------------------------------------------------
function out = comp_icc(job)
nobs = numel(job.srcimgs);
nsub = numel(job.srcimgs{1});
V = spm_vol(job.srcimgs);
spm_check_orientations(cat(1,subsref(cat(1,V{:}),...
struct('type','{}','subs',{{':'}}))));
iccm = zeros(V{1}{1}.dim(1:3));
spm_progress_bar('init', V{1}{1}.dim(3), 'Icc computation', 'Planes completed');
for z=1:V{1}{1}.dim(3)
M = spm_matrix([0 0 z 0 0 0 1 1 1]);
dat = zeros([nsub,nobs,V{1}{1}.dim(1:2)]);
for cs = 1:nsub
for co = 1:nobs
dat(cs,co,:,:) = spm_slice_vol(V{co}{cs},M,V{1}{1}.dim(1:2),[0,NaN]);
end;
end;
for x = 1:V{1}{1}.dim(1)
for y = 1:V{1}{1}.dim(2)
iccm(x,y,z)=icc(dat(:,:,x,y));
end
end
spm_progress_bar('Set',z);
end
iccm(isnan(iccm)) = 0;
Vo = rmfield(V{1}{1},'private');
[p n e v] = spm_fileparts(Vo.fname);
Vo.fname = fullfile(p,['icc_' n e]);
spm_write_vol(Vo,iccm);
spm_progress_bar('clear');
out.iccfile = {Vo.fname};
return
function dep = vout_icc(job)
dep = cfg_dep;
dep.sname = 'ICC volume';
dep.src_output = substruct('.','iccfile');
dep.tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
return;
function cstr = check_obs(srcimgs)
cstr = '';
nobs = numel(srcimgs);
nsub1 = numel(srcimgs{1});
for k = 1:nobs
if numel(srcimgs{k}) ~= nsub1
cstr = sprintf(['Number of subjects in observation 1 and %d differ ' ...
'(%d/%d)'], k, nsub1, numel(srcimgs{k}));
return;
end;
end;
V = spm_vol(srcimgs);
try
spm_check_orientations(cat(1,subsref(cat(1,V{:}),...
struct('type','{}','subs',{{':'}}))));
catch
cstr = 'Images do not all have same orientation or voxel size.';
end;
|
github
|
philippboehmsturm/antx-master
|
tbx_config_icc.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/icc/tbx_config_icc.m
| 2,243 |
utf_8
|
e395073628088e0bc7895a43bb0073d9
|
function opts = spm_config_Icc
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% Russ Poldrack and Volkmar Glauche
% $Id: tbx_config_icc.m,v 1.2 2007-03-30 07:58:52 glauche Exp $
%_______________________________________________________________________
rev='$Revision: 1.2 $';
addpath(fullfile(spm('dir'),'toolbox','icc'));
% see how we are called - if no output argument, then start spm_jobman UI
if nargout == 0
spm_jobman('interactive','','jobs.tools.tbx_Icc');
return;
end;
srcimgs.type = 'files';
srcimgs.name = 'Source Images';
srcimgs.tag = 'srcimgs';
srcimgs.filter = 'image';
srcimgs.num = [1 Inf];
srcimgs.help = {['Enter all images from the same observation. Subject' ...
' ordering must be consistent over all observations.']};
obs.type = 'repeat';
obs.name = 'Observations';
obs.tag = 'obs';
obs.num = [2 Inf];
obs.values = {srcimgs};
obs.help = {['Enter images from at least two observations for the same sample' ...
' of subjects.']};
opts.type = 'branch';
opts.name = 'Icc Calculation';
opts.tag = 'tbx_Icc';
opts.val = {obs};
opts.prog = @comp_icc;
%opts.vfiles = @vfiles;
return;
function comp_icc(job)
nobs = numel(job.srcimgs);
nsub = numel(job.srcimgs{1});
V = spm_vol(job.srcimgs);
spm_check_orientations(cat(1,subsref(cat(1,V{:}),...
struct('type','{}','subs',{{':'}}))));
iccm = zeros(V{1}{1}.dim(1:3));
spm_progress_bar('init', V{1}{1}.dim(3), 'Icc computation', 'Planes completed');
for z=1:V{1}{1}.dim(3)
M = spm_matrix([0 0 z 0 0 0 1 1 1]);
dat = zeros([nsub,nobs,V{1}{1}.dim(1:2)]);
for cs = 1:nsub
for co = 1:nobs
dat(cs,co,:,:) = spm_slice_vol(V{co}{cs},M,V{1}{1}.dim(1:2),[0,NaN]);
end;
end;
for x = 1:V{1}{1}.dim(1)
for y = 1:V{1}{1}.dim(2)
iccm(x,y,z)=icc(dat(:,:,x,y));
end
end
spm_progress_bar('Set',z);
end
iccm(isnan(iccm)) = 0;
Vo = rmfield(V{1}{1},'private');
[p n e v] = spm_fileparts(Vo.fname);
Vo.fname = fullfile(p,['icc_' n e]);
spm_write_vol(Vo,iccm);
spm_progress_bar('clear');
return
function vf = vfiles(job)
[p n e v] = spm_fileparts(job.srcimgs{1}{1});
vf{1} = fullfile(p,['icc_' n e]);
return;
|
github
|
philippboehmsturm/antx-master
|
timediff.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/tsdiffana/timediff.m
| 3,340 |
utf_8
|
1cc63d946f7f8d629436d4357c2a419d
|
function [imdiff, g, slicediff] = timediff(imgs, flags)
% Analyses slice by slice variance across time series
% FORMAT [imdiff, g, slicediff] = timediff(imgs, flags)
%
% imgs - string or cell or spm_vol list of images
% flags - specify options; if contains:
% m - create mean var image (vmean*), max slice var image
% (vsmax*) and scan to scan variance image (vscmean*)
% v - create variance image for between each time point
%
% imdiff - mean variance between each image in time series
% g - mean voxel signal intensity for each image
% slicediff - slice by slice variance between each image
%
% Matthew Brett 17/7/00
imgs = spm_vol(char(imgs));
V1 = imgs(1);
Vr = imgs(2:end);
ndimgs = numel(imgs)-1;
Hold = 0;
if any(flags == 'v') % create variance images
for i = 1:ndimgs
vVr(i) = makevol(Vr(i),'v',16); % float
end
end
if any(flags == 'm') % mean /max variance
mVr = makevol(V1,'vmean',16);
sVr = makevol(V1,'vscmean',16);
xVr = makevol(V1,'vsmax',16);
end
[xydim zno] = deal(V1.dim(1:2),V1.dim(3));
p1 = spm_read_vols(V1);
slicediff = zeros(ndimgs,zno);
g = zeros(ndimgs,1);
for z = 1:zno % across slices
M = spm_matrix([0 0 z]);
pr = p1(:,:,z); % this slice from first volume
if any(flags == 'm')
[mv sx2 sx mxvs] = deal(zeros(size(pr)));
end
% SVD is squared voxel difference (usually a slice of same)
% MSVD is the mean of this measure across voxels (one value)
% DTP is a difference time point (1:T-1)
cmax = 0; % counter for which slice has the largest MSVD
% note that Vr contains volumes 2:T (not the first)
for i = 1:ndimgs % across DTPs
c = spm_slice_vol(Vr(i),M,xydim,Hold); % get slice from this time point
v = (c - pr).^2; % SVD from this slice to last
slicediff(i,z) = mean(v(:)); % MSVD for this slice
g(i) = g(i) + mean(c(:)); % simple mean of data
if slicediff(i,z)>cmax % if this slice has larger MSVD, keep
mxvs = v;
cmax = slicediff(i,z);
end
pr = c; % set current slice data as previous, for next iteration of loop
if any(flags == 'v') % write individual SVD slice for DTP
vVr(i) = spm_write_plane(vVr(i),v,z);
end
if any(flags == 'm')
mv = mv + v; % sum up SVDs for mean SVD (across time points)
sx = sx + c; % sum up data for simple variance calculation
sx2 = sx2 + c.^2; % sum up squared data for simple variance
% calculation
end
end
if any(flags == 'm') % mean variance etc
sVr = spm_write_plane(sVr,mv/(ndimgs),z); % write mean of SVDs
% across time
xVr = spm_write_plane(xVr,mxvs,z); % write maximum SVD
mVr = spm_write_plane(mVr,(sx2-((sx.^2)/ndimgs))./(ndimgs-1),z);
% (above) this is the one-pass simple variance formula
end
end
g = [mean(p1(:)); g/zno];
imdiff = mean(slicediff,2);
return
function Vo = makevol(Vi, prefix, datatype)
Vo = Vi;
fn = Vi.fname;
[p f e] = fileparts(fn);
Vo.fname = fullfile(p, [prefix f e]);
switch lower(spm('ver'))
case {'spm5','spm8','spm8b','spm12','spm12b'}
Vo.dt = [datatype 0];
Vo = spm_create_vol(Vo, 'noopen');
otherwise
error('What ees thees version "%s"', spm('ver'));
end
return
|
github
|
philippboehmsturm/antx-master
|
run_tsdiffana.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/tsdiffana/run_tsdiffana.m
| 2,148 |
utf_8
|
f201c026bb24af7be0e0ffc49ac908b8
|
function varargout = run_tsdiffana(cmd, varargin)
% Wrapper function for tsdiffana routines
switch cmd,
case 'run'
subfun = varargin{1};
job = varargin{2};
switch subfun
case 'timediff'
for k = 1:numel(job.imgs)
[p f e] = spm_fileparts(job.imgs{k}{1});
if job.vf
flags = 'mv';
else
flags = 'm';
end
imgs = char(job.imgs{k});
[td globals slicediff] = timediff(imgs,flags);
out.tdfn{k} = fullfile(p,'timediff.mat');
save(out.tdfn{k}, 'imgs', 'td', 'globals', 'slicediff');
end
varargout{1} = out;
case 'tsdiffplot'
fg = spm_figure('GetWin', 'Graphics');
spm_figure('Clear');
for k = 1:numel(job.tdfn)
h = tsdiffplot(job.tdfn{k}, fg);
spm_figure('NewPage', h);
end
if job.doprint
spm_figure('Print');
end
end
case 'vout'
subfun = varargin{1};
job = varargin{2};
switch subfun
case 'timediff'
for k = 1:numel(job.imgs)
dep(k) = cfg_dep;
dep(k).sname = sprintf('Timeseries Analysis Data File (%d)', k);
dep(k).src_output = substruct('.','tdfn','()',{k});
dep(k).tgt_spec = cfg_findspec({{'filter','mat', ...
'strtype','e'}});
end
varargout{1} = dep;
case 'tsdiffplot'
end
case 'defaults'
if nargin == 2
varargout{1} = local_defs(varargin{1});
else
local_defs(varargin{1:2});
end
end
function varargout = local_defs(defstr, defval)
persistent defs;
if isempty(defs)
defs.vf = false;
defs.doprint = true;
end
if nargin == 1
varargout{1} = defs.(defstr);
else
defs.(defstr) = defval;
end
|
github
|
philippboehmsturm/antx-master
|
moh_unified_segmentation.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/ALI/moh_unified_segmentation.m
| 10,685 |
utf_8
|
3bd937b04b9b19314f52a21a31907abc
|
function moh_unified_segmentation(V, c4prior)
% based on spm segmentation routines
% V: volume structure to be segmented
% c4prior: image that defines the spatial priors for the extra class
%
% Mohamed Seghier 05.08.2008
% =======================================
%
if ~isstruct(V), V = spm_vol(V) ; end
[pth,nam,ext,toto] = spm_fileparts(V.fname) ;
% define options (can be modified)
% opts0: options for the unified segmentation routine
opts0.tpm = char(fullfile(spm('Dir'), 'tpm', 'grey.nii'),...
fullfile(spm('Dir'), 'tpm', 'white.nii'),...
fullfile(spm('Dir'), 'tpm', 'csf.nii'),...
c4prior);
opts0.ngaus = [2 2 2 2 4];
opts0.warpreg = 1;
opts0.warpco = 25;
opts0.biasreg = 0.01;
opts0.biasfwhm = 75;
opts0.regtype = 'mni';
opts0.fudge = 5;
opts0.samp = 3;
opts0.msk = '';
% segmentation in [4 + 1] classes (with different Gaussians per class)
if length(opts0.ngaus)~= size(opts0.tpm,1)+1,
error('Number of Gaussians is not compatible with number of classes');
end;
% opts1: options for writing segmented classes
opts1.biascor = 0 ;
opts1.GM = [0 1 0] ;
opts1.WM = [0 1 0] ;
opts1.CSF = [0 1 0] ;
opts1.EXTRA1 = [0 1 0] ;
opts1.cleanup = 1 ;
% to write 4 classes per segmentation run
if length(fieldnames(opts1))~= size(opts0.tpm,1)+2,
error('Number of written classes is not compatible with segm. classes');
end;
% unified segmentation steps
% --------------------------
% --------------------------
% run the combined segmentation-normalisation procedure
% -----------------------------------------------------
Res = spm_preproc(V, opts0) ;
disp('###### Combined Segmentation and Spatial Normalisation..........OK');
% convert preproc output to a format for writing classes
% ------------------------------------------------------
PO = spm_prep2sn(Res) ;
disp('###### Convert the output to an sn.mat (parameters).............OK');
% save the transformation/parameters files
% ----------------------------------------
VG = PO.VG ;
VF = PO.VF ;
Tr = PO.Tr ;
Affine = PO.Affine ;
flags = PO.flags ;
fnam = fullfile(pth,[nam '_seg_sn.mat']);
if spm_matlab_version_chk('7') >= 0,
save(fnam,'-V6','VG','VF','Tr','Affine','flags');
else
save(fnam,'VG','VF','Tr','Affine','flags');
end;
disp('###### Write transformation/paramters into an *_seg_sn.mat .....OK');
% write segmented classes (see original function spm_preproc_write)
% -----------------------
b0 = spm_load_priors(PO(1).VG);
for i=1:numel(PO),
preproc_apply(PO(i) ,opts1, b0);
end;
disp('###### Write out segmented classes (one per tissue/prior).......OK');
return;
%=======================================================================
%=======================================================================
% for more datails, see original function spm_preproc_write
function preproc_apply(p,opts,b0)
nclasses = size(fieldnames(opts),1) - 2 ;
switch nclasses
case 3
sopts = [opts.GM ; opts.WM ; opts.CSF];
case 4
sopts = [opts.GM ; opts.WM ; opts.CSF ; opts.EXTRA1];
case 5
sopts = [opts.GM ; opts.WM ; opts.CSF ; opts.EXTRA1 ; opts.EXTRA2];
otherwise
error('######## unsupported number of classes....!!!')
end
[pth,nam,ext]=fileparts(p.VF.fname);
T = p.flags.Twarp;
bsol = p.flags.Tbias;
d2 = [size(T) 1];
d = p.VF.dim(1:3);
[x1,x2,o] = ndgrid(1:d(1),1:d(2),1);
x3 = 1:d(3);
d3 = [size(bsol) 1];
B1 = spm_dctmtx(d(1),d2(1));
B2 = spm_dctmtx(d(2),d2(2));
B3 = spm_dctmtx(d(3),d2(3));
bB3 = spm_dctmtx(d(3),d3(3),x3);
bB2 = spm_dctmtx(d(2),d3(2),x2(1,:)');
bB1 = spm_dctmtx(d(1),d3(1),x1(:,1));
mg = p.flags.mg;
mn = p.flags.mn;
vr = p.flags.vr;
K = length(p.flags.mg);
Kb = length(p.flags.ngaus);
for k1=1:size(sopts,1),
%dat{k1} = zeros(d(1:3),'uint8');
dat{k1} = uint8(0);
dat{k1}(d(1),d(2),d(3)) = 0;
if sopts(k1,3),
Vt = struct('fname', fullfile(pth,['c', num2str(k1), nam, ext]),...
'dim', p.VF.dim,...
'dt', [spm_type('uint8') spm_platform('bigend')],...
'pinfo', [1/255 0 0]',...
'mat', p.VF.mat,...
'n', [1 1],...
'descrip', ['Tissue class ' num2str(k1)]);
Vt = spm_create_vol(Vt);
VO(k1) = Vt;
end;
end;
if opts.biascor,
VB = struct('fname', fullfile(pth,['m', nam, ext]),...
'dim', p.VF.dim(1:3),...
'dt', [spm_type('float32') spm_platform('bigend')],...
'pinfo', [1 0 0]',...
'mat', p.VF.mat,...
'n', [1 1],...
'descrip', 'Bias Corrected');
VB = spm_create_vol(VB);
end;
lkp = []; for k=1:Kb, lkp = [lkp ones(1,p.flags.ngaus(k))*k]; end;
spm_progress_bar('init',length(x3),['Working on ' nam],'Planes completed');
M = p.VG(1).mat\p.flags.Affine*p.VF.mat;
for z=1:length(x3),
% Bias corrected image
f = spm_sample_vol(p.VF,x1,x2,o*x3(z),0);
cr = exp(transf(bB1,bB2,bB3(z,:),bsol)).*f;
if opts.biascor,
% Write a plane of bias corrected data
VB = spm_write_plane(VB,cr,z);
end;
if any(sopts(:)),
msk = find(f<p.flags.thresh);
[t1,t2,t3] = defs(T,z,B1,B2,B3,x1,x2,x3,M);
q = zeros([d(1:2) Kb]);
bt = zeros([d(1:2) Kb]);
for k1=1:Kb,
bt(:,:,k1) = spm_sample_priors(b0{k1},t1,t2,t3,k1==Kb);
end;
b = zeros([d(1:2) K]);
for k=1:K,
b(:,:,k) = bt(:,:,lkp(k))*mg(k);
end;
s = sum(b,3);
for k=1:K,
p1 = exp((cr-mn(k)).^2/(-2*vr(k)))/sqrt(2*pi*vr(k)+eps);
q(:,:,lkp(k)) = q(:,:,lkp(k)) + p1.*b(:,:,k)./s;
end;
sq = sum(q,3)+eps;
warning off
for k1=1:size(sopts,1),
tmp = q(:,:,k1);
tmp(msk) = 0;
tmp = tmp./sq;
dat{k1}(:,:,z) = uint8(round(255 * tmp));
end;
warning on
end;
spm_progress_bar('set',z);
end;
spm_progress_bar('clear');
if opts.cleanup > 0,
[dat{1},dat{2},dat{3}] = clean_gwc(dat{1},dat{2},dat{3}, opts.cleanup);
end;
if any(sopts(:,3)),
for z=1:length(x3),
for k1=1:size(sopts,1),
if sopts(k1,3),
tmp = double(dat{k1}(:,:,z))/255;
spm_write_plane(VO(k1),tmp,z);
end;
end;
end;
end;
for k1=1:size(sopts,1),
if any(sopts(k1,1:2)),
so = struct('wrap',[0 0 0],'interp',1,'vox',[NaN NaN NaN],...
'bb',ones(2,3)*NaN,'preserve',0);
ovx = abs(det(p.VG(1).mat(1:3,1:3)))^(1/3);
fwhm = max(ovx./sqrt(sum(p.VF.mat(1:3,1:3).^2))-1,0.1);
dat{k1} = decimate(dat{k1},fwhm);
fn = fullfile(pth,['c', num2str(k1), nam, ext]);
dim = [size(dat{k1}) 1];
VT = struct('fname',fn,'dim',dim(1:3),...
'dt', [spm_type('uint8') spm_platform('bigend')],...
'pinfo',[1/255 0]','mat',p.VF.mat,'dat',dat{k1});
if sopts(k1,2),
spm_write_sn(VT,p,so);
end;
so.preserve = 1;
if sopts(k1,1),
VN = spm_write_sn(VT,p,so);
VN.fname = fullfile(pth,['mwc', num2str(k1), nam, ext]);
spm_write_vol(VN,VN.dat);
end;
end;
end;
return;
%=======================================================================
%=======================================================================
function [x1,y1,z1] = defs(sol,z,B1,B2,B3,x0,y0,z0,M)
x1a = x0 + transf(B1,B2,B3(z,:),sol(:,:,:,1));
y1a = y0 + transf(B1,B2,B3(z,:),sol(:,:,:,2));
z1a = z0(z) + transf(B1,B2,B3(z,:),sol(:,:,:,3));
x1 = M(1,1)*x1a + M(1,2)*y1a + M(1,3)*z1a + M(1,4);
y1 = M(2,1)*x1a + M(2,2)*y1a + M(2,3)*z1a + M(2,4);
z1 = M(3,1)*x1a + M(3,2)*y1a + M(3,3)*z1a + M(3,4);
return;
%=======================================================================
%=======================================================================
function t = transf(B1,B2,B3,T)
if ~isempty(T)
d2 = [size(T) 1];
t1 = reshape(reshape(T, d2(1)*d2(2),d2(3))*B3', d2(1), d2(2));
t = B1*t1*B2';
else
t = zeros(size(B1,1),size(B2,1),size(B3,1));
end;
return;
%=======================================================================
%=======================================================================
function dat = decimate(dat,fwhm)
% Convolve the volume in memory (fwhm in voxels).
lim = ceil(2*fwhm);
x = -lim(1):lim(1); x = spm_smoothkern(fwhm(1),x); x = x/sum(x);
y = -lim(2):lim(2); y = spm_smoothkern(fwhm(2),y); y = y/sum(y);
z = -lim(3):lim(3); z = spm_smoothkern(fwhm(3),z); z = z/sum(z);
i = (length(x) - 1)/2;
j = (length(y) - 1)/2;
k = (length(z) - 1)/2;
spm_conv_vol(dat,dat,x,y,z,-[i j k]);
return;
%=======================================================================
%=======================================================================
function [g,w,c] = clean_gwc(g,w,c, level)
if nargin<4, level = 1; end;
b = w;
b(1) = w(1);
% Build a 3x3x3 seperable smoothing kernel
%-----------------------------------------------------------------------
kx=[0.75 1 0.75];
ky=[0.75 1 0.75];
kz=[0.75 1 0.75];
sm=sum(kron(kron(kz,ky),kx))^(1/3);
kx=kx/sm; ky=ky/sm; kz=kz/sm;
th1 = 0.15;
if level==2, th1 = 0.2; end;
% Erosions and conditional dilations
%-----------------------------------------------------------------------
niter = 32;
spm_progress_bar('Init',niter,'Extracting Brain','Iterations completed');
for j=1:niter,
if j>2, th=th1; else th=0.6; end; % Dilate after two its of erosion.
for i=1:size(b,3),
gp = double(g(:,:,i));
wp = double(w(:,:,i));
bp = double(b(:,:,i))/255;
bp = (bp>th).*(wp+gp);
b(:,:,i) = uint8(round(bp));
end;
spm_conv_vol(b,b,kx,ky,kz,-[1 1 1]);
spm_progress_bar('Set',j);
end;
th = 0.05;
for i=1:size(b,3),
gp = double(g(:,:,i))/255;
wp = double(w(:,:,i))/255;
cp = double(c(:,:,i))/255;
bp = double(b(:,:,i))/255;
bp = ((bp>th).*(wp+gp))>th;
g(:,:,i) = uint8(round(255*gp.*bp./(gp+wp+cp+eps)));
w(:,:,i) = uint8(round(255*wp.*bp./(gp+wp+cp+eps)));
c(:,:,i) = uint8(round(255*(cp.*bp./(gp+wp+cp+eps)+cp.*(1-bp))));
end;
spm_progress_bar('Clear');
return;
%=======================================================================
%=======================================================================
|
github
|
philippboehmsturm/antx-master
|
moh_config_ALI.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/ALI/moh_config_ALI.m
| 18,900 |
utf_8
|
b23f41a3961164c0d0deb0b12c729b63
|
function job = moh_config_ALI
% Configuration file for the Automatic Lesion Identification (ALI)
%_______________________________________________________________________
% Copyright (C) 2009 Wellcome Trust Centre for Neuroimaging
%
% Mohamed Seghier, 28.05.2009
% =========================
entry = inline(['struct(''type'',''entry'',''name'',name,'...
'''tag'',tag,''strtype'',strtype,''num'',num)'],...
'name','tag','strtype','num');
files = inline(['struct(''type'',''files'',''name'',name,'...
'''tag'',tag,''filter'',fltr,''num'',num)'],...
'name','tag','fltr','num');
mnu = inline(['struct(''type'',''menu'',''name'',name,'...
'''tag'',tag,''labels'',{labels},''values'',{values})'],...
'name','tag','labels','values');
branch = inline(['struct(''type'',''branch'',''name'',name,'...
'''tag'',tag,''val'',{val})'],...
'name','tag','val');
repeat = inline(['struct(''type'',''repeat'',''name'',name,''tag'',tag,'...
'''values'',{values})'],'name','tag','values');
choice = inline(['struct(''type'',''choice'',''name'',name,''tag'',tag,'...
'''values'',{values})'],'name','tag','values');
%______________________________________________________________________
%______________________________________________________________________
addpath(fullfile(spm('dir'),'toolbox','ALI'));
% -------------------------------------------------------------------------
% configuation for STEP 1: iterative unified segmentation-normalisation
% -------------------------------------------------------------------------
step1data.type = 'files';
step1data.tag = 'step1data';
step1data.name = 'Images to segment';
step1data.filter = 'image';
step1data.ufilter = '.*';
step1data.num = [0 Inf];
step1data.help = {[...
'Specify the input images for the unified segmentation. ',...
'This should be your anatomical/structural images (e.g. T1 images)',...
' of all your patients...']};
prior_filename = fullfile(spm('Dir'), 'toolbox',...
'ALI', 'Priors_extraClass', 'wc4prior0.img') ;
step1prior.type = 'files';
step1prior.tag = 'step1prior';
step1prior.name = 'Prior EXTRA class';
step1prior.filter = 'image';
step1prior.ufilter = '.*';
step1prior.num = [1 1];
step1prior.val{1} = {prior_filename};
step1prior.help = {[...
'Select the prior (1st guess) for the EXTRA class. ',...
'This prior will be combined with (by default) GM, WM, and CSF priors ',...
' for the iterative unified segmentation routine. In the absence of any ',...
' hypothesis, this prior is empirically set to 05*(CSF + WM). In the ',...
' presence of abnormality, this prior will be updated at every iteration ',...
' of the segmentation procedure so it will then approximate the location ',...
' of the lesion for next segmentation runs. However, users can modify the ',...
' definition of the prior of the EXTRA class (used at iteration 1 as a ',...
' first guess) and include more constrained spatial priors. For instance, ',...
' this prior can be limited to left hemisphere only if all lesions are ',...
' located in the LH...etc. ']};
step1niti.type = 'entry';
step1niti.name = 'Number of iterations';
step1niti.tag = 'step1niti';
step1niti.strtype = 'r';
step1niti.num = [1 1];
step1niti.val = {2};
step1niti.help = {[...
'Specify the number of iterations for the new iterative unified ',...
' segmentation-normalisation procedure. This number will define the number',...
' of segmentation runs. The updated EXTRA class of run (n-1) will be used ',...
' as prior for the EXTRA class of run (n).']};
step1thr_prob.type = 'entry';
step1thr_prob.name = 'Threshold probability';
step1thr_prob.tag = 'step1thr_prob';
step1thr_prob.strtype = 'r';
step1thr_prob.num = [1 1];
step1thr_prob.val = {1/3};
step1thr_prob.help = {[...
'Specify the thershold for the probability of the EXTRA class: ', ...
' at each iteration, the EXTRA class will be cleaned up before ',...
' used as a prior for the next segmentation run. This step will ',...
' help to limit the serach for abnormality for only voxels with ',...
' high probability in the EXTRA class (i.e. voxels with high prob ',...
' are those that cannot be fully explained by the expected GM, WM, ',...
' and CSF classes.']};
step1thr_size.type = 'entry';
step1thr_size.name = 'Threshold size';
step1thr_size.tag = 'step1thr_size';
step1thr_size.strtype = 'r';
step1thr_size.num = [1 1];
step1thr_size.val = {100};
step1thr_size.help = {[...
'Specify the thershold for the size (nb voxels) of the EXTRA class: ', ...
' at each iteration, the EXTRA class will be cleaned up. Only abnornal ',...
' regions with a relatively big size (> thershold) will considered for ',...
' the definition of the prior for the EXTRA class.']};
step1coregister.type = 'menu';
step1coregister.tag = 'step1coregister';
step1coregister.name = 'Coregister to MNI space';
step1coregister.labels = {'YES', 'NO'} ;
step1coregister.values = {1 0} ;
step1coregister.val = {1} ;
step1coregister.help = {['you can coregister your anatomical images ',...
'to MNI space (e.g. target=T1_template). This would help the ', ...
'accuracy of the segmentation algorithm (e.g. avoid having input ',...
' images with abherant centres/locations).']};
unified_segmentation.type = 'branch';
unified_segmentation.tag = 'unified_segmentation';
unified_segmentation.name = 'Unified segmentation';
unified_segmentation.val = {step1data step1prior step1niti ...
step1thr_prob step1thr_size step1coregister};
unified_segmentation.help = {...
'STEP 1: segment in 4 classes all structural T1 images.'};
unified_segmentation.prog = @segment_unified ;
% -------------------------------------------------------------------------
% configuation for STEP 2: spatial smoothing of segmented GM/WM classes
% -------------------------------------------------------------------------
step2data.type = 'files';
step2data.tag = 'step2data';
step2data.name = 'Images to smooth';
step2data.filter = 'image';
step2data.ufilter = '.*';
step2data.num = [0 Inf];
step2data.help = {[...
'Select your segmented GM and WM images: ',...
' all images will be spatially smoothed. Both patients and controls images',...
' can be selected.']};
step2fwhm.type = 'entry';
step2fwhm.name = 'FWHM';
step2fwhm.tag = 'step2fwhm';
step2fwhm.strtype = 'e';
step2fwhm.num = [1 3];
step2fwhm.val = {[8 8 8]};
step2fwhm.help = {[...
'Specify the full-width at half maximum (FWHM) of the Gaussian smoothing ',...
'kernel [in mm]: three values denoting the FWHM in the ',...
'x, y and z directions.']};
spatial_smoothing.type = 'branch';
spatial_smoothing.tag = 'spatial_smoothing';
spatial_smoothing.name = 'Spatial smoothing';
spatial_smoothing.val = {step2data step2fwhm};
spatial_smoothing.help = {...
'STEP 2: spatial smoothing of segmented gray and white matter images.'};
spatial_smoothing.prog = @smooth_spatial ;
% -------------------------------------------------------------------------
% configuation for STEP 3: outliers detection (detection of abnormality)
% -------------------------------------------------------------------------
step3directory.type = 'files';
step3directory.tag = 'step3directory';
step3directory.name = 'Select a directory';
step3directory.help = {'Select a directory where to save the results.'};
step3directory.filter = 'dir';
step3directory.num = 1;
step3patientGM.type = 'files';
step3patientGM.tag = 'step3patientGM';
step3patientGM.name = 'Patients: sGM images';
step3patientGM.filter = 'image';
step3patientGM.ufilter = '.*';
step3patientGM.num = [0 Inf];
step3patientGM.help = {[...
'Specify the smoothed gray matter (GM) images of your patients. ',...
'These images will then be compared, voxel by voxel, to the smoothed ',...
'gray matter (GM) images of all your controls. Any voxel in the patient GM ',...
'that deviates from the normal range will be considered as an outlier, and ',...
'thus included in the lesion. By definition, lesion = set of ',...
'abnornal/outlier voxels.']};
step3patientWM.type = 'files';
step3patientWM.tag = 'step3patientWM';
step3patientWM.name = 'Patients: sWM images';
step3patientWM.filter = 'image';
step3patientWM.ufilter = '.*';
step3patientWM.num = [0 Inf];
step3patientWM.help = {[...
'Specify the smoothed white matter (WM) images of your patients. ',...
'These images will then be compared, voxel by voxel, to the smoothed ',...
'white matter (WM) images of all your controls. Any voxel in the patient WM ',...
'that deviates from the normal range will be considered as an outlier, and ',...
'thus included in the lesion. By definition, lesion = set of ',...
'abnornal/outlier voxels.']};
step3controlGM.type = 'files';
step3controlGM.tag = 'step3controlGM';
step3controlGM.name = 'Controls: sGM images';
step3controlGM.filter = 'image';
step3controlGM.ufilter = '.*';
step3controlGM.num = [0 Inf];
step3controlGM.help = {[...
'Specify the smoothed gray matter (GM) images of your controls. ',...
'These images are used to assess the dergee of "normality" at each voxel ',...
'(e.g. what is the "normal" variability of the healthy tissue?)... ']};
step3controlWM.type = 'files';
step3controlWM.tag = 'step3controlWM';
step3controlWM.name = 'Controls: sWM images';
step3controlWM.filter = 'image';
step3controlWM.ufilter = '.*';
step3controlWM.num = [0 Inf];
step3controlWM.help = {[...
'Specify the smoothed white matter (WM) images of your controls. ',...
'These images are used to assess the dergee of "normality" at each voxel ',...
'(e.g. what is the "normal" variability of the healthy tissue?)... ']};
mask_filename = fullfile(spm('Dir'), 'toolbox',...
'ALI', 'Mask_image', 'mask_controls.img') ;
step3mask.type = 'files';
step3mask.tag = 'step3mask';
step3mask.name = 'Mask (regions of interest)';
step3mask.filter = 'image';
step3mask.ufilter = '.*';
step3mask.num = [1 1];
step3mask.val{1} = {mask_filename};
step3mask.help = {[...
'Select the image mask for your lesion detection analysis: ',...
'the mask can be any image and it is used to limit the lesion detection ',...
'within a the meaningful voxels (e.g. in-brain voxels). By default, ',...
'the mask = whole brain (no assumption about the expected locations).']};
step3mask_thr.type = 'entry';
step3mask_thr.name = 'Threshold for the mask';
step3mask_thr.tag = 'step3mask_thr';
step3mask_thr.strtype = 'r';
step3mask_thr.num = [1 1];
step3mask_thr.val = {0};
step3mask_thr.help = {[...
'Specify the threshold: all voxels of the mask image that have a signal ', ...
'less than the threshold are excluded from the lesion detection.']};
step3Lambda.type = 'entry';
step3Lambda.name = 'Lambda parameter';
step3Lambda.tag = 'step3Lambda';
step3Lambda.strtype = 'r';
step3Lambda.num = [1 1];
step3Lambda.val = {-4};
step3Lambda.help = {[...
'Specify the value of Lambda: equivalent to the fuzziness index "m" in ',...
'standard FCM algorithm (m=1-2/Lambda). By default, Lambda = -4.']};
step3Alpha.type = 'entry';
step3Alpha.name = 'Alpha parameter';
step3Alpha.tag = 'step3Alpha';
step3Alpha.strtype = 'r';
step3Alpha.num = [1 1];
step3Alpha.val = {0.5};
step3Alpha.help = {[...
'Specify the value of Alpha: this is the factor of sensitivity ',...
'(tunning factor), equal here to 0.5 (half the probability interval). ']};
outliers_detection.type = 'branch';
outliers_detection.tag = 'outliers_detection';
outliers_detection.name = 'Abnormality detection (FCP)';
outliers_detection.val = {step3directory step3patientGM step3patientWM ...
step3controlGM step3controlWM step3mask ...
step3mask_thr step3Lambda step3Alpha};
outliers_detection.help = {[...
'STEP 3: outliers detection (lesion = abnormal/outliers voxels) ',...
'from both GM and WM classes (using FCP algorithm). ']};
outliers_detection.prog = @detect_outliers;
% -------------------------------------------------------------------------
% configuation for STEP 4: lesion definition (fuzzy, binary and contour)
% -------------------------------------------------------------------------
step4directory.type = 'files';
step4directory.tag = 'step4directory';
step4directory.name = 'Select a directory';
step4directory.help = {'Select a directory where to save the results'};
step4directory.filter = 'dir';
step4directory.num = 1;
step4fcpGM.type = 'files';
step4fcpGM.tag = 'step4fcpGM';
step4fcpGM.name = 'Negative FCP_GM images';
step4fcpGM.filter = 'image';
step4fcpGM.ufilter = '.*';
step4fcpGM.num = [0 Inf];
step4fcpGM.help = {[...
'Select the FCP_negative of the gray matter images of your patients: ',...
'these images represent where the GM of a given patient is abnormally ',...
'low compared to GM of the controls. These images are those computed ',...
'in the previous step.']};
step4fcpWM.type = 'files';
step4fcpWM.tag = 'step4fcpWM';
step4fcpWM.name = 'Negative FCP_WM images';
step4fcpWM.filter = 'image';
step4fcpWM.ufilter = '.*';
step4fcpWM.num = [0 Inf];
step4fcpWM.help = {[...
'Select the FCP_negative of the white matter images of your patients. ',...
'SELECTED IN THE SAME ORDER AS THOSE OF THE GM IMAGES...!!!! ',...
'These images represent where the WM of a given patient is abnormally ',...
'low compared to WM of the controls. These images are those computed ',...
'in the previous step.']};
step4binary_thr.type = 'entry';
step4binary_thr.name = 'Binary lesion: threshold U';
step4binary_thr.tag = 'step4binary_thr';
step4binary_thr.strtype = 'r';
step4binary_thr.num = [1 1];
step4binary_thr.val = {0.3};
step4binary_thr.help = {[...
'Specify the threshold: all voxels with a degree of abonormality (U) ',...
'bigger than the thereshold will be considered as a lesion. Useful for',...
' the generation of the binary/contour definition of the lesion.']};
step4binary_size.type = 'entry';
step4binary_size.name = 'Binary lesion: minimum size';
step4binary_size.tag = 'step4binary_size';
step4binary_size.strtype = 'r';
step4binary_size.num = [1 1];
step4binary_size.val = {100};
step4binary_size.help = {[...
'Specify the minimum size (nb vox): all abnormal clusters with less than the ',...
'threshold size will be excluded (e.g. tiny/small clusters) will be ',...
'removed for the lesion volume.']};
lesion_definition.type = 'branch';
lesion_definition.tag = 'lesion_definition';
lesion_definition.name = 'Lesion definition (grouping)';
lesion_definition.val = {step4directory step4fcpGM step4fcpWM ...
step4binary_thr step4binary_size};
lesion_definition.help = {[...
'STEP 4: group abnormal (GM and WM) images as a lesion ',...
' (three images generated: fuzzy, binary and contour).']};
lesion_definition.prog = @define_lesion;
% -------------------------------------------------------------------------
% generate lesion overlap maps (LOM): useful for group analysis
% -------------------------------------------------------------------------
step5directory.type = 'files';
step5directory.tag = 'step5directory';
step5directory.name = 'Select a directory';
step5directory.help = {'Select a directory where to save the results'};
step5directory.filter = 'dir';
step5directory.num = 1;
step5LOM.type = 'files';
step5LOM.tag = 'step5LOM';
step5LOM.name = 'Select Binary (lesion) images';
step5LOM.filter = 'image';
step5LOM.ufilter = '.*';
step5LOM.num = [0 Inf];
step5LOM.help = {[...
'Select the binary definition of the lesions of all your patients. ',...
'These binary images are those created in the previous step.']};
lesion_overlap.type = 'branch';
lesion_overlap.tag = 'lesion_overlap';
lesion_overlap.name = 'Lesion Overlap Map (LOM)';
lesion_overlap.val = {step5directory step5LOM};
lesion_overlap.help = {...
'STEP 5: generate lesion overlap maps (LOM): overlap over patients.'};
lesion_overlap.prog = @generate_LOM;
% -------------------------------------------------------------------------
% explore the LOM maps: useful for group analysis
% -------------------------------------------------------------------------
step6LOM_file.type = 'files';
step6LOM_file.tag = 'step6LOM_file';
step6LOM_file.name = 'LOM file';
step6LOM_file.filter = 'mat';
step6LOM_file.ufilter = '.*';
step6LOM_file.num = [1 1];
step6LOM_file.help = {[...
'Select the LOM*.mat that contains all the details of the generated ',...
'lesion overalp map (LOM) from the previous step. The LOM images will ',...
'refelct how many patients do have a lesion at a particular location.']};
step6thr_nb.type = 'entry';
step6thr_nb.name = 'LOM threshold';
step6thr_nb.tag = 'step6thr_nb';
step6thr_nb.strtype = 'e';
step6thr_nb.num = [1 1];
step6thr_nb.val = {1};
step6thr_nb.help = {...
'Specify the threshold of the LOM: minimum overlap to be displayed. '};
lesion_overlap_explore.type = 'branch';
lesion_overlap_explore.tag = 'lesion_overlap_explore';
lesion_overlap_explore.name = 'Explore the LOM';
lesion_overlap_explore.val = {step6LOM_file step6thr_nb};
lesion_overlap_explore.help = {...
'STEP 6: explore the generated lesion overlap maps (LOM).'};
lesion_overlap_explore.prog = @explore_LOM;
%--------------------------------------------------------------------------
% Define ALI job
%--------------------------------------------------------------------------
job.type = 'choice';
job.name = 'ALI';
job.tag = 'ali';
job.values = {unified_segmentation,spatial_smoothing,outliers_detection,...
lesion_definition,lesion_overlap,lesion_overlap_explore};
job.help = {'Automatic Lesion Identification (ALI)'};
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function segment_unified(job)
moh_run_ALI(job);
%------------------------------------------------------------------------
function smooth_spatial(job)
moh_run_ALI(job);
%------------------------------------------------------------------------
function detect_outliers(job)
moh_run_ALI(job);
%------------------------------------------------------------------------
function define_lesion(job)
moh_run_ALI(job);
%------------------------------------------------------------------------
function generate_LOM(job)
moh_run_ALI(job);
%------------------------------------------------------------------------
function explore_LOM(job)
moh_run_ALI(job);
|
github
|
philippboehmsturm/antx-master
|
tbx_fbi_bruker2nifti.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/FBIBruker/tbx_fbi_bruker2nifti.m
| 6,253 |
utf_8
|
448d1d0132da5c52633a2902758bfc18
|
function varargout = tbx_fbi_bruker2nifti(cmd, varargin)
% Convert bruker 2dseq files to NIfTI. The calling
% syntax is
% varargout = tbx_fbi_bruker2nifti(cmd, varargin)
% where cmd is one of
% 'run' - out = tbx_fbi_bruker2nifti('run', job)
% Convert data.
% 'vout' - dep = tbx_fbi_bruker2nifti('vout', job)
% Return virtual output objects. For each 2dseq file, a
% separate output will be created. This output will contain
% the list of NIfTI files converted from the 2dseq file.
% 'check' - str = tbx_fbi_bruker2nifti('check', subcmd, subjob)
% 'defaults' - defval = tbx_fbi_bruker2nifti('defaults', key)
% not implemented
%
% This code is part of a toolbox for SPM. It requires bruker read routines
% and mrstruct read/write routines from MedPhys.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging
% Volkmar Glauche
% $Id: tbx_fbi_bruker2nifti.m 1 2011-01-19 13:04:16Z volkmar $
rev = '$Rev: 1 $'; %#ok
if ischar(cmd)
switch lower(cmd)
case 'run'
job = local_getjob(varargin{1});
out.images = cell(size(job.infiles));
% do computation, return results in variable out
for ci = 1:numel(job.infiles)
dirStr = fileparts(job.infiles{ci});
dirStr = sprintf('%s%s', dirStr, filesep); % read_*_bruker assumes filesep at end of dirStr
% read bruker data into mrstruct - see bruker_read_model
% 255ff
try
infoStruct = read_info_bruker(dirStr);
catch
error('tbx_fbi_bruker2nifti:read_info_bruker',...
'Could not read header information for file ''%s''.',job.infiles{ci});
end
if isempty(infoStruct)
error('tbx_fbi_bruker2nifti:read_info_bruker',...
'Could not read header information for file ''%s''.',job.infiles{ci});
end
[mrStruct, errStr] = read_bruker(dirStr, infoStruct.byte_order);
if ~isempty(errStr)
error('tbx_fbi_bruker2nifti:read_bruker', 'File ''%s'': error ''%s''.', job.infiles{ci}, errStr);
end
if isempty(mrStruct)
error('tbx_fbi_bruker2nifti:read_bruker',...
'No data found in file ''%s''.',job.infiles{ci});
end
switch char(fieldnames(job.createsubdir))
case 'useoutdir'
outdir = job.outdir{1};
case 'usefilepath'
% assume [<subject>]/<seq#>/pdata/<seq1#>/2dseq path
str = textscan(job.infiles{ci},'%s','delimiter',filesep);
if numel(str{1}) >= 5
outdir = fullfile(job.outdir{1}, sprintf('%s_%s_%s', str{1}{end-4}, str{1}{end-3}, str{1}{end-1}));
else
outdir = fullfile(job.outdir{1}, sprintf('%s_%s', str{1}{end-3}, str{1}{end-1}));
end
case 'newsubdir'
outdir = fullfile(job.outdir{1}, sprintf('%s%0*d', job.createsubdir.newsubdir, floor(log10(numel(job.infiles)))+1, ci));
end
if ~exist(outdir,'dir')
mkdir(outdir);
end
[imgs errstr] = mrstruct_to_nifti(mrStruct, fullfile(outdir,'image.nii'), job.dt);
if ~isempty(errstr)
error('tbx_fbi_bruker2nifti:mrstruct_to_nifti',errstr);
end
imgs = [imgs{:}];
out.images{ci} = {imgs.fname}';
end
if nargout > 0
varargout{1} = out;
end
case 'vout'
job = local_getjob(varargin{1});
% initialise empty cfg_dep array
dep = repmat(cfg_dep,size(job.infiles));
% determine outputs, return cfg_dep array in variable dep
for ci = 1:numel(job.infiles)
dep(ci).sname = sprintf('Converted Images - Source File %d', ci);
dep(ci).src_output = substruct('.','images','{}',{ci});
dep(ci).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
end
varargout{1} = dep;
case 'check'
if ischar(varargin{1})
subcmd = lower(varargin{1});
subjob = varargin{2};
str = '';
switch subcmd
% implement checks, return status string in variable str
otherwise
cfg_message('unknown:check', ...
'Unknown check subcmd ''%s''.', subcmd);
end
varargout{1} = str;
else
cfg_message('ischar:check', 'Subcmd must be a string.');
end
case 'defaults'
if nargin == 2
varargout{1} = local_defs(varargin{1});
else
local_defs(varargin{1:2});
end
otherwise
cfg_message('unknown:cmd', 'Unknown command ''%s''.', cmd);
end
else
cfg_message('ischar:cmd', 'Cmd must be a string.');
end
function varargout = local_defs(defstr, defval)
persistent defs;
if isempty(defs)
% initialise defaults
end
if ischar(defstr)
% construct subscript reference struct from dot delimited tag string
tags = textscan(defstr,'%s', 'delimiter','.');
subs = struct('type','.','subs',tags{1}');
try
cdefval = subsref(defs, subs);
catch
cdefval = [];
cfg_message('defaults:noval', ...
'No matching defaults value ''%s'' found.', defstr);
end
if nargin == 1
varargout{1} = cdefval;
else
defs = subsasgn(defs, subs, defval);
end
else
cfg_message('ischar:defstr', 'Defaults key must be a string.');
end
function job = local_getjob(job)
if ~isstruct(job)
cfg_message('isstruct:job', 'Job must be a struct.');
end
|
github
|
philippboehmsturm/antx-master
|
vgtbx_config_Volumes.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/Volumes/vgtbx_config_Volumes.m
| 45,782 |
utf_8
|
2f279a3167e39ed2d3d812e69e9093c5
|
function opt = vgtbx_config_Volumes
% Volumes toolbox
%_______________________________________________________________________
%
% This toolbox contains various helper functions to make image
% manipulation within SPM5 more convenient. Help on each individual item
% can be obtained by selecting the corresponding entry in the help menu.
%
% This toolbox is free but copyright software, distributed under the
% terms of the GNU General Public Licence as published by the Free
% Software Foundation (either version 2, as given in file
% spm_LICENCE.man, or at your option, any later version). Further details
% on "copyleft" can be found at http://www.gnu.org/copyleft/.
% The toolbox consists of the files listed in its Contents.m file.
%
% The source code of this toolbox is available at
%
% http://sourceforge.net/projects/spmtools
%
% Please use the SourceForge forum and tracker system for comments,
% suggestions, bug reports etc. regarding this toolbox.
%_______________________________________________________________________
%
% @(#) $Id: vgtbx_config_Volumes.m 539 2007-12-06 17:31:12Z glauche $
% This is the main config file for the SPM5 job management system. It
% resides in fullfile(spm('dir'),'toolbox','Volumes').
rev='$Revision: 539 $';
addpath(fullfile(spm('dir'),'toolbox','Volumes'));
% see how we are called - if no output argument, then start spm_jobman UI
if nargout == 0
spm_jobman('interactive','','jobs.tools.vgtbx_Volumes');
return;
end;
%-Some input elements common to many functions
%=======================================================================
interp.type = 'menu';
interp.name = 'Interpolation';
interp.tag = 'interp';
interp.labels = {'Nearest neighbour','Trilinear','2nd Degree b-Spline',...
'3rd Degree b-Spline','4th Degree b-Spline','5th Degree b-Spline',...
'6th Degree b-Spline','7th Degree b-Spline','2nd Degree Sinc',...
'3rd Degree Sinc','4th Degree Sinc','5th Degree Sinc',...
'6th Degree Sinc','7th Degree Sinc'};
interp.values = {0,1,2,3,4,5,6,7,-2,-3,-4,-5,-6,-7};
interp.def = 'tools.vgtbx_Volumes.interp';
overwrite.type = 'menu';
overwrite.name = 'Overwrite existing Input/Output Files';
overwrite.tag = 'overwrite';
overwrite.labels = {'Yes', 'No'};
overwrite.values = {1, 0};
overwrite.def = 'tools.vgtbx_Volumes.overwrite';
graphics.type = 'menu';
graphics.name = 'Graphics output';
graphics.tag = 'graphics';
graphics.labels = {'Yes', 'No'};
graphics.values = {1, 0};
graphics.def = 'tools.vgtbx_Volumes.graphics';
%-input and output files
%-----------------------------------------------------------------------
swd.type = 'files';
swd.name = 'Output directory';
swd.tag = 'swd';
swd.filter = 'dir';
swd.num = [1 1];
swd.help = {['Files produced by this function will be written into this ' ...
'output directory']};
srcimgs.type = 'files';
srcimgs.name = 'Source Images';
srcimgs.tag = 'srcimgs';
srcimgs.filter = 'image';
srcimgs.num = [1 Inf];
srcimg.type = 'files';
srcimg.name = 'Source Image';
srcimg.tag = 'srcimg';
srcimg.filter = 'image';
srcimg.num = [1 1];
fname.type = 'entry';
fname.name = 'Output Filename';
fname.tag = 'fname';
fname.strtype = 's';
fname.num = [1 Inf];
fname.val = {'output.img'};
fname.help = {[...
'The output image is written to the selected working directory.']};
outimg.type = 'branch';
outimg.name = 'Output File & Directory';
outimg.tag = 'outimg';
outimg.val = {swd, fname};
outimg.help = {[...
'Specify a output filename and target directory.']};
prefix.type = 'entry';
prefix.name = 'Output Filename Prefix';
prefix.tag = 'prefix';
prefix.strtype = 's';
prefix.num = [1 Inf];
prefix.help = {['The output filename is constructed by prefixing the original filename ' ...
'with this prefix.']};
srcspm.type = 'files';
srcspm.name = 'Source SPM.mat';
srcspm.tag = 'srcspm';
srcspm.filter = 'mat';
srcspm.ufilter = '.*SPM.*\.mat';
srcspm.num = [1 1];
dtype.type = 'menu';
dtype.name = 'Data Type';
dtype.tag = 'dtype';
dtype.labels = {'SAME','UINT8 - unsigned char','INT16 - signed short','INT32 - signed int',...
'FLOAT - single prec. float','DOUBLE - double prec. float'};
dtype.values = {0,spm_type('uint8'),spm_type('int16'),spm_type('int32'),...
spm_type('float32'),spm_type('float64')};
dtype.val = {0};
dtype.help = {'Data-type of output images. SAME indicates the same datatype as the original images.'};
%-Stats tools sub-menu
%=======================================================================
addpath(fullfile(spm('dir'),'toolbox','Volumes','Stats_Tools'));
%-tbxvol_changeSPM
%-----------------------------------------------------------------------
oldpath.type = 'menu';
oldpath.name = 'Path Component to be replaced';
oldpath.tag = 'oldpath';
oldpath.labels = {'Determine and replace', 'Ask before replacing'};
oldpath.values = {'auto','ask'};
oldpath.help = {['The tool tries to guess which parts of the path names ' ...
'need to be replaced by comparing the path stored in ' ...
'SPM.swd with the current path to the SPM.mat file. '], ...
['This does not always work as expected, confirmation ' ...
'before replacement is strongly advised.']};
newpath.type = 'menu';
newpath.name = 'Path Component to be inserted';
newpath.tag = 'newpath';
newpath.labels = {'Determine and insert', 'Ask before inserting'};
newpath.values = {'auto','ask'};
newpath.help = {['The tool tries to quess which parts of the path names ' ...
'need to be replaced by comparing the path stored in ' ...
'SPM.swd with the current path to the SPM.mat file. '], ...
['This does not always work as expected, confirmation ' ...
'before replacement is strongly advised.']};
dpaths.type = 'branch';
dpaths.name = 'Data Files';
dpaths.tag = 'dpaths';
dpaths.val = {newpath,oldpath};
apaths.type = 'branch';
apaths.name = 'Analysis Files';
apaths.tag = 'apaths';
apaths.val = {newpath,oldpath};
bpaths.type = 'branch';
bpaths.name = 'Data&Analysis Files';
bpaths.tag = 'bpaths';
bpaths.val = {newpath,oldpath};
npaths.type = 'const';
npaths.name = 'None';
npaths.tag = 'npaths';
npaths.val = {0};
chpaths.type = 'choice';
chpaths.name = 'Paths to change';
chpaths.tag = 'chpaths';
chpaths.values ={dpaths, apaths, bpaths, npaths};
swap.type = 'menu';
swap.name = 'Change Byte Order Information for Mapped Images?';
swap.tag = 'swap';
swap.labels = {'Yes', 'No'};
swap.values ={1, 0};
swap.help = {['This option may be obsolete for SPM5. With SPM2-style ' ...
'analyses, byte order of an image was stored at the time ' ...
'statistics were run. If one later moved the SPM.mat and ' ...
'analysis files to a machine with different byte order, this ' ...
'was not realised by SPM.']};
changeSPM.type = 'branch';
changeSPM.name = 'Change SPM.mat Image Information';
changeSPM.tag = 'tbxvol_changeSPM';
changeSPM.prog = @tbxvol_changeSPM;
changeSPM.val = {srcspm, chpaths, swap};
changeSPM.help = vgtbx_help2cell('tbxvol_changeSPM');
%-Correct error covariance components
%-----------------------------------------------------------------------
nfactor.type = 'menu';
nfactor.name = '# of Factor with unequal Variance';
nfactor.tag = 'nfactor';
nfactor.labels = {'Factor 1','Factor 2','Factor 3'};
nfactor.values = {2,3,4};
correct_ec_SPM.type = 'branch';
correct_ec_SPM.name = 'Correct Error Covariance components';
correct_ec_SPM.tag = 'tbxvol_correct_ec_SPM';
correct_ec_SPM.prog = @tbxvol_correct_ec_SPM;
correct_ec_SPM.val = {srcspm nfactor};
correct_ec_SPM.help = vgtbx_help2cell('tbxvol_correct_ec_SPM');
%-Transform t maps
%-----------------------------------------------------------------------
option.type = 'menu';
option.name = 'Select output map';
option.tag = 'option';
option.labels = {'1-p', '-log(1-p)', ...
'correlation coefficient cc', 'effect size d'};
option.values = {1,2,3,4};
transform_t2x.type = 'branch';
transform_t2x.name = 'Transform t maps';
transform_t2x.tag = 'tbxvol_transform_t2x';
transform_t2x.prog = @tbxvol_transform_t2x;
transform_t2x.vfiles = @vfiles_tbxvol_transform_t2x;
transform_t2x.val = {srcimgs option};
transform_t2x.help = vgtbx_help2cell('tbxvol_transform_t2x');
%-Compute laterality index
%-----------------------------------------------------------------------
prefix.val = {'li_'};
laterality.type = 'branch';
laterality.name = 'Compute Laterality index';
laterality.tag = 'tbxvol_laterality';
laterality.prog = @tbxvol_laterality;
laterality.vfiles = @vfiles_tbxvol_laterality;
laterality.val = {srcimgs interp dtype prefix};
laterality.help = vgtbx_help2cell('tbxvol_laterality');
%-Analyse ResMS image and compute SNR for regions with different quality
% of fit
%-----------------------------------------------------------------------
optsrcimg = srcimg;
optsrcimg.num = [0 1];
optsrcimg.name = 'Brain mask image (optional)';
optsrcimg.tag = 'maskimg';
optsrcimg.val = {''};
dist.type = 'entry';
dist.name = 'Distance from mean';
dist.tag = 'dist';
dist.strtype = 'e';
dist.num = [1 1];
dist.def = 'tools.vgtbx_Volumes.analyse_resms.dist';
analyse_resms.type = 'branch';
analyse_resms.name = 'Analyse goodness of fit';
analyse_resms.tag = 'tbxvol_analyse_resms';
analyse_resms.prog = @tbxvol_analyse_resms;
analyse_resms.vfiles = @vfiles_tbxvol_analyse_resms;
analyse_resms.val = {srcspm optsrcimg dist graphics};
analyse_resms.help = vgtbx_help2cell('tbxvol_analyse_resms');
% Histogramm summary
%-----------------------------------------------------------------------
maskimgs = srcimgs;
maskimgs.name = 'Mask image(s)';
maskimgs.tag = 'maskimgs';
subject.type = 'branch';
subject.name = 'Subject';
subject.tag = 'subjects';
subject.val = {srcimgs, maskimgs};
subjects.type = 'repeat';
subjects.name = 'Subjects';
subjects.tag = 'subjects';
subjects.num = [1 Inf];
subjects.values = {subject};
bins.type = 'entry';
bins.name = 'Edges of histogramm bins';
bins.tag = 'bins';
bins.strtype = 'e';
bins.num = [1 Inf];
bins.help = {['Enter the edges of histogramm bins. See ''help histc'' '...
'for details.']};
hist_summary.type = 'branch';
hist_summary.name = 'Histogramm summary';
hist_summary.tag = 'tbxvol_hist_summary';
hist_summary.prog = @tbxvol_hist_summary;
hist_summary.val = {subjects bins};
hist_summary.help = vgtbx_help2cell('tbxvol_hist_summary');
%-assemble choice for Stats Tools
%-----------------------------------------------------------------------
Stats_Tools.type = 'choice';
Stats_Tools.name = 'Stats Tools';
Stats_Tools.tag = 'Stats_Tools';
Stats_Tools.values = {changeSPM correct_ec_SPM transform_t2x laterality ...
analyse_resms hist_summary};
%-Multiple Volumes sub-menu
%=======================================================================
addpath(fullfile(spm('dir'),'toolbox','Volumes','Multiple_Volumes'));
% Taken from spm_config_norm
%_______________________________________________________________________
smosrc.type = 'entry';
smosrc.name = 'Source Image Smoothing';
smosrc.tag = 'smosrc';
smosrc.strtype = 'e';
smosrc.num = [1 1];
smosrc.def = 'normalise.estimate.smosrc';
smosrc.help = {[...
'Smoothing to apply to a copy of the source image. ',...
'The template and source images should have approximately ',...
'the same smoothness. Remember that the templates supplied ',...
'with SPM have been smoothed by 8mm, and that smoothnesses ',...
'combine by Pythagoras'' rule.']};
%------------------------------------------------------------------------
smoref.type = 'entry';
smoref.name = 'Template Image Smoothing';
smoref.tag = 'smoref';
smoref.strtype = 'e';
smoref.num = [1 1];
smoref.def = 'normalise.estimate.smoref';
smoref.help = {[...
'Smoothing to apply to a copy of the template image. ',...
'The template and source images should have approximately ',...
'the same smoothness. Remember that the templates supplied ',...
'with SPM have been smoothed by 8mm, and that smoothnesses ',...
'combine by Pythagoras'' rule.']};
%------------------------------------------------------------------------
regtype.type = 'menu';
regtype.name = 'Affine Regularisation';
regtype.tag = 'regtype';
regtype.labels = {'ICBM space template', 'Average sized template','No regularisation'};
regtype.values = {'mni','subj','none'};
regtype.def = 'normalise.estimate.regtype';
regtype.help = {[...
'Affine registration into a standard space can be made more robust by ',...
'regularisation (penalising excessive stretching or shrinking). The ',...
'best solutions can be obtained by knowing the approximate amount of ',...
'stretching that is needed (e.g. ICBM templates are slightly bigger ',...
'than typical brains, so greater zooms are likely to be needed). ',...
'If registering to an image in ICBM/MNI space, then choose the first ',...
'option. If registering to a template that is close in size, then ',...
'select the second option. If you do not want to regularise, then ',...
'choose the third.']};
%------------------------------------------------------------------------
sparams.type = 'files';
sparams.name = 'Initial normalisation params';
sparams.tag = 'sparams';
sparams.filter = 'mat';
sparams.ufilter = '.*sn.mat$';
sparams.num = [0 Inf];
%------------------------------------------------------------------------
template.type = 'files';
template.name = 'Template Image';
template.tag = 'template';
template.filter = 'image';
template.num = [1 Inf];
p1 = [...
'Specify a template image to match the source image with. ',...
'The contrast in the template must be similar to that of the ',...
'source image in order to achieve a good registration. It is ',...
'also possible to select more than one template, in which case ',...
'the registration algorithm will try to find the best linear ',...
'combination of these images in order to best model the intensities ',...
'in the source image.'];
p2 = ['The template(s) will be used for the first iteration of within-group' ...
' normalisation. Further iterations will use an average version of' ...
' the normalised images as template.'];
template.help = {p1, '', p2};
%------------------------------------------------------------------------
weight.type = 'files';
weight.name = 'Template Weighting Image';
weight.tag = 'weight';
weight.filter = 'image';
weight.num = [0 1];
weight.def = 'normalise.estimate.weight';
p1 = [...
'Applies a weighting mask to the template(s) during the parameter ',...
'estimation. With the default brain mask, weights in and around the ',...
'brain have values of one whereas those clearly outside the brain are ',...
'zero. This is an attempt to base the normalization purely upon ',...
'the shape of the brain, rather than the shape of the head (since ',...
'low frequency basis functions can not really cope with variations ',...
'in skull thickness).'];
p2 = [...
'The option is now available for a user specified weighting image. ',...
'This should have the same dimensions and mat file as the template ',...
'images, with values in the range of zero to one.'];
weight.help = {p1,'',p2};
%------------------------------------------------------------------------
stempl.type = 'branch';
stempl.name = 'Initial normalisation template';
stempl.tag = 'stempl';
stempl.val = {template, weight};
%------------------------------------------------------------------------
cutoff.type = 'entry';
cutoff.name = 'Nonlinear Frequency Cutoff';
cutoff.tag = 'cutoff';
cutoff.strtype = 'e';
cutoff.num = [1 1];
cutoff.def = 'normalise.estimate.cutoff';
cutoff.help = {[...
'Cutoff of DCT bases. Only DCT bases of periods longer than the ',...
'cutoff are used to describe the warps. The number used will ',...
'depend on the cutoff and the field of view of the template image(s).']};
%------------------------------------------------------------------------
nits.type = 'entry';
nits.name = 'Nonlinear Iterations';
nits.tag = 'nits';
nits.strtype = 'w';
nits.num = [1 1];
nits.def = 'normalise.estimate.nits';
nits.help = {'Number of iterations of nonlinear warping performed.'};
%------------------------------------------------------------------------
reg.type = 'entry';
reg.name = 'Nonlinear Regularisation';
reg.tag = 'reg';
reg.strtype = 'e';
reg.num = [1 1];
reg.def = 'normalise.estimate.reg';
reg.help = {[...
'The amount of regularisation for the nonlinear part of the spatial ',...
'normalisation. ',...
'Pick a value around one. However, if your normalized images appear ',...
'distorted, then it may be an idea to increase the amount of ',...
'regularization (by an order of magnitude) - or even just use an affine ',...
'normalization. ',...
'The regularization influences the smoothness of the deformation ',...
'fields.']};
%------------------------------------------------------------------------
wtsrc.type = 'files';
wtsrc.name = 'Source Weighting Image';
wtsrc.tag = 'wtsrc';
wtsrc.filter = 'image';
wtsrc.num = [0 1];
wtsrc.val = {{}};
wtsrc.help = {[...
'Optional weighting images (consisting of pixel ',...
'values between the range of zero to one) to be used for registering ',...
'abnormal or lesioned brains. These images should match the dimensions ',...
'of the image from which the parameters are estimated, and should contain ',...
'zeros corresponding to regions of abnormal tissue.']};
%------------------------------------------------------------------------
iteration.type = 'branch';
iteration.name = 'Iteration Options';
iteration.tag = 'iteration';
iteration.val = {smosrc,smoref,regtype,cutoff,nits,reg};
iteration.help = {'Various settings for estimating warps.'};
%------------------------------------------------------------------------
iterations.type = 'repeat';
iterations.name = 'Estimation Iterations';
iterations.tag = 'iterations';
iterations.values = {iteration};
iterations.num = [1 Inf];
%------------------------------------------------------------------------
starting.type = 'choice';
starting.name = 'Initial Normalisation';
starting.tag = 'starting';
starting.values = {stempl, sparams};
%------------------------------------------------------------------------
eoptions.type = 'branch';
eoptions.name = 'Estimation Options';
eoptions.tag = 'eoptions';
eoptions.val = {starting,iterations};
%------------------------------------------------------------------------
source.type = 'files';
source.name = 'Source Images';
source.tag = 'source';
source.num = [1 Inf];
source.filter = 'image';
source.help = {[...
'The images that are warped to match the template(s). The result is ',...
'a set of warps, which can be applied to this image, or any other ',...
'image that is in register with it.']};
%------------------------------------------------------------------------
subj.type = 'branch';
subj.name = 'Subjects';
subj.tag = 'subj';
subj.val = {source, wtsrc};
subj.help = {'Data for all subjects. The same parameters are used within subject.'};
%------------------------------------------------------------------------
normalise.type = 'branch';
normalise.name = 'Group Normalise';
normalise.tag = 'tbxvol_normalise';
normalise.val = {subj,eoptions};
normalise.prog = @tbxvol_normalise;
normalise.vfiles = @vfiles_tbxvol_normalise;
normalise.modality = {'FMRI','PET','VBM'};
p1 = [...
'This module spatially (stereotactically) normalizes MRI, PET or SPECT ',...
'images into a standard space defined by some ideal model or template ',...
'image[s]. The template images supplied with SPM conform to the space ',...
'defined by the ICBM, NIH P-20 project, and approximate that of the ',...
'the space described in the atlas of Talairach and Tournoux (1988). ',...
'The transformation can also be applied to any other image that has ',...
'been coregistered with these scans.'];
p2 = [...
'Generally, the algorithms work by minimising the sum of squares ',...
'difference between the image which is to be normalised, and a linear ',...
'combination of one or more template images. For the least squares ',...
'registration to produce an unbiased estimate of the spatial ',...
'transformation, the image contrast in the templates (or linear ',...
'combination of templates) should be similar to that of the image from ',...
'which the spatial normalization is derived. The registration simply ',...
'searches for an optimum solution. If the starting estimates are not ',...
'good, then the optimum it finds may not find the global optimum.'];
p3 = [...
'The first step of the normalization is to determine the optimum ',...
'12-parameter affine transformation. Initially, the registration is ',...
'performed by matching the whole of the head (including the scalp) to ',...
'the template. Following this, the registration proceeded by only ',...
'matching the brains together, by appropriate weighting of the template ',...
'voxels. This is a completely automated procedure (that does not ',...
'require ``scalp editing'') that discounts the confounding effects of ',...
'skull and scalp differences. A Bayesian framework is used, such that ',...
'the registration searches for the solution that maximizes the a ',...
'posteriori probability of it being correct /* \cite{ashburner97b} */. i.e., it maximizes the ',...
'product of the likelihood function (derived from the residual squared ',...
'difference) and the prior function (which is based on the probability ',...
'of obtaining a particular set of zooms and shears).'];
p4 = [...
'The affine registration is followed by estimating nonlinear deformations, ',...
'whereby the deformations are defined by a linear combination of three ',...
'dimensional discrete cosine transform (DCT) basis functions /* \cite{ashburner99a} */. The default ',...
'options result in each of the deformation fields being described by 1176',...
'parameters, where these represent the coefficients of the deformations in ',...
'three orthogonal directions. The matching involved simultaneously ',...
'minimizing the membrane energies of the deformation fields and the ',...
'residual squared difference between the images and template(s).'];
p5 = [...
'The primarily use is for stereotactic normalization to facilitate inter-subject ',...
'averaging and precise characterization of functional anatomy /* \cite{ashburner97bir} */. It is ',...
'not necessary to spatially normalise the data (this is only a ',...
'pre-requisite for intersubject averaging or reporting in the ',...
'Talairach space). If you wish to circumnavigate this step (e.g. if ',...
'you have single slice data or do not have an appropriate high ',...
'resolution MRI scan) simply specify where you think the anterior ',...
'commissure is with the ORIGIN in the header of the first scan ',...
'(using the ''Display'' facility) and proceed directly to ''Smoothing''',...
'or ''Statistics''.'];
p6 = [...
'All normalized *.img scans are written to the same subdirectory as ',...
'the original *.img, prefixed with a ''w'' (i.e. w*.img). The details ',...
'of the transformations are displayed in the results window, and the ',...
'parameters are saved in the "*_sn.mat" file.'];
opts.help = {p1,'',...
p2,'',p3,'',p4,'',...
p5,'',...
p6};
%------------------------------------------------------------------------
%-tbxvol_combine
%-----------------------------------------------------------------------
voxsz.type = 'entry';
voxsz.name = 'Output Image Voxel Size';
voxsz.tag = 'voxsz';
voxsz.strtype = 'e';
voxsz.num = [1 3];
prefix.val = {'C'};
combine.type = 'branch';
combine.name = 'Combine Volumes';
combine.tag = 'tbxvol_combine';
combine.prog = @tbxvol_combine;
combine.val = {srcimgs, voxsz, interp, dtype, prefix};
combine.help = vgtbx_help2cell('tbxvol_combine');
%-Create/Apply masks
%-----------------------------------------------------------------------
maskand.type = 'const';
maskand.name = 'AND';
maskand.tag = 'maskpredef';
maskand.val = {'and'};
maskand.help = {'Mask expression ''(i1~=0) & ... & (iN ~= 0)'''};
maskor.type = 'const';
maskor.name = 'OR';
maskor.tag = 'maskpredef';
maskor.val = {'or'};
maskor.help = {'Mask expression ''(i1~=0) | ... | (iN ~= 0)'''};
masknand.type = 'const';
masknand.name = 'NAND';
masknand.tag = 'maskpredef';
masknand.val = {'nand'};
masknand.help = {'Mask expression ''~((i1~=0) & ... & (iN ~= 0))'''};
masknor.type = 'const';
masknor.name = 'NOR';
masknor.tag = 'maskpredef';
masknor.val = {'nor'};
masknor.help = {'Mask expression ''~((i1~=0) | ... | (iN ~= 0))'''};
maskcustom.type = 'entry';
maskcustom.name = 'Custom Mask Expression';
maskcustom.tag = 'maskcustom';
maskcustom.strtype = 's';
maskcustom.num = [1 Inf];
maskcustom.help = {'Enter a valid expression for spm_imcalc.'};
mtype.type = 'choice';
mtype.name = 'Mask Type';
mtype.tag = 'mtype';
mtype.values = {maskand maskor masknand masknor maskcustom};
msrcimgs = srcimgs;
msrcimgs.name = 'Source Images for New Mask';
msrcimgs.num = [1 Inf];
moutimg = outimg;
moutimg.name = 'Mask Image Name & Directory';
maskdef.type = 'branch';
maskdef.name = 'Create New Mask';
maskdef.tag = 'maskdef';
maskdef.val = {msrcimgs mtype moutimg};
msrcimg = srcimg;
msrcimg.name = 'Mask Image';
maskspec.type = 'choice';
maskspec.name = 'Mask Specification';
maskspec.tag = 'maskspec';
maskspec.values = {msrcimg maskdef};
maskspec.help = {'Specify an existing mask image or a set of images ' ...
'that will be used to create a mask image.'};
scope.type = 'menu';
scope.name = 'Scope of Mask';
scope.tag = 'scope';
scope.labels = {'Inclusive','Exclusive'};
scope.values = {'i','e'};
scope.help = {['Specify which parts of the images should be kept: parts ' ...
'where the mask image is different from zero (inclusive) ' ...
'or parts where the mask image is zero (exclusive).']};
space.type = 'menu';
space.name = 'Space of Masked Images';
space.tag = 'space';
space.labels = {'Object','Mask'};
space.values = {'object','mask'};
space.help = {['Specify whether the masked images should be written with ' ...
'orientation and voxel size of the original images or of ' ...
'the mask image.']};
prefix.val = {'M'};
nanmask.type = 'menu';
nanmask.name = 'Zero/NaN Masking';
nanmask.tag = 'nanmask';
nanmask.labels = {'No implicit zero mask','Implicit zero mask','NaNs should be zeroed'};
nanmask.values = {0,1,-1};
nanmask.def = 'imcalc.mask';
%nanmask.val = {0};
nanmask.help = {[...
'For data types without a representation of NaN, implicit zero masking ',...
'assummes that all zero voxels are to be treated as missing, and ',...
'treats them as NaN. NaN''s are written as zero (by spm_write_plane), ',...
'for data types without a representation of NaN.']};
maskthresh.type = 'entry';
maskthresh.name = 'Threshold for masking';
maskthresh.tag = 'maskthresh';
maskthresh.strtype = 'e';
maskthresh.num = [1 1];
maskthresh.def = 'tools.vgtbx_Volumes.create_mask.maskthresh';
maskthresh.help = {['Sometimes zeroes are represented as non-zero values ' ...
'due to rounding errors (especially in binary masks). Specify a small non-zero ' ...
'value for zero masking in this case.']};
srcspec.type = 'branch';
srcspec.name = 'Apply Created Mask';
srcspec.tag = 'srcspec';
srcspec.val = {srcimgs, scope, space, prefix, interp, nanmask, maskthresh, ...
overwrite};
srcspec.help = {'Specify images which are to be masked.'};
srcspecs.type = 'repeat';
srcspecs.name = 'Apply Masks';
srcspecs.tag = 'unused';
srcspecs.values = {srcspec};
create_mask.type = 'branch';
create_mask.name = 'Create and Apply Masks';
create_mask.tag = 'tbxvol_create_mask';
create_mask.prog = @tbxvol_create_mask;
create_mask.vfiles = @vfiles_tbxvol_create_mask;
create_mask.val = {maskspec, srcspecs};
create_mask.help = vgtbx_help2cell('tbxvol_create_mask');
%-Split volumes
%-----------------------------------------------------------------------
sliceorder.type = 'menu';
sliceorder.name = 'Slice/Volume Order';
sliceorder.tag = 'sliceorder';
sliceorder.labels = {'Vol1 Slice1..N,...VolM Slice1..N',...
'VolM Slice1..N,...Vol1 Slice1..N',...
'Slice1 Vol1..M,...SliceN Vol1..M',...
'Slice1 VolM..1,...SliceN VolM..1'};
sliceorder.values = {'volume','volume_vrev','slice','slice_vrev'};
noutput.type = 'entry';
noutput.name = '#Output Images';
noutput.tag = 'noutput';
noutput.num = [1 1];
noutput.strtype = 'i';
thickcorr.type = 'menu';
thickcorr.name = 'Correct Slice Thickness';
thickcorr.tag = 'thickcorr';
thickcorr.labels = {'Yes',...
'No' };
thickcorr.values = {1,0};
thickcorr.help = {['If set to ''yes'', the slice thickness is ' ...
'multiplied by the #output images.']};
split.type = 'branch';
split.name = 'Split Volumes';
split.tag = 'tbxvol_split';
split.prog = @tbxvol_split;
split.vfiles=@vfiles_tbxvol_split;
split.val = {srcimgs sliceorder noutput thickcorr};
split.help = vgtbx_help2cell('tbxvol_split');
%-Spike detection
%-----------------------------------------------------------------------
spikethr.type = 'entry';
spikethr.name = 'Threshold (in standard deviations)';
spikethr.tag = 'spikethr';
spikethr.num = [1 1];
spikethr.strtype = 'e';
spike.type = 'branch';
spike.name = 'Detect abnormal slices';
spike.tag = 'tbxvol_spike';
spike.prog = @tbxvol_spike;
spike.val = {srcimgs spikethr};
spike.help = vgtbx_help2cell('tbxvol_spike');
%-Extract subvolume
%-----------------------------------------------------------------------
bbox.type = 'entry';
bbox.name = 'Bounding Box for Extracted Image';
bbox.tag = 'bbox';
bbox.num = [1 6];
bbox.strtype = 'i';
bbox.help = {'Specify the bounding box in voxel coordinates of ' ...
'the original image: X1 X2 Y1 Y2 Z1 Z2.'};
prefix.val = {'E'};
extract_subvol.type = 'branch';
extract_subvol.name = 'Extract Subvolume';
extract_subvol.tag = 'tbxvol_extract_subvol';
extract_subvol.prog = @tbxvol_extract_subvol;
extract_subvol.val = {srcimgs bbox prefix};
extract_subvol.help = vgtbx_help2cell('tbxvol_extract_subvol');
%-assemble choice for Multiple Volumes
%-----------------------------------------------------------------------
Multiple_Volumes.type = 'choice';
Multiple_Volumes.name = 'Multiple Volumes';
Multiple_Volumes.tag = 'Multiple_Volumes';
% leave correct_ec_SPM here for historical reasons
Multiple_Volumes.values = {correct_ec_SPM combine create_mask extract_subvol ...
normalise split spike};
%-Single Volumes sub-menu
%=======================================================================
addpath(fullfile(spm('dir'),'toolbox','Volumes','Single_Volumes'));
%-Extract data
%-----------------------------------------------------------------------
src.type = 'choice';
src.name = 'Data Source';
src.tag = 'src';
src.values = {srcspm srcimgs};
src.help = {['Data can be sampled from raw images, or from an SPM analysis. ' ...
'In case of an SPM analysis, both fitted and raw data will ' ...
'be sampled.']};
avg.type = 'menu';
avg.name = 'Average';
avg.tag = 'avg';
avg.labels = {'No averaging',...
'Average over voxels' };
avg.values = {'none','vox'};
avg.help = {['If set to ''yes'', only averages over the voxel values ' ...
'of each image are returned.']};
avg.def = 'defaults.tools.vgtbx_Volumes.extract.avg';
roistart.type = 'entry';
roistart.name = 'Start Point (in mm)';
roistart.tag = 'roistart';
roistart.num = [3 1];
roistart.strtype = 'e';
roiend.type = 'entry';
roiend.name = 'End Point (in mm)';
roiend.tag = 'roiend';
roiend.num = [3 1];
roiend.strtype = 'e';
roistep.type = 'entry';
roistep.name = 'Sampling Distance along Line (in mm)';
roistep.tag = 'roistep';
roistep.num = [1 1];
roistep.strtype = 'e';
roiline.type = 'branch';
roiline.name = 'Line (Start and End Point)';
roiline.tag = 'roiline';
roiline.val = {roistart roiend roistep};
roiline.help = {['Specify a line in 3D space from a start point to an ' ...
'end point. The image is sampled along this line according ' ...
'to the specified sampling distance.'], ['Note that the sampling ' ...
'positions are computed in mm space and then transformed ' ...
'into the voxel space of the image. This may result in a ' ...
'sparse sampling of the image, if the voxel size is smaller ' ...
'than the sampling distance.'] };
roilinep1.type = 'entry';
roilinep1.name = 'First Point (in mm)';
roilinep1.tag = 'roilinep1';
roilinep1.num = [3 1];
roilinep1.strtype = 'e';
roilinep2.type = 'entry';
roilinep2.name = 'Second Point (in mm)';
roilinep2.tag = 'roilinep2';
roilinep2.num = [3 1];
roilinep2.strtype = 'e';
roilinecoords.type = 'entry';
roilinecoords.name = 'Point List of Line Coordinates';
roilinecoords.tag = 'roilinecoords';
roilinecoords.num = [1 Inf];
roilinecoords.strtype = 'e';
roilineparam.type = 'branch';
roilineparam.name = 'Line (2 Points on Line and Parameters in Line Coords)';
roilineparam.tag = 'roilineparam';
roilineparam.val = {roilinep1 roilinep2 roilinecoords};
roilineparam.help = {['Specify a line in 3D space going through 2 points. ' ...
'The image is sampled along this line according ' ...
'to the specified line coordinates, starting with zero '...
'at the first point. Spacing between line coordinates '...
'can be variable.'],...
['The convention for line coordinates is that negative ' ...
'values run from P1 towards P2, while positive values ' ...
'run from P1 away from P2.'],...
['Note that the sampling ' ...
'positions are computed in mm space and then transformed ' ...
'into the voxel space of the image. This may result in a ' ...
'sparse sampling of the image, if the voxel size is smaller ' ...
'than the sampling distance.'] };
roicent.type = 'entry';
roicent.name = 'Centre Point (in mm)';
roicent.tag = 'roicent';
roicent.num = [3 1];
roicent.strtype = 'e';
roirad.type = 'entry';
roirad.name = 'Radius (in mm)';
roirad.tag = 'roirad';
roirad.num = [1 1];
roirad.strtype = 'e';
roisphere.type = 'branch';
roisphere.name = 'Sphere';
roisphere.tag = 'roisphere';
roisphere.val = {roicent roirad};
roisphere.help = {['Specify a sphere with centre and radius in mm coordinates.' ...
'The actual sampling positions are computed in voxel ' ...
'space, and therefore a contiguous sampling of the ' ...
'specified sphere is guaranteed.']};
roilist.type = 'entry';
roilist.name = 'Point List (in mm)';
roilist.tag = 'roilist';
roilist.num = [3 Inf];
roilist.strtype = 'e';
roilist.help = {['Specify a list of mm positions to be sampled. Note, that ' ...
'this may sample a volume in a non-contiguous way, if the ' ...
'positions do not correspond 1-to-1 to voxel positions.']};
roispec.type = 'repeat';
roispec.name = 'ROI Specification';
roispec.tag = 'roispec';
roispec.values = {srcimg roiline roilineparam roisphere roilist};
roispec.num = [1 Inf];
roispec.help = {['A region of interest can be specified by an image file or ' ...
'a list of (mm)-positions. If an image file is given, data ' ...
'is extracted for all non-zero voxels in the region of ' ...
'interest.']};
extract.type = 'branch';
extract.name = 'Extract Data from ROI';
extract.tag = 'tbxvol_extract';
extract.prog = @tbxvol_extract;
extract.val = {src roispec avg interp};
extract.help = vgtbx_help2cell('tbxvol_extract');
%-Flip volumes
%-----------------------------------------------------------------------
flipdir.type = 'menu';
flipdir.name = 'Flip Direction (Voxel Space)';
flipdir.tag = 'flipdir';
flipdir.labels = {'X', 'Y', 'Z'};
flipdir.values = {1, 2, 3};
prefix.val = {'F'};
flip.type = 'branch';
flip.name = 'Flip Volumes';
flip.tag = 'tbxvol_flip';
flip.prog = @tbxvol_flip;
flip.val = {srcimgs flipdir prefix overwrite};
flip.vfiles = @vfiles_tbxvol_flip;
flip.help = vgtbx_help2cell('tbxvol_flip');
%-Image integrals
%-----------------------------------------------------------------------
get_integrals.type = 'branch';
get_integrals.name = 'Image integrals';
get_integrals.tag = 'tbxvol_get_integrals';
get_integrals.prog = @tbxvol_get_integrals;
get_integrals.val = {srcimgs};
get_integrals.help = vgtbx_help2cell('tbxvol_get_integrals');
%-Intensity histogram
%-----------------------------------------------------------------------
prefix.val = {'H'};
histogramm.type = 'branch';
histogramm.name = 'Histogramm Thresholding';
histogramm.tag = 'tbxvol_histogramm';
histogramm.prog = @tbxvol_histogramm;
histogramm.val = {srcimg prefix overwrite};
histogramm.help = vgtbx_help2cell('tbxvol_histogramm');
%-(De)interleave volumes
%-----------------------------------------------------------------------
interleaved.type = 'const';
interleaved.name = 'Interleaved';
interleaved.tag = 'interleaved';
interleaved.val = {0};
userdef.type = 'entry';
userdef.name = 'User Defined';
userdef.tag = 'userdef';
userdef.num = [1 Inf];
userdef.strtype = 'i';
sliceorder = []; % clear previous instance
sliceorder.type = 'choice';
sliceorder.name = 'Slice Order';
sliceorder.tag = 'sliceorder';
sliceorder.values = {interleaved userdef};
prefix.val = {'I'};
interleave.type = 'branch';
interleave.name = '(De)Interleave Volumes';
interleave.tag = 'tbxvol_interleave';
interleave.prog = @tbxvol_interleave;
interleave.val = {srcimgs sliceorder prefix overwrite};
interleave.help = vgtbx_help2cell('tbxvol_interleave');
%-Replace slice
%-----------------------------------------------------------------------
repslice.type = 'entry';
repslice.name = 'Slice to Replace';
repslice.tag = 'repslice';
repslice.num = [1 1];
repslice.strtype = 'i';
prefix.val = {'R'};
replace_slice.type = 'branch';
replace_slice.name = 'Replace Slice';
replace_slice.tag = 'tbxvol_replace_slice';
replace_slice.prog = @tbxvol_replace_slice;
replace_slice.val = {srcimg repslice prefix overwrite};
replace_slice.help = vgtbx_help2cell('tbxvol_replace_slice');
%-Rescale images
%-----------------------------------------------------------------------
scale.type = 'entry';
scale.name = 'New Scaling Factor';
scale.tag = 'scale';
scale.num = [1 1];
scale.strtype = 'e';
scale.help = {['Set the new scaling factor. To determine this value from ' ...
'your image series, set this field to NaN.']};
offset.type = 'entry';
offset.name = 'New Intensity Offset';
offset.tag = 'offset';
offset.num = [1 1];
offset.strtype = 'e';
offset.def = 'tools.vgtbx_Volumes.tbxvol_rescale.offset';
prefix.val = {'S'};
rescale.type = 'branch';
rescale.name = 'Rescale Images';
rescale.tag = 'tbxvol_rescale';
rescale.prog = @tbxvol_rescale;
rescale.val = {srcimgs scale offset dtype prefix overwrite};
rescale.help = vgtbx_help2cell('tbxvol_rescale');
%-Rescale images
%-----------------------------------------------------------------------
oldscale.type = 'entry';
oldscale.name = 'Old intensity range';
oldscale.tag = 'oldscale';
oldscale.num = [1 2];
oldscale.strtype = 'e';
oldscale.help = {['Original data intensity scaling. To derive min/max' ...
' from the data, set the first or second entry to Inf.']};
newscale.type = 'entry';
newscale.name = 'New intensity range';
newscale.tag = 'newscale';
newscale.num = [1 2];
newscale.strtype = 'e';
newscale.help = {'Set min/max value for new intensity range.'};
prefix.val = {'S'};
rescale_min_max.type = 'branch';
rescale_min_max.name = 'Rescale Images to [min max]';
rescale_min_max.tag = 'tbxvol_rescale_min_max';
rescale_min_max.prog = @tbxvol_rescale_min_max;
rescale_min_max.vfiles = @vfiles_tbxvol_rescale_min_max;
rescale_min_max.val = {srcimgs oldscale newscale prefix};
rescale_min_max.help = vgtbx_help2cell('tbxvol_rescale_min_max');
%-Unwrap volumes
%-----------------------------------------------------------------------
npix.type = 'entry';
npix.name = '#pixels to Unwrap';
npix.tag = 'npix';
npix.num = [1 1];
npix.strtype = 'i';
wrapdir.type = 'menu';
wrapdir.name = 'Wrap Direction (Voxel Space)';
wrapdir.tag = 'wrapdir';
wrapdir.labels = {'X', 'Y', 'Z'};
wrapdir.values = {1, 2, 3};
cor_orig.type = 'menu';
cor_orig.name = 'Correct Origin of Wrapped Images';
cor_orig.tag = 'cor_orig';
cor_orig.labels = {'Yes', 'No'};
cor_orig.values = {1, 0};
cor_orig.def = 'tools.vgtbx_Volumes.tbxvol_unwrap.cor_orig';
prefix.val = {'U'};
unwrap.type = 'branch';
unwrap.name = 'Unwrap Volumes';
unwrap.tag = 'tbxvol_unwrap';
unwrap.prog = @tbxvol_unwrap;
unwrap.val = {srcimgs cor_orig npix wrapdir prefix overwrite};
unwrap.help = vgtbx_help2cell('tbxvol_unwrap');
%-assemble choice for Single Volumes
%-----------------------------------------------------------------------
Single_Volumes.type = 'choice';
Single_Volumes.name = 'Single Volumes';
Single_Volumes.tag = 'Single_Volumes';
Single_Volumes.values = {extract flip get_integrals histogramm interleave replace_slice ...
rescale rescale_min_max unwrap};
%-Main menu level
%=======================================================================
opt.type = 'repeat';
opt.name = 'Volume handling utilities';
opt.tag = 'vgtbx_Volumes';
opt.values = {Single_Volumes Multiple_Volumes Stats_Tools};
opt.num = [0 Inf];
opt.help = vgtbx_help2cell(mfilename);
%-Add defaults
%=======================================================================
global defaults;
% Overwrite images
%-----------------------------------------------------------------------
defaults.tools.vgtbx_Volumes.overwrite = 1;
% Graphics output
%-----------------------------------------------------------------------
defaults.tools.vgtbx_Volumes.graphics = 1;
% Nearest Neighbour interpolation
%-----------------------------------------------------------------------
defaults.tools.vgtbx_Volumes.interp = 0;
% Distance from ResMS mean
%-----------------------------------------------------------------------
defaults.tools.vgtbx_Volumes.analyse_resms.dist = .1;
% Average extracted data
%-----------------------------------------------------------------------
defaults.tools.vgtbx_Volumes.extract.avg = 'none';
% Rescale offset
%-----------------------------------------------------------------------
defaults.tools.vgtbx_Volumes.tbxvol_rescale.offset = 0;
% Correct origin when unwrapping
%-----------------------------------------------------------------------
defaults.tools.vgtbx_Volumes.tbxvol_unwrap.cor_orig = 1;
% Correct origin when unwrapping
%-----------------------------------------------------------------------
defaults.tools.vgtbx_Volumes.create_mask.maskthresh = eps;
function vfiles = vfiles_tbxvol_split(job)
vfiles = {};
for l = 1:numel(job.srcimgs)
[p n e v] = fileparts(job.srcimgs{l});
c = findstr(e, ',');
if ~isempty(c)
e = e(1:c-1);
end;
fs = sprintf('_%%0%dd',ceil(log10(job.noutput)));
for k = 1:job.noutput
vfiles{end+1} = fullfile(p,[n sprintf(fs,k) e ',1' v]);
end;
end;
function vfiles = vfiles_tbxvol_create_mask(job)
vfiles = {};
if isfield(job.maskspec,'maskdef')
[p n e v] = fileparts(job.maskspec.maskdef.outimg.fname);
c = findstr(e, ',');
if ~isempty(c)
e = e(1:c-1);
end;
vfiles{end+1} = fullfile(job.maskspec.maskdef.outimg.swd{1}, [n e ',1' v]);
end;
for l=1:numel(job.srcspec)
for k=1:numel(job.srcspec(l).srcimgs);
[p n e v] = fileparts(job.srcspec(l).srcimgs{k});
c = findstr(e, ',');
if ~isempty(c)
e = e(1:c-1);
end;
vfiles{end+1} = fullfile(p,[job.srcspec(l).prefix ...
lower(job.srcspec(l).scope) n e ',1' v]);
end;
end;
function vfiles = vfiles_tbxvol_transform_t2x(job)
for k = 1:numel(job.srcimgs)
[pth nm xt vr] = spm_fileparts(job.srcimgs{k});
switch job.option
case 1
nm2 = 'P';
case 2
nm2 = 'logP';
case 3
nm2 = 'R';
case 4
nm2 = 'D';
end
% name should follow convention spm?_0*.img
if strcmp(nm(1:3),'spm') & strcmp(nm(4:6),'T_0')
num = str2num(nm(length(nm)-2:length(nm)));
vfiles{k} = fullfile(pth,[nm(1:3) nm2 nm(5:end) xt ',1']);
else
vfiles{k} = fullfile(pth,['spm' nm2 '_' nm xt ',1']);
end
end;
function vfiles = vfiles_tbxvol_laterality(job)
for k = 1:numel(job.srcimgs)
[pth nm xt vr] = spm_fileparts(job.srcimgs{k});
vfiles{k} = fullfile(pth, [job.prefix nm xt ',1']);
end;
function vfiles = vfiles_tbxvol_rescale_min_max(job)
for k = 1:numel(job.srcimgs)
[pth nm xt vr] = spm_fileparts(job.srcimgs{k});
vfiles{k} = fullfile(pth, [job.prefix nm xt ',1']);
end;
function vfiles = vfiles_tbxvol_flip(job)
vfiles = job.srcimgs;
if ~job.overwrite
dirs = 'XYZ';
for k=1:numel(job.srcimgs)
[p n e v] = fileparts(job.srcimgs{k});
vfiles{k} = fullfile(p,[job.prefix dirs(job.flipdir) n e v]);
end;
end;
function vf = vfiles_tbxvol_normalise(varargin)
job = varargin{1};
vf = cell(numel(job.subj.source));
for i=1:numel(job.subj.source),
[pth,nam,ext,num] = spm_fileparts(deblank(job.subj.source{i}));
vf{i} = fullfile(pth,[nam,'_gr_sn.mat']);
end;
|
github
|
philippboehmsturm/antx-master
|
tbx_cfg_vgtbx_Volumes.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/Volumes/tbx_cfg_vgtbx_Volumes.m
| 103,487 |
utf_8
|
0e4f45d959bdbdd19f162cff91b351de
|
function vgtbx_Volumes = tbx_cfg_vgtbx_Volumes
% Volumes toolbox
%_______________________________________________________________________
%
% This toolbox contains various helper functions to make image
% manipulation within SPM5 more convenient. Help on each individual item
% can be obtained by selecting the corresponding entry in the help menu.
%
% This toolbox is free but copyright software, distributed under the
% terms of the GNU General Public Licence as published by the Free
% Software Foundation (either version 2, as given in file
% spm_LICENCE.man, or at your option, any later version). Further details
% on "copyleft" can be found at http://www.gnu.org/copyleft/.
% The toolbox consists of the files listed in its Contents.m file.
%
% The source code of this toolbox is available at
%
% http://sourceforge.net/projects/spmtools
%
% Please use the SourceForge forum and tracker system for comments,
% suggestions, bug reports etc. regarding this toolbox.
%_______________________________________________________________________
%
% @(#) $Id: vgtbx_config_Volumes.m 539 2007-12-06 17:31:12Z glauche $
rev='$Revision: 539 $';
addpath(fullfile(spm('dir'),'toolbox','Volumes'));
% MATLABBATCH Configuration file for toolbox 'Volume handling utilities'
% This code has been automatically generated.
% ---------------------------------------------------------------------
% Toolbox paths - added manually
% ---------------------------------------------------------------------
tbxdir = fileparts(mfilename('fullpath'));
addpath(tbxdir);
addpath(fullfile(tbxdir, 'Single_Volumes'));
addpath(fullfile(tbxdir, 'Multiple_Volumes'));
addpath(fullfile(tbxdir, 'Stats_Tools'));
% ---------------------------------------------------------------------
% srcspm Source SPM.mat
% ---------------------------------------------------------------------
srcspm = cfg_files;
srcspm.tag = 'srcspm';
srcspm.name = 'Source SPM.mat';
srcspm.help = {''};
srcspm.filter = 'mat';
srcspm.ufilter = '.*SPM.*\.mat';
srcspm.num = [1 1];
% ---------------------------------------------------------------------
% srcimgs Source Images
% ---------------------------------------------------------------------
srcimgs = cfg_files;
srcimgs.tag = 'srcimgs';
srcimgs.name = 'Source Images';
srcimgs.help = {''};
srcimgs.filter = 'image';
srcimgs.ufilter = '.*';
srcimgs.num = [1 Inf];
% ---------------------------------------------------------------------
% src Data Source
% ---------------------------------------------------------------------
src = cfg_choice;
src.tag = 'src';
src.name = 'Data Source';
src.help = {'Data can be sampled from raw images, or from an SPM analysis. In case of an SPM analysis, both fitted and raw data will be sampled.'};
src.values = {srcspm srcimgs };
% ---------------------------------------------------------------------
% srcimg Source Image
% ---------------------------------------------------------------------
srcimg = cfg_files;
srcimg.tag = 'srcimg';
srcimg.name = 'Source Image';
srcimg.help = {''};
srcimg.filter = 'image';
srcimg.ufilter = '.*';
srcimg.num = [1 1];
% ---------------------------------------------------------------------
% roistart Start Point (in mm)
% ---------------------------------------------------------------------
roistart = cfg_entry;
roistart.tag = 'roistart';
roistart.name = 'Start Point (in mm)';
roistart.help = {''};
roistart.strtype = 'e';
roistart.num = [3 1];
% ---------------------------------------------------------------------
% roiend End Point (in mm)
% ---------------------------------------------------------------------
roiend = cfg_entry;
roiend.tag = 'roiend';
roiend.name = 'End Point (in mm)';
roiend.help = {''};
roiend.strtype = 'e';
roiend.num = [3 1];
% ---------------------------------------------------------------------
% roistep Sampling Distance along Line (in mm)
% ---------------------------------------------------------------------
roistep = cfg_entry;
roistep.tag = 'roistep';
roistep.name = 'Sampling Distance along Line (in mm)';
roistep.help = {''};
roistep.strtype = 'e';
roistep.num = [1 1];
% ---------------------------------------------------------------------
% roiline Line (Start and End Point)
% ---------------------------------------------------------------------
roiline = cfg_branch;
roiline.tag = 'roiline';
roiline.name = 'Line (Start and End Point)';
roiline.val = {roistart roiend roistep };
roiline.help = {
'Specify a line in 3D space from a start point to an end point. The image is sampled along this line according to the specified sampling distance.'
'Note that the sampling positions are computed in mm space and then transformed into the voxel space of the image. This may result in a sparse sampling of the image, if the voxel size is smaller than the sampling distance.'
}';
% ---------------------------------------------------------------------
% roilinep1 First Point (in mm)
% ---------------------------------------------------------------------
roilinep1 = cfg_entry;
roilinep1.tag = 'roilinep1';
roilinep1.name = 'First Point (in mm)';
roilinep1.help = {''};
roilinep1.strtype = 'e';
roilinep1.num = [3 1];
% ---------------------------------------------------------------------
% roilinep2 Second Point (in mm)
% ---------------------------------------------------------------------
roilinep2 = cfg_entry;
roilinep2.tag = 'roilinep2';
roilinep2.name = 'Second Point (in mm)';
roilinep2.help = {''};
roilinep2.strtype = 'e';
roilinep2.num = [3 1];
% ---------------------------------------------------------------------
% roilinecoords Point List of Line Coordinates
% ---------------------------------------------------------------------
roilinecoords = cfg_entry;
roilinecoords.tag = 'roilinecoords';
roilinecoords.name = 'Point List of Line Coordinates';
roilinecoords.help = {''};
roilinecoords.strtype = 'e';
roilinecoords.num = [1 Inf];
% ---------------------------------------------------------------------
% roilineparam Line (2 Points on Line and Parameters in Line Coords)
% ---------------------------------------------------------------------
roilineparam = cfg_branch;
roilineparam.tag = 'roilineparam';
roilineparam.name = 'Line (2 Points on Line and Parameters in Line Coords)';
roilineparam.val = {roilinep1 roilinep2 roilinecoords };
roilineparam.help = {
'Specify a line in 3D space going through 2 points. The image is sampled along this line according to the specified line coordinates, starting with zero at the first point. Spacing between line coordinates can be variable.'
'The convention for line coordinates is that negative values run from P1 towards P2, while positive values run from P1 away from P2.'
'Note that the sampling positions are computed in mm space and then transformed into the voxel space of the image. This may result in a sparse sampling of the image, if the voxel size is smaller than the sampling distance.'
}';
% ---------------------------------------------------------------------
% roicent Centre Point (in mm)
% ---------------------------------------------------------------------
roicent = cfg_entry;
roicent.tag = 'roicent';
roicent.name = 'Centre Point (in mm)';
roicent.help = {''};
roicent.strtype = 'e';
roicent.num = [3 1];
% ---------------------------------------------------------------------
% roirad Radius (in mm)
% ---------------------------------------------------------------------
roirad = cfg_entry;
roirad.tag = 'roirad';
roirad.name = 'Radius (in mm)';
roirad.help = {''};
roirad.strtype = 'e';
roirad.num = [1 1];
% ---------------------------------------------------------------------
% roisphere Sphere
% ---------------------------------------------------------------------
roisphere = cfg_branch;
roisphere.tag = 'roisphere';
roisphere.name = 'Sphere';
roisphere.val = {roicent roirad };
roisphere.help = {'Specify a sphere with centre and radius in mm coordinates.The actual sampling positions are computed in voxel space, and therefore a contiguous sampling of the specified sphere is guaranteed.'};
% ---------------------------------------------------------------------
% roilist Point List (in mm)
% ---------------------------------------------------------------------
roilist = cfg_entry;
roilist.tag = 'roilist';
roilist.name = 'Point List (in mm)';
roilist.help = {'Specify a list of mm positions to be sampled. Note, that this may sample a volume in a non-contiguous way, if the positions do not correspond 1-to-1 to voxel positions.'};
roilist.strtype = 'e';
roilist.num = [3 Inf];
% ---------------------------------------------------------------------
% roispec ROI Specification
% ---------------------------------------------------------------------
roispec = cfg_repeat;
roispec.tag = 'roispec';
roispec.name = 'ROI Specification';
roispec.help = {'A region of interest can be specified by an image file or a list of (mm)-positions. If an image file is given, data is extracted for all non-zero voxels in the region of interest.'};
roispec.values = {srcimg roiline roilineparam roisphere roilist };
roispec.num = [1 Inf];
% ---------------------------------------------------------------------
% avg Average
% ---------------------------------------------------------------------
avg = cfg_menu;
avg.tag = 'avg';
avg.name = 'Average';
avg.help = {'If set to ''yes'', only averages over the voxel values of each image are returned.'};
avg.labels = {
'No averaging'
'Average over voxels'
}';
avg.values = {
'none'
'vox'
}';
% ---------------------------------------------------------------------
% interp Interpolation
% ---------------------------------------------------------------------
interp = cfg_menu;
interp.tag = 'interp';
interp.name = 'Interpolation';
interp.help = {''};
interp.labels = {
'Nearest neighbour'
'Trilinear'
'2nd Degree b-Spline'
'3rd Degree b-Spline'
'4th Degree b-Spline'
'5th Degree b-Spline'
'6th Degree b-Spline'
'7th Degree b-Spline'
'2nd Degree Sinc'
'3rd Degree Sinc'
'4th Degree Sinc'
'5th Degree Sinc'
'6th Degree Sinc'
'7th Degree Sinc'
}';
interp.values = {0 1 2 3 4 5 6 7 -2 -3 -4 -5 -6 -7};
% ---------------------------------------------------------------------
% tbxvol_extract Extract Data from ROI
% ---------------------------------------------------------------------
cfg_tbxvol_extract = cfg_exbranch;
cfg_tbxvol_extract.tag = 'tbxvol_extract';
cfg_tbxvol_extract.name = 'Extract Data from ROI';
cfg_tbxvol_extract.val = {src roispec avg interp };
cfg_tbxvol_extract.help = vgtbx_help2cell('tbxvol_extract');
cfg_tbxvol_extract.prog = @tbxvol_extract;
cfg_tbxvol_extract.vout = @vout_tbxvol_extract;
% ---------------------------------------------------------------------
% srcimgs Source Images
% ---------------------------------------------------------------------
srcimgs = cfg_files;
srcimgs.tag = 'srcimgs';
srcimgs.name = 'Source Images';
srcimgs.help = {''};
srcimgs.filter = 'image';
srcimgs.ufilter = '.*';
srcimgs.num = [1 Inf];
% ---------------------------------------------------------------------
% flipdir Flip Direction (Voxel Space)
% ---------------------------------------------------------------------
flipdir = cfg_menu;
flipdir.tag = 'flipdir';
flipdir.name = 'Flip Direction (Voxel Space)';
flipdir.help = {''};
flipdir.labels = {
'X'
'Y'
'Z'
}';
flipdir.values = {1 2 3};
% ---------------------------------------------------------------------
% prefix Output Filename Prefix
% ---------------------------------------------------------------------
prefix = cfg_entry;
prefix.tag = 'prefix';
prefix.name = 'Output Filename Prefix';
prefix.val = {'F'};
prefix.help = {'The output filename is constructed by prefixing the original filename with this prefix.'};
prefix.strtype = 's';
prefix.num = [1 Inf];
% ---------------------------------------------------------------------
% overwrite Overwrite existing Input/Output Files
% ---------------------------------------------------------------------
overwrite = cfg_menu;
overwrite.tag = 'overwrite';
overwrite.name = 'Overwrite existing Input/Output Files';
overwrite.help = {''};
overwrite.labels = {
'Yes'
'No'
}';
overwrite.values = {true false};
% ---------------------------------------------------------------------
% tbxvol_flip Flip Volumes
% ---------------------------------------------------------------------
cfg_tbxvol_flip = cfg_exbranch;
cfg_tbxvol_flip.tag = 'tbxvol_flip';
cfg_tbxvol_flip.name = 'Flip Volumes';
cfg_tbxvol_flip.val = {srcimgs flipdir prefix overwrite };
cfg_tbxvol_flip.help = {'No help available for topic ''tbxvol_flip''.'};
cfg_tbxvol_flip.prog = @tbxvol_flip;
cfg_tbxvol_flip.vfiles = @vfiles_tbxvol_flip;
% ---------------------------------------------------------------------
% srcimgs Source Images
% ---------------------------------------------------------------------
srcimgs = cfg_files;
srcimgs.tag = 'srcimgs';
srcimgs.name = 'Source Images';
srcimgs.help = {''};
srcimgs.filter = 'image';
srcimgs.ufilter = '.*';
srcimgs.num = [1 Inf];
% ---------------------------------------------------------------------
% tbxvol_get_integrals Image integrals
% ---------------------------------------------------------------------
cfg_tbxvol_get_integrals = cfg_exbranch;
cfg_tbxvol_get_integrals.tag = 'tbxvol_get_integrals';
cfg_tbxvol_get_integrals.name = 'Image integrals';
cfg_tbxvol_get_integrals.val = {srcimgs };
cfg_tbxvol_get_integrals.help = {'No help available for topic ''tbxvol_get_integrals''.'};
cfg_tbxvol_get_integrals.prog = @(job)tbxvol_get_integrals('run',job);
cfg_tbxvol_get_integrals.vout = @(job)tbxvol_get_integrals('vout',job);
% ---------------------------------------------------------------------
% srcimg Source Image
% ---------------------------------------------------------------------
srcimg = cfg_files;
srcimg.tag = 'srcimg';
srcimg.name = 'Source Image';
srcimg.help = {''};
srcimg.filter = 'image';
srcimg.ufilter = '.*';
srcimg.num = [1 1];
% ---------------------------------------------------------------------
% prefix Output Filename Prefix
% ---------------------------------------------------------------------
prefix = cfg_entry;
prefix.tag = 'prefix';
prefix.name = 'Output Filename Prefix';
prefix.val = {'H'};
prefix.help = {'The output filename is constructed by prefixing the original filename with this prefix.'};
prefix.strtype = 's';
prefix.num = [1 Inf];
% ---------------------------------------------------------------------
% overwrite Overwrite existing Input/Output Files
% ---------------------------------------------------------------------
overwrite = cfg_menu;
overwrite.tag = 'overwrite';
overwrite.name = 'Overwrite existing Input/Output Files';
overwrite.help = {''};
overwrite.labels = {
'Yes'
'No'
}';
overwrite.values = {true false};
% ---------------------------------------------------------------------
% tbxvol_histogramm Histogramm Thresholding
% ---------------------------------------------------------------------
cfg_tbxvol_histogramm = cfg_exbranch;
cfg_tbxvol_histogramm.tag = 'tbxvol_histogramm';
cfg_tbxvol_histogramm.name = 'Histogramm Thresholding';
cfg_tbxvol_histogramm.val = {srcimg prefix overwrite };
cfg_tbxvol_histogramm.help = {'No help available for topic ''tbxvol_histogramm''.'};
cfg_tbxvol_histogramm.prog = @tbxvol_histogramm;
% ---------------------------------------------------------------------
% srcimgs Source Images
% ---------------------------------------------------------------------
srcimgs = cfg_files;
srcimgs.tag = 'srcimgs';
srcimgs.name = 'Source Images';
srcimgs.help = {''};
srcimgs.filter = 'image';
srcimgs.ufilter = '.*';
srcimgs.num = [1 Inf];
% ---------------------------------------------------------------------
% interleaved Interleaved
% ---------------------------------------------------------------------
interleaved = cfg_const;
interleaved.tag = 'interleaved';
interleaved.name = 'Interleaved';
interleaved.val{1} = double(0);
interleaved.help = {''};
% ---------------------------------------------------------------------
% userdef User Defined
% ---------------------------------------------------------------------
userdef = cfg_entry;
userdef.tag = 'userdef';
userdef.name = 'User Defined';
userdef.help = {''};
userdef.strtype = 'i';
userdef.num = [1 Inf];
% ---------------------------------------------------------------------
% sliceorder Slice Order
% ---------------------------------------------------------------------
sliceorder = cfg_choice;
sliceorder.tag = 'sliceorder';
sliceorder.name = 'Slice Order';
sliceorder.help = {''};
sliceorder.values = {interleaved userdef };
% ---------------------------------------------------------------------
% prefix Output Filename Prefix
% ---------------------------------------------------------------------
prefix = cfg_entry;
prefix.tag = 'prefix';
prefix.name = 'Output Filename Prefix';
prefix.val = {'I'};
prefix.help = {'The output filename is constructed by prefixing the original filename with this prefix.'};
prefix.strtype = 's';
prefix.num = [1 Inf];
% ---------------------------------------------------------------------
% overwrite Overwrite existing Input/Output Files
% ---------------------------------------------------------------------
overwrite = cfg_menu;
overwrite.tag = 'overwrite';
overwrite.name = 'Overwrite existing Input/Output Files';
overwrite.help = {''};
overwrite.labels = {
'Yes'
'No'
}';
overwrite.values = {true false};
% ---------------------------------------------------------------------
% tbxvol_interleave (De)Interleave Volumes
% ---------------------------------------------------------------------
cfg_tbxvol_interleave = cfg_exbranch;
cfg_tbxvol_interleave.tag = 'tbxvol_interleave';
cfg_tbxvol_interleave.name = '(De)Interleave Volumes';
cfg_tbxvol_interleave.val = {srcimgs sliceorder prefix overwrite };
cfg_tbxvol_interleave.help = {'No help available for topic ''tbxvol_interleave''.'};
cfg_tbxvol_interleave.prog = @tbxvol_interleave;
% ---------------------------------------------------------------------
% srcimg Source Image
% ---------------------------------------------------------------------
srcimg = cfg_files;
srcimg.tag = 'srcimg';
srcimg.name = 'Source Image';
srcimg.help = {''};
srcimg.filter = 'image';
srcimg.ufilter = '.*';
srcimg.num = [1 1];
% ---------------------------------------------------------------------
% repslice Slice to Replace
% ---------------------------------------------------------------------
repslice = cfg_entry;
repslice.tag = 'repslice';
repslice.name = 'Slice to Replace';
repslice.help = {''};
repslice.strtype = 'i';
repslice.num = [1 1];
% ---------------------------------------------------------------------
% prefix Output Filename Prefix
% ---------------------------------------------------------------------
prefix = cfg_entry;
prefix.tag = 'prefix';
prefix.name = 'Output Filename Prefix';
prefix.val = {'R'};
prefix.help = {'The output filename is constructed by prefixing the original filename with this prefix.'};
prefix.strtype = 's';
prefix.num = [1 Inf];
% ---------------------------------------------------------------------
% overwrite Overwrite existing Input/Output Files
% ---------------------------------------------------------------------
overwrite = cfg_menu;
overwrite.tag = 'overwrite';
overwrite.name = 'Overwrite existing Input/Output Files';
overwrite.help = {''};
overwrite.labels = {
'Yes'
'No'
}';
overwrite.values = {true false};
% ---------------------------------------------------------------------
% tbxvol_replace_slice Replace Slice
% ---------------------------------------------------------------------
cfg_tbxvol_replace_slice = cfg_exbranch;
cfg_tbxvol_replace_slice.tag = 'tbxvol_replace_slice';
cfg_tbxvol_replace_slice.name = 'Replace Slice';
cfg_tbxvol_replace_slice.val = {srcimg repslice prefix overwrite };
cfg_tbxvol_replace_slice.help = {'No help available for topic ''tbxvol_replace_slice''.'};
cfg_tbxvol_replace_slice.prog = @tbxvol_replace_slice;
% ---------------------------------------------------------------------
% srcimgs Source Images
% ---------------------------------------------------------------------
srcimgs = cfg_files;
srcimgs.tag = 'srcimgs';
srcimgs.name = 'Source Images';
srcimgs.help = {''};
srcimgs.filter = 'image';
srcimgs.ufilter = '.*';
srcimgs.num = [1 Inf];
% ---------------------------------------------------------------------
% scale New Scaling Factor
% ---------------------------------------------------------------------
scale = cfg_entry;
scale.tag = 'scale';
scale.name = 'New Scaling Factor';
scale.help = {'Set the new scaling factor. To determine this value from your image series, set this field to NaN.'};
scale.strtype = 'e';
scale.num = [1 1];
% ---------------------------------------------------------------------
% offset New Intensity Offset
% ---------------------------------------------------------------------
offset = cfg_entry;
offset.tag = 'offset';
offset.name = 'New Intensity Offset';
offset.help = {''};
offset.strtype = 'e';
offset.num = [1 1];
% ---------------------------------------------------------------------
% dtype Data Type
% ---------------------------------------------------------------------
dtype = cfg_menu;
dtype.tag = 'dtype';
dtype.name = 'Data Type';
dtype.val{1} = double(0);
dtype.help = {'Data-type of output images. SAME indicates the same datatype as the original images.'};
dtype.labels = cellstr(char('SAME',spm_type(spm_type)));
dtype.values = num2cell([0 spm_type]);
% ---------------------------------------------------------------------
% prefix Output Filename Prefix
% ---------------------------------------------------------------------
prefix = cfg_entry;
prefix.tag = 'prefix';
prefix.name = 'Output Filename Prefix';
prefix.val = {'S'};
prefix.help = {'The output filename is constructed by prefixing the original filename with this prefix.'};
prefix.strtype = 's';
prefix.num = [1 Inf];
% ---------------------------------------------------------------------
% overwrite Overwrite existing Input/Output Files
% ---------------------------------------------------------------------
overwrite = cfg_menu;
overwrite.tag = 'overwrite';
overwrite.name = 'Overwrite existing Input/Output Files';
overwrite.help = {''};
overwrite.labels = {
'Yes'
'No'
}';
overwrite.values = {true false};
% ---------------------------------------------------------------------
% tbxvol_rescale Rescale Images
% ---------------------------------------------------------------------
cfg_tbxvol_rescale = cfg_exbranch;
cfg_tbxvol_rescale.tag = 'tbxvol_rescale';
cfg_tbxvol_rescale.name = 'Rescale Images';
cfg_tbxvol_rescale.val = {srcimgs scale offset dtype prefix overwrite };
cfg_tbxvol_rescale.help = {'No help available for topic ''tbxvol_rescale''.'};
cfg_tbxvol_rescale.prog = @tbxvol_rescale;
cfg_tbxvol_rescale.vout = @vout_tbxvol_rescale;
% ---------------------------------------------------------------------
% srcimgs Source Images
% ---------------------------------------------------------------------
srcimgs = cfg_files;
srcimgs.tag = 'srcimgs';
srcimgs.name = 'Source Images';
srcimgs.help = {''};
srcimgs.filter = 'image';
srcimgs.ufilter = '.*';
srcimgs.num = [1 Inf];
% ---------------------------------------------------------------------
% oldscale Old intensity range
% ---------------------------------------------------------------------
oldscale = cfg_entry;
oldscale.tag = 'oldscale';
oldscale.name = 'Old intensity range';
oldscale.help = {'Original data intensity scaling. To derive min/max from the data, set the first or second entry to Inf.'};
oldscale.strtype = 'e';
oldscale.num = [1 2];
% ---------------------------------------------------------------------
% newscale New intensity range
% ---------------------------------------------------------------------
newscale = cfg_entry;
newscale.tag = 'newscale';
newscale.name = 'New intensity range';
newscale.help = {'Set min/max value for new intensity range.'};
newscale.strtype = 'e';
newscale.num = [1 2];
% ---------------------------------------------------------------------
% prefix Output Filename Prefix
% ---------------------------------------------------------------------
prefix = cfg_entry;
prefix.tag = 'prefix';
prefix.name = 'Output Filename Prefix';
prefix.val = {'S'};
prefix.help = {'The output filename is constructed by prefixing the original filename with this prefix.'};
prefix.strtype = 's';
prefix.num = [1 Inf];
% ---------------------------------------------------------------------
% tbxvol_rescale_min_max Rescale Images to [min max]
% ---------------------------------------------------------------------
cfg_tbxvol_rescale_min_max = cfg_exbranch;
cfg_tbxvol_rescale_min_max.tag = 'tbxvol_rescale_min_max';
cfg_tbxvol_rescale_min_max.name = 'Rescale Images to [min max]';
cfg_tbxvol_rescale_min_max.val = {srcimgs oldscale newscale prefix };
cfg_tbxvol_rescale_min_max.help = {'No help available for topic ''tbxvol_rescale_min_max''.'};
cfg_tbxvol_rescale_min_max.prog = @tbxvol_rescale_min_max;
cfg_tbxvol_rescale_min_max.vout = @vout_tbxvol_rescale_min_max;
% ---------------------------------------------------------------------
% srcimgs Source Images
% ---------------------------------------------------------------------
srcimgs = cfg_files;
srcimgs.tag = 'srcimgs';
srcimgs.name = 'Source Images';
srcimgs.help = {''};
srcimgs.filter = 'image';
srcimgs.ufilter = '.*';
srcimgs.num = [1 Inf];
% ---------------------------------------------------------------------
% cor_orig Correct Origin of Wrapped Images
% ---------------------------------------------------------------------
cor_orig = cfg_menu;
cor_orig.tag = 'cor_orig';
cor_orig.name = 'Correct Origin of Wrapped Images';
cor_orig.help = {''};
cor_orig.labels = {
'Yes'
'No'
}';
cor_orig.values = {true false};
% ---------------------------------------------------------------------
% npix #pixels to Unwrap
% ---------------------------------------------------------------------
npix = cfg_entry;
npix.tag = 'npix';
npix.name = '#pixels to Unwrap';
npix.help = {''};
npix.strtype = 'i';
npix.num = [1 1];
% ---------------------------------------------------------------------
% wrapdir Wrap Direction (Voxel Space)
% ---------------------------------------------------------------------
wrapdir = cfg_menu;
wrapdir.tag = 'wrapdir';
wrapdir.name = 'Wrap Direction (Voxel Space)';
wrapdir.help = {''};
wrapdir.labels = {
'X'
'Y'
'Z'
}';
wrapdir.values = {1 2 3};
% ---------------------------------------------------------------------
% prefix Output Filename Prefix
% ---------------------------------------------------------------------
prefix = cfg_entry;
prefix.tag = 'prefix';
prefix.name = 'Output Filename Prefix';
prefix.val = {'U'};
prefix.help = {'The output filename is constructed by prefixing the original filename with this prefix.'};
prefix.strtype = 's';
prefix.num = [1 Inf];
% ---------------------------------------------------------------------
% overwrite Overwrite existing Input/Output Files
% ---------------------------------------------------------------------
overwrite = cfg_menu;
overwrite.tag = 'overwrite';
overwrite.name = 'Overwrite existing Input/Output Files';
overwrite.help = {''};
overwrite.labels = {
'Yes'
'No'
}';
overwrite.values = {true false};
% ---------------------------------------------------------------------
% tbxvol_unwrap Unwrap Volumes
% ---------------------------------------------------------------------
cfg_tbxvol_unwrap = cfg_exbranch;
cfg_tbxvol_unwrap.tag = 'tbxvol_unwrap';
cfg_tbxvol_unwrap.name = 'Unwrap Volumes';
cfg_tbxvol_unwrap.val = {srcimgs cor_orig npix wrapdir prefix overwrite };
cfg_tbxvol_unwrap.help = {'No help available for topic ''tbxvol_unwrap''.'};
cfg_tbxvol_unwrap.prog = @tbxvol_unwrap;
% ---------------------------------------------------------------------
% tbxvol_list_max List Local Maxima
% ---------------------------------------------------------------------
cfg_tbxvol_list_max = cfg_exbranch;
cfg_tbxvol_list_max.tag = 'tbxvol_list_max';
cfg_tbxvol_list_max.name = 'List Local Maxima';
cfg_tbxvol_list_max.val = {srcimgs };
cfg_tbxvol_list_max.help = {'No help available for topic ''tbxvol_list_max''.'};
cfg_tbxvol_list_max.prog = @tbxvol_list_max;
% ---------------------------------------------------------------------
% interp Interpolation
% ---------------------------------------------------------------------
interp = cfg_menu;
interp.tag = 'interp';
interp.name = 'Interpolation';
interp.help = {''};
interp.labels = {
'Integrate (Downsampling only)'
'Nearest neighbour'
'Trilinear'
'2nd Degree b-Spline'
'3rd Degree b-Spline'
'4th Degree b-Spline'
'5th Degree b-Spline'
'6th Degree b-Spline'
'7th Degree b-Spline'
'2nd Degree Sinc'
'3rd Degree Sinc'
'4th Degree Sinc'
'5th Degree Sinc'
'6th Degree Sinc'
'7th Degree Sinc'
}';
interp.values = {NaN 0 1 2 3 4 5 6 7 -2 -3 -4 -5 -6 -7};
% ---------------------------------------------------------------------
% ndim New Image Dimensions
% ---------------------------------------------------------------------
ndim = cfg_entry;
ndim.tag = 'ndim';
ndim.name = 'New Image Dimensions (voxels)';
ndim.help = {'The new image will have the specified matrix size and number of slices.'};
ndim.strtype = 'i';
ndim.num = [1 3];
% ---------------------------------------------------------------------
% vxsz New Voxel Size
% ---------------------------------------------------------------------
vxsz = cfg_entry;
vxsz.tag = 'vxsz';
vxsz.name = 'New Voxel Size (mm)';
vxsz.help = {'The new image will have the specified voxel size.'};
vxsz.strtype = 'r';
vxsz.num = [1 3];
% ---------------------------------------------------------------------
% vxsc Voxel Size Scaling
% ---------------------------------------------------------------------
vxsc = cfg_entry;
vxsc.tag = 'vxsc';
vxsc.name = 'Voxel Size Scaling';
vxsc.help = {'The voxel size in the new image will be the original size multiplied by these scaling factors.'};
vxsc.strtype = 'r';
vxsc.num = [1 3];
% ---------------------------------------------------------------------
% sctype Resampling Specification
% ---------------------------------------------------------------------
sctype = cfg_choice;
sctype.tag = 'sctype';
sctype.name = 'Resampling Specification';
sctype.help = {''};
sctype.values = {ndim vxsz vxsc};
% ---------------------------------------------------------------------
% prefix Output Filename Prefix
% ---------------------------------------------------------------------
prefix = cfg_entry;
prefix.tag = 'prefix';
prefix.name = 'Output Filename Prefix';
prefix.val = {'r'};
prefix.help = {'The output filename is constructed by prefixing the original filename with this prefix.'};
prefix.strtype = 's';
prefix.num = [1 Inf];
% ---------------------------------------------------------------------
% tbxvol_regrid Regrid Volumes
% ---------------------------------------------------------------------
cfg_tbxvol_regrid = cfg_exbranch;
cfg_tbxvol_regrid.tag = 'tbxvol_regrid';
cfg_tbxvol_regrid.name = 'Regrid Volumes';
cfg_tbxvol_regrid.val = {srcimgs interp sctype dtype prefix};
cfg_tbxvol_regrid.help = {'No help available for topic ''tbxvol_regrid''.'};
cfg_tbxvol_regrid.prog = @tbxvol_regrid;
cfg_tbxvol_regrid.vout = @vout_tbxvol_regrid;
% ---------------------------------------------------------------------
% Single_Volumes Single Volumes
% ---------------------------------------------------------------------
Single_Volumes = cfg_choice;
Single_Volumes.tag = 'Single_Volumes';
Single_Volumes.name = 'Single Volumes';
Single_Volumes.help = {''};
Single_Volumes.values = {cfg_tbxvol_extract cfg_tbxvol_flip cfg_tbxvol_get_integrals cfg_tbxvol_histogramm cfg_tbxvol_interleave cfg_tbxvol_replace_slice cfg_tbxvol_rescale cfg_tbxvol_rescale_min_max cfg_tbxvol_unwrap cfg_tbxvol_list_max cfg_tbxvol_regrid};
% ---------------------------------------------------------------------
% srcspm Source SPM.mat
% ---------------------------------------------------------------------
srcspm = cfg_files;
srcspm.tag = 'srcspm';
srcspm.name = 'Source SPM.mat';
srcspm.help = {''};
srcspm.filter = 'mat';
srcspm.ufilter = '.*SPM.*\.mat';
srcspm.num = [1 1];
% ---------------------------------------------------------------------
% nfactor # of Factor with unequal Variance
% ---------------------------------------------------------------------
nfactor = cfg_menu;
nfactor.tag = 'nfactor';
nfactor.name = '# of Factor with unequal Variance';
nfactor.help = {''};
nfactor.labels = {
'Factor 1'
'Factor 2'
'Factor 3'
}';
nfactor.values = {2 3 4};
% ---------------------------------------------------------------------
% tbxvol_correct_ec_SPM Correct Error Covariance components
% ---------------------------------------------------------------------
cfg_tbxvol_correct_ec_SPM = cfg_exbranch;
cfg_tbxvol_correct_ec_SPM.tag = 'tbxvol_correct_ec_SPM';
cfg_tbxvol_correct_ec_SPM.name = 'Correct Error Covariance components';
cfg_tbxvol_correct_ec_SPM.val = {srcspm nfactor };
cfg_tbxvol_correct_ec_SPM.help = {'No help available for topic ''tbxvol_correct_ec_SPM''.'};
cfg_tbxvol_correct_ec_SPM.prog = @tbxvol_correct_ec_SPM;
% ---------------------------------------------------------------------
% srcimgs Source Images
% ---------------------------------------------------------------------
srcimgs = cfg_files;
srcimgs.tag = 'srcimgs';
srcimgs.name = 'Source Images';
srcimgs.help = {''};
srcimgs.filter = 'image';
srcimgs.ufilter = '.*';
srcimgs.num = [1 Inf];
% ---------------------------------------------------------------------
% voxsz Output Image Voxel Size
% ---------------------------------------------------------------------
voxsz = cfg_entry;
voxsz.tag = 'voxsz';
voxsz.name = 'Output Image Voxel Size';
voxsz.help = {''};
voxsz.strtype = 'e';
voxsz.num = [1 3];
% ---------------------------------------------------------------------
% interp Interpolation
% ---------------------------------------------------------------------
interp = cfg_menu;
interp.tag = 'interp';
interp.name = 'Interpolation';
interp.help = {''};
interp.labels = {
'Nearest neighbour'
'Trilinear'
'2nd Degree b-Spline'
'3rd Degree b-Spline'
'4th Degree b-Spline'
'5th Degree b-Spline'
'6th Degree b-Spline'
'7th Degree b-Spline'
'2nd Degree Sinc'
'3rd Degree Sinc'
'4th Degree Sinc'
'5th Degree Sinc'
'6th Degree Sinc'
'7th Degree Sinc'
}';
interp.values = {0 1 2 3 4 5 6 7 -2 -3 -4 -5 -6 -7};
% ---------------------------------------------------------------------
% dtype Data Type
% ---------------------------------------------------------------------
dtype = cfg_menu;
dtype.tag = 'dtype';
dtype.name = 'Data Type';
dtype.val{1} = double(0);
dtype.help = {'Data-type of output images. SAME indicates the same datatype as the original images.'};
dtype.labels = cellstr(char('SAME',spm_type(spm_type)));
dtype.values = num2cell([0 spm_type]);
% ---------------------------------------------------------------------
% prefix Output Filename Prefix
% ---------------------------------------------------------------------
prefix = cfg_entry;
prefix.tag = 'prefix';
prefix.name = 'Output Filename Prefix';
prefix.val = {'C'};
prefix.help = {'The output filename is constructed by prefixing the original filename with this prefix.'};
prefix.strtype = 's';
prefix.num = [1 Inf];
% ---------------------------------------------------------------------
% tbxvol_combine Combine Volumes
% ---------------------------------------------------------------------
cfg_tbxvol_combine = cfg_exbranch;
cfg_tbxvol_combine.tag = 'tbxvol_combine';
cfg_tbxvol_combine.name = 'Combine Volumes';
cfg_tbxvol_combine.val = {srcimgs voxsz interp dtype prefix };
cfg_tbxvol_combine.help = {'No help available for topic ''tbxvol_combine''.'};
cfg_tbxvol_combine.prog = @tbxvol_combine;
% ---------------------------------------------------------------------
% srcimg Mask Image
% ---------------------------------------------------------------------
srcimg = cfg_files;
srcimg.tag = 'srcimg';
srcimg.name = 'Mask Image';
srcimg.help = {''};
srcimg.filter = 'image';
srcimg.ufilter = '.*';
srcimg.num = [1 1];
% ---------------------------------------------------------------------
% srcimgs Source Images for New Mask
% ---------------------------------------------------------------------
srcimgs = cfg_files;
srcimgs.tag = 'srcimgs';
srcimgs.name = 'Source Images for New Mask';
srcimgs.help = {''};
srcimgs.filter = 'image';
srcimgs.ufilter = '.*';
srcimgs.num = [1 Inf];
% ---------------------------------------------------------------------
% maskpredef AND
% ---------------------------------------------------------------------
maskpredef = cfg_const;
maskpredef.tag = 'maskpredef';
maskpredef.name = 'AND';
maskpredef.val = {'and'};
maskpredef.help = {'Mask expression ''(i1~=0) & ... & (iN ~= 0)'''};
% ---------------------------------------------------------------------
% maskpredef OR
% ---------------------------------------------------------------------
maskpredef1 = cfg_const;
maskpredef1.tag = 'maskpredef';
maskpredef1.name = 'OR';
maskpredef1.val = {'or'};
maskpredef1.help = {'Mask expression ''(i1~=0) | ... | (iN ~= 0)'''};
% ---------------------------------------------------------------------
% maskpredef NAND
% ---------------------------------------------------------------------
maskpredef2 = cfg_const;
maskpredef2.tag = 'maskpredef';
maskpredef2.name = 'NAND';
maskpredef2.val = {'nand'};
maskpredef2.help = {'Mask expression ''~((i1~=0) & ... & (iN ~= 0))'''};
% ---------------------------------------------------------------------
% maskpredef NOR
% ---------------------------------------------------------------------
maskpredef3 = cfg_const;
maskpredef3.tag = 'maskpredef';
maskpredef3.name = 'NOR';
maskpredef3.val = {'nor'};
maskpredef3.help = {'Mask expression ''~((i1~=0) | ... | (iN ~= 0))'''};
% ---------------------------------------------------------------------
% maskcustom Custom Mask Expression
% ---------------------------------------------------------------------
maskcustom = cfg_entry;
maskcustom.tag = 'maskcustom';
maskcustom.name = 'Custom Mask Expression';
maskcustom.help = {'Enter a valid expression for spm_imcalc.'};
maskcustom.strtype = 's';
maskcustom.num = [1 Inf];
% ---------------------------------------------------------------------
% mtype Mask Type
% ---------------------------------------------------------------------
mtype = cfg_choice;
mtype.tag = 'mtype';
mtype.name = 'Mask Type';
mtype.help = {''};
mtype.values = {maskpredef maskpredef1 maskpredef2 maskpredef3 maskcustom };
% ---------------------------------------------------------------------
% swd Output directory
% ---------------------------------------------------------------------
swd = cfg_files;
swd.tag = 'swd';
swd.name = 'Output directory';
swd.help = {'Files produced by this function will be written into this output directory'};
swd.filter = 'dir';
swd.ufilter = '.*';
swd.num = [1 1];
% ---------------------------------------------------------------------
% fname Output Filename
% ---------------------------------------------------------------------
fname = cfg_entry;
fname.tag = 'fname';
fname.name = 'Output Filename';
fname.val = {'output.img'};
fname.help = {'The output image is written to the selected working directory.'};
fname.strtype = 's';
fname.num = [1 Inf];
% ---------------------------------------------------------------------
% outimg Mask Image Name & Directory
% ---------------------------------------------------------------------
outimg = cfg_branch;
outimg.tag = 'outimg';
outimg.name = 'Mask Image Name & Directory';
outimg.val = {swd fname };
outimg.help = {'Specify a output filename and target directory.'};
% ---------------------------------------------------------------------
% maskdef Create New Mask
% ---------------------------------------------------------------------
maskdef = cfg_branch;
maskdef.tag = 'maskdef';
maskdef.name = 'Create New Mask';
maskdef.val = {srcimgs mtype outimg };
maskdef.help = {''};
% ---------------------------------------------------------------------
% centers Sphere Centers
% ---------------------------------------------------------------------
centers = cfg_entry;
centers.tag = 'centers';
centers.name = 'Sphere Centers';
centers.help = {['Enter the coordinates of the ROI centers in voxel ' ...
'space of the reference image.']};
centers.strtype = 'e';
centers.num = [Inf 3];
% ---------------------------------------------------------------------
% radii Radii
% ---------------------------------------------------------------------
radii = cfg_entry;
radii.tag = 'radii';
radii.name = 'Radii';
radii.help = {['Enter the radii (in mm). ' ...
'Enter either one radius for all spheres or one per ROI.']};
radii.strtype = 'e';
radii.num = [Inf 1];
% ---------------------------------------------------------------------
% refimg Mask Image
% ---------------------------------------------------------------------
refimg = cfg_files;
refimg.tag = 'refimg';
refimg.name = 'Reference Image';
refimg.help = {['The masks will be created with orientation and voxel ' ...
'size of this image.']};
refimg.filter = 'image';
refimg.ufilter = '.*';
refimg.num = [1 1];
% ---------------------------------------------------------------------
% spheres Create Masks from Coordinates
% ---------------------------------------------------------------------
spheres = cfg_branch;
spheres.tag = 'spheres';
spheres.name = 'Create Masks from Coordinates';
spheres.val = {centers radii refimg outimg};
spheres.check = @(job)tbxvol_create_mask('check',job,'spheres');
% ---------------------------------------------------------------------
% maskspec Mask Specification
% ---------------------------------------------------------------------
maskspec = cfg_choice;
maskspec.tag = 'maskspec';
maskspec.name = 'Mask Specification';
maskspec.help = {
'Specify an existing mask image or a set of images '
'that will be used to create a mask image.'
}';
maskspec.values = {srcimg maskdef spheres };
% ---------------------------------------------------------------------
% srcimgs Source Images
% ---------------------------------------------------------------------
srcimgs = cfg_files;
srcimgs.tag = 'srcimgs';
srcimgs.name = 'Source Images';
srcimgs.help = {''};
srcimgs.filter = 'image';
srcimgs.ufilter = '.*';
srcimgs.num = [1 Inf];
% ---------------------------------------------------------------------
% scope Scope of Mask
% ---------------------------------------------------------------------
scope = cfg_menu;
scope.tag = 'scope';
scope.name = 'Scope of Mask';
scope.help = {'Specify which parts of the images should be kept: parts where the mask image is different from zero (inclusive) or parts where the mask image is zero (exclusive).'};
scope.labels = {
'Inclusive'
'Exclusive'
}';
scope.values = {
'i'
'e'
}';
% ---------------------------------------------------------------------
% space Space of Masked Images
% ---------------------------------------------------------------------
space = cfg_menu;
space.tag = 'space';
space.name = 'Space of Masked Images';
space.help = {'Specify whether the masked images should be written with orientation and voxel size of the original images or of the mask image.'};
space.labels = {
'Object'
'Mask'
}';
space.values = {
'object'
'mask'
}';
% ---------------------------------------------------------------------
% prefix Output Filename Prefix
% ---------------------------------------------------------------------
prefix = cfg_entry;
prefix.tag = 'prefix';
prefix.name = 'Output Filename Prefix';
prefix.val = {'M'};
prefix.help = {'The output filename is constructed by prefixing the original filename with this prefix.'};
prefix.strtype = 's';
prefix.num = [1 Inf];
% ---------------------------------------------------------------------
% interp Interpolation
% ---------------------------------------------------------------------
interp = cfg_menu;
interp.tag = 'interp';
interp.name = 'Interpolation';
interp.help = {''};
interp.labels = {
'Nearest neighbour'
'Trilinear'
'2nd Degree b-Spline'
'3rd Degree b-Spline'
'4th Degree b-Spline'
'5th Degree b-Spline'
'6th Degree b-Spline'
'7th Degree b-Spline'
'2nd Degree Sinc'
'3rd Degree Sinc'
'4th Degree Sinc'
'5th Degree Sinc'
'6th Degree Sinc'
'7th Degree Sinc'
}';
interp.values = {0 1 2 3 4 5 6 7 -2 -3 -4 -5 -6 -7};
% ---------------------------------------------------------------------
% nanmask Zero/NaN Masking
% ---------------------------------------------------------------------
nanmask = cfg_menu;
nanmask.tag = 'nanmask';
nanmask.name = 'Zero/NaN Masking';
nanmask.help = {'For data types without a representation of NaN, implicit zero masking assummes that all zero voxels are to be treated as missing, and treats them as NaN. NaN''s are written as zero (by spm_write_plane), for data types without a representation of NaN.'};
nanmask.labels = {
'No implicit zero mask'
'Implicit zero mask'
'NaNs should be zeroed'
}';
nanmask.values = {0 1 -1};
% ---------------------------------------------------------------------
% maskthresh Threshold for masking
% ---------------------------------------------------------------------
maskthresh = cfg_entry;
maskthresh.tag = 'maskthresh';
maskthresh.name = 'Threshold for masking';
maskthresh.help = {'Sometimes zeroes are represented as non-zero values due to rounding errors (especially in binary masks). Specify a small non-zero value for zero masking in this case.'};
maskthresh.strtype = 'e';
maskthresh.num = [1 1];
% ---------------------------------------------------------------------
% overwrite Overwrite existing Input/Output Files
% ---------------------------------------------------------------------
overwrite = cfg_menu;
overwrite.tag = 'overwrite';
overwrite.name = 'Overwrite existing Input/Output Files';
overwrite.help = {''};
overwrite.labels = {
'Yes'
'No'
}';
overwrite.values = {true false};
% ---------------------------------------------------------------------
% srcspec Apply Created Mask
% ---------------------------------------------------------------------
srcspec = cfg_branch;
srcspec.tag = 'srcspec';
srcspec.name = 'Apply Created Mask';
srcspec.val = {srcimgs scope space prefix interp nanmask maskthresh overwrite };
srcspec.help = {'Specify images which are to be masked.'};
% ---------------------------------------------------------------------
% unused Apply Masks
% ---------------------------------------------------------------------
unused = cfg_repeat;
unused.tag = 'unused';
unused.name = 'Apply Masks';
unused.help = {''};
unused.values = {srcspec };
unused.num = [0 Inf];
% ---------------------------------------------------------------------
% tbxvol_create_mask Create and Apply Masks
% ---------------------------------------------------------------------
cfg_tbxvol_create_mask = cfg_exbranch;
cfg_tbxvol_create_mask.tag = 'tbxvol_create_mask';
cfg_tbxvol_create_mask.name = 'Create and Apply Masks';
cfg_tbxvol_create_mask.val = {maskspec unused };
cfg_tbxvol_create_mask.help = {'No help available for topic ''tbxvol_create_mask''.'};
cfg_tbxvol_create_mask.prog = @(job)tbxvol_create_mask('run',job);
cfg_tbxvol_create_mask.vout = @(job)tbxvol_create_mask('vout',job);
% ---------------------------------------------------------------------
% srcimgs Source Images
% ---------------------------------------------------------------------
srcimgs = cfg_files;
srcimgs.tag = 'srcimgs';
srcimgs.name = 'Source Images';
srcimgs.help = {''};
srcimgs.filter = 'image';
srcimgs.ufilter = '.*';
srcimgs.num = [1 Inf];
% ---------------------------------------------------------------------
% bbox Bounding Box for Extracted Image
% ---------------------------------------------------------------------
bbox = cfg_entry;
bbox.tag = 'bbox';
bbox.name = 'Bounding Box for Extracted Image';
bbox.help = {
'Specify the bounding box in voxel coordinates of '
'the original image: X1 X2 Y1 Y2 Z1 Z2.'
}';
bbox.strtype = 'i';
bbox.num = [1 6];
% ---------------------------------------------------------------------
% prefix Output Filename Prefix
% ---------------------------------------------------------------------
prefix = cfg_entry;
prefix.tag = 'prefix';
prefix.name = 'Output Filename Prefix';
prefix.val = {'E'};
prefix.help = {'The output filename is constructed by prefixing the original filename with this prefix.'};
prefix.strtype = 's';
prefix.num = [1 Inf];
% ---------------------------------------------------------------------
% tbxvol_extract_subvol Extract Subvolume
% ---------------------------------------------------------------------
cfg_tbxvol_extract_subvol = cfg_exbranch;
cfg_tbxvol_extract_subvol.tag = 'tbxvol_extract_subvol';
cfg_tbxvol_extract_subvol.name = 'Extract Subvolume';
cfg_tbxvol_extract_subvol.val = {srcimgs bbox prefix };
cfg_tbxvol_extract_subvol.help = {'No help available for topic ''tbxvol_extract_subvol''.'};
cfg_tbxvol_extract_subvol.prog = @tbxvol_extract_subvol;
% ---------------------------------------------------------------------
% source Source Images
% ---------------------------------------------------------------------
source = cfg_files;
source.tag = 'source';
source.name = 'Source Images';
source.help = {'The images that are warped to match the template(s). The result is a set of warps, which can be applied to this image, or any other image that is in register with it.'};
source.filter = 'image';
source.ufilter = '.*';
source.num = [1 Inf];
% ---------------------------------------------------------------------
% wtsrc Source Weighting Image
% ---------------------------------------------------------------------
wtsrc = cfg_files;
wtsrc.tag = 'wtsrc';
wtsrc.name = 'Source Weighting Image';
wtsrc.val{1} = {};
wtsrc.help = {'Optional weighting images (consisting of pixel values between the range of zero to one) to be used for registering abnormal or lesioned brains. These images should match the dimensions of the image from which the parameters are estimated, and should contain zeros corresponding to regions of abnormal tissue.'};
wtsrc.filter = 'image';
wtsrc.ufilter = '.*';
wtsrc.num = [0 1];
% ---------------------------------------------------------------------
% subj Subjects
% ---------------------------------------------------------------------
subj = cfg_branch;
subj.tag = 'subj';
subj.name = 'Subjects';
subj.val = {source wtsrc };
subj.help = {'Data for all subjects. The same parameters are used within subject.'};
% ---------------------------------------------------------------------
% template Template Image
% ---------------------------------------------------------------------
template = cfg_files;
template.tag = 'template';
template.name = 'Template Image';
template.help = {
'Specify a template image to match the source image with. The contrast in the template must be similar to that of the source image in order to achieve a good registration. It is also possible to select more than one template, in which case the registration algorithm will try to find the best linear combination of these images in order to best model the intensities in the source image.'
''
'The template(s) will be used for the first iteration of within-group normalisation. Further iterations will use an average version of the normalised images as template.'
}';
template.filter = 'image';
template.ufilter = '.*';
template.num = [1 Inf];
% ---------------------------------------------------------------------
% weight Template Weighting Image
% ---------------------------------------------------------------------
weight = cfg_files;
weight.tag = 'weight';
weight.name = 'Template Weighting Image';
weight.help = {
'Applies a weighting mask to the template(s) during the parameter estimation. With the default brain mask, weights in and around the brain have values of one whereas those clearly outside the brain are zero. This is an attempt to base the normalization purely upon the shape of the brain, rather than the shape of the head (since low frequency basis functions can not really cope with variations in skull thickness).'
''
'The option is now available for a user specified weighting image. This should have the same dimensions and mat file as the template images, with values in the range of zero to one.'
}';
weight.filter = 'image';
weight.ufilter = '.*';
weight.num = [0 1];
% ---------------------------------------------------------------------
% stempl Initial normalisation template
% ---------------------------------------------------------------------
stempl = cfg_branch;
stempl.tag = 'stempl';
stempl.name = 'Initial normalisation template';
stempl.val = {template weight };
stempl.help = {''};
% ---------------------------------------------------------------------
% sparams Initial normalisation params
% ---------------------------------------------------------------------
sparams = cfg_files;
sparams.tag = 'sparams';
sparams.name = 'Initial normalisation params';
sparams.help = {''};
sparams.filter = 'mat';
sparams.ufilter = '.*sn.mat$';
sparams.num = [0 Inf];
% ---------------------------------------------------------------------
% starting Initial Normalisation
% ---------------------------------------------------------------------
starting = cfg_choice;
starting.tag = 'starting';
starting.name = 'Initial Normalisation';
starting.help = {''};
starting.values = {stempl sparams };
% ---------------------------------------------------------------------
% smosrc Source Image Smoothing
% ---------------------------------------------------------------------
smosrc = cfg_entry;
smosrc.tag = 'smosrc';
smosrc.name = 'Source Image Smoothing';
smosrc.help = {'Smoothing to apply to a copy of the source image. The template and source images should have approximately the same smoothness. Remember that the templates supplied with SPM have been smoothed by 8mm, and that smoothnesses combine by Pythagoras'' rule.'};
smosrc.strtype = 'e';
smosrc.num = [1 1];
% ---------------------------------------------------------------------
% smoref Template Image Smoothing
% ---------------------------------------------------------------------
smoref = cfg_entry;
smoref.tag = 'smoref';
smoref.name = 'Template Image Smoothing';
smoref.help = {'Smoothing to apply to a copy of the template image. The template and source images should have approximately the same smoothness. Remember that the templates supplied with SPM have been smoothed by 8mm, and that smoothnesses combine by Pythagoras'' rule.'};
smoref.strtype = 'e';
smoref.num = [1 1];
% ---------------------------------------------------------------------
% regtype Affine Regularisation
% ---------------------------------------------------------------------
regtype = cfg_menu;
regtype.tag = 'regtype';
regtype.name = 'Affine Regularisation';
regtype.help = {'Affine registration into a standard space can be made more robust by regularisation (penalising excessive stretching or shrinking). The best solutions can be obtained by knowing the approximate amount of stretching that is needed (e.g. ICBM templates are slightly bigger than typical brains, so greater zooms are likely to be needed). If registering to an image in ICBM/MNI space, then choose the first option. If registering to a template that is close in size, then select the second option. If you do not want to regularise, then choose the third.'};
regtype.labels = {
'ICBM space template'
'Average sized template'
'No regularisation'
}';
regtype.values = {
'mni'
'subj'
'none'
}';
% ---------------------------------------------------------------------
% cutoff Nonlinear Frequency Cutoff
% ---------------------------------------------------------------------
cutoff = cfg_entry;
cutoff.tag = 'cutoff';
cutoff.name = 'Nonlinear Frequency Cutoff';
cutoff.help = {'Cutoff of DCT bases. Only DCT bases of periods longer than the cutoff are used to describe the warps. The number used will depend on the cutoff and the field of view of the template image(s).'};
cutoff.strtype = 'e';
cutoff.num = [1 1];
% ---------------------------------------------------------------------
% nits Nonlinear Iterations
% ---------------------------------------------------------------------
nits = cfg_entry;
nits.tag = 'nits';
nits.name = 'Nonlinear Iterations';
nits.help = {'Number of iterations of nonlinear warping performed.'};
nits.strtype = 'w';
nits.num = [1 1];
% ---------------------------------------------------------------------
% reg Nonlinear Regularisation
% ---------------------------------------------------------------------
reg = cfg_entry;
reg.tag = 'reg';
reg.name = 'Nonlinear Regularisation';
reg.help = {'The amount of regularisation for the nonlinear part of the spatial normalisation. Pick a value around one. However, if your normalized images appear distorted, then it may be an idea to increase the amount of regularization (by an order of magnitude) - or even just use an affine normalization. The regularization influences the smoothness of the deformation fields.'};
reg.strtype = 'e';
reg.num = [1 1];
% ---------------------------------------------------------------------
% iteration Iteration Options
% ---------------------------------------------------------------------
iteration = cfg_branch;
iteration.tag = 'iteration';
iteration.name = 'Iteration Options';
iteration.val = {smosrc smoref regtype cutoff nits reg };
iteration.help = {'Various settings for estimating warps.'};
% ---------------------------------------------------------------------
% iterations Estimation Iterations
% ---------------------------------------------------------------------
iterations = cfg_repeat;
iterations.tag = 'iterations';
iterations.name = 'Estimation Iterations';
iterations.help = {''};
iterations.values = {iteration };
iterations.num = [1 Inf];
% ---------------------------------------------------------------------
% eoptions Estimation Options
% ---------------------------------------------------------------------
eoptions = cfg_branch;
eoptions.tag = 'eoptions';
eoptions.name = 'Estimation Options';
eoptions.val = {starting iterations };
eoptions.help = {''};
% ---------------------------------------------------------------------
% tbxvol_normalise Group Normalise
% ---------------------------------------------------------------------
cfg_tbxvol_normalise = cfg_exbranch;
cfg_tbxvol_normalise.tag = 'tbxvol_normalise';
cfg_tbxvol_normalise.name = 'Group Normalise';
cfg_tbxvol_normalise.val = {subj eoptions };
cfg_tbxvol_normalise.help = {''};
cfg_tbxvol_normalise.prog = @tbxvol_normalise;
cfg_tbxvol_normalise.vfiles = @vfiles_tbxvol_normalise;
cfg_tbxvol_normalise.modality = {
'FMRI'
'PET'
'VBM'
}';
% ---------------------------------------------------------------------
% srcimgs Source Images
% ---------------------------------------------------------------------
srcimgs = cfg_files;
srcimgs.tag = 'srcimgs';
srcimgs.name = 'Source Images';
srcimgs.help = {''};
srcimgs.filter = 'image';
srcimgs.ufilter = '.*';
srcimgs.num = [1 Inf];
% ---------------------------------------------------------------------
% sliceorder Slice/Volume Order
% ---------------------------------------------------------------------
sliceorder = cfg_menu;
sliceorder.tag = 'sliceorder';
sliceorder.name = 'Slice/Volume Order';
sliceorder.help = {''};
sliceorder.labels = {
'Vol1 Slice1..N,...VolM Slice1..N'
'VolM Slice1..N,...Vol1 Slice1..N'
'Slice1 Vol1..M,...SliceN Vol1..M'
'Slice1 VolM..1,...SliceN VolM..1'
}';
sliceorder.values = {
'volume'
'volume_vrev'
'slice'
'slice_vrev'
}';
% ---------------------------------------------------------------------
% noutput #Output Images
% ---------------------------------------------------------------------
noutput = cfg_entry;
noutput.tag = 'noutput';
noutput.name = '#Output Images';
noutput.help = {''};
noutput.strtype = 'i';
noutput.num = [1 1];
% ---------------------------------------------------------------------
% thickcorr Correct Slice Thickness
% ---------------------------------------------------------------------
thickcorr = cfg_menu;
thickcorr.tag = 'thickcorr';
thickcorr.name = 'Correct Slice Thickness';
thickcorr.help = {'If set to ''yes'', the slice thickness is multiplied by the #output images.'};
thickcorr.labels = {
'Yes'
'No'
}';
thickcorr.values = {true false};
% ---------------------------------------------------------------------
% tbxvol_split Split Volumes
% ---------------------------------------------------------------------
cfg_tbxvol_split = cfg_exbranch;
cfg_tbxvol_split.tag = 'tbxvol_split';
cfg_tbxvol_split.name = 'Split Volumes';
cfg_tbxvol_split.val = {srcimgs sliceorder noutput thickcorr };
cfg_tbxvol_split.help = {'No help available for topic ''tbxvol_split''.'};
cfg_tbxvol_split.prog = @tbxvol_split;
cfg_tbxvol_split.vfiles = @vfiles_tbxvol_split;
% ---------------------------------------------------------------------
% srcimgs Source Images
% ---------------------------------------------------------------------
srcimgs = cfg_files;
srcimgs.tag = 'srcimgs';
srcimgs.name = 'Source Images';
srcimgs.help = {''};
srcimgs.filter = 'image';
srcimgs.ufilter = '.*';
srcimgs.num = [1 Inf];
% ---------------------------------------------------------------------
% spikethr Threshold (in standard deviations)
% ---------------------------------------------------------------------
spikethr = cfg_entry;
spikethr.tag = 'spikethr';
spikethr.name = 'Threshold (in standard deviations)';
spikethr.help = {''};
spikethr.strtype = 'e';
spikethr.num = [1 1];
% ---------------------------------------------------------------------
% tbxvol_spike Detect abnormal slices
% ---------------------------------------------------------------------
cfg_tbxvol_spike = cfg_exbranch;
cfg_tbxvol_spike.tag = 'tbxvol_spike';
cfg_tbxvol_spike.name = 'Detect abnormal slices';
cfg_tbxvol_spike.val = {srcimgs spikethr };
cfg_tbxvol_spike.help = {'No help available for topic ''tbxvol_spike''.'};
cfg_tbxvol_spike.prog = @tbxvol_spike;
% ---------------------------------------------------------------------
% srcimgs - Source Images
% ---------------------------------------------------------------------
srcimgs = cfg_files;
srcimgs.tag = 'srcimgs';
srcimgs.name = 'Source Images';
srcimgs.help = {'A list of images to be analysed. The computed selection indices will refer to this list of images.'};
srcimgs.filter = 'image';
srcimgs.ufilter = '.*';
srcimgs.num = [1 Inf];
% ---------------------------------------------------------------------
% maskimg - Mask Image
% ---------------------------------------------------------------------
maskimg = cfg_files;
maskimg.tag = 'maskimg';
maskimg.name = 'Mask Image';
maskimg.help = {'Each source image will be weighted by this mask image before thresholding.'
'The mask image should have values between 0 (voxel does not belong to ROI) and 1 (voxel does belong to ROI). Fractional values are allowed.'};
maskimg.filter = 'image';
maskimg.ufilter = '.*';
maskimg.num = [1 1];
% ---------------------------------------------------------------------
% invert - Invert Mask
% ---------------------------------------------------------------------
invert = cfg_menu;
invert.tag = 'invert';
invert.name = 'Invert Mask';
invert.help = {'Yes: source images will be masked with (1-mask value).'
'No: source images will be masked with (mask value).'};
invert.labels = {'Yes'; 'No'};
invert.values = {true; false};
% ---------------------------------------------------------------------
% masking - Mask Specification
% ---------------------------------------------------------------------
masking = cfg_branch;
masking.tag = 'masking';
masking.name = 'Mask Specification';
masking.val = {maskimg invert};
% ---------------------------------------------------------------------
% thresh - Threshold
% ---------------------------------------------------------------------
thresh = cfg_entry;
thresh.tag = 'thresh';
thresh.name = 'Intensity Threshold';
thresh.help = {'Voxels with a value higher than this threshold will be counted as ''bad''.'};
thresh.strtype = 'r';
thresh.num = [1 1];
% ---------------------------------------------------------------------
% ratio - Bad Voxels per Slice Ratio
% ---------------------------------------------------------------------
ratio = cfg_entry;
ratio.tag = 'ratio';
ratio.name = 'Bad Voxels per Slice Ratio';
ratio.help = {'If the ratio of ''bad'' voxels to inmask volume exceeds this ratio a slice will be marked ''bad'' and the volume will be discarded.'};
ratio.strtype = 'r';
ratio.num = [1 1];
% ---------------------------------------------------------------------
% crit - Exclusion Criteria
% ---------------------------------------------------------------------
crit = cfg_branch;
crit.tag = 'crit';
crit.name = 'Exclusion Criteria';
crit.val = {thresh ratio};
% ---------------------------------------------------------------------
% cfg_tbxvol_spike_mask - Detect Spikes in Mask
% ---------------------------------------------------------------------
cfg_tbxvol_spike_mask = cfg_exbranch;
cfg_tbxvol_spike_mask.tag = 'tbxvol_spike_mask';
cfg_tbxvol_spike_mask.name = 'Detect Spikes in Mask';
cfg_tbxvol_spike_mask.val = {srcimgs masking crit};
cfg_tbxvol_spike_mask.help = {'A very crude method to detect spikes.'
['Images will be weighted by the mask image or its inverse (1-mask). ', ...
'Afterwards, for each slice the number of voxels exceeding the ', ...
'specified threshold will be counted. Images will be marked ''bad'' ', ...
'if more than a specified percentage of voxels per slice exceed the threshold.']
'This method is useful to detect rare spikes on a set of e.g. '
'standard deviation images of a time series.'};
cfg_tbxvol_spike_mask.prog = @(job)tbxvol_spike_mask('run', job);
cfg_tbxvol_spike_mask.vout = @(job)tbxvol_spike_mask('vout', job);
% ---------------------------------------------------------------------
% srcimgs Images
% ---------------------------------------------------------------------
srcimgs = cfg_files;
srcimgs.tag = 'srcimgs';
srcimgs.name = 'Images';
srcimgs.help = {'These images will be read and their histogramms displayed.'};
srcimgs.filter = 'image';
srcimgs.ufilter = '.*';
srcimgs.num = [1 Inf];
% ---------------------------------------------------------------------
% int Intensity Range
% ---------------------------------------------------------------------
int = cfg_entry;
int.tag = 'int';
int.name = 'Intensity Range';
int.help = {'The histogramm will only be created from voxels with intensities in this range.'};
int.strtype = 'r';
int.num = [1 2];
% ---------------------------------------------------------------------
% hstart Image #s
% ---------------------------------------------------------------------
hstart = cfg_entry;
hstart.tag = 'hstart';
hstart.name = 'Image #s';
hstart.help = {'Image numbers (in the input image list) for which histogramms should be created.'};
hstart.strtype = 'n';
hstart.num = [1 Inf];
% ---------------------------------------------------------------------
% hnum #Averages
% ---------------------------------------------------------------------
hnum = cfg_entry;
hnum.tag = 'hnum';
hnum.name = '#Averages';
hnum.help = {'The number of consecutive image to average in one histogramm.'};
hnum.strtype = 'n';
hnum.num = [1 1];
% ---------------------------------------------------------------------
% nbins Histogramm timebins
% ---------------------------------------------------------------------
nbins = cfg_entry;
nbins.tag = 'nbins';
nbins.name = 'Histogramm timebins';
nbins.strtype = 'n';
nbins.num = [1 1];
% ---------------------------------------------------------------------
% holdhist Reference Histogramms
% ---------------------------------------------------------------------
holdhist = cfg_menu;
holdhist.tag = 'holdhist';
holdhist.name = 'Reference Histogramms';
holdhist.labels = {
'First'
'Last'
'Both'
'None'
}';
holdhist.values = {
'first'
'last'
'both'
'none'
}';
% ---------------------------------------------------------------------
% cfg_tbxvol_histogramm_movie Histogramm movie
% ---------------------------------------------------------------------
cfg_tbxvol_histogramm_movie = cfg_exbranch;
cfg_tbxvol_histogramm_movie.tag = 'cfg_tbxvol_histogramm_movie';
cfg_tbxvol_histogramm_movie.name = 'Histogramm movie';
cfg_tbxvol_histogramm_movie.val = {srcimgs int hstart hnum nbins holdhist };
cfg_tbxvol_histogramm_movie.check = @(job)tbxvol_histogramm_movie('check',job);
cfg_tbxvol_histogramm_movie.prog = @(job)tbxvol_histogramm_movie('run',job);
cfg_tbxvol_histogramm_movie.vout = @(job)tbxvol_histogramm_movie('vout',job);
% ---------------------------------------------------------------------
% Multiple_Volumes Multiple Volumes
% ---------------------------------------------------------------------
Multiple_Volumes = cfg_choice;
Multiple_Volumes.tag = 'Multiple_Volumes';
Multiple_Volumes.name = 'Multiple Volumes';
Multiple_Volumes.help = {''};
Multiple_Volumes.values = {cfg_tbxvol_correct_ec_SPM cfg_tbxvol_combine cfg_tbxvol_create_mask cfg_tbxvol_extract_subvol cfg_tbxvol_normalise cfg_tbxvol_split cfg_tbxvol_spike cfg_tbxvol_spike_mask cfg_tbxvol_histogramm_movie cfg_tbxvol_gw_boundary};
% ---------------------------------------------------------------------
% srcspm Source SPM.mat
% ---------------------------------------------------------------------
srcspm = cfg_files;
srcspm.tag = 'srcspm';
srcspm.name = 'Source SPM.mat';
srcspm.help = {''};
srcspm.filter = 'mat';
srcspm.ufilter = '.*SPM.*\.mat';
srcspm.num = [1 1];
% ---------------------------------------------------------------------
% newpath Path Component to be inserted
% ---------------------------------------------------------------------
newpath = cfg_menu;
newpath.tag = 'newpath';
newpath.name = 'Path Component to be inserted';
newpath.help = {
'The tool tries to quess which parts of the path names need to be replaced by comparing the path stored in SPM.swd with the current path to the SPM.mat file. '
'This does not always work as expected, confirmation before replacement is strongly advised.'
}';
newpath.labels = {
'Determine and insert'
'Ask before inserting'
}';
newpath.values = {
'auto'
'ask'
}';
% ---------------------------------------------------------------------
% oldpath Path Component to be replaced
% ---------------------------------------------------------------------
oldpath = cfg_menu;
oldpath.tag = 'oldpath';
oldpath.name = 'Path Component to be replaced';
oldpath.help = {
'The tool tries to guess which parts of the path names need to be replaced by comparing the path stored in SPM.swd with the current path to the SPM.mat file. '
'This does not always work as expected, confirmation before replacement is strongly advised.'
}';
oldpath.labels = {
'Determine and replace'
'Ask before replacing'
}';
oldpath.values = {
'auto'
'ask'
}';
% ---------------------------------------------------------------------
% dpaths Data Files
% ---------------------------------------------------------------------
dpaths = cfg_branch;
dpaths.tag = 'dpaths';
dpaths.name = 'Data Files';
dpaths.val = {newpath oldpath };
dpaths.help = {''};
% ---------------------------------------------------------------------
% newpath Path Component to be inserted
% ---------------------------------------------------------------------
newpath = cfg_menu;
newpath.tag = 'newpath';
newpath.name = 'Path Component to be inserted';
newpath.help = {
'The tool tries to quess which parts of the path names need to be replaced by comparing the path stored in SPM.swd with the current path to the SPM.mat file. '
'This does not always work as expected, confirmation before replacement is strongly advised.'
}';
newpath.labels = {
'Determine and insert'
'Ask before inserting'
}';
newpath.values = {
'auto'
'ask'
}';
% ---------------------------------------------------------------------
% oldpath Path Component to be replaced
% ---------------------------------------------------------------------
oldpath = cfg_menu;
oldpath.tag = 'oldpath';
oldpath.name = 'Path Component to be replaced';
oldpath.help = {
'The tool tries to guess which parts of the path names need to be replaced by comparing the path stored in SPM.swd with the current path to the SPM.mat file. '
'This does not always work as expected, confirmation before replacement is strongly advised.'
}';
oldpath.labels = {
'Determine and replace'
'Ask before replacing'
}';
oldpath.values = {
'auto'
'ask'
}';
% ---------------------------------------------------------------------
% apaths Analysis Files
% ---------------------------------------------------------------------
apaths = cfg_branch;
apaths.tag = 'apaths';
apaths.name = 'Analysis Files';
apaths.val = {newpath oldpath };
apaths.help = {''};
% ---------------------------------------------------------------------
% newpath Path Component to be inserted
% ---------------------------------------------------------------------
newpath = cfg_menu;
newpath.tag = 'newpath';
newpath.name = 'Path Component to be inserted';
newpath.help = {
'The tool tries to quess which parts of the path names need to be replaced by comparing the path stored in SPM.swd with the current path to the SPM.mat file. '
'This does not always work as expected, confirmation before replacement is strongly advised.'
}';
newpath.labels = {
'Determine and insert'
'Ask before inserting'
}';
newpath.values = {
'auto'
'ask'
}';
% ---------------------------------------------------------------------
% oldpath Path Component to be replaced
% ---------------------------------------------------------------------
oldpath = cfg_menu;
oldpath.tag = 'oldpath';
oldpath.name = 'Path Component to be replaced';
oldpath.help = {
'The tool tries to guess which parts of the path names need to be replaced by comparing the path stored in SPM.swd with the current path to the SPM.mat file. '
'This does not always work as expected, confirmation before replacement is strongly advised.'
}';
oldpath.labels = {
'Determine and replace'
'Ask before replacing'
}';
oldpath.values = {
'auto'
'ask'
}';
% ---------------------------------------------------------------------
% bpaths Data&Analysis Files
% ---------------------------------------------------------------------
bpaths = cfg_branch;
bpaths.tag = 'bpaths';
bpaths.name = 'Data&Analysis Files';
bpaths.val = {newpath oldpath };
bpaths.help = {''};
% ---------------------------------------------------------------------
% npaths None
% ---------------------------------------------------------------------
npaths = cfg_const;
npaths.tag = 'npaths';
npaths.name = 'None';
npaths.val{1} = double(0);
npaths.help = {''};
% ---------------------------------------------------------------------
% chpaths Paths to change
% ---------------------------------------------------------------------
chpaths = cfg_choice;
chpaths.tag = 'chpaths';
chpaths.name = 'Paths to change';
chpaths.help = {''};
chpaths.values = {dpaths apaths bpaths npaths };
% ---------------------------------------------------------------------
% swap Change Byte Order Information for Mapped Images?
% ---------------------------------------------------------------------
swap = cfg_menu;
swap.tag = 'swap';
swap.name = 'Change Byte Order Information for Mapped Images?';
swap.help = {'This option may be obsolete for SPM5. With SPM2-style analyses, byte order of an image was stored at the time statistics were run. If one later moved the SPM.mat and analysis files to a machine with different byte order, this was not realised by SPM.'};
swap.labels = {
'Yes'
'No'
}';
swap.values = {true false};
% ---------------------------------------------------------------------
% tbxvol_changeSPM Change SPM.mat Image Information
% ---------------------------------------------------------------------
cfg_tbxvol_changeSPM = cfg_exbranch;
cfg_tbxvol_changeSPM.tag = 'tbxvol_changeSPM';
cfg_tbxvol_changeSPM.name = 'Change SPM.mat Image Information';
cfg_tbxvol_changeSPM.val = {srcspm chpaths swap };
cfg_tbxvol_changeSPM.help = {'No help available for topic ''tbxvol_changeSPM''.'};
cfg_tbxvol_changeSPM.prog = @tbxvol_changeSPM;
% ---------------------------------------------------------------------
% srcspm Source SPM.mat
% ---------------------------------------------------------------------
srcspm = cfg_files;
srcspm.tag = 'srcspm';
srcspm.name = 'Source SPM.mat';
srcspm.help = {''};
srcspm.filter = 'mat';
srcspm.ufilter = '.*SPM.*\.mat';
srcspm.num = [1 1];
% ---------------------------------------------------------------------
% nfactor # of Factor with unequal Variance
% ---------------------------------------------------------------------
nfactor = cfg_menu;
nfactor.tag = 'nfactor';
nfactor.name = '# of Factor with unequal Variance';
nfactor.help = {''};
nfactor.labels = {
'Factor 1'
'Factor 2'
'Factor 3'
}';
nfactor.values = {2 3 4};
% ---------------------------------------------------------------------
% tbxvol_correct_ec_SPM Correct Error Covariance components
% ---------------------------------------------------------------------
cfg_tbxvol_correct_ec_SPM = cfg_exbranch;
cfg_tbxvol_correct_ec_SPM.tag = 'tbxvol_correct_ec_SPM';
cfg_tbxvol_correct_ec_SPM.name = 'Correct Error Covariance components';
cfg_tbxvol_correct_ec_SPM.val = {srcspm nfactor };
cfg_tbxvol_correct_ec_SPM.help = {'No help available for topic ''tbxvol_correct_ec_SPM''.'};
cfg_tbxvol_correct_ec_SPM.prog = @tbxvol_correct_ec_SPM;
% ---------------------------------------------------------------------
% srcimgs Source Images
% ---------------------------------------------------------------------
srcimgs = cfg_files;
srcimgs.tag = 'srcimgs';
srcimgs.name = 'Source Images';
srcimgs.help = {''};
srcimgs.filter = 'image';
srcimgs.ufilter = '.*';
srcimgs.num = [1 Inf];
% ---------------------------------------------------------------------
% option Select output map
% ---------------------------------------------------------------------
option = cfg_menu;
option.tag = 'option';
option.name = 'Select output map';
option.help = {''};
option.labels = {
'p'
'-log(1-p)'
'correlation coefficient cc'
'effect size d'
}';
option.values = {1 2 3 4};
% ---------------------------------------------------------------------
% tbxvol_transform_t2x Transform t maps
% ---------------------------------------------------------------------
cfg_tbxvol_transform_t2x = cfg_exbranch;
cfg_tbxvol_transform_t2x.tag = 'tbxvol_transform_t2x';
cfg_tbxvol_transform_t2x.name = 'Transform t maps';
cfg_tbxvol_transform_t2x.val = {srcimgs option };
cfg_tbxvol_transform_t2x.help = {'No help available for topic ''tbxvol_transform_t2x''.'};
cfg_tbxvol_transform_t2x.prog = @tbxvol_transform_t2x;
cfg_tbxvol_transform_t2x.vfiles = @vfiles_tbxvol_transform_t2x;
% ---------------------------------------------------------------------
% srcimgs Source Images
% ---------------------------------------------------------------------
srcimgs = cfg_files;
srcimgs.tag = 'srcimgs';
srcimgs.name = 'Source Images';
srcimgs.help = {''};
srcimgs.filter = 'image';
srcimgs.ufilter = '.*';
srcimgs.num = [1 Inf];
% ---------------------------------------------------------------------
% interp Interpolation
% ---------------------------------------------------------------------
interp = cfg_menu;
interp.tag = 'interp';
interp.name = 'Interpolation';
interp.help = {''};
interp.labels = {
'Nearest neighbour'
'Trilinear'
'2nd Degree b-Spline'
'3rd Degree b-Spline'
'4th Degree b-Spline'
'5th Degree b-Spline'
'6th Degree b-Spline'
'7th Degree b-Spline'
'2nd Degree Sinc'
'3rd Degree Sinc'
'4th Degree Sinc'
'5th Degree Sinc'
'6th Degree Sinc'
'7th Degree Sinc'
}';
interp.values = {0 1 2 3 4 5 6 7 -2 -3 -4 -5 -6 -7};
% ---------------------------------------------------------------------
% dtype Data Type
% ---------------------------------------------------------------------
dtype = cfg_menu;
dtype.tag = 'dtype';
dtype.name = 'Data Type';
dtype.val{1} = double(0);
dtype.help = {'Data-type of output images. SAME indicates the same datatype as the original images.'};
dtype.labels = cellstr(char('SAME',spm_type(spm_type)));
dtype.values = num2cell([0 spm_type]);
% ---------------------------------------------------------------------
% prefix Output Filename Prefix
% ---------------------------------------------------------------------
prefix = cfg_entry;
prefix.tag = 'prefix';
prefix.name = 'Output Filename Prefix';
prefix.val = {'li_'};
prefix.help = {'The output filename is constructed by prefixing the original filename with this prefix.'};
prefix.strtype = 's';
prefix.num = [1 Inf];
% ---------------------------------------------------------------------
% tbxvol_laterality Compute Laterality index
% ---------------------------------------------------------------------
cfg_tbxvol_laterality = cfg_exbranch;
cfg_tbxvol_laterality.tag = 'tbxvol_laterality';
cfg_tbxvol_laterality.name = 'Compute Laterality index';
cfg_tbxvol_laterality.val = {srcimgs interp dtype prefix };
cfg_tbxvol_laterality.help = {'No help available for topic ''tbxvol_laterality''.'};
cfg_tbxvol_laterality.prog = @tbxvol_laterality;
cfg_tbxvol_laterality.vfiles = @vfiles_tbxvol_laterality;
% ---------------------------------------------------------------------
% srcspm Source SPM.mat
% ---------------------------------------------------------------------
srcspm = cfg_files;
srcspm.tag = 'srcspm';
srcspm.name = 'Source SPM.mat';
srcspm.help = {''};
srcspm.filter = 'mat';
srcspm.ufilter = '.*SPM.*\.mat';
srcspm.num = [1 1];
% ---------------------------------------------------------------------
% maskimg Brain mask image (optional)
% ---------------------------------------------------------------------
maskimg = cfg_files;
maskimg.tag = 'maskimg';
maskimg.name = 'Brain mask image (optional)';
maskimg.val = {''};
maskimg.help = {''};
maskimg.filter = 'image';
maskimg.ufilter = '.*';
maskimg.num = [0 1];
% ---------------------------------------------------------------------
% dist Distance from mean
% ---------------------------------------------------------------------
dist = cfg_entry;
dist.tag = 'dist';
dist.name = 'Distance from mean';
dist.help = {''};
dist.strtype = 'e';
dist.num = [1 1];
% ---------------------------------------------------------------------
% graphics Graphics output
% ---------------------------------------------------------------------
graphics = cfg_menu;
graphics.tag = 'graphics';
graphics.name = 'Graphics output';
graphics.help = {''};
graphics.labels = {
'Yes'
'No'
}';
graphics.values = {true false};
% ---------------------------------------------------------------------
% tbxvol_analyse_resms Analyse goodness of fit
% ---------------------------------------------------------------------
cfg_tbxvol_analyse_resms = cfg_exbranch;
cfg_tbxvol_analyse_resms.tag = 'tbxvol_analyse_resms';
cfg_tbxvol_analyse_resms.name = 'Analyse goodness of fit';
cfg_tbxvol_analyse_resms.val = {srcspm maskimg dist graphics };
cfg_tbxvol_analyse_resms.help = {'No help available for topic ''tbxvol_analyse_resms''.'};
cfg_tbxvol_analyse_resms.prog = @tbxvol_analyse_resms;
%cfg_tbxvol_analyse_resms.vfiles = @vfiles_tbxvol_analyse_resms;
% ---------------------------------------------------------------------
% srcimgs Source Images
% ---------------------------------------------------------------------
srcimgs = cfg_files;
srcimgs.tag = 'srcimgs';
srcimgs.name = 'Source Images';
srcimgs.help = {''};
srcimgs.filter = 'image';
srcimgs.ufilter = '.*';
srcimgs.num = [1 Inf];
% ---------------------------------------------------------------------
% maskimgs Mask image(s)
% ---------------------------------------------------------------------
maskimgs = cfg_files;
maskimgs.tag = 'maskimgs';
maskimgs.name = 'Mask image(s)';
maskimgs.help = {''};
maskimgs.filter = 'image';
maskimgs.ufilter = '.*';
maskimgs.num = [1 Inf];
% ---------------------------------------------------------------------
% subjects Subject
% ---------------------------------------------------------------------
subjects1 = cfg_branch;
subjects1.tag = 'subjects';
subjects1.name = 'Subject';
subjects1.val = {srcimgs maskimgs };
subjects1.help = {''};
% ---------------------------------------------------------------------
% subjects Subjects
% ---------------------------------------------------------------------
subjects = cfg_repeat;
subjects.tag = 'subjects';
subjects.name = 'Subjects';
subjects.help = {''};
subjects.values = {subjects1 };
subjects.num = [1 Inf];
% ---------------------------------------------------------------------
% bins Edges of histogramm bins
% ---------------------------------------------------------------------
bins = cfg_entry;
bins.tag = 'bins';
bins.name = 'Edges of histogramm bins';
bins.help = {'Enter the edges of histogramm bins. See ''help histc'' for details.'};
bins.strtype = 'e';
bins.num = [1 Inf];
% ---------------------------------------------------------------------
% tbxvol_hist_summary Histogramm summary
% ---------------------------------------------------------------------
cfg_tbxvol_hist_summary = cfg_exbranch;
cfg_tbxvol_hist_summary.tag = 'tbxvol_hist_summary';
cfg_tbxvol_hist_summary.name = 'Histogramm summary';
cfg_tbxvol_hist_summary.val = {subjects bins };
cfg_tbxvol_hist_summary.help = {'No help available for topic ''tbxvol_hist_summary''.'};
cfg_tbxvol_hist_summary.prog = @(job)tbxvol_hist_summary('run',job);
cfg_tbxvol_hist_summary.vout = @(job)tbxvol_hist_summary('vout',job);
% ---------------------------------------------------------------------
% num Session #
% ---------------------------------------------------------------------
num = cfg_entry;
num.tag = 'num';
num.name = 'Session #';
num.strtype = 'n';
num.num = [1 1];
num.help = {['Orthogonalisation will be performed per Session. Enter ' ...
'the number of the session to be orthogonalised.']};
% ---------------------------------------------------------------------
% c Conditions
% ---------------------------------------------------------------------
c = cfg_entry;
c.tag = 'c';
c.name = 'Conditions';
c.strtype = 'n';
c.num = [1 Inf];
c.help = {['Enter the condition numbers to orthogonalise. The order of ' ...
'conditions is important, orthogonalisation will be performed from ' ...
'to right.']};
% ---------------------------------------------------------------------
% Sess
% ---------------------------------------------------------------------
Sess = cfg_branch;
Sess.tag = 'Sess';
Sess.name = 'Session';
Sess.val = {num c};
% ---------------------------------------------------------------------
% Sessrep Sessions
% ---------------------------------------------------------------------
Sessrep = cfg_repeat;
Sessrep.tag = 'Sessrep';
Sessrep.name = 'Sessions';
Sessrep.num = [1 Inf];
Sessrep.values = {Sess};
% ---------------------------------------------------------------------
% cfg_tbxvol_orth_conditions Orthogonalise conditions
% ---------------------------------------------------------------------
cfg_tbxvol_orth_conditions = cfg_exbranch;
cfg_tbxvol_orth_conditions.tag = 'tbxvol_orth_conditions';
cfg_tbxvol_orth_conditions.name = 'Orthogonalise conditions';
cfg_tbxvol_orth_conditions.val = {srcspm Sessrep};
cfg_tbxvol_orth_conditions.prog = @(job)tbxvol_orth_conditions('run',job);
cfg_tbxvol_orth_conditions.vout = @(job)tbxvol_orth_conditions('vout',job);
cfg_tbxvol_orth_conditions.help = vgtbx_help2cell('tbxvol_orth_conditions');
% ---------------------------------------------------------------------
% Latency computation - modified copy of spm_cfg_imcalc
% ---------------------------------------------------------------------
cfg_tbxvol_latency = spm_cfg_imcalc;
cfg_tbxvol_latency.tag = 'tbxvol_latency';
cfg_tbxvol_latency.name = 'Latency (Image Calculator)';
cfg_tbxvol_latency.val{1}.name = 'HRF+Derivative con images';
cfg_tbxvol_latency.val{1}.num = [2 2];
cfg_tbxvol_latency.val{4}.val = {'2*1.78/(1+exp(3.10*i2/i1))-1.78)'};
% ---------------------------------------------------------------------
% Stats_Tools Stats Tools
% ---------------------------------------------------------------------
Stats_Tools = cfg_choice;
Stats_Tools.tag = 'Stats_Tools';
Stats_Tools.name = 'Stats Tools';
Stats_Tools.help = {''};
Stats_Tools.values = {cfg_tbxvol_changeSPM cfg_tbxvol_correct_ec_SPM cfg_tbxvol_transform_t2x cfg_tbxvol_laterality cfg_tbxvol_analyse_resms cfg_tbxvol_hist_summary cfg_tbxvol_orth_conditions cfg_tbxvol_latency};
% ---------------------------------------------------------------------
% vgtbx_Volumes Volume handling utilities
% ---------------------------------------------------------------------
vgtbx_Volumes = cfg_choice;
vgtbx_Volumes.tag = 'vgtbx_Volumes';
vgtbx_Volumes.name = 'Volume handling utilities';
vgtbx_Volumes.help = {
'Volumes toolbox'
'_______________________________________________________________________'
''
'This toolbox contains various helper functions to make image manipulation within SPM5 more convenient. Help on each individual item can be obtained by selecting the corresponding entry in the help menu.'
''
'This toolbox is free but copyright software, distributed under the terms of the GNU General Public Licence as published by the Free Software Foundation (either version 2, as given in file spm_LICENCE.man, or at your option, any later version). Further details on "copyleft" can be found at http://www.gnu.org/copyleft/.'
'The toolbox consists of the files listed in its Contents.m file.'
''
'The source code of this toolbox is available at'
''
'http://sourceforge.net/projects/spmtools'
''
'Please use the SourceForge forum and tracker system for comments, suggestions, bug reports etc. regarding this toolbox.'
'_______________________________________________________________________'
''
'@(#) $Id: vgtbx_config_Volumes.m 539 2007-12-06 17:31:12Z glauche $'
}';
vgtbx_Volumes.values = {Single_Volumes Multiple_Volumes Stats_Tools };
% ---------------------------------------------------------------------
% Virtual outputs/files
% ---------------------------------------------------------------------
function dep = vout_tbxvol_extract(job)
dep = cfg_dep;
dep.sname = 'Extract Data (All)';
dep.src_output = substruct('()',{':',1:numel(job.roispec)});
dep.tgt_spec = cfg_findspec({{'strtype','e'}});
if numel(job.roispec) > 1
for l = 1:numel(job.roispec)
dep(l+1) = cfg_dep;
dep(l+1).sname = sprintf('Extract Data (ROI %d)', l);
dep(l+1).src_output = substruct('()', {':',l});
dep(l+1).tgt_spec = cfg_findspec({{'strtype','e'}});
end;
end;
function dep = vout_tbxvol_rescale(job)
dep = cfg_dep;
dep.sname = 'Rescaled Images';
dep.src_output = substruct('.','rimgs');
dep.tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
function vfiles = vfiles_tbxvol_split(job)
vfiles = {};
for l = 1:numel(job.srcimgs)
[p n e] = spm_fileparts(job.srcimgs{l});
fs = sprintf('_%%0%dd',ceil(log10(job.noutput)));
for k = 1:job.noutput
vfiles{end+1} = fullfile(p,[n sprintf(fs,k) e]);
end;
end;
function vfiles = vfiles_tbxvol_transform_t2x(job)
for k = 1:numel(job.srcimgs)
[pth nm xt] = spm_fileparts(job.srcimgs{k});
switch job.option
case 1
nm2 = 'P';
case 2
nm2 = 'logP';
case 3
nm2 = 'R';
case 4
nm2 = 'D';
end
% name should follow convention spm?_0*.img
if strcmp(nm(1:3),'spm') && strcmp(nm(4:6),'T_0')
vfiles{k} = fullfile(pth,[nm(1:3) nm2 nm(5:end) xt ',1']);
else
vfiles{k} = fullfile(pth,['spm' nm2 '_' nm xt ',1']);
end
end;
function vfiles = vfiles_tbxvol_laterality(job)
for k = 1:numel(job.srcimgs)
[pth nm xt] = spm_fileparts(job.srcimgs{k});
vfiles{k} = fullfile(pth, [job.prefix nm xt ',1']);
end;
function vout = vout_tbxvol_rescale_min_max(job)
vout = cfg_dep;
vout.sname = 'Rescaled Images';
vout.src_output = substruct('.','scimgs');
vout.tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
function vout = vout_tbxvol_regrid(job)
vout = cfg_dep;
vout.sname = 'Regridded Images';
vout.src_output = substruct('.','outimgs');
vout.tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
function vfiles = vfiles_tbxvol_flip(job)
vfiles = job.srcimgs;
if ~job.overwrite
dirs = 'XYZ';
for k=1:numel(job.srcimgs)
[p n e v] = spm_fileparts(job.srcimgs{k});
vfiles{k} = fullfile(p,[job.prefix dirs(job.flipdir) n e v]);
end;
end;
function vf = vfiles_tbxvol_normalise(varargin)
job = varargin{1};
vf = cell(numel(job.subj.source));
for i=1:numel(job.subj.source),
[pth,nam,ext,num] = spm_fileparts(deblank(job.subj.source{i}));
vf{i} = fullfile(pth,[nam,'_gr_sn.mat']);
end;
|
github
|
philippboehmsturm/antx-master
|
tbxvol_normalise.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/Volumes/Multiple_Volumes/tbxvol_normalise.m
| 16,914 |
utf_8
|
b6240c42997c1004290a795f609a7858
|
function tbxvol_normalise(varargin)
job = varargin{1};
eflags = job.eoptions.iteration;
for i=1:numel(job.subj.source),
[pth,nam,ext,ind] = spm_fileparts(char(job.subj.source{i}));
matname{i} = fullfile(pth,[nam '_gr_sn.mat']);
end;
if isfield(job.eoptions.starting,'stempl')
VG = char(job.eoptions.starting.stempl.template{:});
VWG = char(job.eoptions.starting.stempl.weight{:});
sparams = '';
else
VG = '';
VWG = '';
sparams = job.eoptions.starting.sparams;
end;
vg_normalise(VG,...
char(job.subj.source{:}), matname,...
VWG, char(job.subj.wtsrc{:}), ...
eflags, sparams);
return;
function params = vg_normalise(VG,VF,matname,VWG,VWF,flags,starting)
% Spatial (stereotactic) normalization
%
% FORMAT params = spm_normalise(VG,VF,matname,VWG,VWF,flags)
% VG - template handle(s)
% VF - handle of image to estimate params from
% matname - name of file to store deformation definitions
% VWG - template weighting image
% VWF - source weighting image
% flags - flags. If any field is not passed, then defaults are assumed.
% smosrc - smoothing of source image (FWHM of Gaussian in mm).
% Defaults to 8.
% smoref - smoothing of template image (defaults to 0).
% regtype - regularisation type for affine registration
% See spm_affreg.m (default = 'mni').
% cutoff - Cutoff of the DCT bases. Lower values mean more
% basis functions are used (default = 30mm).
% nits - number of nonlinear iterations (default=16).
% reg - amount of regularisation (default=0.1)
% starting - (optional) list of parameters for initial normalisation
% step - e.g. obtained from segmentation - one file per VF image
% ___________________________________________________________________________
%
% This module spatially (stereotactically) normalizes MRI, PET or SPECT
% images into a standard space defined by some ideal model or template
% image[s]. The template images supplied with SPM conform to the space
% defined by the ICBM, NIH P-20 project, and approximate that of the
% the space described in the atlas of Talairach and Tournoux (1988).
% The transformation can also be applied to any other image that has
% been coregistered with these scans.
%
%
% Mechanism
% Generally, the algorithms work by minimising the sum of squares
% difference between the image which is to be normalised, and a linear
% combination of one or more template images. For the least squares
% registration to produce an unbiased estimate of the spatial
% transformation, the image contrast in the templates (or linear
% combination of templates) should be similar to that of the image from
% which the spatial normalization is derived. The registration simply
% searches for an optimum solution. If the starting estimates are not
% good, then the optimum it finds may not find the global optimum.
%
% The first step of the normalization is to determine the optimum
% 12-parameter affine transformation. Initially, the registration is
% performed by matching the whole of the head (including the scalp) to
% the template. Following this, the registration proceeded by only
% matching the brains together, by appropriate weighting of the template
% voxels. This is a completely automated procedure (that does not
% require ``scalp editing'') that discounts the confounding effects of
% skull and scalp differences. A Bayesian framework is used, such that
% the registration searches for the solution that maximizes the a
% posteriori probability of it being correct. i.e., it maximizes the
% product of the likelihood function (derived from the residual squared
% difference) and the prior function (which is based on the probability
% of obtaining a particular set of zooms and shears).
%
% The affine registration is followed by estimating nonlinear deformations,
% whereby the deformations are defined by a linear combination of three
% dimensional discrete cosine transform (DCT) basis functions.
% The parameters represent coefficients of the deformations in
% three orthogonal directions. The matching involved simultaneously
% minimizing the bending energies of the deformation fields and the
% residual squared difference between the images and template(s).
%
% An option is provided for allowing weighting images (consisting of pixel
% values between the range of zero to one) to be used for registering
% abnormal or lesioned brains. These images should match the dimensions
% of the image from which the parameters are estimated, and should contain
% zeros corresponding to regions of abnormal tissue.
%
%
% Uses
% Primarily for stereotactic normalization to facilitate inter-subject
% averaging and precise characterization of functional anatomy. It is
% not necessary to spatially normalise the data (this is only a
% pre-requisite for intersubject averaging or reporting in the
% Talairach space).
%
% Inputs
% The first input is the image which is to be normalised. This image
% should be of the same modality (and MRI sequence etc) as the template
% which is specified. The same spatial transformation can then be
% applied to any other images of the same subject. These files should
% conform to the SPM data format (See 'Data Format'). Many subjects can
% be entered at once, and there is no restriction on image dimensions
% or voxel size.
%
% Providing that the images have a correct ".mat" file associated with
% them, which describes the spatial relationship between them, it is
% possible to spatially normalise the images without having first
% resliced them all into the same space. The ".mat" files are generated
% by "spm_realign" or "spm_coregister".
%
% Default values of parameters pertaining to the extent and sampling of
% the standard space can be changed, including the model or template
% image[s].
%
%
% Outputs
% All normalized *.img scans are written to the same subdirectory as
% the original *.img, prefixed with a 'n' (i.e. n*.img). The details
% of the transformations are displayed in the results window, and the
% parameters are saved in the "*_sn.mat" file.
%
%
%____________________________________________________________________________
% Refs:
% K.J. Friston, J. Ashburner, C.D. Frith, J.-B. Poline,
% J.D. Heather, and R.S.J. Frackowiak
% Spatial Registration and Normalization of Images.
% Human Brain Mapping 2:165-189(1995)
%
% J. Ashburner, P. Neelin, D.L. Collins, A.C. Evans and K. J. Friston
% Incorporating Prior Knowledge into Image Registration.
% NeuroImage 6:344-352 (1997)
%
% J. Ashburner and K. J. Friston
% Nonlinear Spatial Normalization using Basis Functions.
% Human Brain Mapping 7(4):in press (1999)
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% John Ashburner
% $Id: tbxvol_normalise.m 712 2010-06-30 14:20:19Z glauche $
if nargin<2, error('Incorrect usage.'); end;
if ischar(VF), VF = spm_vol(VF); end;
if ischar(VG), VG = spm_vol(VG); end;
if nargin<3,
if nargout==0,
for k = 1:numel(VF)
[pth,nm,xt,vr] = spm_fileparts(deblank(VF(k).fname));
matname{k} = fullfile(pth,[nm '_sn.mat']);
end;
else
matname = '';
end;
end;
if nargin<4, VWG = ''; end;
if nargin<5, VWF = ''; end;
if ischar(VWG), VWG=spm_vol(VWG); end;
if ischar(VWF), VWF=spm_vol(VWF); end;
def_flags = struct('smosrc',4,'smoref',4,'regtype','mni',...
'cutoff',15,'nits',16,'reg',0.01,'graphics',0);
if nargin < 6,
flags = def_flags;
else
fnms = fieldnames(def_flags);
for i=1:length(fnms),
if ~isfield(flags,fnms{i}),
for k = 1:numel(flags)
flags(k).(fnms{i}) = def_flags.(fnms{i});
end;
end;
end;
end;
fprintf('Smoothing by %g & %gmm..\n', flags(1).smoref, flags(1).smosrc);
for k = 1:numel(VF)
VF1(k) = spm_smoothto8bit(VF(k),flags(1).smosrc);
% Rescale images so that globals are better conditioned
VF1(k).pinfo(1:2,:) = VF1(k).pinfo(1:2,:)/spm_global(VF1(k));
end;
if (nargin < 7) || isempty(starting)
% use specified template
for i=1:numel(VG),
VG1(i) = spm_smoothto8bit(VG(i),flags(1).smoref);
VG1(i).pinfo(1:2,:) = VG1(i).pinfo(1:2,:)/spm_global(VG(i));
end;
% Affine Normalisation
%-----------------------------------------------------------------------
for k = 1:numel(VF1)
fprintf('Coarse Affine Registration..\n');
aflags = struct('sep',max(flags(1).smoref,flags(1).smosrc), 'regtype',flags(1).regtype,...
'WG',[],'WF',[],'globnorm',0);
aflags.sep = max(aflags.sep,max(sqrt(sum(VG(1).mat(1:3,1:3).^2))));
aflags.sep = max(aflags.sep,max(sqrt(sum(VF(k).mat(1:3,1:3).^2))));
M = eye(4); %spm_matrix(prms');
spm_chi2_plot('Init','Affine Registration','Mean squared difference','Iteration');
[M,scal] = spm_affreg(VG1, VF1(k), aflags, M);
fprintf('Fine Affine Registration..\n');
aflags.WG = VWG;
aflags.WF = VWF;
aflags.sep = aflags.sep/2;
[M,scal] = spm_affreg(VG1, VF1(k), aflags, M,scal);
Affine{k} = inv(VG(1).mat\M*VF1(k).mat);
spm_chi2_plot('Clear');
end;
Tr(1:numel(VF1)) = {[]};
bb = Inf*ones(2,3);
vox = Inf*ones(1,3);
else
for k = 1:numel(VF1)
prm = load(starting{k});
Affine{k} = prm.Affine;
Tr{k} = prm.Tr;
VGtmp(k) = prm.VG(1);
end;
try
spm_check_orientations(VGtmp);
catch
error(['Templates for initial normalisation step do not have same' ...
' orientation and voxel size.\n']);
end;
[bb vox] = bbvox_from_V(VGtmp(1));
fprintf('Computing template image for iteration 1.\n');
for k = 1:numel(VF1)
VN(k) = spm_write_sn(VF(k),starting{k},...
struct('interp',4,...
'bb',bb,...
'vox',vox));
end;
VGnew = rmfield(VN(1),'dat');
[p n e v] = spm_fileparts(VGnew.fname);
VGnew.fname = fullfile(p,sprintf('mean%d%s%s',1,n,e));
VGnew = spm_imcalc(VN,VGnew,'mean(X)',{1,0,-4});
VG1 = spm_smoothto8bit(VGnew,flags(1).smoref);
VG1.pinfo(1:2,:) = VG1.pinfo(1:2,:)/spm_global(VGnew);
end;
% Basis function Normalisation
%-----------------------------------------------------------------------
spm_progress_bar('init', 100, 'Parameter Estimation', '% completed');
for it = 1:numel(flags)
for k = 1:numel(VF1)
fov = VF1(k).dim(1:3).*sqrt(sum(VF1(k).mat(1:3,1:3).^2));
if any(fov<15*flags(it).smosrc/2 & VF1(k).dim(1:3)<15),
fprintf('Field of view too small for nonlinear registration\n');
Tr{k} = [];
elseif isfinite(flags(it).cutoff) && flags(it).nits && ~isinf(flags(it).reg),
fprintf('3D CT Norm...\n');
Tr{k} = snbasis(VG1,VF1(k),VWG,VWF,Affine{k},...
max(flags(it).smoref,flags(it).smosrc),flags(it).cutoff, ...
flags(it).nits,flags(it).reg, Tr{k});
else
Tr{k} = [];
end;
params = struct('Affine',Affine{k}, 'Tr',Tr{k}, 'VF',VF(k), 'VG',VG, ...
'flags',flags(it));
VN(k) = spm_write_sn(VF(k),params,struct('interp',4,...
'bb',bb,...
'vox',vox));
spm_progress_bar('set', 100*((it-1)*numel(VF1)+k)/ ...
(numel(flags)*numel(VF1)));
end;
if it < numel(flags)
fprintf('Computing template image for iteration %d.\n',it+1);
VWF = [];
VWG = [];
VGnew = rmfield(VN(1),'dat');
[p n e v] = spm_fileparts(VGnew.fname);
VGnew.fname = fullfile(p,sprintf('mean%d%s%s',it+1,n,e));
VGnew = spm_imcalc(VN,VGnew,'mean(X)',{1,0,-4});
VG1 = spm_smoothto8bit(VGnew,flags(it+1).smoref);
VG1.pinfo(1:2,:) = VG1.pinfo(1:2,:)/spm_global(VGnew);
end;
end;
clear VF1 VG1
% Remove dat fields before saving
%-----------------------------------------------------------------------
if isfield(VF,'dat'), VF = rmfield(VF,'dat'); end;
if isfield(VG,'dat'), VG = rmfield(VG,'dat'); end;
if ~isempty(matname),
AffineList = Affine;
TrList = Tr;
VFList = VF;
spm_progress_bar('init', numel(VFList), 'Saving Parameters');
for k = 1:numel(VFList)
fprintf('Saving Parameters..\n');
Affine = AffineList{k};
Tr = TrList{k};
VF = VFList(k);
if spm_matlab_version_chk('7') >= 0,
save(matname{k},'-V6','Affine','Tr','VF','VG','flags');
else
save(matname{k},'Affine','Tr','VF','VG','flags');
end;
spm_progress_bar('set', k);
end;
end;
spm_progress_bar('clear');
return;
%_______________________________________________________________________
%_______________________________________________________________________
function Tr = snbasis(VG,VF,VWG,VWF,Affine,fwhm,cutoff,nits,reg,Tr)
% 3D Basis Function Normalization
% FORMAT Tr = snbasis(VG,VF,VWG,VWF,Affine,fwhm,cutoff,nits,reg)
% VG - Template volumes (see spm_vol).
% VF - Volume to normalize.
% VWG - weighting Volume - for template.
% VWF - weighting Volume - for object.
% Affine - A 4x4 transformation (in voxel space).
% fwhm - smoothness of images.
% cutoff - frequency cutoff of basis functions.
% nits - number of iterations.
% reg - regularisation.
% Tr - Discrete cosine transform of the warps in X, Y & Z.
%
% snbasis performs a spatial normalization based upon a 3D
% discrete cosine transform.
%
%______________________________________________________________________
fwhm = [fwhm 30];
% Number of basis functions for x, y & z
%-----------------------------------------------------------------------
tmp = sqrt(sum(VG(1).mat(1:3,1:3).^2));
k = max(round((VG(1).dim(1:3).*tmp)/cutoff),[1 1 1]);
if ~isempty(Tr)
% take at least same number of parameters as before, set
% uninitialised parameters to zero
k1 = size(Tr);
k = max(k,k1(1:3));
Tr((end+1):k(1),(end+1):k(2),(end+1):k(3),:) = 0;
end;
% Scaling is to improve stability.
%-----------------------------------------------------------------------
stabilise = 8;
basX = spm_dctmtx(VG(1).dim(1),k(1))*stabilise;
basY = spm_dctmtx(VG(1).dim(2),k(2))*stabilise;
basZ = spm_dctmtx(VG(1).dim(3),k(3))*stabilise;
dbasX = spm_dctmtx(VG(1).dim(1),k(1),'diff')*stabilise;
dbasY = spm_dctmtx(VG(1).dim(2),k(2),'diff')*stabilise;
dbasZ = spm_dctmtx(VG(1).dim(3),k(3),'diff')*stabilise;
vx1 = sqrt(sum(VG(1).mat(1:3,1:3).^2));
vx2 = vx1;
kx = (pi*((1:k(1))'-1)/VG(1).dim(1)/vx1(1)).^2; ox=ones(k(1),1);
ky = (pi*((1:k(2))'-1)/VG(1).dim(2)/vx1(2)).^2; oy=ones(k(2),1);
kz = (pi*((1:k(3))'-1)/VG(1).dim(3)/vx1(3)).^2; oz=ones(k(3),1);
if 1,
% BENDING ENERGY REGULARIZATION
% Estimate a suitable sparse diagonal inverse covariance matrix for
% the parameters (IC0).
%-----------------------------------------------------------------------
IC0 = (1*kron(kz.^2,kron(ky.^0,kx.^0)) +...
1*kron(kz.^0,kron(ky.^2,kx.^0)) +...
1*kron(kz.^0,kron(ky.^0,kx.^2)) +...
2*kron(kz.^1,kron(ky.^1,kx.^0)) +...
2*kron(kz.^1,kron(ky.^0,kx.^1)) +...
2*kron(kz.^0,kron(ky.^1,kx.^1)) );
IC0 = reg*IC0*stabilise^6;
IC0 = [IC0*vx2(1)^4 ; IC0*vx2(2)^4 ; IC0*vx2(3)^4 ; zeros(numel(VG)*4,1)];
IC0 = sparse(1:length(IC0),1:length(IC0),IC0,length(IC0),length(IC0));
else
% MEMBRANE ENERGY (LAPLACIAN) REGULARIZATION
%-----------------------------------------------------------------------
IC0 = kron(kron(oz,oy),kx) + kron(kron(oz,ky),ox) + kron(kron(kz,oy),ox);
IC0 = reg*IC0*stabilise^6;
IC0 = [IC0*vx2(1)^2 ; IC0*vx2(2)^2 ; IC0*vx2(3)^2 ; zeros(prod(size(VG))*4,1)];
IC0 = sparse(1:length(IC0),1:length(IC0),IC0,length(IC0),length(IC0));
end;
% Generate starting estimates.
%-----------------------------------------------------------------------
s1 = 3*prod(k);
s2 = s1 + numel(VG)*4;
T = zeros(s2,1);
T(s1+(1:4:numel(VG)*4)) = 1;
if exist('Tr','var') && ~isempty(Tr)
T(1:s1) = Tr(:)/stabilise.^3;
end;
pVar = Inf;
for iter=1:nits,
fprintf(' iteration %2d: ', iter);
[Alpha,Beta,Var,fw] = spm_brainwarp(VG,VF,Affine,basX,basY,basZ,dbasX,dbasY,dbasZ,T,fwhm,VWG, VWF);
if Var>pVar, scal = pVar/Var ; Var = pVar; else scal = 1; end;
pVar = Var;
T = (Alpha + IC0*scal)\(Alpha*T + Beta);
fwhm(2) = min([fw fwhm(2)]);
fprintf(' FWHM = %6.4g Var = %g\n', fw,Var);
end;
% Values of the 3D-DCT - for some bizarre reason, this needs to be done
% as two seperate statements in Matlab 6.5...
%-----------------------------------------------------------------------
Tr = reshape(T(1:s1),[k 3]);
drawnow;
Tr = Tr*stabilise.^3;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [bb,vx] = bbvox_from_V(V)
vx = sqrt(sum(V.mat(1:3,1:3).^2));
if det(V.mat(1:3,1:3))<0, vx(1) = -vx(1); end;
o = V.mat\[0 0 0 1]';
o = o(1:3)';
bb = [-vx.*(o-1) ; vx.*(V.dim(1:3)-o)];
return;
|
github
|
philippboehmsturm/antx-master
|
tbxvol_spike_mask.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/Volumes/Multiple_Volumes/tbxvol_spike_mask.m
| 6,666 |
utf_8
|
6653019fed50774babb90f080393b12e
|
function varargout = tbxvol_spike_mask(cmd, varargin)
% Template function to implement callbacks for an cfg_exbranch. The calling
% syntax is
% varargout = tbxvol_spike_mask(cmd, varargin)
% where cmd is one of
% 'run' - out = tbxvol_spike_mask('run', job)
% Run a job, and return its output argument
% 'vout' - dep = tbxvol_spike_mask('vout', job)
% Examine a job structure with all leafs present and return an
% array of cfg_dep objects.
% 'check' - str = tbxvol_spike_mask('check', subcmd, subjob)
% Examine a part of a fully filled job structure. Return an empty
% string if everything is ok, or a string describing the check
% error. subcmd should be a string that identifies the part of
% the configuration to be checked.
% 'defaults' - defval = tbxvol_spike_mask('defaults', key)
% Retrieve defaults value. key must be a sequence of dot
% delimited field names into the internal def struct which is
% kept in function local_def. An error is returned if no
% matching field is found.
% tbxvol_spike_mask('defaults', key, newval)
% Set the specified field in the internal def struct to a new
% value.
% Application specific code needs to be inserted at the following places:
% 'run' - main switch statement: code to compute the results, based on
% a filled job
% 'vout' - main switch statement: code to compute cfg_dep array, based
% on a job structure that has all leafs, but not necessarily
% any values filled in
% 'check' - create and populate switch subcmd switchyard
% 'defaults' - modify initialisation of defaults in subfunction local_defs
% Callbacks can be constructed using anonymous function handles like this:
% 'run' - @(job)tbxvol_spike_mask('run', job)
% 'vout' - @(job)tbxvol_spike_mask('vout', job)
% 'check' - @(job)tbxvol_spike_mask('check', 'subcmd', job)
% 'defaults' - @(val)tbxvol_spike_mask('defaults', 'defstr', val{:})
% Note the list expansion val{:} - this is used to emulate a
% varargin call in this function handle.
%
% This code is part of a batch job configuration system for MATLAB. See
% help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging
% Volkmar Glauche
% $Id: tbxvol_spike_mask.m 720 2011-09-27 05:11:51Z glauche $
rev = '$Rev: 720 $'; %#ok
if ischar(cmd)
switch lower(cmd)
case 'run'
job = local_getjob(varargin{1});
% do computation, return results in variable out
spm_progress_bar('Init',numel(job.srcimgs),'','images completed');
VM = spm_vol(job.masking.maskimg{1});
sel = true(size(job.srcimgs));
for ci = 1:numel(job.srcimgs)
Vi = [spm_vol(job.srcimgs{ci}) VM];
%-Loop over planes
%-----------------------------------------------------------------------
for p = 1:Vi(1).dim(3),
B = spm_matrix([0 0 -p 0 0 0 1 1 1]);
X=zeros(2,prod(Vi(1).dim(1:2)));
for i = 1:2
M = inv(B*inv(Vi(1).mat)*Vi(i).mat);
d = spm_slice_vol(Vi(i),M,Vi(1).dim(1:2),[0,NaN]);
d(isnan(d))=0;
X(i,:) = d(:)';
end
if job.masking.invert
sel(ci) = sum(X(1,:).*(1-X(2,:)) > job.crit.thresh)./sum(1-X(2,:)) < job.crit.ratio;
else
sel(ci) = sum(X(1,:).*X(2,:) > job.crit.thresh)./sum(X(2,:)) < job.crit.ratio;
end
if ~sel(ci)
% found a bad slice
break
end
end
spm_progress_bar('set',ci);
end
spm_progress_bar('clear');
out.goodimgs = job.srcimgs(sel);
out.badimgs = job.srcimgs(~sel);
if nargout > 0
varargout{1} = out;
end
case 'vout'
job = local_getjob(varargin{1});
% initialise empty cfg_dep array
dep(1) = cfg_dep;
dep(1).sname = '''Good'' images';
dep(1).src_output = substruct('.','goodimgs');
dep(1).tgt_spec = cfg_findspec({{'filter','image'}});
dep(2) = cfg_dep;
dep(2).sname = '''Bad'' images';
dep(2).src_output = substruct('.','badimgs');
dep(2).tgt_spec = cfg_findspec({{'filter','image'}});
% determine outputs, return cfg_dep array in variable dep
varargout{1} = dep;
case 'check'
if ischar(varargin{1})
subcmd = lower(varargin{1});
subjob = varargin{2};
str = '';
switch subcmd
% implement checks, return status string in variable str
otherwise
cfg_message('unknown:check', ...
'Unknown check subcmd ''%s''.', subcmd);
end
varargout{1} = str;
else
cfg_message('ischar:check', 'Subcmd must be a string.');
end
case 'defaults'
if nargin == 2
varargout{1} = local_defs(varargin{1});
else
local_defs(varargin{1:2});
end
otherwise
cfg_message('unknown:cmd', 'Unknown command ''%s''.', cmd);
end
else
cfg_message('ischar:cmd', 'Cmd must be a string.');
end
function varargout = local_defs(defstr, defval)
persistent defs;
if isempty(defs)
% initialise defaults
end
if ischar(defstr)
% construct subscript reference struct from dot delimited tag string
tags = textscan(defstr,'%s', 'delimiter','.');
subs = struct('type','.','subs',tags{1}');
try
cdefval = subsref(defs, subs);
catch
cdefval = [];
cfg_message('defaults:noval', ...
'No matching defaults value ''%s'' found.', defstr);
end
if nargin == 1
varargout{1} = cdefval;
else
defs = subsasgn(defs, subs, defval);
end
else
cfg_message('ischar:defstr', 'Defaults key must be a string.');
end
function job = local_getjob(job)
if ~isstruct(job)
cfg_message('isstruct:job', 'Job must be a struct.');
end
|
github
|
philippboehmsturm/antx-master
|
tbxvol_spike.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/Volumes/Multiple_Volumes/tbxvol_spike.m
| 3,212 |
utf_8
|
2008e72d56a97eef2685b07a7f2f3083
|
function tbxvol_spike(bch)
% Detect slices with abnormal intensities or standard deviations
% FORMAT tbxvol_spike(bch)
% ======
% For each volume, normalised mean signal and standard deviation are computed per
% slice. These values are then compared to their mean over all volumes,
% and slices that deviate from these means by more than a given threshold
% are reported a suspicious.
% This function is part of the volumes toolbox for SPM. For general help
% about this toolbox, bug reports, licensing etc. type
% spm_help vgtbx_config_Volumes
% in the matlab command window after the toolbox has been launched.
%_______________________________________________________________________
%
% @(#) $Id: tbxvol_spike.m 714 2010-07-30 14:28:55Z glauche $
rev = '$Revision: 714 $';
funcname = 'Spike detection';
% function preliminaries
Finter=spm_figure('GetWin','Interactive');
Fgraph=spm_figure('GetWin','Graphics');
Finter=spm('FigName',funcname,Finter);
SPMid = spm('FnBanner',mfilename,rev);
% function code starts here
spm('pointer','watch');
% map image files into memory
Vin = spm_vol(char(bch.srcimgs));
nimg = numel(bch.srcimgs);
Mean_result = zeros(Vin(1).dim(3),nimg);
Std_result = zeros(Vin(1).dim(3),nimg);
spm_progress_bar('Init',nimg,'Images',' ');
for m=1:nimg,
d = spm_read_vols(Vin(m));
Mean_result(:,m) = squeeze(mean(mean(d)));
Std_result(:,m) = squeeze(std(std(d)));
spm_progress_bar('Set',m);
end;
spm_progress_bar('Clear');
%Normalize to mean = 0, std = 1
%---------------------
Nmean = normit(Mean_result');
Nstd = normit(Std_result');
MNmean = repmat(mean(Nmean),nimg,1);
MNstd = repmat(mean(Nstd),nimg,1);
Gt_MNmean = abs(Nmean-MNmean) > bch.spikethr;
Gt_MNstd = abs(Nstd-MNstd) > bch.spikethr;
GtMask_MNmean = zeros(size(Nmean));
GtMask_MNstd = zeros(size(Nstd));
GtMask_MNmean(Gt_MNmean) = 1;
GtMask_MNstd(Gt_MNstd) = 1;
%display results
%--------------------------------------
%Mean
%----
figure(Fgraph); spm_clf;
colormap hot;
subplot(4,1,1);
imagesc(Nmean');
caxis([-bch.spikethr bch.spikethr]);
colorbar;
xlabel('scan');
ylabel('slice');
title('Mean');
%Std
%---
subplot(4,1,2);
imagesc(Nstd');
caxis([-bch.spikethr bch.spikethr]);
colorbar;
xlabel('scan');
ylabel('slice');
title('Std');
%Nmean-MNmean
%----
subplot(4,1,3);
imagesc(Nmean'-MNmean');
caxis([-bch.spikethr bch.spikethr]);
colorbar;
xlabel('scan');
ylabel('slice');
title('Mean-Mean(Mean) per slice');
%NStd-MNstd
%---
subplot(4,1,4);
imagesc(Nstd'-MNstd');
caxis([-bch.spikethr bch.spikethr]);
colorbar;
xlabel('scan');
ylabel('slice');
title('Std-Mean(Std) per slice');
cs = 0;
spikes = struct('fnames',{{}}, 'slices',{[]});
for j = 1:nimg
if any(GtMask_MNmean(j,:)) || any(GtMask_MNstd(j,:))
cs = cs+1;
spikes.fnames{cs} = bch.srcimgs{j};
spikes.slices{cs} = find(GtMask_MNmean(j,:) | GtMask_MNstd(j,:));
end
end
disp('Information about suspicious scans and slices has been saved to workspace variable ''spikes'':');
disp(spikes);
assignin('base','spikes',spikes);
spm('pointer','arrow');
function ret = normit(in)
szin = size(in);
meanin = in - repmat(mean(in,2),1,szin(2));
ret = meanin./repmat(std(meanin,[],2),1,szin(2));
|
github
|
philippboehmsturm/antx-master
|
spm_ov_extract.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/Volumes/spm_orthviews/spm_ov_extract.m
| 15,182 |
utf_8
|
375359110bf9079b2bb1552b44279cf7
|
function ret = spm_ov_extract(varargin)
% Wrapper for tbxvol_extract
% This function provides an interface to tbxvol_extract from
% an spm_orthviews display. The main features include:
% ROI selection alternatives
% - cross hair selection for start and end point of a profile line
% (after selection, the line will be added as a yellow blob to the
% displayed image)
% - ROI specification based on displayed blobs (1 ROI per blob set)
% - ROI specification from active ROI tool
% - ROI specification from saved files (1 ROI per file)
% - Current crosshair position
% - Sphere at current crosshair position
% Extraction alternatives
% - Raw and adjusted data from SPM analysis (SPM.mat)
% - Raw data from image series
% - Raw data from current image only
% Plotting alternatives
% - no plot (just save extracted data)
% - plot over voxels (1 line per image)
% - plot over images (1 line per voxel)
% - average over voxels/images (average line and scatter plot of
% individual values)
% - if DTI toolbox installed: average over voxels and diffusion
% weighting
% If data is extracted from the current image, then only plotting
% over voxels is available.
%
% This routine is a plugin to spm_orthviews for SPM5. For general help about
% spm_orthviews and plugins type
% help spm_orthviews
% at the matlab prompt.
%_______________________________________________________________________
%
% @(#) $Id: spm_ov_extract.m 660 2009-06-29 07:12:45Z glauche $
rev = '$Revision: 660 $';
global st;
if isempty(st)
error(['%s: This routine can only be called as a plugin for' ...
' spm_orthviews!'], mfilename);
end;
if nargin < 2
error(['%s: Wrong number of arguments. Usage:' ...
' spm_orthviews(''extract'', cmd, volhandle, varargin)'], ...
mfilename);
end;
cmd = lower(varargin{1});
volhandle = varargin{2};
switch cmd
%-------------------------------------------------------------------------
% Context menu and callbacks
case 'context_menu'
if exist(fullfile(spm('dir'),'toolbox','Volumes', ...
'Single_Volumes'),'dir')
addpath(fullfile(spm('dir'),'toolbox','Volumes', ...
'Single_Volumes'));
else
return;
end;
if ~any(exist('tbxvol_extract')==2:6)
warning([mfilename ':init'], 'function tbxvol_extract not found!');
return;
end;
item0 = uimenu(varargin{3}, 'Label', 'Extract+Plot Data', ...
'Tag', sprintf('%s_0_%d', upper(mfilename),...
num2str(volhandle)));
item1 = uimenu(item0, 'Label','Time Series (SPM): - Raw and Fitted Data',...
'Callback', sprintf(...
['feval(''%s'',''context_init'', %d,'...
' ''SPMboth'', ''ser'');'], ...
mfilename, volhandle),...
'Tag', sprintf('%s_0_%d', upper(mfilename),...
num2str(volhandle)));
item1 = uimenu(item0, 'Label','Image Series: - Raw Data',...
'Callback', sprintf(...
['feval(''%s'',''context_init'', %d,'...
' ''ROIfiles'',''ser'');'], ...
mfilename, volhandle),...
'Tag', sprintf('%s_0_%d', upper(mfilename),...
num2str(volhandle)));
item1 = uimenu(item0, 'Label','Current Image: - Raw Data',...
'Callback', sprintf(...
['feval(''%s'',''context_init'', %d,'...
' ''ROIfiles'',''cur'');'], ...
mfilename, volhandle),...
'Tag', sprintf('%s_0_%d', upper(mfilename),...
num2str(volhandle)));
item10 = uimenu(item0, 'Label', 'Help', 'Callback', ...
['feval(''spm_help'',''' mfilename ''');']);
case 'context_init'
mode = lower(varargin{3});
possel = {'Sphere at Current Point','Current Point','ROI file(s)'};
posselsrc = {'sphere','point','froi'};
if isfield(st.vols{volhandle},'roi')
possel{end+1} = 'Current ROI';
posselsrc{end+1} = 'croi';
elseif isfield(st.vols{volhandle},'blobs')
possel{end+1} = 'Current blobs';
posselsrc{end+1} = 'blobs';
end;
if strcmp(mode,'roifiles')
possel{end+1} = 'Trajectory through image';
posselsrc{end+1} = 'line';
end;
if strcmp(varargin{4},'cur')
bch.src.srcimgs = {st.vols{volhandle}.fname};
plotsel = {'Don''t plot', 'Plot over voxels - no averaging'};
else
if strcmp(mode,'roifiles')
bch.src.srcimgs = cellstr(spm_select([1 inf],'image', ...
'Images to Extract Data from'));
else
bch.src.srcspm = {spm_select([1 1],'.*SPM.*\.mat', ...
'SPM Analysis to Extract Data from')};
end;
plotsel = {'Don''t plot', 'Plot over voxels - no averaging',...
'Plot over images - no averaging',...
'Plot over voxels - Average over images'...
'Plot over images - Average over voxels'};
if (exist(fullfile(spm('dir'),'toolbox',...
'Diffusion','Helpers','dti_extract_dirs.m'),'file')||...
exist('dti_extract_dirs'))
addpath(fullfile(spm('dir'),'toolbox','Diffusion','Helpers'))
plotsel{end+1} = 'DTI: Average over voxels and diffusion weighting';
end;
end;
possel = char(spm_input('Voxels to extract from', '+1', 'm', possel, ...
posselsrc));
plotsel = spm_input('Plot data','!+1','m',...
plotsel, 0:(numel(plotsel)-1), 0);
bch.interp = spm_input('Interpolation hold','+1','m',...
['Nearest Neighbour|Trilinear|2nd Degree B-Spline|'...
'3rd Degree B-Spline|4th Degree B-Spline|5th Degree B-Spline|'...
'6th Degree B-Spline|7th Degree B-Spline'],...
[0 1 2 3 4 5 6 7],0);
switch possel
case 'croi'
bch.roispec{1}.roilist = st.vols{volhandle}.roi.Vroi.mat*...
[st.vols{volhandle}.roi.xyz; ...
ones(1,size(st.vols{volhandle}.roi.xyz,2))];
bch.roispec{1}.roilist = bch.roispec{1}.roilist(1:3,:);
case 'froi'
[froiname sts] = spm_select([1 Inf], 'image', 'Select ROI file(s)');
if ~sts
warning('%s: No ROI file selected - exiting\n', mfilename);
return;
end;
for k = 1:size(froiname,1)
bch.roispec{k}.srcimg = {froiname(k,:)};
end;
case 'blobs'
nroi = numel(st.vols{volhandle}.blobs);
for k = 1:nroi
if isstruct(st.vols{volhandle}.blobs{k}.vol)
dat=spm_read_vols(st.vols{volhandle}.blobs{k}.vol);
else
dat=st.vols{volhandle}.blobs{k}.vol;
end;
dat(isnan(dat))=0;
[x y z] = ind2sub(size(dat), find(dat));
bch.roispec{k}.roilist = st.vols{volhandle}.blobs{k}.mat*...
[x(:)'; y(:)'; z(:)'; ones(size(x(:)'))];
bch.roispec{k}.roilist = bch.roispec{k}.roilist(1:3,:);
end;
case 'point',
bch.roispec{1}.roilist = spm_orthviews('pos');
case 'sphere',
bch.roispec{1}.roisphere.roicent = spm_orthviews('pos');
bch.roispec{1}.roisphere.roirad = spm_input(...
'Radius of sphere (mm)', '!+1', 'e', '10', [1 1]);
case 'line'
msgbox(['Place cross hair at start position and press middle mouse' ...
' button'],'Extract data');
st.vols{volhandle}.extract=struct('cb',[], 'plotsel',plotsel,...
'bch',bch, 'mode',mode);
clear bch;
for k = 1:3
st.vols{volhandle}.extract.cb{k} = ...
get(st.vols{volhandle}.ax{k}.ax, 'ButtonDownFcn');
set(st.vols{volhandle}.ax{k}.ax,...
'ButtonDownFcn',...
['switch get(gcf,''SelectionType'')',...
'case ''normal'', spm_orthviews(''Reposition'');',...
'case ''extend'', spm_orthviews(''extract'',''getline'',', ...
num2str(volhandle), ');',...
'case ''alt'', spm_orthviews(''context_menu'',''ts'',1);',...
'end;']);
end;
end;
case 'getline'
if ~isfield(st.vols{volhandle}.extract,'start')
st.vols{volhandle}.extract.start = spm_orthviews('pos');
msgbox(['Place cross hair at end position and press middle mouse' ...
' button'],'Extract data');
else
bch = st.vols{volhandle}.extract.bch;
bch.roispec{1}.roiline.roistart = st.vols{volhandle}.extract.start;
bch.roispec{1}.roiline.roiend = spm_orthviews('pos');
bch.roispec{1}.roiline.roistep = spm_input('Sampling Distance (mm)', ...
'!+1', 'e', '1', [1 1]);
for k = 1:3
set(st.vols{volhandle}.ax{k}.ax, 'ButtonDownFcn',...
st.vols{volhandle}.extract.cb{k});
end;
plotsel = st.vols{volhandle}.extract.plotsel;
st.vols{volhandle} = rmfield(st.vols{volhandle},'extract');
end;
case 'redraw'
% do nothing
otherwise
fprintf('spm_orthviews(''extract'', ...): Unknown action %s', cmd);
end;
if exist('bch','var')
bch.avg = 'none';
ext=tbxvol_extract(bch);
assignin('base','ext',ext);
disp('extracted data saved to workspace variable ''ext''');
disp(ext);
if strcmp(cmd,'getline')
spm_orthviews('addcolouredblobs', volhandle, ...
st.vols{volhandle}.mat\...
[ext.posmm;ones(1, size(ext.posmm,2))],...
ones(1,size(ext.posmm,2)), st.vols{volhandle}.mat,...
[1 1 0]);
spm_orthviews('redraw');
end;
for sub = 1:size(ext,2)
switch plotsel
case 1,
dirs.dirsel='voxno';
case 2,
dirs.dirsel='imgno';
case 3,
dirs.dirsel='voxavg';
case 4,
dirs.dirsel='imgavg';
case 5,
dirsbch{1}.spm.tools.vgtbx_Diffusion.dti_extract_dirs.saveinf = 0;
dirsbch{1}.spm.tools.vgtbx_Diffusion.dti_extract_dirs.ref.refscanner = 1;
dirsbch{1}.spm.tools.vgtbx_Diffusion.dti_extract_dirs.sep = 1;
dirsbch{1}.spm.tools.vgtbx_Diffusion.dti_extract_dirs.dtol = .95;
dirsbch{1}.spm.tools.vgtbx_Diffusion.dti_extract_dirs.ltol = 10;
try
load(bch.src.srcspm{1});
dirsbch{1}.spm.tools.vgtbx_Diffusion.dti_extract_dirs.srcimgs=SPM.xY.P;
dirs = spm_jobman('run',dirsbch);
catch
try
dirsbch{1}.spm.tools.vgtbx_Diffusion.dti_extract_dirs.srcimgs = bch.src.srcimgs;
dirs = spm_jobman('run',dirsbch);
catch
error('Cannot extract DTI information for plotting.');
end;
end;
dirs = dirs{1};
end;
if plotsel
if ~isempty(ext(1,sub).raw)
try
data = cat(1,ext(:,sub).raw);
catch
fprintf(['Can not plot data from ' ...
'images with different ' ...
'voxel sizes and orientations.\n']);
error(lasterr);
end;
extract_fig(data,dirs, sprintf('ROI %d: Raw data',sub));
end;
if ~isempty(ext(1,sub).adj)
% in this case, we only have one ext
% struct per ROI
extract_fig(ext(1,sub).adj,dirs, sprintf('ROI %d: Fitted data',sub));
end;
end;
end;
end;
spm('pointer','arrow');
function extract_fig(data,dirres,titlestr)
figure;
axp = axes;
hold on;
title(titlestr);
if ischar(dirres.dirsel)
if strcmp(dirres.dirsel(1:3),'vox')
data = data';
end,
switch dirres.dirsel(4:end)
case 'no'
l = plot(data);
case 'avg'
plot(data,'rd');
lmean=plot(mean(data,2));
end;
set(axp,'Xgrid','on', 'Xtick',1:size(data,1));
ax = axis;
axis([.5 size(data,1)+.5 ax(3:4)])
else
% DTI plot
cmean = zeros(1,size(dirres.dirsel,1));
for k=1:size(dirres.dirsel,1)
cind= dirres.dirsel(k,:) ~= 0;
cdata=data(cind,:);
cmean(k)=mean(cdata(:));
plot(k,cdata(:),'rd');
end;
lmean=plot(cmean);
set(axp,'Xgrid','on', 'Xtick',1:size(cmean,2));
ax = axis;
axis([.5 size(cmean,2)+.5 ax(3:4)])
if isfield(dirres,'b')
lmeanb0=plot([1 size(dirres.dirsel,1)],cmean([1 1]),'r');
set(axp,'Position',[.13 .31 .775 .615])
axb=axes('Position',[.13 .21 .775 .05],...
'Xtick',.5:size(dirres.dirsel,1)+.5, 'XTickLabel',[],...
'Ytick',[], 'box','on');
hold on;
imagesc(dirres.b');
colormap gray;
axis tight;
axd=axes('Position',[.13 .16 .775 .05],...
'Xtick',.5:size(dirres.dirsel,1)+.5, 'XTickLabel',[],...
'Ytick',[],'box','on');
hold on;
imagesc(dirres.g',[-1 1]);
axis tight;
end;
end;
|
github
|
philippboehmsturm/antx-master
|
tbxvol_laterality.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/Volumes/Stats_Tools/tbxvol_laterality.m
| 1,709 |
utf_8
|
21c27d2d5e1d04f27ceebbe0b9334c1f
|
function varargout = tbxvol_laterality(bch)
% Compute laterality index of images with range [0,1]
% FORMAT tbxvol_laterality(bch)
% ======
% Input arguments:
% bch.srcimg - file name of input image
%
% This routine computes the laterality index for images with positive
% data range as (normal-flipped)./(normal+flipped) using spm_imcalc.
%
% This function is part of the volumes toolbox for SPM5. For general help
% about this toolbox, bug reports, licensing etc. type
% spm_help vgtbx_config_Volumes
% in the matlab command window after the toolbox has been launched.
%_______________________________________________________________________
%
% @(#) $Id: tbxvol_laterality.m 724 2012-01-24 13:26:05Z glauche $
rev = '$Revision: 724 $';
funcname = 'Compute laterality index';
% function preliminaries
Finter=spm_figure('GetWin','Interactive');
Finter=spm('FigName',funcname,Finter);
SPMid = spm('FnBanner',mfilename,rev);
% function code starts here
out.files = cellfun(@(src)prepend(src, bch.prefix), bch.srcimgs, 'UniformOutput', false);
cellfun(@(srcimg,oimg)comp_laterality(srcimg, oimg, bch.dtype, bch.interp), bch.srcimgs, out.files);
if nargout > 0
varargout{1} = out;
end
end
function comp_laterality(srcimg, oimg, dtype, interp)
Vo = rmfield(spm_vol(srcimg),'private');
V = [Vo Vo];
% flip 2nd image by pre-multiplying its coordinate transformation
V(2).mat = diag([-1 1 1 1])*V(2).mat;
% create output filename
Vo.fname = oimg;
Vo.n = [1 1];
if dtype ~= 0
Vo.dt(1) = dtype;
end;
Vo.pinfo = [Inf; 0; 0];
spm_imcalc(V, Vo, '(i1-i2)./(i1+i2)', {0, 0, interp});
end
function ofile = prepend(ifile, prefix)
[p n e v] = spm_fileparts(ifile);
ofile = fullfile(p,[prefix n e]);
end
|
github
|
philippboehmsturm/antx-master
|
tbxvol_orth_conditions.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/Volumes/Stats_Tools/tbxvol_orth_conditions.m
| 5,935 |
utf_8
|
2aaafa037ff5edeefe25805fee8b3a71
|
function varargout = tbxvol_orth_conditions(cmd, varargin)
% Orthogonalise conditions in an SPM design matrix.
% By default, SPM does not orthogonalise timeseries of different
% conditions. Under some conditions two conditions may be highly correlated
% (usually due to an imperfect experimental design). If only one of them is
% of interest, then the remaining ones can be orthogonalised with respect
% to this condition. The regressors of the orthogonalised conditions are
% no longer meaningful in itself, they only describe extra variance not
% caught by the regressors for the condition of interest.
%
% varargout = tbxvol_orth_conditions(cmd, varargin)
% where cmd is one of
% 'run' - out = tbxvol_orth_conditions('run', job)
% Run a job, and return its output argument
% 'vout' - dep = tbxvol_orth_conditions('vout', job)
% Examine a job structure with all leafs present and return an
% array of cfg_dep objects.
% 'check' - str = tbxvol_orth_conditions('check', subcmd, subjob)
% Examine a part of a fully filled job structure. Return an empty
% string if everything is ok, or a string describing the check
% error. subcmd should be a string that identifies the part of
% the configuration to be checked.
% 'defaults' - defval = tbxvol_orth_conditions('defaults', key)
% Retrieve defaults value. key must be a sequence of dot
% delimited field names into the internal def struct which is
% kept in function local_def. An error is returned if no
% matching field is found.
% tbxvol_orth_conditions('defaults', key, newval)
% Set the specified field in the internal def struct to a new
% value.
% Application specific code needs to be inserted at the following places:
% 'run' - main switch statement: code to compute the results, based on
% a filled job
% 'vout' - main switch statement: code to compute cfg_dep array, based
% on a job structure that has all leafs, but not necessarily
% any values filled in
% 'check' - create and populate switch subcmd switchyard
% 'defaults' - modify initialisation of defaults in subfunction local_defs
% Callbacks can be constructed using anonymous function handles like this:
% 'run' - @(job)tbxvol_orth_conditions('run', job)
% 'vout' - @(job)tbxvol_orth_conditions('vout', job)
% 'check' - @(job)tbxvol_orth_conditions('check', 'subcmd', job)
% 'defaults' - @(val)tbxvol_orth_conditions('defaults', 'defstr', val{:})
% Note the list expansion val{:} - this is used to emulate a
% varargin call in this function handle.
%
% This code is part of a batch job configuration system for MATLAB. See
% help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging
% Volkmar Glauche
% $Id: tbxvol_orth_conditions.m 631 2008-09-02 12:18:36Z glauche $
rev = '$Rev: 631 $'; %#ok
if ischar(cmd)
switch lower(cmd)
case 'run'
job = local_getjob(varargin{1});
% do computation, return results in variable out
load(job.srcspm{1});
for k=1:numel(job.Sess)
Fcind = SPM.Sess(job.Sess(k).num).col(cat(2,SPM.Sess(job.Sess(k).num).Fc(job.Sess(k).c).i));
SPM.xX.X(:,Fcind) = spm_orth(SPM.xX.X(:,Fcind));
end
out.outspm = job.srcspm;
copyfile(job.srcspm{1}, sprintf('%s.save',job.srcspm{1}));
save(out.outspm{1},'SPM','-v7')
if nargout > 0
varargout{1} = out;
end
case 'vout'
job = local_getjob(varargin{1});
% initialise empty cfg_dep array
dep = cfg_dep;
% determine outputs, return cfg_dep array in variable dep
dep(1).sname = 'SPM.mat (orthogonalised)';
dep(1).src_output = substruct('.','outspm');
dep(1).tgt_spec = cfg_findspec({{'strtype','e','filter','mat'}});
varargout{1} = dep;
case 'check'
if ischar(varargin{1})
subcmd = lower(varargin{1});
subjob = varargin{2};
str = '';
switch subcmd
% implement checks, return status string in variable str
otherwise
cfg_message('unknown:check', ...
'Unknown check subcmd ''%s''.', subcmd);
end
varargout{1} = str;
else
cfg_message('ischar:check', 'Subcmd must be a string.');
end
case 'defaults'
if nargin == 2
varargout{1} = local_defs(varargin{1});
else
local_defs(varargin{1:2});
end
otherwise
cfg_message('unknown:cmd', 'Unknown command ''%s''.', cmd);
end
else
cfg_message('ischar:cmd', 'Cmd must be a string.');
end
function varargout = local_defs(defstr, defval)
persistent defs;
if isempty(defs)
% initialise defaults
end
if ischar(defstr)
% construct subscript reference struct from dot delimited tag string
tags = textscan(defstr,'%s', 'delimiter','.');
subs = struct('type','.','subs',tags{1}');
try
cdefval = subsref(local_def, subs);
catch
cdefval = [];
cfg_message('defaults:noval', ...
'No matching defaults value ''%s'' found.', defstr);
end
if nargin == 1
varargout{1} = cdefval;
else
defs = subsasgn(defs, subs, defval);
end
else
cfg_message('ischar:defstr', 'Defaults key must be a string.');
end
function job = local_getjob(job)
if ~isstruct(job)
cfg_message('isstruct:job', 'Job must be a struct.');
end
|
github
|
philippboehmsturm/antx-master
|
tbxvol_hist_summary.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/Volumes/Stats_Tools/tbxvol_hist_summary.m
| 4,425 |
utf_8
|
bda66ed96d74109d394c178884a9f31e
|
function varargout = tbxvol_hist_summary(cmd, varargin)
% Compute histogramm summary
% FORMAT tbxvol_hist_summary(bch)
% ======
%
% This function is part of the volumes toolbox for SPM5. For general help
% about this toolbox, bug reports, licensing etc. type
% spm_help vgtbx_config_Volumes
% in the matlab command window after the toolbox has been launched.
%_______________________________________________________________________
%
% @(#) $Id: tbxvol_hist_summary.m 712 2010-06-30 14:20:19Z glauche $
rev = '$Revision: 712 $';
if ischar(cmd)
switch lower(cmd)
case 'run'
job = local_getjob(varargin{1});
out = local_hist_summary(job);
% do computation, return results in variable out
if nargout > 0
varargout{1} = out;
end
case 'vout'
job = local_getjob(varargin{1});
% initialise empty cfg_dep array
dep = cfg_dep;
dep = dep(false);
% determine outputs, return cfg_dep array in variable dep
for k = 1:numel(job.subjects)
dep(k) = cfg_dep;
dep(k).sname = sprintf('Extracted histogramm data - Subject %d',k);
dep(k).src_output = substruct('{}', {k});
dep(k).tgt_spec = cfg_findspec({{'strtype','e'}});
end
varargout{1} = dep;
% case 'check'
% if ischar(varargin{1})
% subcmd = lower(varargin{1});
% subjob = varargin{2};
% str = '';
% switch subcmd
% % implement checks, return status string in variable str
% otherwise
% cfg_message('unknown:check', ...
% 'Unknown check subcmd ''%s''.', subcmd);
% end
% varargout{1} = str;
% else
% cfg_message('ischar:check', 'Subcmd must be a string.');
% end
% case 'defaults'
% if nargin == 2
% varargout{1} = local_defs(varargin{1});
% else
% local_defs(varargin{1:2});
% end
otherwise
cfg_message('unknown:cmd', 'Unknown command ''%s''.', cmd);
end
else
cfg_message('ischar:cmd', 'Cmd must be a string.');
end
function job = local_getjob(job)
if ~isstruct(job)
cfg_message('isstruct:job', 'Job must be a struct.');
end
function varargout = local_hist_summary(bch)
% test, whether statistics toolbox is installed
stats = license('test','statistics_toolbox');
spm_progress_bar('init',numel(bch.subjects),'Subjects completed')
ext = cell(size(bch.subjects));
for k = 1:numel(bch.subjects)
for m = 1:numel(bch.subjects(k).maskimgs)
Vm = spm_vol(bch.subjects(k).maskimgs{m});
for l = 1:numel(bch.subjects(k).srcimgs)
Vi = spm_vol(bch.subjects(k).srcimgs{l});
dat = [];
nvx = 0;
%-Loop over planes computing result Y
%-----------------------------------------------------------------------
for p = 1:Vi.dim(3),
B = spm_matrix([0 0 -p 0 0 0 1 1 1]);
M = inv(B/Vi.mat*Vm.mat);
msk = logical(spm_slice_vol(Vm,M,Vi.dim(1:2),[0,0]));
tmp = spm_slice_vol(Vi,inv(B),Vi.dim(1:2),[0,NaN]);
msk = msk & isfinite(tmp);
dat = [dat; tmp(msk(:))];
nvx = nvx + nnz(msk(:));
end;
cext.volvx = nvx;
cext.volmm3 = prod(sqrt(sum(Vi.mat(1:3,1:3).^2)))*nvx;
cext.median = median(dat);
cext.mean = mean(dat);
if stats
cext.skewness = skewness(dat);
cext.kurtosis = kurtosis(dat);
else
cext.skewness = [];
cext.kurtosis = [];
end;
cext.std = std(dat);
cext.hist = histc(dat,bch.bins);
cext.low = sum(dat<min(bch.bins));
cext.high = sum(dat>max(bch.bins));
ext{k}{m,l} = cext;
end;
end;
spm_progress_bar('set',k);
end;
spm_progress_bar('clear');
spm_input('!DeleteInputObj');
if nargout > 0
varargout{1}=ext;
else
assignin('base','ext',ext);
fprintf('extracted data saved to workspace variable ''ext''\n');
disp(ext);
end;
|
github
|
philippboehmsturm/antx-master
|
tbxvol_changeSPM.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/Volumes/Stats_Tools/tbxvol_changeSPM.m
| 6,862 |
utf_8
|
ecf4e78064941de74e69f7a0bfd78cf5
|
function varargout = tbxvol_changeSPM(bch)
% Change path names or byte order of image files in SPM structure
% FORMAT tbxvol_changeSPM(bch)
% ======
% Input arguments:
% bch.srcspm - file name of SPM.mat files to change
% bch.chpaths - which paths to change: one of
% - .dpaths - data files
% - .apaths - analysis files
% - .bpaths - both
% - .npaths - none
% .{d,a,b}paths.oldpath - path component to be replaced OR
% - "auto" automatically determine component
% - "ask" automatically determine component, but ask before
% replacing
% - .{d,a,b}paths.newpath - path component to be inserted OR
% - "auto" automatically determine component
% - "ask" automatically determine component, but ask before
% replacing
% bch.swap - swap byte order code of volume datatypes
%
% For all absolute references in SPM.xY occurences of oldpath are
% replaced by newpath (using Matlab strrep). This will only work if the
% overall structure of the file tree has not changed (i.e. moving an
% entire analysis dir will work, but not renaming each individual
% subject). In addition, byte order information of mapped files can be
% changed without touching other file information (such as scaling,
% dimensions etc).
% The new SPM struct is saved to the original SPM.mat file. A copy of the
% original SPM.mat is kept in the same directory under the filename
% SPM.mat.save.
% Multiple SPM.mat file names can be given, and the same string
% replacement will be done for all of them.
%
% This function is part of the volumes toolbox for SPM5. For general help
% about this toolbox, bug reports, licensing etc. type
% spm_help vgtbx_config_Volumes
% in the matlab command window after the toolbox has been launched.
%_______________________________________________________________________
%
% @(#) $Id: tbxvol_changeSPM.m 714 2010-07-30 14:28:55Z glauche $
rev = '$Revision: 714 $';
funcname = 'Change SPM.mat paths';
% function preliminaries
Finter=spm_figure('GetWin','Interactive');
Finter=spm('FigName',funcname,Finter);
SPMid = spm('FnBanner',mfilename,rev);
% function code starts here
load(bch.srcspm{1});
% save a copy
[newp n e] = fileparts(bch.srcspm{1});
save_cfg=fullfile(newp, [n e '.save']);
if spm_matlab_version_chk('7') < 0
save(save_cfg, '-mat', 'SPM');
else
save(save_cfg, '-mat', '-V6', 'SPM');
end;
chpaths = fieldnames(bch.chpaths);
if ~strcmp(chpaths{1},'npaths')
if isfield(SPM,'swd')
oldp = SPM.swd;
else
if iscell(SPM.xY.P)
[oldp n e v] = spm_fileparts(SPM.xY.P{1});
else
[oldp n e v] = spm_fileparts(SPM.xY.P(1,:));
end;
end;
% try to be smart in finding leading path differences
% first, tokenise paths
ot={};
[op ot{end+1}] = fileparts(oldp);
while ~isempty(ot{end})
[op ot{end+1}] = fileparts(op);
end;
ot=ot(1:end-1);
nt={};
[np nt{end+1}] = fileparts(newp);
while ~isempty(nt{end})
[np nt{end+1}] = fileparts(np);
end;
nt=nt(1:end-1);
commp='';
for k=1:min(numel(nt),numel(ot))
if strcmp(nt{k},ot{k})
commp=fullfile(nt{k},commp);
else
break;
end;
end;
oldp = strrep(oldp,commp,'');
newp = strrep(newp,commp,'');
switch bch.chpaths.(chpaths{1}).oldpath
case 'ask',
bch.chpaths.(chpaths{1}).oldpath = spm_input('Replace path component','!+1','s',oldp);
case 'auto',
bch.chpaths.(chpaths{1}).oldpath = oldp;
end;
switch bch.chpaths.(chpaths{1}).newpath
case 'ask',
bch.chpaths.(chpaths{1}).newpath = spm_input('Insert path component','!+1','s',newp);
case 'auto',
bch.chpaths.(chpaths{1}).newpath = newp;
end;
if strcmp(chpaths{1},'dpaths')||strcmp(chpaths{1},'bpaths')
if iscell(SPM.xY.P)
oldP=SPM.xY.P;
else
oldP=cellstr(SPM.xY.P);
end;
newP = cell(size(oldP));
for k=1:numel(oldP)
fprintf('Old file name: %s\n', oldP{k});
newP{k}=strrep(oldP{k},bch.chpaths.(chpaths{1}).oldpath,...
bch.chpaths.(chpaths{1}).newpath);
SPM.xY.VY(k).fname=strrep(SPM.xY.VY(k).fname,...
bch.chpaths.(chpaths{1}).oldpath,...
bch.chpaths.(chpaths{1}).newpath);
fprintf('New file name: %s\n', newP{k});
end
if iscell(SPM.xY.P)
SPM.xY.P=newP;
else
SPM.xY.P=char(newP);
end;
end;
if strcmp(chpaths{1},'apaths')||strcmp(chpaths{1},'bpaths')
% strip paths from SPM analysis files
try
[p n e v] = spm_fileparts(SPM.xVol.VRpv.fname);
SPM.xVol.VRpv.fname = [n e v];
end;
for cb = 1:numel(SPM.Vbeta)
try
[p n e v] = spm_fileparts(SPM.Vbeta(cb).fname);
SPM.Vbeta(cb).fname = [n e v];
end;
end;
try
[p n e v] = spm_fileparts(SPM.VResMS.fname);
SPM.VResMS.fname = [n e v];
end;
try
[p n e v] = spm_fileparts(SPM.xM.VM.fname);
SPM.xM.VM.fname = [n e v];
end;
for cc = 1:numel(SPM.xCon)
try
[p n e v] = spm_fileparts(SPM.xCon(cc).Vcon.fname);
SPM.xCon(cc).Vcon.fname = [n e v];
end
try
[p n e v] = spm_fileparts(SPM.xCon(cc).Vspm.fname);
SPM.xCon(cc).Vspm.fname = [n e v];
end
end;
% replace SPM.swd with path to SPM.mat
[p n e v] = spm_fileparts(bch.srcspm{1});
SPM.swd = p;
end;
end;
if bch.swap
try
SPM.xVol.VRpv = swaporder(SPM.xVol.VRpv);
end;
try
SPM.Vbeta = swaporder(SPM.Vbeta);
end;
try
SPM.VResMS = swaporder(SPM.VResMS);
end;
try
SPM.xM.VM = swaporder(SPM.xM.VM);
end
try
for cc = 1:numel(SPM.xCon)
try
SPM.xCon(cc).Vcon = swaporder(SPM.xCon(cc).Vcon);
end;
try
SPM.xCon(cc).Vspm = swaporder(SPM.xCon(cc).Vspm);
end;
end;
end;
for k = 1:numel(SPM.xY.VY)
SPM.xY.VY(k) = swaporder(SPM.xY.VY(k));
end;
end;
if spm_matlab_version_chk('7') < 0
save(bch.srcspm{1},'SPM','-append');
else
save(bch.srcspm{1},'SPM','-append','-V6');
end;
function Vo=swaporder(V)
Vo=V;
for k=1:numel(V)
if isfield(Vo,'dt')
Vo.dt(2) = ~Vo.dt(2);
else
warning(['File %s:\n Pre-SPM5-style SPM.mat. No byte ' ...
'swapping applied.\n'], Vo.fname);
end;
end;
|
github
|
philippboehmsturm/antx-master
|
tbxvol_extract.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/Volumes/Single_Volumes/tbxvol_extract.m
| 8,179 |
utf_8
|
27680807150f62c0c527f5fe5638f7a9
|
function varargout=tbxvol_extract(bch)
% read an intensity profile along a given trajectory
% FORMAT extr=tbxvol_extract(bch)
% ======
% Read intensity values from a set of images within one or more given
% regions of interest. The images to be sampled can be specified by an
% SPM.mat or a list of images.
% Multiple ROIs can be defined on the same image set. ROIs can be
% specified as images (all voxels of the mask image with intensities
% other than 0 will be included), sphere around a certain point,
% pointlist, or a line through the image defined by start point, end
% point and sampling distance.
% Note, that all coordinates need to be given in mm coordinates. However,
% for mask images and spheres the sampled coordinates will be determined
% in each image's voxel space (such that all voxels within the scope of
% the mask or sphere will be sampled exactly once), whereas for point
% lists and trajectories the given mm coordinates will be translated into
% voxel coordinates, regardless of whether two of them specify the same
% voxel or the sampling will miss out voxels in between the specified
% points.
%
% If an SPM.mat is given, the extracted data will be saved in an
% 1-by-#ROI struct array with fields
% .posmm - mm positions sampled in ROI
% .posvx - voxel positions sampled in ROI
% .raw - raw data, read from images (scaled as in the SPM.mat)
% .adj - SPM.xX.X*beta fitted data
% If images are given as a list of filenames, the extracted data will be
% saved as a #imgs-by-#ROI struct array as described above, but with an
% empty .adj field.
%
% If no output argument is given, extracted data will be saved into
% Matlab's standard workspace and can be treatead as any other Matlab
% variable.
% To access the extracted data in a SPM batch job, use "Pass Output to
% Workspace" or "Save Variables" from BasicIO.
%
% This function is part of the volumes toolbox for SPM. For general help
% about this toolbox, bug reports, licensing etc. type
% spm_help vgtbx_config_Volumes
% in the matlab command window after the toolbox has been launched.
%_______________________________________________________________________
%
% @(#) $Id: tbxvol_extract.m 722 2011-10-18 12:21:24Z glauche $
rev = '$Revision: 722 $';
funcname = 'Extract Trajectory/ROI';
% function preliminaries
Finter=spm_figure('GetWin','Interactive');
Finter=spm('FigName',funcname,Finter);
SPMid = spm('FnBanner',mfilename,rev);
% function code starts here
res = struct('raw',[], 'adj',[], 'posmm',[], 'Vspace',[]);
if isfield(bch.src, 'srcspm')
opwd = pwd;
p = fileparts(bch.src.srcspm{1});
cd(p);
load(bch.src.srcspm{1});
for l = 1:numel(bch.roispec)
spm_progress_bar('init', numel(SPM.Vbeta),...
'ROI - Fitted data',...
'Volumes sampled');
% assume all images of one analysis are in the same space
res(1,l).Vspace = rmfield(SPM.Vbeta(1),{'fname','private'});
[res(1,l).posmm res(1,l).posvx] = get_pos(bch.roispec{l}, res(1,l).Vspace);
beta = zeros(numel(SPM.Vbeta),size(res(1,l).posvx,2));
for k = 1:numel(SPM.Vbeta)
beta(k,:) = spm_sample_vol(SPM.Vbeta(k), ...
res(1,l).posvx(1,:),res(1,l).posvx(2,:),res(1,l).posvx(3,:), bch.interp);
spm_progress_bar('set',k);
end;
adj = SPM.xX.X*beta;
clear beta;
switch bch.avg
case 'none'
res(1,l).adj = adj;
case 'vox'
res(1,l).adj.mean = zeros(size(adj,1),1);
res(1,l).adj.std = zeros(size(adj,1),1);
spm_progress_bar('init', size(adj,1), 'ROI - Adjusted data',...
'Averaging');
for k = 1:size(adj,1)
res(1,l).adj.mean(k) = mean(adj(k,:));
res(1,l).adj.std(k) = std(adj(k,:));
spm_progress_bar('set',k);
end;
end;
clear adj;
spm_progress_bar('init', numel(SPM.xY.VY), 'ROI - Raw data',...
'Volumes sampled');
switch bch.avg
case 'none'
res(1,l).raw = zeros(numel(SPM.xY.VY),size(res(1,l).posvx, ...
2));
case 'vox'
res(1,l).raw.mean = zeros(numel(SPM.xY.VY),1);
res(1,l).raw.std = zeros(numel(SPM.xY.VY),1);
end;
for k = 1:numel(SPM.xY.VY)
raw = spm_sample_vol(SPM.xY.VY(k),...
res(1,l).posvx(1,:),res(1,l).posvx(2,:),res(1,l).posvx(3,:), ...
bch.interp);
switch bch.avg
case 'none'
res(1,l).raw(k,:) = raw;
case 'vox',
res(1,l).raw.mean(k) = mean(raw);
res(1,l).raw.std(k) = std(raw);
spm_progress_bar('set',k);
end;
end;
end;
cd(opwd);
else
spm_progress_bar('init', numel(bch.src.srcimgs), ...
'Trajectory/ROI', 'volumes completed');
for k=1:numel(bch.src.srcimgs)
V = spm_vol(bch.src.srcimgs{k});
for l = 1:numel(bch.roispec)
res(k,l).Vspace = rmfield(V,{'fname','private'});
[res(k,l).posmm res(k,l).posvx] = get_pos(bch.roispec{l},V);
raw = spm_sample_vol(V, res(k,l).posvx(1,:), ...
res(k,l).posvx(2,:), res(k,l).posvx(3,:), ...
bch.interp);
switch bch.avg
case 'none'
res(k,l).raw = raw;
case 'vox'
res(k,l).raw.mean = mean(raw);
res(k,l).raw.std = std(raw);
end;
end;
spm_progress_bar('set',k);
end;
end;
spm_progress_bar('clear');
if nargout > 0
varargout{1}=res;
else
assignin('base','ext',res);
fprintf('extracted data saved to workspace variable ''ext''\n');
disp(res);
end;
function [posmm, posvx] = get_pos(roispec, V)
if isfield(roispec, 'roiline')
% get points in mm space, then convert to voxel space
dt = roispec.roiline.roiend-roispec.roiline.roistart;
ldt = sqrt(sum(dt.^2));
posmm = dt*(0:roispec.roiline.roistep/ldt:1) +...
repmat(roispec.roiline.roistart, [1 length(0:roispec.roiline.roistep:ldt)]);
posvx = V.mat\[posmm; ones(1,size(posmm,2))];
posvx = posvx(1:3,:);
elseif isfield(roispec, 'roilineparam')
% get points in mm space, then convert to voxel space
dt = roispec.roilineparam.roilinep1-roispec.roilineparam.roilinep2;
ldt = sqrt(sum(dt.^2));
posmm = (dt/ldt)*roispec.roilineparam.roilinecoords + ...
repmat(roispec.roilineparam.roilinep1, ...
size(roispec.roilineparam.roilinecoords));
posvx = V.mat\[posmm; ones(1,size(posmm,2))];
posvx = posvx(1:3,:);
elseif isfield(roispec, 'srcimg')
% resample mask VM in space of current image V
VM = spm_vol(roispec.srcimg{1});
x = []; y = []; z = [];
[x1 y1] = ndgrid(1:V.dim(1),1:V.dim(2));
for p = 1:V.dim(3)
B = spm_matrix([0 0 -p 0 0 0 1 1 1]);
M = VM.mat\(V.mat/B);
msk = find(spm_slice_vol(VM,M,V.dim(1:2),0));
if ~isempty(msk)
z1 = p*ones(size(msk(:)));
x = [x; x1(msk(:))];
y = [y; y1(msk(:))];
z = [z; z1];
end;
end;
posvx = [x'; y'; z'];
xyzmm = V.mat*[posvx;ones(1,size(posvx,2))];
posmm = xyzmm(1:3,:);
elseif isfield(roispec, 'roisphere')
cent = round(V.mat\[roispec.roisphere.roicent; 1]);
tmp = spm_imatrix(V.mat);
vdim = tmp(7:9);
vxrad = ceil((roispec.roisphere.roirad*ones(1,3))./ ...
vdim)';
[x y z] = ndgrid(-vxrad(1):sign(vdim(1)):vxrad(1), ...
-vxrad(2):sign(vdim(2)):vxrad(2), ...
-vxrad(3):sign(vdim(3)):vxrad(3));
sel = (x./vxrad(1)).^2 + (y./vxrad(2)).^2 + (z./vxrad(3)).^2 <= 1;
x = cent(1)+x(sel(:));
y = cent(2)+y(sel(:));
z = cent(3)+z(sel(:));
posvx = [x y z]';
xyzmm = V.mat*[posvx;ones(1,size(posvx,2))];
posmm = xyzmm(1:3,:);
elseif isfield(roispec, 'roilist')
posmm = roispec.roilist;
posvx = V.mat\[posmm; ones(1,size(posmm,2))];
posvx = posvx(1:3,:);
end;
|
github
|
philippboehmsturm/antx-master
|
tbxvol_extract2image.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/Volumes/Single_Volumes/tbxvol_extract2image.m
| 6,869 |
utf_8
|
7503acd7ed22a4ca14ae4dfb97f9ae1e
|
function varargout = tbxvol_extract2image(cmd, varargin)
% Place output from tbxvol_extract back into an image
% varargout = tbxvol_extract2image(cmd, varargin)
% where cmd is one of
% 'run' - out = tbxvol_extract2image('run', job)
% Run a job, and return its output argument
% job has the following fields
% .outdir
% .outfilename
% .dtype
% .extsrc
% either .extspec or .extvar. extvar is a extraction
% variable, .extspec is a struct with fields
% .fname file name of image defining reference space
% .raw data
% .posvx position of voxels in voxel space
% 'vout' - dep = tbxvol_extract2image('vout', job)
% Examine a job structure with all leafs present and return an
% array of cfg_dep objects.
% 'check' - str = tbxvol_extract2image('check', subcmd, subjob)
% Examine a part of a fully filled job structure. Return an empty
% string if everything is ok, or a string describing the check
% error. subcmd should be a string that identifies the part of
% the configuration to be checked.
% 'defaults' - defval = tbxvol_extract2image('defaults', key)
% Retrieve defaults value. key must be a sequence of dot
% delimited field names into the internal def struct which is
% kept in function local_def. An error is returned if no
% matching field is found.
% tbxvol_extract2image('defaults', key, newval)
% Set the specified field in the internal def struct to a new
% value.
% Application specific code needs to be inserted at the following places:
% 'run' - main switch statement: code to compute the results, based on
% a filled job
% 'vout' - main switch statement: code to compute cfg_dep array, based
% on a job structure that has all leafs, but not necessarily
% any values filled in
% 'check' - create and populate switch subcmd switchyard
% 'defaults' - modify initialisation of defaults in subfunction local_defs
% Callbacks can be constructed using anonymous function handles like this:
% 'run' - @(job)tbxvol_extract2image('run', job)
% 'vout' - @(job)tbxvol_extract2image('vout', job)
% 'check' - @(job)tbxvol_extract2image('check', 'subcmd', job)
% 'defaults' - @(val)tbxvol_extract2image('defaults', 'defstr', val{:})
% Note the list expansion val{:} - this is used to emulate a
% varargin call in this function handle.
%
% This code is part of a batch job configuration system for MATLAB. See
% help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging
% Volkmar Glauche
% $Id: tbxvol_extract2image.m 680 2009-09-15 12:56:30Z glauche $
rev = '$Rev: 680 $'; %#ok
if ischar(cmd)
switch lower(cmd)
case 'run'
job = local_getjob(varargin{1});
% do computation, return results in variable out
% get volume information for output image - must be the same
% orientation and voxel size as the extraction space
if isfield(job.extsrc,'extspec')
ext = job.extsrc.extspec;
ext.Vspace = rmfield(spm_vol(job.extsrc.extspec.fspace),'private');
elseif isfield(job.extsrc,'extvar')
ext = job.extsrc.extvar;
end
% set new filename and scaling
[p n e v] = spm_fileparts(job.outfilename);
if ~any(strcmpi(e,{'.img','.nii'}))
e = '.nii';
end
if job.dtype > 0
ext.Vspace.dt(1) = job.dtype;
end
ext.Vspace.fname = fullfile(job.outdir{1}, [n e v]);
ext.Vspace.pinfo(1:2) = inf;
% create output array
dat = zeros(ext.Vspace.dim);
% ext is the extraction structure - use its position
% information to get a linear index into the data array
ind = sub2ind(ext.Vspace.dim(1:3), round(ext.posvx(1,:)), ...
round(ext.posvx(:,2)), round(ext.posvx(:,3)));
% put back all raw data - this will work only for single-volume
% extracted data
dat(ind) = ext.raw;
% write the image
spm_create_vol(ext.Vspace);
spm_write_vol(ext.Vspace,dat);
out.image = {ext.Vspace.fname};
if nargout > 0
varargout{1} = out;
end
case 'vout'
job = local_getjob(varargin{1});
% initialise empty cfg_dep array
dep = cfg_dep;
dep.sname = 'Exported image';
dep.src_output = substruct('.','image');
dep.tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
% determine outputs, return cfg_dep array in variable dep
varargout{1} = dep;
case 'check'
if ischar(varargin{1})
subcmd = lower(varargin{1});
subjob = varargin{2};
str = '';
switch subcmd
% implement checks, return status string in variable str
otherwise
cfg_message('unknown:check', ...
'Unknown check subcmd ''%s''.', subcmd);
end
varargout{1} = str;
else
cfg_message('ischar:check', 'Subcmd must be a string.');
end
case 'defaults'
if nargin == 2
varargout{1} = local_defs(varargin{1});
else
local_defs(varargin{1:2});
end
otherwise
cfg_message('unknown:cmd', 'Unknown command ''%s''.', cmd);
end
else
cfg_message('ischar:cmd', 'Cmd must be a string.');
end
function varargout = local_defs(defstr, defval)
persistent defs;
if isempty(defs)
% initialise defaults
end
if ischar(defstr)
% construct subscript reference struct from dot delimited tag string
tags = textscan(defstr,'%s', 'delimiter','.');
subs = struct('type','.','subs',tags{1}');
try
cdefval = subsref(local_def, subs);
catch
cdefval = [];
cfg_message('defaults:noval', ...
'No matching defaults value ''%s'' found.', defstr);
end
if nargin == 1
varargout{1} = cdefval;
else
defs = subsasgn(defs, subs, defval);
end
else
cfg_message('ischar:defstr', 'Defaults key must be a string.');
end
function job = local_getjob(job)
if ~isstruct(job)
cfg_message('isstruct:job', 'Job must be a struct.');
end
|
github
|
philippboehmsturm/antx-master
|
amr_test_fit.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/Perfusion/amr_test_fit.m
| 3,362 |
utf_8
|
02b23187c24963f7c81571e691674dc2
|
function [fitfunc] = amr_test_fit(base, tail, rcbv,at,alpha,beta,method);
%
% function [fitfunc] = amr_test_fit(base, tail, rcbv,at,alpha,beta,method);
%
% method: 'ge' or 'se'; default is 'ge'
%
% Examples:
% for ge:
% [fitfunc_ge] = amr_test_fit(base_ge, tail_ge, rcbv_ge,at_ge,alpha_ge,beta_ge,'ge');
% for se:
% [fitfunc_se] = amr_test_fit(base_se, tail_se, rcbv_se,at_se,alpha_se,beta_se,'se');
%
if mrstruct_istype(base,'volume')
[size_x,size_y,size_z] = size(base.dataAy);
n_slices = size_z;
fitfunc = mrstruct_init('series3D');
elseif mrstruct_istype(base,'image')
[size_x,size_y] = size(base.dataAy);
size_z=1;
fitfunc = mrstruct_init('series2D');
end
amr_global
if (nargin >= 7)
if strcmp(method,'ge')
amr_init_ge;
elseif strcmp(method,'se')
amr_init_se;
end
else
amr_init_ge;
end
TE = base.te/1000;
skip = DEFAULT_POWELL(1);
kon = 1;
default_powell = [DEFAULT_POWELL TE];
size_t = rcbv.user;
t = 1:size_t;
S0_start = DEFAULT_POWELL(1);
S0_stop = DEFAULT_POWELL(2);
SE_int = DEFAULT_POWELL(3);
dil_rate = 10;
im_size = size_x*size_y;
% slice = 7;
for slice=1:size_z;
%data = squeeze(reshape(in.dataAy(:,:,slice,:),im_size,size_t));
if mrstruct_query(alpha,'size_z')==1
slice=1
end
alpha1 = alpha.dataAy(:,:,slice);
beta1 = beta.dataAy(:,:,slice);
rcbv1 = rcbv.dataAy(:,:,slice);
at1 = at.dataAy(:,:,slice);
base1 = base.dataAy(:,:,slice);
tail1 = tail.dataAy(:,:,slice);
alpha1 = alpha1(:);
beta1 = beta1(:);
rcbv1 = rcbv1(:);
at1 = at1(:);
base1 = base1(:);
tail1 = tail1(:);
if length(at1)~=im_size
error('Image size of data and parameter maps do not fit!');
end;
mask = zeros(im_size,1);
at1 = at1+ 1; % t0 in matlab= 1, in real. aber t0= 0;
mask = find(beta1 ~=0);
mask_size = length(mask);
out = zeros(im_size,size_t);
alpha1 = alpha1(mask);
beta1 = beta1(mask);
rcbv1 = rcbv1(mask);
at1 = at1(mask);
base1 = base1(mask);
tail1 = tail1(mask);
%for k=1:mask_size
tat = ones([1 mask_size])'*t;
tat = tat- (at1*ones([1 size_t]));
ind = find(tat<0);
tat(ind)= 0;
rcbv1 = rcbv1 * ones([1 size_t]);
Ct = rcbv1.*gammafunc(tat,alpha1,beta1,size_t);
rbf_S0 = base1;
rbf_SE = tail1;
rbf_SS = rbf_S0 - rbf_SE;
rbf_S0 = rbf_S0 * ones([1 size_t]);
y = rbf_S0.* exp(-kon.*TE.*Ct);
rbf_SS = rbf_SS * ones([1 size_t]);
dil = (1- exp(-tat./dil_rate)).* rbf_SS;
% y = y-dil;
out(mask,:)=y;
%end;
out = reshape(out,size_x,size_y,size_t);
fitfunc.dataAy(:,:,slice,:) = out;
end;
fitfunc.vox = base.vox;
fitfunc.patient = base.patient;
fitfunc.te = base.te;
fitfunc.tr = base.tr;
fitfunc.method = base.method;
clear A tmp A_min_max mi ma mask mask_size im_size slice i;
clear alpha1 beta1 rcbv1 base1 rcbf1;
function f = gammafunc(x,alpha,beta,size_t);
alpha = alpha * ones([1 size_t]);
beta = beta * ones([1 size_t]);
f = x.^alpha.*exp(-x./beta)./gamma(alpha+1)./beta.^(alpha+1);
|
github
|
philippboehmsturm/antx-master
|
tbxrend_nifti_to_df3.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/Render3D/tbxrend_nifti_to_df3.m
| 1,912 |
utf_8
|
b2c969d334a35385f40a16d7579aa38a
|
function tbxrend_nifti_to_df3(bch)
% export NIfTI image to POVray df3 format
% produces the df3 file itself and a coordinate transform from unit cube
% to NIfTI world space
% bch.srcimg
% bch.outimg.fname
% bch.outimg.swd
% bch.outres - 'uint8','uint16','uint32'
% data will be scaled to fit range, non-finite values set to minimum of data. A mask
% df3 will be written which contains 1 for valid data, 0 for non-finite data
V = spm_vol(bch.srcimg{1});
[ps ns e v] = spm_fileparts(bch.srcimg{1});
if isempty(bch.outimg.swd{1})
po = ps;
else
po = bch.outimg.swd{1};
end;
if isempty(bch.outimg.fname)
no = ns;
else
no = bch.outimg.fname;
end;
out.dfile{1} = fullfile(po,[ns '.df3']);
out.mfile{1} = fullfile(po,[ns '_msk.df3']);
out.dinclude{1} = fullfile(po,[ns '.inc']);
out.minclude{1} = fullfile(po,[ns '_msk.inc']);
X = spm_read_vols(V);
msk = uint8(isfinite(X));
mn = min(X(logical(msk(:))));
mx = max(X(logical(msk(:))));
X(~logical(msk)) = mn;
switch bch.outres
case 'uint8'
mxval = 2^8-1;
case 'uint16'
mxval = 2^16-1;
case 'uint32'
mxval = 2^32-1;
end;
dat = eval(sprintf('%s(round((X-mn)/(mx-mn)*mxval))',bch.outres));
fid = fopen(out.dfile{1},'w','ieee-be');
fwrite(fid,uint16(V.dim(1:3)),'uint16');
fwrite(fid,dat,bch.outres);
fclose(fid);
fid = fopen(out.mfile{1},'w','ieee-be');
fwrite(fid,uint16(V.dim(1:3)),'uint16');
fwrite(fid,msk,'uint8');
fclose(fid);
% transformation from unit cube to mm via voxels
M = V.mat*[diag(V.dim(1:3)-1) ones(3,1); 0 0 0 1];
write_include(out.dinclude{1}, out.dfile{1}, M);
write_include(out.minclude{1}, out.mfile{1}, M);
function write_include(iname, dname, M)
fid = fopen(iname,'w');
fprintf(fid,'{\n density_file df3 "%s"\n', dname);
fprintf(fid,' matrix < %.02f, %.02f, %.02f,\n %.02f, %.02f, %.02f,\n %.02f, %.02f, %.02f,\n %.02f, %.02f, %.02f >\n', M(1:3,:));
fprintf(fid,'}\n');
fclose(fid);
|
github
|
philippboehmsturm/antx-master
|
tbxrend_export_surf.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/Render3D/tbxrend_export_surf.m
| 1,692 |
utf_8
|
2ddd5ddf94e98d9dd38aa20da08a4f47
|
function tbxvol_export_surf(srf)
% export surfaces to blender format
% can handle either patch structures or patch graphics objects
% in the latter case, colouring will be approximately translated
% (blender does not seem to allow for vertex colouring, so colours need
% to be interpolated per face)
for cs=1:numel(srf)
switch surftype(srf{cs}),
case 'handle',
vertices = get(srf{cs}, 'Vertices')';
faces = get(srf{cs}, 'Faces')'-1;
facecol = squeeze(get(srf{cs}, 'CData'));
if ndims(facecol)==3
% we have vertex colours and need to compute face colours
warning(['Vertex colouring not supported, using mean colour value ' ...
'per surface']);
facecol = squeeze(mean(facecol));
end;
facesstr=sprintf('%d%s\\t0x%%02x%%02x%%02x\\n', ...
size(faces,1), repmat('\t%d', 1,size(faces,1)));
faces = [faces; round(facecol'*255)];
faces = faces(:,all(isfinite(faces)));
case 'struct',
vertices=srf{cs}.vertices';
faces=srf{cs}.faces'-1;
facecol = [128 128 128];
facesstr=sprintf('%d%s\\t0x%02x%02x%02x\\n', ...
size(faces,1), repmat('\t%d', 1,size(faces,1)), ...
facecol);
end;
fid=fopen(sprintf('surf-%d.obj',cs),'w');
fprintf(fid,'3DG1\n%d\n',size(vertices,2));
fprintf(fid,'%.3f\t%.3f\t%.3f\n',vertices);
fprintf(fid,facesstr,faces);
fclose(fid);
end;
return;
function t=surftype(srf)
if isstruct(srf)
if isfield(srf,'vertices') && isfield(srf,'faces')
t='struct';
return;
end;
elseif ishandle(srf) && strcmp(get(srf,'type'),'patch')
t='handle';
return;
else
error('Don''t know how to handle this surface');
end;
|
github
|
philippboehmsturm/antx-master
|
tbxrend_multi_cmip.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/Render3D/tbxrend_multi_cmip.m
| 9,147 |
utf_8
|
b2e36164911fe0ffc5edd6c198f2c8f6
|
function varargout = tbxrend_multi_cmip(cmd, varargin)
% Template function to implement callbacks for an cfg_exbranch. The calling
% syntax is
% varargout = tbxrend_multi_cmip(cmd, varargin)
% where cmd is one of
% 'run' - out = tbxrend_multi_cmip('run', job)
% Run a job, return an object handle for each mip.
% 'vout' - dep = tbxrend_multi_cmip('vout', job)
% Examine a job structure, return a cfg_dep object for each
% mip.
% 'check' - str = tbxrend_multi_cmip('check', subcmd, subjob)
% Valid subcmd
% 'spmmip' - check whether subjob.XYZ and subjob.Z have the
% same length
% 'defaults' - defval = tbxrend_multi_cmip('defaults', key)
% Valid key
% 'colour' - colour for new mip
%
% This code is part of a batch job configuration system for MATLAB. See
% help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging
% Volkmar Glauche
% $Id: tbxrend_multi_cmip.m 728 2012-05-31 07:52:56Z glauche $
rev = '$Rev: 728 $'; %#ok
if ischar(cmd)
switch lower(cmd)
case 'run'
job = local_getjob(varargin{1});
% do computation, return results in variable out
out = zeros(1,numel(job.mips)+1);
%-Display format
%==========================================================================
load(spm_get_defaults('stats.results.mipmat'));
%-Single slice case
%--------------------------------------------------------------------------
if isempty(job.units{3})
%-2d case
%----------------------------------------------------------------------
if ~job.bgopts.grid
grid_trans = zeros(size(grid_trans)); %#ok<NODEF>
end
if ~job.bgopts.outline
mask_trans = zeros(size(mask_trans)); %#ok<NODEF>
end
mip = 4*grid_trans + mask_trans;
elseif job.units{3} == '%'
%-3d case: Space-time
%----------------------------------------------------------------------
if ~job.bgopts.grid
grid_time = zeros(size(grid_time)); %#ok<NODEF>
end
if ~job.bgopts.outline
mask_trans = zeros(size(mask_trans)); %#ok<NODEF>
end
mip = 4*grid_time + mask_trans;
else
%-3d case: Space
%----------------------------------------------------------------------
if ~job.bgopts.grid
grid_all = zeros(size(grid_all)); %#ok<NODEF>
end
if ~job.bgopts.outline
mask_all = zeros(size(grid_all));
end
mip = 4*grid_all + mask_all;
end
% Load mip and create maximum intensity projection
%--------------------------------------------------------------------------
szmip = size(mip);
mip = rot90(mip/max(mip(:)));
figure('color','white');
out(end) = image('cdata',zeros([size(mip) 3]), 'alphadata',.5*mip);
axis tight; axis off;daspect([1 1 1]);
set(gca, 'YDir','reverse');
hold on;
for k = 1:numel(job.mips)
switch char(fieldnames(job.mips(k).mip))
case 'filemip',
V = spm_vol(job.mips(k).mip.filemip{1});
[Z XYZ] = spm_read_vols(V);
if min(Z(:)) >= 0
sel = ~isnan(Z(:)) & Z(:) > 0;
else
sel = ~isnan(Z(:));
end
sel = sel & Z(:) >= job.mips(k).range(1) & Z(:) <= job.mips(k).range(2);
Z = Z(sel);
XYZ = XYZ(:,sel(:));
M = V.mat;
case 'spmmip',
Z = job.mips(k).mip.spmmip.Z;
XYZ = job.mips(k).mip.spmmip.XYZ;
M = job.mips(k).mip.spmmip.M;
end
sel = XYZ(1,:) >= job.mips(k).bbox(1,1) & XYZ(1,:) <= job.mips(k).bbox(2,1) & ...
XYZ(2,:) >= job.mips(k).bbox(1,2) & XYZ(2,:) <= job.mips(k).bbox(2,2) & ...
XYZ(3,:) >= job.mips(k).bbox(1,3) & XYZ(3,:) <= job.mips(k).bbox(2,3);
out(k) = local_mip(Z(sel), XYZ(:,sel), M, job.mips(k).colour, job.mips(k).alpha, job.mips(k).invert, szmip);
end
if nargout > 0
varargout{1} = out;
end
case 'vout'
job = local_getjob(varargin{1});
% initialise empty cfg_dep array
dep = cfg_dep;
dep = dep(false);
% determine outputs, return cfg_dep array in variable dep
for k = 1:numel(job.mips)
dep(k) = cfg_dep;
dep(k).sname = sprintf('Graphics handle (MIP %d)', k);
dep(k).src_output = substruct('()',{k});
dep(k).tgt_spec = cfg_findspec({{'strtype','e'}});
end
dep(numel(job.mips)+1) = cfg_dep;
dep(numel(job.mips)+1).sname = 'Graphics handle (MIP outline)';
dep(numel(job.mips)+1).src_output = substruct('()',{numel(job.mips)+1});
dep(numel(job.mips)+1).tgt_spec = cfg_findspec({{'strtype','e'}});
varargout{1} = dep;
case 'check'
if ischar(varargin{1})
subcmd = lower(varargin{1});
subjob = varargin{2};
str = '';
switch subcmd
% implement checks, return status string in variable str
case 'spmmip'
if size(subjob.Z, 2) ~= size(subjob.XYZ, 2)
str = sprintf('Size mismatch: size(Z,2) = %d does not match size(XYZ,2) = %d', ...
size(subjob.Z,1), size(subjob.XYZ, 1));
end
case 'units'
if ~iscellstr(subjob)
str = sprintf('Value for ''units'' must be a cellstr.');
end
otherwise
cfg_message('unknown:check', ...
'Unknown check subcmd ''%s''.', subcmd);
end
varargout{1} = str;
else
cfg_message('ischar:check', 'Subcmd must be a string.');
end
case 'defaults'
if nargin == 2
varargout{1} = local_defs(varargin{1});
else
local_defs(varargin{1:2});
end
otherwise
cfg_message('unknown:cmd', 'Unknown command ''%s''.', cmd);
end
else
cfg_message('ischar:cmd', 'Cmd must be a string.');
end
function varargout = local_defs(defstr, defval)
persistent defs;
if isempty(defs)
% initialise defaults
defs.colour = [1 0 0]';
defs.alpha = [.25 .9];
defs.units = {'mm' 'mm' 'mm'};
defs.range = [-Inf Inf];
defs.bbox = [-Inf -Inf -Inf; Inf Inf Inf];
defs.grid = true;
defs.outline= true;
defs.invert = false;
end
if ischar(defstr)
% construct subscript reference struct from dot delimited tag string
tags = textscan(defstr,'%s', 'delimiter','.');
subs = struct('type','.','subs',tags{1}');
try
cdefval = subsref(defs, subs);
catch %#ok<CTCH>
cdefval = [];
cfg_message('defaults:noval', ...
'No matching defaults value ''%s'' found.', defstr);
end
if nargin == 1
varargout{1} = cdefval;
else
defs = subsasgn(defs, subs, defval);
end
else
cfg_message('ischar:defstr', 'Defaults key must be a string.');
end
function job = local_getjob(job)
if ~isstruct(job)
cfg_message('isstruct:job', 'Job must be a struct.');
end
function h = local_mip(Z, XYZ, M, col, alpha, invert, szmip)
Z = Z - min(Z);
mx = max(Z);
if invert
Z = mx - Z;
end
if isempty(mx),
Z = [];
elseif isfinite(mx) && (numel(Z) ~= 1),
Z = (alpha(2)-alpha(1))*Z/max(Z) + alpha(1);
else
Z = alpha(2)*ones(1,length(Z));
end
% Create maximum intensity projection
%--------------------------------------------------------------------------
c = [0 0 0 ;
0 0 1 ;
0 1 0 ;
0 1 1 ;
1 0 0 ;
1 0 1 ;
1 1 0 ;
1 1 1 ] - 0.5;
c = c*M(1:3,1:3);
dim = [(max(c) - min(c)) szmip];
adata = rot90(spm_project(Z,round(XYZ),dim));
cdata = cat(3, col(1)*ones(size(adata)), col(2)*ones(size(adata)), ...
col(3)*ones(size(adata)));
h = image('cdata',cdata, 'alphadata',adata);
|
github
|
philippboehmsturm/antx-master
|
tbxrend_fancy_render.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/Render3D/tbxrend_fancy_render.m
| 37,531 |
utf_8
|
ffbbc76d528fbc3c3bcfd24be5437ee9
|
function varargout = tbxrend_fancy_render(varargin)
% Fancy rendering of intensities of one brain superimposed on surface
% FORMAT fr = tbxrend_fancy_render(cmd, ...)
% ======
% Commands are
% 'init' - Initialise rendering
% 'load' - Load rendering from fr*.mat file
% 'save' - Save information about used data, slices and cuts into
% fr_<name of structural image>.mat
% 'addblobs' - Select new SPM/image set for colouring
% 'addsurf' - Add another surface patch given as
% - gifti file
% - filename for a .mat file with a struct FV
% - Matlab struct with faces and vertices from the workspace
% - image file to be spm_surf'ed. The image will be resliced
% to space and resolution of the brain mask (if present). The
% surface will be created on a slightly smoothed image at
% threshold 0.5
% - thresholded SPM, saved and resliced to the space of the
% brain mask (if present)
% 'addline' - Add lines as streamtubes given as
% - filename for a .mat file with variables "vertices" (cell
% array of lines in xyz mm coordinates) and optionally "width"
% - Matlab struct with vertices and width fields from the workspace
% - widths can alternatively be sampled from a file (e.g. FA)
% See MATLABs streamtube command for details
% 'redraw' - Redraw the figure
% 'render' - Re-render the surface patch
% 'slice' - Add a "slice" through the structural image
% the slice must be given as a function sfunc(x, y, z)
% the resulting slice is at sfunc(x, y, z) = 0
% examples:
% 'x-20' produces a slice at x = 20 (x-20 = 0)
% 'x.^2 + y.^2 - r.^2' produces a slice on a cylinder with
% radius r along the z axis
% a slice sub-volume can be specified as a range of x,
% y, z where the slice function should be evaluated
% (in most cases, this will be the inverse of the
% corresponding cut expression)
% enter '1' or 'none' if no sub-volume needed
% 'cut' - Cut a piece of surface and slices
% the cut expression must specify the range of x, y, z
% which should be cut away
% 'axison' - Turn axis labels on (useful to determine cut coordinates)
% 'axisoff' - Turn axis labels off
% 'relight' - Reset lighting after rotation of the figure
%
% This function is part of the volumes toolbox for SPM2. For general help
% about this toolbox, bug reports, licensing etc. type
% spm_help vgtbx_config_Volumes
% in the matlab command window after the toolbox has been launched.
%_______________________________________________________________________
%
% @(#) $Id: tbxrend_fancy_render.m 721 2011-09-27 11:30:49Z glauche $
% core code taken from fancy_rendering by John Ashburner
rev='$Revision: 721 $'; %#ok<NASGU>
funcname = 'Fancy render';
if nargin == 0,
fr = tbxrend_fancy_render('init');
if nargout > 0
varargout{1} = fr;
end;
return;
end;
% defaults
mydefaults = struct('camcolour',[1 1 1], 'slicecolour',[.7 .7 .7], ...
'indper',.6, 'colfunc','colrgb', 'slicescuts',{{}}, ...
'VM',[], 'VV',[], 'blobs',{{}}, 'surf',{{}}, 'line',{{}},...
'slicepatch',[], 'x',[], 'y',[], 'z',[]);
mydefaultssurf = struct('data',[], 'quality',.3, 'colour',[.8 .8 .9], 'tcol',1, 'cut',1, ...
'patch',[], 'alpha',1, 'cutalpha',0.3, 'specularstrength',.2);
mydefaultsline = struct('vertices',[], 'width',1, 'colour',[.8 .8 .9], 'alpha',1,...
'N',20, 'specularstrength',.2);
% menu setup
if nargin==2
if ischar(varargin{1}) && ishandle(varargin{2})
if strcmpi(varargin{1},'menu')
VMfancy = uimenu(varargin{2},'Label',funcname, 'Tag', 'VMFANCY');
VMfancyinit = uimenu(VMfancy,'Label','Init',...
'Callback',[mfilename '(''menuinit'');' ],...
'Tag','VMFANCY0');
VMfancyload = uimenu(VMfancy,'Label','Load',...
'Callback',[mfilename '(''menuload'');' ],...
'Tag','VMFANCY0');
VMfancycut = uimenu(VMfancy, 'Label', 'Cut',...
'Callback',[mfilename '(''addcut'');' ],...
'Tag','VMFANCY1','Visible','off');
VMfancyslice = uimenu(VMfancy, 'Label', 'Slice',...
'Callback',[mfilename '(''addslice'');' ],...
'Tag','VMFANCY1','Visible','off');
VMfancyaddsurf = uimenu(VMfancy, 'Label', 'Add surface',...
'Callback',[mfilename '(''addsurf'');' ],...
'Tag','VMFANCY1','Visible','off');
VMfancyrelight = uimenu(VMfancy, 'Label', 'Relight',...
'Callback',[mfilename '(''relight'');' ],...
'Tag','VMFANCY1','Visible','off');
VMfancyblobs = uimenu(VMfancy, 'Label', 'New blobs',...
'Callback',[mfilename '(''addblobs'');' ],...
'Tag','VMFANCY1','Visible','off');
VMfancyax = uimenu(VMfancy, 'Label', 'Axis',...
'Tag','VMFANCY1','Visible','off');
VMfancyaxison = uimenu(VMfancyax, 'Label', 'On',...
'Callback',[mfilename '(''menuaxison'');' ],...
'Tag','VMFANCY1_AXISON');
VMfancyaxisoff = uimenu(VMfancyax, 'Label', 'Off', 'Checked','on',...
'Callback',[mfilename '(''menuaxisoff'');' ],...
'Tag','VMFANCY1_AXISOFF');
VMfancysave = uimenu(VMfancy, 'Label', 'Save',...
'Callback',[mfilename '(''save'');' ],...
'Tag','VMFANCY1','Visible','off');
VMfancyexp = uimenu(VMfancy, 'Label', 'Export to Workspace',...
'Callback',[mfilename '(''export'');' ],...
'Tag','VMFANCY1','Visible','off');
VMfancyimp = uimenu(VMfancy, 'Label', 'Import from Workspace',...
'Callback',[mfilename '(''import'');' ],...
'Tag','VMFANCY1','Visible','off');
VMfancyclear = uimenu(VMfancy, 'Label', 'Clear',...
'Callback',[mfilename '(''menuclear'');' ],...
'Tag','VMFANCY1','Visible','off');
if nargout > 0
varargout{1} = VMfancy;
end;
return;
end;
if strcmpi(varargin{1},'hmenu')
Menu = uimenu(varargin{2},'Label',['Help on ' funcname],...
'Callback',['spm_help(''' mfilename ''')']);
if nargout > 0
varargout{1} = Menu;
end;
return;
end;
end;
end;
switch lower(varargin{1})
%=======================================================================
% menu functions
%=======================================================================
case 'defaults'
varargout{1} = mydefaults;
varargout{2} = mydefaultssurf;
return;
case {'menuinit', 'menuload'}
spm_input('!DeleteInputObj');
fr = feval(mfilename,varargin{1}(5:end), varargin{2:end});
set(findobj(get(gcbo,'Parent'),'Tag','VMFANCY0'),'Visible','off');
set(findobj(get(gcbo,'Parent'),'Tag','VMFANCY1'),'Visible','on');
if nargout > 0
varargout{1} = fr;
end;
return;
case 'menuclear',
shh = get(0,'ShowHiddenHandles');
set(0,'ShowHiddenHandles','on');
set(findobj(0, 'Tag','VMFANCY0'), 'Visible','on');
set(findobj(0, 'Tag','VMFANCY1'), 'Visible','off');
set(0,'ShowHiddenHandles',shh);
if nargin == 1
FGraph=get(findobj(0,'Tag',mfilename),'Parent');
else
FGraph=varargin{2};
end;
delete(FGraph);
return;
case 'menuaxison'
spm('pointer','watch');
set(findobj(get(gcbo,'Parent'),'Tag','VMFANCY1_AXISON'),'Checked','on');
set(findobj(get(gcbo,'Parent'),'Tag','VMFANCY1_AXISOFF'),'Checked','off');
feval(mfilename,varargin{1}(5:end), varargin{2:end});
spm('pointer','arrow');
return;
case 'menuaxisoff'
spm('pointer','watch');
set(findobj(get(gcbo,'Parent'),'Tag','VMFANCY1_AXISON'),'Checked','off');
set(findobj(get(gcbo,'Parent'),'Tag','VMFANCY1_AXISOFF'),'Checked','on');
feval(mfilename,varargin{1}(5:end), varargin{2:end});
spm('pointer','arrow');
return;
%=======================================================================
% data specification functions
%=======================================================================
% tbxrend_fancy_render('init')
%=======================================================================
case ('init')
if nargin > 1
fr = fillstruct(mydefaults, varargin{2});
if ~isempty(fr.surf)
fr.surf{1} = fillstruct(mydefaultssurf, fr.surf{1});
end;
else
fr = mydefaults;
end;
if isempty(fr.surf)
fr = tbxrend_fancy_render('addsurf',fr);
end;
if isempty(fr.VV)
fr.VV = spm_vol(spm_select(1, 'image', 'Volume Data'));
end;
if isempty(fr.VM)
tmp = spm_vol(spm_select([0 1], 'image', 'Volume Mask (opt.)'));
if ~isempty(tmp)
fr.VM = tmp;
tmp = spm_input('mask threshold [min max]','+1','e','0 1',2);
fr.VM.min = tmp(1);
fr.VM.max = tmp(2);
end;
end;
if isempty(fr.blobs)
fr=tbxrend_fancy_render('addblobs',fr);
end;
% create meshgrid on x y z coordinates at voxel edges
st = fr.VV.mat*[1 1 1 1]';
en = fr.VV.mat*[fr.VV.dim(1:3) 1]';
tmp = spm_imatrix(fr.VV.mat);
step= (en-st)./abs(spm_matrix([0 0 0 tmp(4:6)])*[(fr.VV.dim(1:3)-1) 1]');
FV = get_faces_vertices(fr.surf{1});
x = st(1):step(1):en(1);
x = x((x>=min(FV.vertices(:,1)-step(1))) &...
(x<=max(FV.vertices(:,1)+step(1))));
y = st(2):step(2):en(2);
y = y((y>=min(FV.vertices(:,2)-step(2))) &...
(y<=max(FV.vertices(:,2)+step(2))));
z = st(3):step(3):en(3);
z = z((z>=min(FV.vertices(:,3)-step(3))) &...
(z<=max(FV.vertices(:,3)+step(3))));
clear FV;
[fr.x fr.y fr.z]=meshgrid(x,y,z);
fr=tbxrend_fancy_render('redraw',fr);
if nargout > 0
varargout{1} = fr;
end;
return;
% tbxrend_fancy_render('load')
%=======================================================================
case('load')
var = load(spm_select(1,'fr.*\.mat', 'Rendering Description'));
fr = var.fr;
% convert to new fr struct, if necessary
if isfield(fr,'VR')
fr.blobs={};
for k=1:numel(fr.VR)
fr.blobs{k} = fr.VR(k);
fr.blobs{k}.min = -Inf;
fr.blobs{k}.max = Inf;
end;
end;
for k=1:numel(fr.blobs)
if ~isfield(fr.blobs{k},'scaling')
fr.blobs{k}.scaling = 'rel';
end;
end;
if isfield(fr,'surfname')
if ischar(fr.surfname)
fr.surf{1} = mydefaultssurf;
fr.surf{1}.data = fr.surfname;
else
for k=1:numel(fr.surfname)
fr.surf{k} = mydefaultssurf;
fr.surf{k}.data = fr.surfname{k};
if size(fr.surfcolour,1)<=k
fr.surf{k}.colour = fr.surfcolour(k,:);
end;
if length(fr.surftcol)<=k
fr.surf{k}.tcol = fr.surftcol(k);
end;
if length(fr.surfcut)<=k
fr.surf{k}.cut = fr.surfcut(k);
end;
end;
end;
end;
if isfield(fr,'reshold') && isfield(fr, 'blobs')
for k = 1:numel(fr.blobs)
fr.blobs{k}.interp = fr.reshold;
end;
end;
if isfield(fr,'VM')
if ~isfield(fr.VM, 'min')
fr.VM.min = eps;
end;
if ~isfield(fr.VM, 'max')
fr.VM.max = Inf;
end;
end;
fr = fillstruct(mydefaults, fr);
fr = tbxrend_fancy_render('redraw',fr);
if nargout > 0
varargout{1} = fr;
end;
return;
% tbxrend_fancy_render('save')
%=======================================================================
case('save')
ax = findobj(0,'Tag',mfilename);
fr = get(ax,'UserData');
if ischar(fr.surf{1}.data)
[p n e]=fileparts(fr.surf{1}.data);
fn = fullfile(p,['fr_' n e]);
else
[p n] = uiputfile([], 'select filename');
if n == 0
return;
end;
fn = fullfile(p,n);
end;
save(fn,'fr');
return;
% tbxrend_fancy_render('export')
%=======================================================================
case('export')
ax = findobj(0,'Tag',mfilename);
fr = get(ax,'UserData');
assignin('base','fr',fr);
evalin('base','disp(fr)');
% tbxrend_fancy_render('import')
%=======================================================================
case('import')
fr = evalin('base','fr');
ax = findobj(0,'Tag',mfilename);
set(ax,'Userdata',fr);
tbxrend_fancy_render('redraw');
% tbxrend_fancy_render('addblobs')
%=======================================================================
case('addblobs') % Possible argument: fr-structure, update it and return it
if nargin==2
fr = varargin{2};
else
ax = findobj(0,'Tag',mfilename);
axes(ax);
fr = get(ax,'UserData');
end;
fr.blobs = {};
nblobs = spm_input('# blob sets','+1','b',{'none','1','2','3'}, ...
0:3);
if nblobs==1 % only 1 results image
fr.colfunc = spm_input('Colour mode', '+1', 'm', 'RGB|Indexed', ...
['colrgb';'colind']);
else
fr.colfunc = 'colrgb';
end;
for k = 1:nblobs
if spm_input(sprintf('Add blob set #%d from', k), '+1', 'b', ...
{'SPM', 'image'},[1 2]) == 1
opwd = pwd; % work around spm_getSPM's "cd" behaviour
[SPM VOL] = spm_getSPM;
rcp = round(VOL.XYZ);
dim = max(rcp,[],2)';
off = rcp(1,:) + dim(1)*(rcp(2,:)-1 + dim(2)*(rcp(3,:)-1));
vol = zeros(dim)+NaN;
vol(off) = VOL.Z;
fr.blobs{k}.vol = reshape(vol,dim);
fr.blobs{k}.mat = VOL.M;
cd(opwd);
else
fr.blobs{k} = spm_vol(spm_select(1,'image',...
sprintf('Results Image #%d',k)));
end;
fr.blobs{k}.interp = spm_input('Interpolation of results', '+1', ...
'm', 'Nearest Neighbour|Trilinear|Sinc',[0;1;-7],1);
fr.blobs{k}.min = -Inf;
fr.blobs{k}.max = Inf;
fr.blobs{k}.scaling = 'rel';
end;
if nargin==1
set(ax,'UserData',fr);
fr = tbxrend_fancy_render('redraw');
end;
if nargout > 0
varargout{1} = fr;
end;
return;
% tbxrend_fancy_render('addcut')
%=======================================================================
case 'addcut',
if nargin==2
fr = varargin{2};
else
ax = findobj(0,'Tag',mfilename);
axes(ax);
fr = get(ax,'UserData');
end;
ind = size(fr.slicescuts,2)+1;
fr.slicescuts{ind}.type='cut';
ok = 0;
x = 0; y=0; z=0; %#ok<NASGU> used in cut expression
while ~ok
fr.slicescuts{ind}.val = spm_input('Cut expression','+1', ...
's');
eval(sprintf('ok=islogical(%s);',fr.slicescuts{ind}.val),...
'ok=0;');
if ~ok
uiwait(msgbox(sprintf(['Invalid cut expression '...
'''%s'''], fr.slicescuts{ind}.val),...
funcname,'modal'));
end;
end;
if nargin==1
set(ax,'UserData',fr);
fr = tbxrend_fancy_render('redraw');
end;
if nargout > 0
varargout{1} = fr;
end;
return;
% tbxrend_fancy_render('addslice')
%=======================================================================
case 'addslice',
if nargin==2
fr = varargin{2};
else
ax = findobj(0,'Tag',mfilename);
axes(ax);
fr = get(ax,'UserData');
end;
ind = size(fr.slicescuts,2)+1;
fr.slicescuts{ind}.type='slice';
fr.slicescuts{ind}.val = spm_input('Slice expression', '+1', 's');
fr.slicescuts{ind}.bounds = spm_input('Slice sub-volume', ...
'+1', 's', 'none');
if strcmpi(fr.slicescuts{ind}.bounds,'none')
fr.slicescuts{ind}.bounds = '1';
end;
if nargin==1
set(ax,'UserData',fr);
fr = tbxrend_fancy_render('redraw');
end;
if nargout > 0
varargout{1} = fr;
end;
return;
% tbxrend_fancy_render('addsurf')
%=======================================================================
case('addsurf') % Possible argument: fr-structure, update it and return it
if nargin==2
fr = varargin{2};
else
ax = findobj(0,'Tag',mfilename);
axes(ax);
fr = get(ax,'UserData');
end;
cs = numel(fr.surf)+1;
fr.surf{cs} = mydefaultssurf;
fr.surf{cs}.colour = uisetcolor(fr.surf{cs}.colour,'Surface colour');
fr.surf{cs}.tcol = spm_input('Overlay results onto this surface',...
'+1', 'b', {'Yes', 'No'},[1 0]);
fr.surf{cs}.cut = spm_input('Cut this surface',...
'+1', 'b', {'Yes', 'No'},[1 0]);
src= spm_input('Add surface from?', '+1', 'm',...
{'GIFTI mesh', 'surf*.mat', 'matlab variable', 'image file',...
'SPM result'}, {'gifti', 'mat','var','img','SPM'});
switch char(src),
case 'gifti',
fr.surf{cs}.data=spm_select(1, 'mesh', ...
'Select surface data');
case 'mat',
fr.surf{cs}.data=spm_select(1, 'surf_.*\.mat', ...
'Select surface data');
case 'var',
ok = 0;
while ~ok
tmp = spm_input('Variable name', '+1', 'e');
if isstruct(tmp)
if isfield(tmp, 'faces') && isfield(tmp, 'vertices')
fr.surf{cs}.data = tmp;
ok = 1;
end;
end;
if ~ok
msgbox(funcname,...
['Please give a name for a struct containing ' ...
'the fields ''faces'' and ''vertices''.\n'...
'See ''help patch'' for details.']);
end;
end;
case {'img','SPM'}
if strcmp(src,'img')
V = spm_vol(spm_select([1 1], 'image',...
'Image to create surface from'));
slevels = spm_input('Add surfaces at image intensity levels','+1',...
'e', .5);
else
[SPM xSPM] = spm_getSPM;
slevels = spm_input('Add surfaces at Stats levels','+1','e', ...
num2str([min(xSPM.Z) max(xSPM.Z)]));
V = xSPM.Vspm;
end;
if ~isempty(fr.VM)
msk = spm_input('Apply brain mask for surface creation?',...
'+1', 'b', {'Yes', 'No'},[1 0]);
else
msk = 0;
end;
if msk
for k=1:numel(V)
Vmtmp = fr.VM;
[p n e v] = spm_fileparts(V(k).fname);
Vmtmp.fname = fullfile(p, ['fr_' n e v]);
Vm(k) = spm_imcalc([orderfields(rmfield(fr.VM,{'min','max'}),...
V(k)), V(k)],Vmtmp, ...
sprintf('i2.*((i1>=%f)&(i1<=%f))',...
fr.VM.min,fr.VM.max));
end;
else
Vm = V;
end;
if numel(slevels) > 1
slevels = sort(slevels);
col2 = uisetcolor(fr.surf{cs}.colour,...
'Surface colour for maximum intensity');
else
col2 = fr.surf{cs}.colour;
end;
out = spm_surf(struct('data',{{Vm.fname}},'mode',2,'thresh',slevels));
if numel(slevels) == 1
fr.surf{cs}.data = out.surffile{1};
else
for k=1:numel(slevels)
clevel = (slevels(k)-min(slevels))/(max(slevels)-min(slevels));
fr.surf{cs+k-1} = fr.surf{cs};
fr.surf{cs+k-1}.alpha = .3+.7*clevel;
fr.surf{cs+k-1}.data = out.surffile{k};
fr.surf{cs+k-1}.colour = fr.surf{cs}.colour + ...
clevel*(col2 - fr.surf{cs}.colour);
end;
end;
end;
if nargin==1
set(ax,'UserData',fr);
fr = tbxrend_fancy_render('redraw');
end;
if nargout > 0
varargout{1} = fr;
end;
return;
% tbxrend_fancy_render('addline')
%=======================================================================
case('addline') % Possible argument: fr-structure, update it and return it
if nargin==2
fr = varargin{2};
else
ax = findobj(0,'Tag',mfilename);
axes(ax);
fr = get(ax,'UserData');
end;
cl = numel(fr.line)+1;
fr.line{cl} = mydefaultsline;
src= spm_input('Add lines from?', '+1', 'm',...
{'line*.mat', 'matlab variable'}, {'mat','var'});
ok = 0;
while ~ok
switch char(src),
case 'mat',
tmp = load(spm_select(1, 'line_.*\.mat', ...
'Select line data'));
case 'var',
tmp = spm_input('Variable name', '+1', 'e');
end;
if isstruct(tmp)
if isfield(tmp, 'vertices') && iscell(tmp.vertices)
fr.line{cl}.vertices = tmp.vertices;
ok = 1;
end
elseif iscell(tmp)
fr.line{cl}.vertices = tmp;
ok = 1;
end;
if ~ok
msgbox(funcname,...
['Please give a name for a cell or a file containing ' ...
'the variable ''vertices''.']);
end;
end;
src= spm_input('Line Colour Specification', '+1', 'm',...
{'Select colour', 'matlab variable', 'images'}, {'ui','var','img'});
switch char(src),
case 'img',
tmp = spm_vol(spm_select(3, 'image', ...
'Select line colour images (R,G,B)'));
for k = 1:numel(fr.line{cl}.vertices)
col = zeros(size(fr.line{cl}.vertices{k},1),3);
for c = 1:3
xyz = inv(tmp(c).mat)*...
[fr.line{cl}.vertices{k} ...
ones(size(fr.line{cl}.vertices{k},1),1)]';
col(:,c) = spm_sample_vol(tmp(c),xyz(1,:), xyz(2,:), ...
xyz(3,:),0);
end;
fr.line{cl}.colour{k} = col;
end;
case 'var',
fr.line{cl}.colour = spm_input('Colour', '+1', 'e');
case 'ui'
fr.line{cl}.colour = uisetcolor('Line Colour');
end;
src= spm_input('Line Width Specification', '+1', 'm',...
{'matlab variable', 'images'}, {'var','img'});
switch char(src),
case 'img',
tmp = spm_vol(spm_select(1, 'image', ...
'Select line width images'));
for k = 1:numel(fr.line{cl}.vertices)
xyz = inv(tmp.mat)*...
[fr.line{cl}.vertices{k} ...
ones(size(fr.line{cl}.vertices{k},1),1)]';
fr.line{cl}.width{k} = ...
spm_sample_vol(tmp(c),xyz(1,:), xyz(2,:), ...
xyz(3,:),0);
end;
case 'var',
fr.line{cl}.width = spm_input('Line Width', '+1', 'e');
end;
src= spm_input('Line Alpha Specification', '+1', 'm',...
{'matlab variable', 'images'}, {'var','img'});
switch char(src),
case 'img',
tmp = spm_vol(spm_select(1, 'image', ...
'Select line alpha images'));
for k = 1:numel(fr.line{cl}.vertices)
xyz = inv(tmp.mat)*...
[fr.line{cl}.vertices{k} ...
ones(size(fr.line{cl}.vertices{k},1),1)]';
fr.line{cl}.alpha{k} = ...
spm_sample_vol(tmp(c),xyz(1,:), xyz(2,:), ...
xyz(3,:),0);
end;
case 'var',
fr.line{cl}.alpha = spm_input('Line Alpha', '+1', 'e');
end;
if nargin==1
set(ax,'UserData',fr);
fr = tbxrend_fancy_render('redraw');
end;
if nargout > 0
varargout{1} = fr;
end;
return;
%=======================================================================
% drawing callbacks
%=======================================================================
% tbxrend_fancy_render('axison')
%=======================================================================
case('axison')
ax = findobj(0,'Tag',mfilename);
axes(ax);
axis image on;
xlabel('X'); ylabel('Y'); zlabel('Z');
return;
% tbxrend_fancy_render('axisoff')
%=======================================================================
case('axisoff')
ax = findobj(0,'Tag',mfilename);
axes(ax);
axis image off;
return;
% tbxrend_fancy_render('cut')
%=======================================================================
case ('cut')
if nargin == 2
ax = findobj(0,'Tag',mfilename);
axes(ax);
fr = get(ax,'UserData');
ind=varargin{2};
else
fr = varargin{2};
ind = varargin{3};
end;
% cut surfaces
for cs = 1:numel(fr.surf)
if fr.surf{cs}.cut,
v = get(fr.surf{cs}.patch,'Vertices');
x=v(:,1); %#ok<NASGU> used in cut expression
y=v(:,2); %#ok<NASGU>
z=v(:,3); %#ok<NASGU>
fva = get(fr.surf{cs}.patch,'FaceVertexAlphaData');
if isempty(fva)
fva = fr.surf{cs}.alpha*ones(size(v,1),1);
end;
fva(eval(fr.slicescuts{ind}.val)) = fr.surf{cs}.cutalpha;
set(fr.surf{cs}.patch,'FaceVertexAlphaData',fva);
end;
end;
% cut slices
for cs = 1:numel(fr.slicepatch)
v = get(fr.slicepatch(cs),'Vertices');
x=v(:,1); %#ok<NASGU> used in cut expression
y=v(:,2); %#ok<NASGU>
z=v(:,3); %#ok<NASGU>
col = get(fr.slicepatch(cs),'FaceVertexCData');
col(eval(fr.slicescuts{ind}.val)) = NaN;
if any(~isnan(col(:)))
set(fr.slicepatch(cs),'FaceVertexCData',col);
else
if ishandle(fr.slicepatch(cs))
delete(fr.slicepatch(cs));
end;
end;
end;
if nargin == 2
set(ax,'UserData',fr);
end;
if nargout > 0
varargout{1} = fr;
end;
return;
% tbxrend_fancy_render('render')
%=======================================================================
case('render')
ax = findobj(0,'Tag',mfilename);
axes(ax);
fr = get(ax,'UserData');
for cs = 1:numel(fr.surf)
FV = get_faces_vertices(fr.surf{cs});
col = ones(size(FV.vertices,1),3).*...
repmat(fr.surf{cs}.colour, [size(FV.vertices,1) 1]);
if fr.surf{cs}.tcol
tcol = feval(fr.colfunc,FV,fr);
col = repmat(1-max(tcol,[],2),[1 3]).*col + tcol;
end;
fr.surf{cs}.patch = patch(FV, 'Parent',ax,...
'AlphaDataMapping', 'none',...
'FaceVertexAlphaData',...
fr.surf{cs}.alpha*ones(size(FV.vertices,1),1),...
'FaceAlpha', 'interp',...
'FaceColor', 'interp',...
'FaceVertexCData', col,...
'EdgeColor', 'none',...
'FaceLighting', 'phong',...
'SpecularStrength' , fr.surf{cs}.specularstrength,...
'AmbientStrength', 0.1,...
'DiffuseStrength', 0.7,...
'SpecularExponent', 10,...
'Tag',sprintf('%s_surf',mfilename));
end;
set(ax,'UserData',fr);
return;
%=======================================================================
% tbxrend_fancy_render('relight')
case ('relight')
ax = findobj(0,'Tag',mfilename);
axes(ax);
fr = get(ax,'UserData');
l = findobj(get(ax,'Children'), 'Type', 'light');
if isempty(l)
l = camlight(-20, 10);
else
l = camlight(l, -20, 10);
end;
set(l,'Color',fr.camcolour);
return;
%=======================================================================
% tbxrend_fancy_render('redraw')
case('redraw') % Possible argument: fr-structure, draw and set it as UserData
if nargin==2
fr = varargin{2};
fg = figure;
ax = axes('Parent',fg,'Clipping','off','tag',mfilename);
set(0,'CurrentFigure',fg);
set(fg,'CurrentAxes',ax,...
'CloseRequestFcn',[mfilename '(''menuclear'',',num2str(fg),')']);
set(ax,'UserData',fr);
view(3);
[az el] = view;
daspect([1 1 1]);
axis image off;
box on;
rotate3d on;
else
ax = findobj(0,'Tag',mfilename);
axes(ax);
[az el] = view;
fr = get(ax,'UserData');
end;
delete(findobj(ax,'tag',sprintf('%s_surf',mfilename)));
delete(findobj(ax,'tag',sprintf('%s_slice',mfilename)));
for cs = 1:numel(fr.surf)
fr.surf{cs}.patch=[];
end;
fr.slicepatch=[];
set(ax,'Userdata',fr);
tbxrend_fancy_render render;
for k=1:size(fr.slicescuts,2)
tbxrend_fancy_render(fr.slicescuts{k}.type,k);
end;
view(az,el);
axis tight;
tbxrend_fancy_render relight;
if nargout >0
varargout{1} = fr;
end;
return;
%=======================================================================
% tbxrend_fancy_render('slice')
case ('slice')
ax = findobj(0,'Tag',mfilename);
axes(ax);
fr = get(ax,'UserData');
ind = varargin{2};
if isempty(findstr(fr.slicescuts{ind}.val,'fr.'))
tmp = strrep(fr.slicescuts{ind}.val,'x','fr.x');
tmp = strrep(tmp,'y','fr.y');
tmp = strrep(tmp,'z','fr.z');
else % compatibility with old fr structs
tmp = fr.slicescuts{ind}.val;
end;
sel = round(eval(tmp));
if isfield(fr.slicescuts{ind},'bounds')
tmp = strrep(fr.slicescuts{ind}.bounds,'x','fr.x');
tmp = strrep(tmp,'y','fr.y');
tmp = strrep(tmp,'z','fr.z');
sel(~eval(tmp))=NaN;
end;
s = isosurface(fr.x,fr.y,fr.z,sel,0);
clear sel;
if isempty(s.vertices)
warning([mfilename ':emptySlice'],...
'Empty slice after evaluating isosurface\n ''%s''\n',...
fr.slicescuts{ind}.val);
return;
end;
M = inv(fr.VV.mat);
xyz = (M(1:3,:)*[s.vertices' ; ones(1, size(s.vertices,1))])';
col1 = spm_sample_vol(fr.VV,xyz(:,1), xyz(:,2), xyz(:,3), -4);
if ~isempty(fr.VM)
M = inv(fr.VM.mat);
xyz = (M(1:3,:)*[s.vertices' ; ones(1, size(s.vertices, ...
1))])';
msk = spm_sample_vol(fr.VM, xyz(:,1), xyz(:,2), xyz(:,3), 0);
col1((msk<fr.VM.min)|(msk>fr.VM.max)|isnan(msk))=0;
else % we do not have an explicit mask, use non-interpolated volume data instead
msk = spm_sample_vol(fr.VV,xyz(:,1), xyz(:,2), xyz(:,3), 0);
col1(isnan(msk))=0;
end;
cmap=contrast(col1(col1~=0),1024);
cmax=max(col1(isfinite(col1)));
cmin=min(col1((col1~=0)&isfinite(col1)));
if isempty(cmin)
cmin = cmax-1;
end;
% use only first row of cmap (grayscale cmap!)
col=repmat(interp1(cmin:(cmax-cmin)/1023:cmax,cmap(:,1),col1),[1 3]);
col(col1==0)=NaN; % zero masking according to original data
col = col.*repmat(fr.slicecolour,[size(col,1) 1]); % apply color shade
tcol = feval(fr.colfunc,s,fr);
col = repmat(1-max(tcol,[],2),[1 3]).*col + tcol;
axes(ax);
fr.slicepatch(end+1) = patch(s,...
'FaceColor', 'interp', 'FaceVertexCData', col,...
'EdgeColor', 'none',...
'FaceLighting', 'phong',...
'SpecularStrength' ,0.7, 'AmbientStrength', 0.1,...
'DiffuseStrength', 0.7, 'SpecularExponent', 10,...
'Tag',sprintf('%s_slice',mfilename));
set(ax,'UserData',fr);
return;
end
function tcol=colrgb(FV,fr)
tcol=zeros(size(FV.vertices,1),3);
for l=1:numel(fr.blobs)
tcol(:,l) = samplecol(FV,fr.blobs{l});
end;
function tcol=colind(FV,fr)
tcol=zeros(size(FV.vertices,1),3);
if numel(fr.blobs) ~= 1
error('Can only handle 1 results image in indexed mode');
end;
t = samplecol(FV,fr.blobs{1});
t = ceil(t*1024);
cmap = hsv(1024);
tcol(t~=0,:) = cmap(t(t~=0),:)*fr.indper;
function t = samplecol(FV,V)
M = inv(V.mat);
xyz = (M(1:3,:)*[FV.vertices' ; ...
ones(1, size(FV.vertices, 1))])';
if isfield(V,'vol')
t = spm_sample_vol(V.vol, xyz(:,1), xyz(:,2), xyz(:,3), ...
V.interp);
else
t = spm_sample_vol(V, xyz(:,1), xyz(:,2), xyz(:,3), ...
V.interp);
end;
imean = zeros(size(t));
if isfield(V,'VMean')
M = inv(V.VMean.mat);
xyz = (M(1:3,:)*[FV.vertices' ; ...
ones(1, size(FV.vertices, 1))])';
if isfield(V.VMean,'vol')
imean = spm_sample_vol(V.VMean.vol, ...
xyz(:,1), xyz(:,2), xyz(:,3), ...
V.interp);
else
imean = spm_sample_vol(V.VMean, ...
xyz(:,1), xyz(:,2), xyz(:,3), ...
V.interp);
end;
end;
t = t-imean;
imsk = ones(size(t));
if isfield(V,'VM')
M = inv(V.VM.mat);
xyz = (M(1:3,:)*[FV.vertices' ; ...
ones(1, size(FV.vertices, 1))])';
if isfield(V.VM,'vol')
imsk = spm_sample_vol(V.VM.vol, ...
xyz(:,1), xyz(:,2), xyz(:,3), ...
V.interp);
else
imsk = spm_sample_vol(V.VM, ...
xyz(:,1), xyz(:,2), xyz(:,3), ...
V.interp);
end;
end;
t(t<V.min) = V.min;
t(t>V.max) = V.max;
t(~isfinite(t) | ~imsk) = 0;
switch V.scaling
case 'rel'
mx = max([eps max(t)]);
case 'abs'
mx = V.max;
case 'minmax'
mx = V.max-V.min;
t = t - V.min;
end;
t = t/mx;
% do the masking again
t(~isfinite(t) | ~imsk) = 0;
function FV = get_faces_vertices(source)
if isstruct(source.data)
FV=source.data;
else
[p n e] = fileparts(source.data);
switch e
case '.mat'
FV = load(source.data);
case '.gii'
FV = gifti(source.data);
FV = export(FV,'patch');
% reducepatch does not work single precision vertices
FV.vertices = double(FV.vertices);
end
end;
FV = reducepatch(FV,source.quality);
|
github
|
philippboehmsturm/antx-master
|
pm_segment.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/FieldMap/pm_segment.m
| 25,512 |
utf_8
|
37ff3bd4d9d649e61cc402f3b114c256
|
function [VO,M] = pm_segment(VF,PG,flags)
% Segment an MR image into Gray, White & CSF.
%
% FORMAT VO = pm_segment(PF,PG,flags)
% PF - name(s) of image(s) to segment (must have same dimensions).
% PG - name(s) of template image(s) for realignment.
% - or a 4x4 transformation matrix which maps from the image to
% the set of templates.
% flags - a structure normally based on defaults.segment
% VO - optional output volume
% M - affine transformation between template and image to segment
%
% The algorithm is four step:
%
% 1) Determine the affine transform which best matches the image with a
% template image. If the name of more than one image is passed, then
% the first image is used in this step. This step is not performed if
% no template images are specified.
%
% 2) Perform Cluster Analysis with a modified Mixture Model and a-priori
% information about the likelihoods of each voxel being one of a
% number of different tissue types. If more than one image is passed,
% then they they are all assumed to be in register, and the voxel
% values are fitted to multi-normal distributions.
%
% 3) Perform morphometric operations on the grey and white partitions
% in order to more accurately identify brain tissue. This is then used
% to clean up the grey and white matter segments.
%
% 4) If no or 2 output arguments is/are specified, then the segmented
% images are written to disk. The names of these images have "c1",
% "c2" & "c3" appended to the name of the first image passed. The
% 'brainmask' is also created with "BrMsk_" as an appendix.
%
%_______________________________________________________________________
% Refs:
%
% Ashburner J & Friston KJ (1997) Multimodal Image Coregistration and
% Partitioning - a Unified Framework. NeuroImage 6:209-217
%
%_______________________________________________________________________
%
% The template image, and a-priori likelihood images are modified
% versions of those kindly supplied by Alan Evans, MNI, Canada
% (ICBM, NIH P-20 project, Principal Investigator John Mazziotta).
%_______________________________________________________________________
%
% This is a renamed version of the original spm_segment which has been
% removed from the main spm distribution, but copied into the FieldMap
% toolbox where it is still used.
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: pm_segment.m 4148 2011-01-04 16:49:23Z guillaume $
% Create some suitable default values
%-----------------------------------------------------------------------
def_flags.estimate.priors = char(...
fullfile(spm('Dir'),'apriori','grey.nii'),...
fullfile(spm('Dir'),'apriori','white.nii'),...
fullfile(spm('Dir'),'apriori','csf.nii'));
def_flags.estimate.reg = 0.01;
def_flags.estimate.cutoff = 30;
def_flags.estimate.samp = 3;
def_flags.estimate.bb = [[-88 88]' [-122 86]' [-60 95]'];
def_flags.estimate.affreg.smosrc = 8;
def_flags.estimate.affreg.regtype = 'mni';
def_flags.estimate.affreg.weight = '';
def_flags.write.cleanup = 1;
def_flags.write.wrt_cor = 1;
def_flags.write.wrt_brV = 0;
def_flags.graphics = 1;
if nargin<3, flags = def_flags; end;
if ~isfield(flags,'estimate'), flags.estimate = def_flags.estimate; end;
if ~isfield(flags.estimate,'priors'), flags.estimate.priors = def_flags.estimate.priors; end;
if ~isfield(flags.estimate,'reg'), flags.estimate.reg = def_flags.estimate.reg; end;
if ~isfield(flags.estimate,'cutoff'), flags.estimate.cutoff = def_flags.estimate.cutoff; end;
if ~isfield(flags.estimate,'samp'), flags.estimate.samp = def_flags.estimate.samp; end;
if ~isfield(flags.estimate,'bb'), flags.estimate.bb = def_flags.estimate.bb; end;
if ~isfield(flags.estimate,'affreg'), flags.estimate.affreg = def_flags.estimate.affreg; end;
if ~isfield(flags.estimate.affreg,'smosrc'),
flags.estimate.affreg.smosrc = def_flags.estimate.affreg.smosrc;
end;
if ~isfield(flags.estimate.affreg,'regtype'),
flags.estimate.affreg.regtype = def_flags.estimate.affreg.regtype;
end;
if ~isfield(flags.estimate.affreg,'weight'),
flags.estimate.affreg.weight = def_flags.estimate.affreg.weight;
end;
if ~isfield(flags,'write'), flags.write = def_flags.write; end;
if ~isfield(flags.write,'cleanup'), flags.write.cleanup = def_flags.write.cleanup; end;
if ~isfield(flags.write,'wrt_cor'), flags.write.wrt_cor = def_flags.write.wrt_cor; end;
if ~isfield(flags.write,'wrt_brV'), flags.write.wrt_brV = def_flags.write.wrt_brV; end;
if ~isfield(flags,'graphics'), flags.graphics = def_flags.graphics; end;
%-----------------------------------------------------------------------
if ischar(VF), VF= spm_vol(VF); end;
SP = init_sp(flags.estimate,VF,PG);
[x1,x2,x3] = get_sampling(SP.MM,VF,flags.estimate.samp,flags.estimate.bb);
BP = init_bp(VF, flags.estimate.cutoff, flags.estimate.reg);
CP = init_cp(VF,x3);
sums = zeros(8,1);
for pp=1:length(x3),
[raw,msk] = get_raw(VF,x1,x2,x3(pp));
s = get_sp(SP,x1,x2,x3(pp));
CP = update_cp_est(CP,s,raw,msk,pp);
sums = sums + reshape(sum(sum(s,1),2),8,1);
end;
sums = sums/sum(sums);
CP = shake_cp(CP);
[CP,BP,SP] = run_segment(CP,BP,SP,VF,sums,x1,x2,x3);
%save segmentation_results.mat CP BP SP VF sums
[g,w,c] = get_gwc(VF,BP,SP,CP,sums,flags.write.wrt_cor);
if flags.write.cleanup, [g,w,c,b] = clean_gwc(g,w,c); end;
% Create the segmented images + the brain mask.
%-----------------------------------------------------------------------
%offs = cumsum(repmat(prod(VF(1).dim(1:2)),1,VF(1).dim(3)))-prod(VF(1).dim(1:2));
%pinfo = [repmat([1/255 0]',1,VF(1).dim(3)) ; offs];
[pth,nm,xt] = fileparts(deblank(VF(1).fname));
if flags.write.wrt_brV
Nwrt = 4;
else
Nwrt = 3;
end
for j=1:Nwrt,
tmp = fullfile(pth,['c', num2str(j), nm, xt]);
if j==4, tmp = fullfile(pth,['BrMsk_', nm xt]); end
VO(j) = struct(...
'fname',tmp,...
'dim', VF(1).dim(1:3),...
'dt', [spm_type('uint8'), spm_platform('bigend')],...
'mat', VF(1).mat,...
'pinfo', [1/255 0 0]',...
'descrip','Segmented image');
end;
if nargout==0 || nargout==2,
VO = spm_create_vol(VO);
spm_progress_bar('Init',VF(1).dim(3),'Writing Segmented','planes completed');
for pp=1:VF(1).dim(3),
VO(1) = spm_write_plane(VO(1),double(g(:,:,pp))/255,pp);
VO(2) = spm_write_plane(VO(2),double(w(:,:,pp))/255,pp);
VO(3) = spm_write_plane(VO(3),double(c(:,:,pp))/255,pp);
if flags.write.wrt_brV
VO(4) = spm_write_plane(VO(4),double(b(:,:,pp))/255,pp);
end
spm_progress_bar('Set',pp);
end;
spm_progress_bar('Clear');
end;
VO(1).dat = g; VO(1).pinfo = VO(1).pinfo(1:2,:);
VO(2).dat = w; VO(2).pinfo = VO(2).pinfo(1:2,:);
VO(3).dat = c; VO(3).pinfo = VO(3).pinfo(1:2,:);
if flags.write.wrt_brV
VO(4).dat = b; VO(4).pinfo = VO(4).pinfo(1:2,:);
end
if nargout==2
M = SP.MM/VF(1).mat;
end
if flags.graphics, display_graphics(VF,VO,CP.mn,CP.cv,CP.mg); end;
return;
%=======================================================================
%=======================================================================
function [y1,y2,y3] = affine_transform(x1,x2,x3,M)
y1 = M(1,1)*x1 + M(1,2)*x2 + M(1,3)*x3 + M(1,4);
y2 = M(2,1)*x1 + M(2,2)*x2 + M(2,3)*x3 + M(2,4);
y3 = M(3,1)*x1 + M(3,2)*x2 + M(3,3)*x3 + M(3,4);
return;
%=======================================================================
%=======================================================================
function display_graphics(VF,VS,mn,cv,mg)
% Do the graphics
nb = 3;
spm_figure('Clear','Graphics');
fg = spm_figure('FindWin','Graphics');
if ~isempty(fg),
% Show some text
%-----------------------------------------------------------------------
ax = axes('Position',[0.05 0.8 0.9 0.2],'Visible','off','Parent',fg);
text(0.5,0.80, 'Segmentation','FontSize',16,'FontWeight','Bold',...
'HorizontalAlignment','center','Parent',ax);
text(0,0.65, ['Image: ' spm_str_manip(VF(1).fname,'k50d')],...
'FontSize',14,'FontWeight','Bold','Parent',ax);
text(0,0.40, 'Means:','FontSize',12,'FontWeight','Bold','Parent',ax);
text(0,0.30, 'Std devs:' ,'FontSize',12,'FontWeight','Bold','Parent',ax);
text(0,0.20, 'N vox:','FontSize',12,'FontWeight','Bold','Parent',ax);
for j=1:nb,
text((j+0.5)/(nb+1),0.40, num2str(mn(1,j)),...
'FontSize',12,'FontWeight','Bold',...
'HorizontalAlignment','center','Parent',ax);
text((j+0.5)/(nb+1),0.30, num2str(sqrt(cv(1,1,j))),...
'FontSize',12,'FontWeight','Bold',...
'HorizontalAlignment','center','Parent',ax);
text((j+0.5)/(nb+1),0.20, num2str(mg(1,j)/sum(mg(1,:))),...
'FontSize',12,'FontWeight','Bold',...
'HorizontalAlignment','center','Parent',ax);
end;
if length(VF) > 1,
text(0,0.10,...
'Note: only means and variances for the first image are shown',...
'Parent',ax,'FontSize',12);
end;
M1 = VS(1).mat;
M2 = VF(1).mat;
for i=1:5,
M = spm_matrix([0 0 i*VF(1).dim(3)/6]);
img = spm_slice_vol(VF(1),M,VF(1).dim(1:2),1);
img(1,1) = eps;
ax = axes('Position',...
[0.05 0.75*(1-i/5)+0.05 0.9/(nb+1) 0.75/5],...
'Visible','off','Parent',fg);
imagesc(rot90(img), 'Parent', ax);
set(ax,'Visible','off','DataAspectRatio',[1 1 1]);
for j=1:3,
img = spm_slice_vol(VS(j),M2\M1*M,VF(1).dim(1:2),1);
ax = axes('Position',...
[0.05+j*0.9/(nb+1) 0.75*(1-i/5)+0.05 0.9/(nb+1) 0.75/5],...
'Visible','off','Parent',fg);
image(rot90(img*64), 'Parent', ax);
set(ax,'Visible','off','DataAspectRatio',[1 1 1]);
end;
end;
spm_print;
drawnow;
end;
return;
%=======================================================================
%=======================================================================
function M = get_affine_mapping(VF,VG,aflags)
if ~isempty(VG) && ischar(VG), VG = spm_vol(VG); end;
if ~isempty(VG) && isstruct(VG),
% Affine registration so that a priori images match the image to
% be segmented.
%-----------------------------------------------------------------------
VFS = spm_smoothto8bit(VF(1),aflags.smosrc);
% Scale all images approximately equally
% ---------------------------------------------------------------
for i=1:length(VG),
VG(i).pinfo(1:2,:) = VG(i).pinfo(1:2,:)/spm_global(VG(i));
end;
VFS(1).pinfo(1:2,:) = VFS(1).pinfo(1:2,:)/spm_global(VFS(1));
spm_plot_convergence('Init','Affine Registration','Mean squared difference','Iteration');
flags = struct('sep',aflags.smosrc, 'regtype',aflags.regtype,'WG',[],'globnorm',0,'debug',0);
M = eye(4);
[M,scal] = spm_affreg(VG, VFS, flags, M);
if ~isempty(aflags.weight), flags.WG = spm_vol(aflags.weight); end;
flags.sep = aflags.smosrc/2;
M = spm_affreg(VG, VFS, flags, M,scal);
spm_plot_convergence('Clear');
elseif all(size(VG) == [4 4])
% Assume that second argument is a matrix that will do the job
%-----------------------------------------------------------------------
M = VG;
else
% Assume that image is normalized
%-----------------------------------------------------------------------
M = eye(4);
end
return;
%=======================================================================
%=======================================================================
function [x1,x2,x3] = get_sampling(MM,VF,samp,bb1)
% Voxels to sample during the cluster analysis
%-----------------------------------------------------------------------
% A bounding box for the brain in Talairach space.
%bb = [ [-88 88]' [-122 86]' [-60 95]'];
%c = [bb(1,1) bb(1,2) bb(1,3) 1
% bb(1,1) bb(1,2) bb(2,3) 1
% bb(1,1) bb(2,2) bb(1,3) 1
% bb(1,1) bb(2,2) bb(2,3) 1
% bb(2,1) bb(1,2) bb(1,3) 1
% bb(2,1) bb(1,2) bb(2,3) 1
% bb(2,1) bb(2,2) bb(1,3) 1
% bb(2,1) bb(2,2) bb(2,3) 1]';
%tc = MM\c;
%tc = tc(1:3,:)';
%mx = max(tc);
%mn = min(tc);
%bb = [mn ; mx];
%vx = sqrt(sum(VF(1).mat(1:3,1:3).^2));
%samp = round(max(abs([4 4 4]./vx), [1 1 1]));
%x1 = bb(1,1):samp(1):bb(2,1);
%x2 = bb(1,2):samp(2):bb(2,2);
%x3 = bb(1,3):samp(3):bb(2,3);
%return;
% A bounding box for the brain in Talairach space.
if nargin<4, bb1 = [ [-88 88]' [-122 86]' [-60 95]']; end;
% A mapping from a unit radius sphere to a hyper-ellipse
% that is just enclosed by the bounding box in Talairach
% space.
M0 = [diag(diff(bb1)/2) mean(bb1)';[0 0 0 1]];
% The mapping from voxels to Talairach space is MM,
% so the ellipse in the space of the image becomes:
M0 = MM\M0;
% So to work out the bounding box in the space of the
% image that just encloses the hyper-ellipse.
tmp = M0(1:3,1:3);
tmp = diag(tmp*tmp'/diag(sqrt(diag(tmp*tmp'))));
bb = round([M0(1:3,4)-tmp M0(1:3,4)+tmp])';
bb = min(max(bb,[1 1 1 ; 1 1 1]),[VF(1).dim(1:3) ; VF(1).dim(1:3)]);
% Want to sample about every 3mm
tmp = sqrt(sum(VF(1).mat(1:3,1:3).^2))';
samp = round(max(abs(tmp.^(-1)*samp), [1 1 1]'));
x1 = bb(1,1):samp(1):bb(2,1);
x2 = bb(1,2):samp(2):bb(2,2);
x3 = bb(1,3):samp(3):bb(2,3);
return;
%=======================================================================
%=======================================================================
function [CP,BP,SP] = run_segment(CP,BP,SP,VF,sums,x1,x2,x3)
oll = -Inf;
spm_plot_convergence('Init','Segmenting','Log-likelihood','Iteration #');
for iter = 1:64,
ll= 0;
for pp = 1:length(x3), % Loop over planes
bf = get_bp(BP,x1,x2,x3(pp));
[raw,msk] = get_raw(VF,x1,x2,x3(pp));
s = get_sp(SP,x1,x2,x3(pp));
cor = bf.*raw;
[P,ll0] = get_p(cor,msk,s,sums,CP,bf);
ll = ll + ll0;
CP = update_cp_est(CP,P,cor,msk,pp);
BP = update_bp_est(BP,P,cor,CP,msk,x1,x2,x3(pp));
end;
BP = update_bp(BP);
if iter>1, spm_plot_convergence('Set',ll); end;
%fprintf('\t%g\n', ll);
% Stopping criterion
%-----------------------------------------------------------------------
if iter == 2,
ll2 = ll;
elseif iter > 2 && abs((ll-oll)/(ll-ll2)) < 0.0001
break;
end;
oll = ll;
end;
spm_plot_convergence('Clear');
return;
%=======================================================================
%=======================================================================
function BP = init_bp(VF,co,reg)
m = length(VF);
tmp = sqrt(sum(VF(1).mat(1:3,1:3).^2));
BP.nbas = max(round((VF(1).dim(1:3).*tmp)/co),[1 1 1]);
BP.B1 = spm_dctmtx(VF(1).dim(1),BP.nbas(1));
BP.B2 = spm_dctmtx(VF(1).dim(2),BP.nbas(2));
BP.B3 = spm_dctmtx(VF(1).dim(3),BP.nbas(3));
nbas = BP.nbas;
if prod(BP.nbas)>1,
% Set up a priori covariance matrix
vx = sqrt(sum(VF(1).mat(1:3,1:3).^2));
kx=(pi*((1:nbas(1))'-1)*pi/vx(1)/VF(1).dim(1)*10).^2;
ky=(pi*((1:nbas(2))'-1)*pi/vx(2)/VF(1).dim(2)*10).^2;
kz=(pi*((1:nbas(3))'-1)*pi/vx(3)/VF(1).dim(3)*10).^2;
% Cost function based on sum of squares of 4th derivatives
IC0 = (1*kron(kz.^4,kron(ky.^0,kx.^0)) +...
1*kron(kz.^0,kron(ky.^4,kx.^0)) +...
1*kron(kz.^0,kron(ky.^0,kx.^4)) +...
4*kron(kz.^3,kron(ky.^1,kx.^0)) +...
4*kron(kz.^3,kron(ky.^0,kx.^1)) +...
4*kron(kz.^1,kron(ky.^3,kx.^0)) +...
4*kron(kz.^0,kron(ky.^3,kx.^1)) +...
4*kron(kz.^1,kron(ky.^0,kx.^3)) +...
4*kron(kz.^0,kron(ky.^1,kx.^3)) +...
6*kron(kz.^2,kron(ky.^2,kx.^0)) +...
6*kron(kz.^2,kron(ky.^0,kx.^2)) +...
6*kron(kz.^0,kron(ky.^2,kx.^2)) +...
12*kron(kz.^2,kron(ky.^1,kx.^1)) +...
12*kron(kz.^1,kron(ky.^2,kx.^1)) +...
12*kron(kz.^1,kron(ky.^1,kx.^2)) )*reg;
%IC0(1) = max(IC0);
BP.IC0 = diag(IC0(2:end));
% Initial estimate for intensity modulation field
BP.T = zeros(nbas(1),nbas(2),nbas(3),length(VF));
%-----------------------------------------------------------------------
else
BP.T = zeros([1 1 1 length(VF)]);
BP.IC0 = [];
end;
BP.Alpha = zeros(prod(BP.nbas(1:3)),prod(BP.nbas(1:3)),m);
BP.Beta = zeros(prod(BP.nbas(1:3)),m);
return;
%=======================================================================
%=======================================================================
function BP = update_bp_est(BP,p,cor,CP,msk,x1,x2,x3)
if prod(BP.nbas)<=1, return; end;
B1 = BP.B1(x1,:);
B2 = BP.B2(x2,:);
B3 = BP.B3(x3,:);
for j=1:size(BP.Alpha,3),
cr = cor(:,:,j);
w1 = zeros(size(cr));
w2 = zeros(size(cr));
for i=[1 2 3 4 5 6 7 8],
tmp = p(:,:,i)*CP.cv(j,j,i)^(-1);
w1 = w1 + tmp.*(CP.mn(j,i) - cr);
w2 = w2 + tmp;
end;
wt1 = 1 + cr.*w1;
wt2 = cr.*(cr.*w2 - w1);
wt1(~msk) = 0;
wt2(~msk) = 0;
BP.Beta(:,j) = BP.Beta(:,j) + kron(B3',spm_krutil(wt1,B1,B2,0));
BP.Alpha(:,:,j) = BP.Alpha(:,:,j) + kron(B3'*B3,spm_krutil(wt2,B1,B2,1));
end;
return;
%=======================================================================
%=======================================================================
function BP = update_bp(BP)
if prod(BP.nbas)<=1, return; end;
for j=1:size(BP.Alpha,3),
x = BP.T(:,:,:,j);
x = x(:);
x = x(2:end);
Alpha = BP.Alpha(2:end,2:end,j);
Beta = BP.Beta(2:end,j);
x = (Alpha + BP.IC0)\(Alpha*x + Beta);
BP.T(:,:,:,j) = reshape([0 ; x],BP.nbas(1:3));
BP.Alpha = zeros(size(BP.Alpha));
BP.Beta = zeros(size(BP.Beta));
end;
return;
%=======================================================================
%=======================================================================
function bf = get_bp(BP,x1,x2,x3)
bf = ones(length(x1),length(x2),size(BP.Alpha,3));
if prod(BP.nbas)<=1, return; end;
B1 = BP.B1(x1,:);
B2 = BP.B2(x2,:);
B3 = BP.B3(x3,:);
for i=1:size(BP.Alpha,3),
t = reshape(reshape(BP.T(:,:,:,i),...
BP.nbas(1)*BP.nbas(2),BP.nbas(3))*B3', BP.nbas(1), BP.nbas(2));
bf(:,:,i) = exp(B1*t*B2');
end;
return;
%=======================================================================
%=======================================================================
function [dat,msk] = get_raw(VF,x1,x2,x3)
[X1,X2,X3] = ndgrid(x1,x2,x3);
for i=1:length(VF),
[Y1,Y2,Y3] = affine_transform(X1,X2,X3,VF(i).mat\VF(1).mat);
dat(:,:,i) = spm_sample_vol(VF(i),Y1,Y2,Y3,1);
end;
msk = all(dat,3) & all(isfinite(double(dat)),3);
return;
%=======================================================================
%=======================================================================
function CP = init_cp(VF,x3)
n = 8;
m = length(VF);
p = length(x3);
CP.mom0 = zeros(1,n,p)+eps;
CP.mom1 = zeros(m,n,p);
CP.mom2 = zeros(m,m,n,p)+eps;
% Occasionally the dynamic range of the images is such that many voxels
% all have the same intensity. Adding cv0 is an attempt to improve the
% stability of the algorithm if this occurs. The value 0.083 was obtained
% from var(rand(1000000,1)). It prbably isn't the best way of doing
% things, but it appears to work.
CP.cv0 = zeros(m,m);
for i=1:m,
if spm_type(VF(i).dt(1),'intt'),
CP.cv0(i,i)=0.083*mean(VF(i).pinfo(1,:));
end;
end;
return;
%=======================================================================
%=======================================================================
function CP = shake_cp(CP)
CP.mom0(:,5,:) = CP.mom0(:,1,:);
CP.mom0(:,6,:) = CP.mom0(:,2,:);
CP.mom0(:,7,:) = CP.mom0(:,3,:);
CP.mom1(:,5,:) = CP.mom1(:,1,:);
CP.mom1(:,6,:) = CP.mom1(:,2,:);
CP.mom1(:,7,:) = CP.mom1(:,3,:);
CP.mom1(:,8,:) = 0;
CP.mom2(:,:,5,:) = CP.mom2(:,:,1,:);
CP.mom2(:,:,6,:) = CP.mom2(:,:,2,:);
CP.mom2(:,:,7,:) = CP.mom2(:,:,3,:);
return;
%=======================================================================
%=======================================================================
function CP = update_cp_est(CP,P,dat,msk,p)
m = size(dat,3);
d = size(P);
P = reshape(P,[d(1)*d(2),d(3)]);
dat = reshape(dat,[d(1)*d(2),m]);
P(~msk(:),:) = [];
dat(~msk(:),:) = [];
for i=1:size(CP.mom0,2),
CP.mom0(1,i,p) = sum(P(:,i));
CP.mom1(:,i,p) = sum((P(:,i)*ones(1,m)).*dat)';
CP.mom2(:,:,i,p) = ((P(:,i)*ones(1,m)).*dat)'*dat;
end;
for i=1:size(CP.mom0,2),
CP.mg(1,i) = sum(CP.mom0(1,i,:),3);
CP.mn(:,i) = sum(CP.mom1(:,i,:),3)/CP.mg(1,i);
tmp = (CP.mg(1,i).*CP.mn(:,i))*CP.mn(:,i)';
tmp = tmp-eye(size(tmp))*eps*1e6;
CP.cv(:,:,i) = (sum(CP.mom2(:,:,i,:),4) - tmp)/CP.mg(1,i) + CP.cv0;
end;
CP.mg = CP.mg/sum(CP.mg);
return;
%=======================================================================
%=======================================================================
function [p,ll] = get_p(cor,msk,s,sums,CP,bf)
d = [size(cor) 1 1];
n = size(CP.mg,2);
cor = reshape(cor,d(1)*d(2),d(3));
cor = cor(msk,:);
p = zeros(d(1)*d(2),n);
if ~any(msk), p = reshape(p,d(1),d(2),n); ll=0; return; end;
for i=1:n,
amp = 1/sqrt((2*pi)^d(3) * det(CP.cv(:,:,i)));
dst = (cor-ones(size(cor,1),1)*CP.mn(:,i)')/sqrtm(CP.cv(:,:,i));
dst = sum(dst.*dst,2);
tmp = s(:,:,i);
p(msk,i) = (amp*CP.mg(1,i)/sums(i))*exp(-0.5*dst).*tmp(msk) +eps;
end;
sp = sum(p,2);
ll = sum(log(sp(msk).*bf(msk)+eps));
sp(~msk) = Inf;
for i=1:n, p(:,i) = p(:,i)./sp; end;
p = reshape(p,d(1),d(2),n);
return;
%=======================================================================
%=======================================================================
function SP = init_sp(flags,VF,PG)
SP.VB = spm_vol(flags.priors);
MM = get_affine_mapping(VF,PG,flags.affreg);
%VF = spm_vol(PF);
SP.MM = MM*VF(1).mat;
SP.w = 0.98;
return;
%=======================================================================
%=======================================================================
function s = get_sp(SP,x1,x2,x3)
[X1,X2,X3] = ndgrid(x1,x2,x3);
[Y1,Y2,Y3] = affine_transform(X1,X2,X3,SP.VB(1).mat\SP.MM);
w1 = SP.w;
w2 = (1-w1)/2;
s = zeros([size(Y1),4]);
for i=1:3,
s(:,:,i) = spm_sample_vol(SP.VB(i),Y1,Y2,Y3,1)*w1+w2;
end;
s(:,:,4:8) = repmat(abs(1-sum(s(:,:,1:3),3))/5,[1 1 5]);
return;
%=======================================================================
%=======================================================================
function [g,w,c] = get_gwc(VF,BP,SP,CP,sums,wc)
if wc,
VC = VF;
for j=1:length(VF),
[pth,nm,xt,vr] = spm_fileparts(deblank(VF(j).fname));
VC(j).fname = fullfile(pth,['m' nm xt vr]);
VC(j).descrip = 'Bias corrected image';
end;
VC = spm_create_vol(VC);
end;
spm_progress_bar('Init',VF(1).dim(3),'Creating Segmented','planes completed');
x1 = 1:VF(1).dim(1);
x2 = 1:VF(1).dim(2);
x3 = 1:VF(1).dim(3);
g = uint8(0); g(VF(1).dim(1),VF(1).dim(2),VF(1).dim(3)) = 0;
w = uint8(0); w(VF(1).dim(1),VF(1).dim(2),VF(1).dim(3)) = 0;
c = uint8(0); c(VF(1).dim(1),VF(1).dim(2),VF(1).dim(3)) = 0;
for pp=1:length(x3),
bf = get_bp(BP,x1,x2,x3(pp));
[raw,msk] = get_raw(VF,x1,x2,x3(pp));
cor = raw.*bf;
if wc,
for j=1:length(VC),
VC(j) = spm_write_plane(VC(j),cor(:,:,j),pp);
end;
end;
s = get_sp(SP,x1,x2,x3(pp));
p = get_p(cor,msk,s,sums,CP,bf);
g(:,:,pp) = uint8(round(p(:,:,1)*255));
w(:,:,pp) = uint8(round(p(:,:,2)*255));
c(:,:,pp) = uint8(round(p(:,:,3)*255));
spm_progress_bar('Set',pp);
end;
spm_progress_bar('Clear');
return;
%=======================================================================
%=======================================================================
function [g,w,c,b] = clean_gwc(g,w,c)
b = w;
b(1) = w(1);
% Build a 3x3x3 seperable smoothing kernel
%-----------------------------------------------------------------------
kx=[0.75 1 0.75];
ky=[0.75 1 0.75];
kz=[0.75 1 0.75];
sm=sum(kron(kron(kz,ky),kx))^(1/3);
kx=kx/sm; ky=ky/sm; kz=kz/sm;
% Erosions and conditional dilations
%-----------------------------------------------------------------------
niter = 32;
spm_progress_bar('Init',niter,'Extracting Brain','Iterations completed');
for j=1:niter,
if j>2, th=0.15; else th=0.6; end; % Dilate after two its of erosion.
for i=1:size(b,3),
gp = double(g(:,:,i));
wp = double(w(:,:,i));
bp = double(b(:,:,i))/255;
bp = (bp>th).*(wp+gp);
b(:,:,i) = uint8(round(bp));
end;
spm_conv_vol(b,b,kx,ky,kz,-[1 1 1]);
spm_progress_bar('Set',j);
end;
th = 0.05;
for i=1:size(b,3),
gp = double(g(:,:,i))/255;
wp = double(w(:,:,i))/255;
cp = double(c(:,:,i))/255;
bp = double(b(:,:,i))/255;
bp = ((bp>th).*(wp+gp))>th;
g(:,:,i) = uint8(round(255*gp.*bp./(gp+wp+cp+eps)));
w(:,:,i) = uint8(round(255*wp.*bp./(gp+wp+cp+eps)));
c(:,:,i) = uint8(round(255*(cp.*bp./(gp+wp+cp+eps)+cp.*(1-bp))));
b(:,:,i) = uint8(round(255*bp));
end;
spm_progress_bar('Clear');
return;
|
github
|
philippboehmsturm/antx-master
|
FieldMap_applyvdm.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/FieldMap/FieldMap_applyvdm.m
| 8,720 |
utf_8
|
9761a5b5d2184cd48650ef88da884109
|
function out = FieldMap_applyvdm(job)
% Apply VDM and reslice images
% FORMAT FieldMap_applyvdm(job)
% job.data(sessnum).scans - images for session/run sessnum
% job.data(sessnum).vdmfile - VDM file for session/run sessnum
% job.roptions.rinterp - interpolation method
% job.roptions.wrap - perform warp around in specified dimensions
% job.roptions.mask - perform masking
% job.roptions.which(1) - reslice images in time series only
% job.roptions.which(2) - reslice images in time series and mean
% job.roptions.prefix - prefix for vdm applied files
% job.roptions.pedir - phase encode direction (i.e. aplly vdm file along
% this dimension
%__________________________________________________________________________
%
% A VDM (voxel displacement map) created using the FieldMap toolbox
% can be used to resample and reslice realigned images to the original
% subdirectory with the same (prefixed) filename.
%
% Voxels in the images will be shifted according to the values in the VDM
% file along the direction specified by job.roptions.pedir (i.e. this is
% usually the phase encode direction) and resliced to the space of the
% first image in the time series.
%
% Inputs:
% A job structure containing fields for the input data and the processing
% options. The input data contains the series of images conforming to
% SPM data format (see 'Data Format'), the relative displacement of the images
% is stored in their header and a VDM which has (probably) been created
% using the FieldMap toolbox and matched to the first image in the time
% series (this can also be done via the FieldMap toolbox).
%
% Outputs:
% The resmapled and resliced images resliced to the same subdirectory with a prefix.
%__________________________________________________________________________
% Copyright (C) 2011 Wellcome Trust Centre for Neuroimaging
% Chloe Hutton
% $Id: FieldMap_applyvdm.m 4228 2011-03-04 15:00:15Z chloe $
tiny = 5e-2;
% assemble roptions
%-----------------------------------------------------------------------
flags.interp = job.roptions.rinterp;
flags.wrap = job.roptions.wrap;
flags.mask = job.roptions.mask;
flags.which = job.roptions.which(1);
flags.mean = job.roptions.which(2);
flags.prefix = job.roptions.prefix;
flags.pedir = job.roptions.pedir;
hold = [repmat(flags.interp,1,3) flags.wrap];
% Determine dimension along which to apply vdm
applydim=flags.pedir;
if applydim~=1 & applydim~=2 & applydim~=3
applydim=2;
end
% Gather up data into ds structure which holds images and vdm file
%-----------------------------------------------------------------------
P = {};
for i = 1:numel(job.data)
P{i} = strvcat(job.data(i).scans{:});
ds(i).P=spm_vol(P{i});
if ~isempty(job.data(i).vdmfile)
sfP{i} = job.data(i).vdmfile{1};
ds(i).sfP=spm_vol(sfP{i});
else
sfP{i} = [];
end
ds(i).hold = [1 1 1 0 1 0];
end
ntot = 0;
for i=1:length(ds)
ntot = ntot + length(ds(i).P);
end
% Set up x y z for resampling
%-----------------------------------------------------------------------
[x,y,z] = ndgrid(1:ds(1).P(1).dim(1),1:ds(1).P(1).dim(2),1:ds(1).P(1).dim(3));
xyz = [x(:) y(:) z(:) ones(prod(ds(1).P(1).dim(1:3)),1)]; clear x y z;
% Create mask if required (usually default and required to create mean)
%-----------------------------------------------------------------------
if flags.mask || flags.mean,
spm_progress_bar('Init',ntot,'Computing available voxels',...
'volumes completed');
if flags.mean
Count = zeros(prod(ds(1).P(1).dim(1:3)),1);
Integral = zeros(prod(ds(1).P(1).dim(1:3)),1);
end
% if flags.mask
msk = zeros(prod(ds(1).P(1).dim(1:3)),1);
% end
% To create mean, read each session specific vdmfile in
% to the space of the first image of first session
tv = 1;
for s=1:length(ds)
T = ds(s).sfP.mat\ds(1).P(1).mat;
txyz = xyz * T';
c = spm_bsplinc(ds(s).sfP,ds(1).hold);
ds(s).sfield = spm_bsplins(c,txyz(:,1),txyz(:,2),txyz(:,3),ds(1).hold);
ds(s).sfield = ds(s).sfield(:);
clear c txyz;
sess_msk = zeros(prod(ds(s).P(1).dim(1:3)),1);
% Read in each images in space of first image of first session
for i = 1:numel(ds(s).P)
T = inv(ds(s).P(i).mat) * ds(1).P(1).mat;
txyz = xyz * T';
txyz(:,applydim) = txyz(:,applydim) + ds(s).sfield;
tmp = false(size(txyz,1),1);
if ~flags.wrap(1), tmp = tmp | txyz(:,1) < (1-tiny) | txyz(:,1) > (ds(s).P(i).dim(1)+tiny); end
if ~flags.wrap(2), tmp = tmp | txyz(:,2) < (1-tiny) | txyz(:,2) > (ds(s).P(i).dim(2)+tiny); end
if ~flags.wrap(3), tmp = tmp | txyz(:,3) < (1-tiny) | txyz(:,3) > (ds(s).P(i).dim(3)+tiny); end
sess_msk = sess_msk + real(tmp);
spm_progress_bar('Set',tv);
tv = tv+1;
end
msk = msk + sess_msk;
if flags.mean, Count = Count + repmat(length(ds(s).P),prod(ds(s).P(1).dim(1:3)),1) - sess_msk; end
%
% Include static field in estmation of mask.
%
if isfield(ds(s),'sfP') && ~isempty(ds(s).sfP)
T = inv(ds(1).sfP.mat) * ds(1).P(1).mat;
txyz = xyz * T';
tmp = false(size(txyz,1),1);
if ~flags.wrap(1), tmp = tmp | txyz(:,1) < (1-tiny) | txyz(:,1) > (ds(1).sfP.dim(1)+tiny); end
if ~flags.wrap(2), tmp = tmp | txyz(:,2) < (1-tiny) | txyz(:,2) > (ds(1).sfP.dim(2)+tiny); end
if ~flags.wrap(3), tmp = tmp | txyz(:,3) < (1-tiny) | txyz(:,3) > (ds(1).sfP.dim(3)+tiny); end
msk = msk + real(tmp);
end
if isfield(ds(1),'sfield') && ~isempty(ds(1).sfield)
ds(1).sfield = [];
end
end
if flags.mask, msk = find(msk ~= 0); end
end
% Apply fieldmap to all files, looping through sessions
%-----------------------------------------------------------------------
spm_progress_bar('Init',ntot,'Reslicing','volumes completed');
tv = 1;
for s = 1:numel(ds)
% Get transformation between distortion field and first image
T = ds(s).sfP.mat\ds(1).P(1).mat;
txyz = xyz * T';
c = spm_bsplinc(ds(s).sfP,ds(1).hold);
ds(s).sfield = spm_bsplins(c,txyz(:,1),txyz(:,2),txyz(:,3),ds(1).hold);
ds(s).sfield = ds(s).sfield(:);
% Read in each images in space of first image of first session
for i = 1:numel(ds(s).P)
T = inv(ds(s).P(i).mat) * ds(1).P(1).mat;
txyz = xyz * T';
txyz(:,applydim) = txyz(:,applydim) + ds(s).sfield;
c = spm_bsplinc(ds(s).P(i),hold);
ima = spm_bsplins(c,txyz(:,1),txyz(:,2),txyz(:,3),hold);
%
% Write out resliced images
%
if flags.which
PO = ds(s).P(i);
[pth,nm,xt,vr] = spm_fileparts(deblank(PO.fname));
PO.fname = fullfile(pth,[flags.prefix nm xt vr]);
PO.mat = ds(1).P(1).mat;
PO.descrip = sprintf('spm - applied vdm');
ivol = ima;
if flags.mask
ivol(msk) = NaN;
end
ivol = reshape(ivol,PO.dim(1:3));
PO = spm_create_vol(PO);
spm_write_vol(PO,ivol);
if nargout > 0
out.sess(s).rfiles{i} = PO.fname;
end
end
%
% Build up mean image if so required.
%
if flags.mean
Integral = Integral + nan2zero(ima);
end
spm_progress_bar('Set',tv);
tv = tv+1;
end
if isfield(ds(s),'sfield') && ~isempty(ds(s).sfield)
ds(s).sfield = [];
end
end
% Write mean image
%-----------------------------------------------------------
if flags.mean
% Write integral image (16 bit signed)
%-----------------------------------------------------------
sw = warning('off','MATLAB:divideByZero');
Integral = Integral./Count;
warning(sw);
PO = ds(1).P(1);
[pth,nm,xt,vr] = spm_fileparts(deblank(ds(1).P(1).fname));
PO.fname = fullfile(pth,['mean' flags.prefix nm xt vr]);
PO.pinfo = [max(max(max(Integral)))/32767 0 0]';
PO.descrip = 'spm - mean applied vdm image';
PO.dt = [spm_type('int16') spm_platform('bigend')];
ivol = reshape(Integral,PO.dim);
spm_write_vol(PO,ivol);
end
if nargout > 0
out.rmean{1} = PO.fname;
end
spm_figure('Clear','Interactive');
%_______________________________________________________________________
function vo = nan2zero(vi)
vo = vi;
vo(~isfinite(vo)) = 0;
return;
%_______________________________________________________________________
|
github
|
philippboehmsturm/antx-master
|
pm_brain_mask.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/FieldMap/pm_brain_mask.m
| 4,163 |
utf_8
|
1c73d1378400faa40089ab34da5760d1
|
function bmask = pm_brain_mask(P,flags)
% Calculate a brain mask
% FORMAT bmask = pm_brain_mask(P,flags)
%
% P - is a single pointer to a single image
%
% flags - structure containing various options
% template - which template for segmentation
% fwhm - fwhm of smoothing kernel for generating mask
% nerode - number of erosions
% thresh - threshold for smoothed mask
% ndilate - number of dilations
%
%__________________________________________________________________________
%
% Inputs
% A single *.img conforming to SPM data format (see 'Data Format').
%
% Outputs
% Brain mask in a matrix
%__________________________________________________________________________
%
% The brain mask is generated by segmenting the image into GM, WM and CSF,
% adding these components together then thresholding above zero.
% A morphological opening is performed to get rid of stuff left outside of
% the brain. Any leftover holes are filled.
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Chloe Hutton
% $Id: pm_brain_mask.m 2616 2009-01-19 16:49:42Z chloe $
if nargin < 2 | isempty(flags)
flags.template=fullfile(spm('Dir'),'templates','T1.nii');
flags.fwhm=5;
flags.nerode=2;
flags.ndilate=4;
flags.thresh=0.5;
flags.reg = 0.02;
flags.graphics=0;
end
disp('Segmenting and extracting brain...');
seg_flags.estimate.reg=flags.reg;
seg_flags.graphics = flags.graphics;
% Updated to use renamed version of spm_segment
VO=pm_segment(P.fname,flags.template,seg_flags);
bmask=double(VO(1).dat)+double(VO(2).dat)+double(VO(3).dat)>0;
%bmask=open_it(bmask,flags.nerode,flags.ndilate); % Do opening to get rid of scalp
bmask=open_it(bmask,flags.nerode,flags.ndilate); % Do opening to get rid of scalp
% Calculate kernel in voxels:
vxs = sqrt(sum(P.mat(1:3,1:3).^2));
fwhm = repmat(flags.fwhm,1,3)./vxs;
bmask=fill_it(bmask,fwhm,flags.thresh); % Do fill to fill holes
OP=P;
brain_mask = [spm_str_manip(P.fname,'h') '/bmask',...
spm_str_manip(P.fname,'t')];
OP.fname=brain_mask;
OP.descrip=sprintf('Mask:erode=%d,dilate=%d,fwhm=%d,thresh=%1.1f',flags.nerode,flags.ndilate,flags.fwhm,flags.thresh);
spm_write_vol(OP,bmask);
%__________________________________________________________________________
function ovol=open_it(vol,ne,nd)
% Do a morphological opening. This consists of an erosion, followed by
% finding the largest connected component, followed by a dilation.
% Do an erosion then a connected components then a dilation
% to get rid of stuff outside brain.
for i=1:ne
nvol=spm_erode(double(vol));
vol=nvol;
end
nvol=connect_it(vol);
vol=nvol;
for i=1:nd
nvol=spm_dilate(double(vol));
vol=nvol;
end
ovol=nvol;
%__________________________________________________________________________
%__________________________________________________________________________
function ovol=fill_it(vol,k,thresh)
% Do morpholigical fill. This consists of finding the largest connected
% component and assuming that is outside of the head. All the other
% components are set to 1 (in the mask). The result is then smoothed by k
% and thresholded by thresh.
ovol=vol;
% Need to find connected components of negative volume
vol=~vol;
[vol,NUM]=spm_bwlabel(double(vol),26);
% Now get biggest component and assume this is outside head..
pnc=0;
maxnc=1;
for i=1:NUM
nc=size(find(vol==i),1);
if nc>pnc
maxnc=i;
pnc=nc;
end
end
% We know maxnc is largest cluster outside brain, so lets make all the
% others = 1.
for i=1:NUM
if i~=maxnc
nc=find(vol==i);
ovol(nc)=1;
end
end
spm_smooth(ovol,ovol,k);
ovol=ovol>thresh;
%_______________________________________________________________________
%_______________________________________________________________________
function ovol=connect_it(vol)
% Find connected components and return the largest one.
[vol,NUM]=spm_bwlabel(double(vol),26);
% Get biggest component
pnc=0;
maxnc=1;
for i=1:NUM
nc=size(find(vol==i),1);
if nc>pnc
maxnc=i;
pnc=nc;
end
end
ovol=(vol==maxnc);
|
github
|
philippboehmsturm/antx-master
|
FieldMap.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/FieldMap/FieldMap.m
| 83,497 |
utf_8
|
26a90d75ac07852199822d233d5c731a
|
function varargout=FieldMap(varargin)
%
% FieldMap is an SPM8 Toolbox for creating field maps and unwarping EPI.
% A full description of the toolbox and a usage manual can be found in
% FieldMap.man. This can launched by the toolbox help button or using
% spm_help FieldMap.man.The theoretical and practical principles behind
% the toolbox are described in principles.man.
%
% FORMAT FieldMap
%
% FieldMap launches the gui-based toolbox. Help is available via the
% help button (which calls spm_help FieldMap.man). FieldMap is a multi
% function function so that the toolbox routines can also be accessed
% without using the gui. A description of how to do this can be found
% in FieldMap_ngui.m
%
% Input parameters and the mode in which the toolbox works can be
% customised using the defaults file called pm_defaults.m.
%
% Main data structure:
%
% IP.P : 4x1 cell array containing real part short TE,
% imaginary part short TE, real part long TE and
% imaginary part long TE.
% IP.pP : Cell containing pre-calculated phase map. N.B.
% IP.P and IP.pP are mutually exclusive.
% IP.epiP : Cell containing EPI image used to demonstrate
% effects of unwarping.
% IP.fmagP : Cell containing fieldmap magnitude image used for
% coregistration
% IP.wfmagP : Cell containing forward warped fieldmap magnitude
% image used for coregistration
% IP.uepiP : Cell containing unwarped EPI image.
% IP.nwarp : Cell containing non-distorted image.
% IP.vdmP : Cell containing the voxel displacement map (VDM)
% IP.et : 2x1 Cell array with short and long echo-time (ms).
% IP.epifm : Flag indicating EPI based field map (1) or not (0).
% IP.blipdir : Direction of phase-encode blips for k-space traversal
% (1 = positive or -1 = negative)
% IP.ajm : Flag indicating if Jacobian modulation should be applied
% (1) or not (0).
% IP.tert : Total epi readout time (ms).
% IP.maskbrain : Flag indicating whether to mask the brain for fieldmap creation
% IP.uflags : Struct containing parameters guiding the unwrapping.
% Further explanations of these parameters are in
% FieldMap.man and pm_make_fieldmap.m
% .iformat : 'RI' or 'PM'
% .method : 'Huttonish', 'Mark3D' or 'Mark2D'
% .fwhm : FWHM (mm) of Gaussian filter for field map smoothing
% .pad : Size (in-plane voxels) of padding kernel.
% .etd : Echo time difference (ms).
% .bmask
%
% IP.mflags : Struct containing parameters for brain maskin
% .template : Name of template for segmentation.
% .fwhm : fwhm of smoothing kernel for generating mask.
% .nerode : number of erosions
% .ndilate : number of dilations
% .thresh : threshold for smoothed mask.
% .reg : bias field regularisation
% .graphics : display or not
%
% IP.fm : Struct containing field map information
% IP.fm.upm : Phase-unwrapped field map (Hz).
% IP.fm.mask : Binary mask excluding the noise in the phase map.
% IP.fm.opm : "Raw" field map (Hz) (not unwrapped).
% IP.fm.fpm : Phase-unwrapped, regularised field map (Hz).
% IP.fm.jac : Partial derivative of field map in y-direction.
%
% IP.vdm : Struct with voxel displacement map information
% IP.vdm.vdm : Voxel displacement map (scaled version of IP.fm.fpm).
% IP.vdm.jac : Jacobian-1 of forward transform.
% IP.vdm.ivdm : Inverse transform of voxel displacement
% (used to unwarp EPI image if field map is EPI based)
% (used to warp flash image prior to coregistration when
% field map is flash based (or other T2 weighting).
% IP.vdm.ijac : Jacobian-1 of inverse transform.
% IP.jim : Jacobian sampled in space of EPI.
%
% IP.cflags : Struct containing flags for coregistration
% (these are the default SPM coregistration flags -
% defaults.coreg).
% .cost_fun
% .sep
% .tol
% .fwhm
%
%_______________________________________________________________________
% Refs and Background reading:
%
% Jezzard P & Balaban RS. 1995. Correction for geometric distortion in
% echo planar images from Bo field variations. MRM 34:65-73.
%
% Hutton C et al. 2002. Image Distortion Correction in fMRI: A Quantitative
% Evaluation, NeuroImage 16:217-240.
%
% Cusack R & Papadakis N. 2002. New robust 3-D phase unwrapping
% algorithms: Application to magnetic field mapping and
% undistorting echoplanar images. NeuroImage 16:754-764.
%
% Jenkinson M. 2003. Fast, automated, N-dimensional phase-
% unwrapping algorithm. MRM 49:193-197.
%
%_______________________________________________________________________
% Acknowledegments
%
% Wellcome Trust and IBIM Consortium
%_______________________________________________________________________
% UPDATE 02/07
% Updated version of FieldMap for SPM5.
%
% UPDATE 27/01/05
%_______________________________________________________________________
% Copyright (C) 2006 Wellcome Department of Imaging Neuroscience
% Jesper Andersson and Chloe Hutton
% $Id: FieldMap.m 4571 2011-11-23 17:34:12Z chloe $
%_______________________________________________________________________
persistent PF FS WS PM % GUI related constants
persistent ID % Image display
persistent IP % Input and results
persistent DGW % Delete Graphics Window (if we created it)
global st % Global for spm_orthviews
if nargin == 0
Action = 'welcome';
else
Action = varargin{1};
end
%
% We have tried to divide the Actions into 3 categories:
% 1) Functions that can be called directly from the GUI are at the
% beginning.
% 2) Next come other GUI-related 'utility' functions - ie those that
% care of the GUI behind the scenes.
% 3) Finally, call-back functions that are not GUI dependent and can
% be called from a script are situated towards the end.
% See FieldMap_ngui.m for details on how to use these.
%
switch lower(Action)
%=======================================================================
%
% Create and initialise GUI for FieldMap toolbox
%
%=======================================================================
case 'welcome'
% Unless specified, set visibility to on
if nargin==2
if ~strcmp(varargin{2},'off') & ~strcmp(varargin{2},'Off')
visibility = 'On';
else
visibility = 'Off';
end
else
visibility = 'On';
end
DGW = 0;
% Get all default values (these may effect GUI)
IP = FieldMap('Initialise');
%
% Since we are using persistent variables we better make sure
% there is no-one else out there.
%
if ~isempty(PM)
figure(PM);
set(PM,'Visible',visibility);
return
end
S0 = spm('WinSize','0',1);
WS = spm('WinScale');
FS = spm('FontSizes');
PF = spm_platform('fonts');
rect = [100 100 510 520].*WS;
PM = figure('IntegerHandle','off',...
'Name',sprintf('%s%s','FieldMap Toolbox, ver.2.1',...
spm('GetUser',' (%s)')),...
'NumberTitle','off',...
'Tag','FieldMap',...
'Position',[S0(1),S0(2),0,0] + rect,...
'Resize','off',...
'Pointer','Arrow',...
'Color',[1 1 1]*.8,...
'MenuBar','none',...
'DefaultTextFontName',PF.helvetica,...
'DefaultTextFontSize',FS(10),...
'DefaultUicontrolFontName',PF.helvetica,...
'DefaultUicontrolFontSize',FS(10),...
'HandleVisibility','on',...
'Visible',visibility,...
'DeleteFcn','FieldMap(''Quit'');');
%-Create phase map controls
%-Frames and text
uicontrol(PM,'Style','Frame','BackgroundColor',spm('Colour'),...
'Position',[10 270 490 240].*WS);
uicontrol(PM,'Style','Text','String','Create field map in Hz',...
'Position',[100 480 300 020].*WS,...
'ForegroundColor','k','BackgroundColor',spm('Colour'),...
'FontName',PF.times,'FontAngle','Italic')
uicontrol(PM,'Style','Text','String','Short TE',...
'Position',[25 452 60 20].*WS,...
'ForegroundColor','k','BackgroundColor',spm('Colour'),...
'FontName',PF.times)
uicontrol(PM,'Style','Text','String','ms',...
'Position',[78 430 30 20].*WS,...
'ForegroundColor','k','BackgroundColor',spm('Colour'),...
'FontName',PF.times)
uicontrol(PM,'Style','Text','String','Long TE',...
'Position',[25 392 60 20].*WS,...
'ForegroundColor','k','BackgroundColor',spm('Colour'),...
'FontName',PF.times)
uicontrol(PM,'Style','Text','String','ms',...
'Position',[78 370 30 20].*WS,...
'ForegroundColor','k','BackgroundColor',spm('Colour'),...
'FontName',PF.times)
uicontrol(PM,'Style','Text','String',{'Mask brain:'},...
'Position',[30 310 80 35].*WS,...
'ForegroundColor','k','BackgroundColor',spm('Colour'),...
'FontName',PF.times)
uicontrol(PM,'Style','Text','String',{'Precalculated','field map:'},...
'Position',[30 275 80 35].*WS,...
'ForegroundColor','k','BackgroundColor',spm('Colour'),...
'FontName',PF.times)
uicontrol(PM,'Style','Text','String',{'Field map value:'},...
'Position',[240 280 100 20].*WS,...
'ForegroundColor','k','BackgroundColor',spm('Colour'),...
'FontName',PF.times)
uicontrol(PM,'Style','Text','String',{'Hz'},...
'Position',[403 280 20 20].*WS,...
'ForegroundColor','k','BackgroundColor',spm('Colour'),...
'FontName',PF.times)
%-Objects with Callbacks
uicontrol(PM,'Style','radiobutton',...
'String','RI',...
'Position',[30 480 44 022].*WS,...
'ToolTipString','Select Real/Imaginary input images',...
'CallBack','FieldMap(''InputFormat'');',...
'UserData',1,...
'Tag','IFormat');
uicontrol(PM,'Style','radiobutton',...
'String','PM',...
'Position',[76 480 44 022].*WS,...
'ToolTipString','Select phase/magnitude input images',...
'CallBack','FieldMap(''InputFormat'');',...
'UserData',2,...
'Tag','IFormat');
uicontrol(PM,'Style','Edit',...
'Position',[30 430 50 024].*WS,...
'ToolTipString','Give shortest echo-time in ms',...
'CallBack','FieldMap(''EchoTime'');',...
'UserData',1,...
'Tag','ShortTime');
uicontrol(PM,'Style','Edit',...
'Position',[30 370 50 024].*WS,...
'ToolTipString','Give longest echo-time in ms',...
'CallBack','FieldMap(''EchoTime'');',...
'UserData',2,...
'Tag','LongTime');
% Here we set up appropriate gui
FieldMap('IFormat_Gui');
uicontrol(PM,'String','Calculate',...
'Position',[265 337 90 022].*WS,...
'Enable','Off',...
'ToolTipString','Go ahead and create unwrapped field map (in Hz)',...
'CallBack','FieldMap(''CreateFieldmap_Gui'');',...
'Tag','CreateFieldMap');
uicontrol(PM,'String','Write',...
'Position',[370 337 90 022].*WS,...
'Enable','Off',...
'ToolTipString','Write Analyze image containing fininshed field map (in Hz)',...
'CallBack','FieldMap(''WriteFieldMap_Gui'');',...
'Tag','WriteFieldMap');
uicontrol(PM,'String','Load',...
'Position',[125 280 90 022].*WS,...
'ToolTipString','Load Analyze image containing finished field map (in Hz)',...
'CallBack','FieldMap(''LoadFieldMap_Gui'');',...
'Tag','LoadFieldMap');
% Empty string written to Fieldmap value box
uicontrol(PM,'Style','Text',...
'Position',[340 280 50 020].*WS,...
'HorizontalAlignment','left',...
'String','');
%-Create voxel-displacement-map controls
%-Frames and text
uicontrol(PM,'Style','Frame','BackgroundColor',spm('Colour'),...
'Position',[10 10 490 250].*WS);
uicontrol(PM,'Style','Text',...
'String','Create voxel displacement map (VDM) and unwarp EPI',...
'Position',[70 235 350 020].*WS,...
'ForegroundColor','k','BackgroundColor',spm('Colour'),...
'FontName',PF.times,'FontAngle','Italic')
uicontrol(PM,'Style','Text',...
'String','EPI-based field map',...
'Position',[50 200 200 020].*WS,...
'ForegroundColor','k','BackgroundColor',spm('Colour'),...
'FontName',PF.times)
uicontrol(PM,'Style','Text',...
'String','Polarity of phase-encode blips',...
'Position',[50 170 200 020].*WS,...
'ForegroundColor','k','BackgroundColor',spm('Colour'),...
'FontName',PF.times)
uicontrol(PM,'Style','Text',...
'String','Apply Jacobian modulation',...
'Position',[50 140 200 020].*WS,...
'ForegroundColor','k','BackgroundColor',spm('Colour'),...
'FontName',PF.times)
uicontrol(PM,'Style','Text',...
'String','Total EPI readout time',...
'Position',[50 110 200 020].*WS,...
'ForegroundColor','k','BackgroundColor',spm('Colour'),...
'FontName',PF.times)
uicontrol(PM,'Style','Text',...
'String','ms',...
'Position',[370 110 30 020].*WS,...
'ForegroundColor','k','BackgroundColor',spm('Colour'),...
'FontName',PF.times)
%-Objects with Callbacks
uicontrol(PM,'style','RadioButton',...
'String','Yes',...
'Position',[300 200 60 022].*WS,...
'ToolTipString','Field map is based on EPI data and needs inverting before use',...
'CallBack','FieldMap(''RadioButton'');',...
'Tag','EPI',...
'UserData',1);
uicontrol(PM,'style','RadioButton',...
'String','No',...
'Position',[370 200 60 022].*WS,...
'ToolTipString','Phase-map is based on non-EPI (Flash) data and can be used directly',...
'CallBack','FieldMap(''RadioButton'');',...
'Tag','EPI',...
'UserData',2);
uicontrol(PM,'style','RadioButton',...
'String','+ve',...
'Position',[370 170 60 022].*WS,...
'ToolTipString','K-space is traversed using positive phase-encode blips',...
'CallBack','FieldMap(''RadioButton'');',...
'Tag','BlipDir',...
'UserData',1);
uicontrol(PM,'style','RadioButton',...
'String','-ve',...
'Position',[300 170 60 022].*WS,...
'ToolTipString','K-space is traversed using negative phase-encode blips',...
'CallBack','FieldMap(''RadioButton'');',...
'Tag','BlipDir',...
'UserData',2);
uicontrol(PM,'style','RadioButton',...
'String','Yes',...
'Position',[300 140 60 022].*WS,...
'ToolTipString','Do Jacobian intensity modulation to compensate for compression/stretching',...
'CallBack','FieldMap(''RadioButton'');',...
'Tag','Jacobian',...
'UserData',1);
uicontrol(PM,'style','RadioButton',...
'String','No',...
'Position',[370 140 60 022].*WS,...
'ToolTipString','Don''t do Jacobian intensity modulation to compensate for compression/stretching',...
'CallBack','FieldMap(''RadioButton'');',...
'Tag','Jacobian',...
'UserData',2);
uicontrol(PM,'Style','Edit',...
'Position',[300 110 70 024].*WS,...
'ToolTipString','Give total time for readout of EPI echo train ms',...
'CallBack','FieldMap(''ReadOutTime'');',...
'Tag','ReadTime');
uicontrol(PM,'String','Load EPI image',...
'Position',[30 70 120 022].*WS,...
'ToolTipString','Load sample modulus EPI Analyze image',...
'CallBack','FieldMap(''LoadEpi_Gui'');',...
'Tag','LoadEpi');
uicontrol(PM,'String','Match VDM to EPI',...
'Position',[165 70 120 022].*WS,...
'ToolTipString','Match vdm to EPI (but only if you want to...)',...
'CallBack','FieldMap(''MatchVDM_gui'');',...
'Tag','MatchVDM');
uicontrol(PM,'String','Write unwarped',...
'Position',[300 70 120 022].*WS,...
'ToolTipString','Write unwarped EPI Analyze image',...
'CallBack','FieldMap(''WriteUnwarped_Gui'');',...
'Tag','WriteUnwarped');
uicontrol(PM,'String','Load structural',...
'Position',[30 30 120 022].*WS,...
'ToolTipString','Load structural image (but only if you want to...)',...
'CallBack','FieldMap(''LoadStructural_Gui'');',...
'Tag','LoadStructural');
uicontrol(PM,'String','Match structural',...
'Position',[164 30 120 022].*WS,...
'ToolTipString','Match structural image to EPI (but only if you want to...)',...
'CallBack','FieldMap(''MatchStructural_Gui'');',...
'Tag','MatchStructural');
uicontrol(PM,'String','Help',...
'Position',[320 30 80 022].*WS,...
'ToolTipString','Help',...
'CallBack','FieldMap(''Help_Gui'');',...
'ForegroundColor','g',...
'Tag','Help');
uicontrol(PM,'String','Quit',...
'Position',[420 30 60 022].*WS,...
'Enable','On',...
'ToolTipString','Exit toolbox',...
'CallBack','FieldMap(''Quit'');',...
'ForegroundColor','r',...
'Tag','Quit');
uicontrol(PM,'style','RadioButton',...
'String','Yes',...
'Position',[123 330 48 022].*WS,...
'ToolTipString','Mask brain using magnitude image before processing',...
'CallBack','FieldMap(''MaskBrain'');',...
'Tag','MaskBrain',...
'UserData',1);
uicontrol(PM,'style','RadioButton',...
'String','No',...
'Position',[173 330 46 022].*WS,...
'ToolTipString','Do not mask brain using magnitude image before processing',...
'CallBack','FieldMap(''MaskBrain'');',...
'Tag','MaskBrain',...
'UserData',2);
% Find list of default files and set up menu accordingly
def_files = FieldMap('GetDefaultFiles');
menu_items = FieldMap('DefFiles2MenuItems',def_files);
if length(menu_items)==1
uicontrol(PM,'String',menu_items{1},...
'Enable','Off',...
'ToolTipString','Site specific default files',...
'Position',[400 480 60 22].*WS);
else
uicontrol(PM,'Style','PopUp',...
'String',menu_items,...
'Enable','On',...
'ToolTipString','Site specific default files',...
'Position',[390 480 90 22].*WS,...
'callback','FieldMap(''DefaultFile_Gui'');',...
'UserData',def_files);
end
%-Apply defaults to buttons
FieldMap('SynchroniseButtons');
%
% Disable necessary buttons and parameters until phase-map is finished.
%
FieldMap('Reset_Gui');
%=======================================================================
%
% Make sure buttons reflect current parameter values
%
%=======================================================================
case 'synchronisebuttons'
% Set input format
if ~isempty(IP.uflags.iformat)
if strcmp(IP.uflags.iformat,'RI');
h = findobj(get(PM,'Children'),'Tag','IFormat','UserData',1);
FieldMap('RadioOn',h);
IP.uflags.iformat = 'RI';
else
h = findobj(get(PM,'Children'),'Tag','IFormat','UserData',2);
FieldMap('RadioOn',h);
IP.uflags.iformat = 'PM';
end
else % Default to RI
h = findobj(get(PM,'Children'),'Tag','IFormat','UserData',1);
FieldMap('RadioOn',h);
IP.uflags.iformat = 'RI';
end
% Set brain masking defaults
if ~isempty(IP.maskbrain)
if IP.maskbrain == 1
h = findobj(get(PM,'Children'),'Tag','MaskBrain','UserData',1);
FieldMap('RadioOn',h);
IP.maskbrain = 1;
else
h = findobj(get(PM,'Children'),'Tag','MaskBrain','UserData',2);
FieldMap('RadioOn',h);
IP.maskbrain = 0;
end
else % Default to no
h = findobj(get(PM,'Children'),'Tag','MaskBrain','UserData',2);
FieldMap('RadioOn',h);
IP.maskbrain = 0;
end
% Set echo Times
if ~isempty(IP.et{1})
h = findobj(get(PM,'Children'),'Tag','ShortTime');
set(h,'String',sprintf('%2.2f',IP.et{1}));
end
if ~isempty(IP.et{2})
h = findobj(get(PM,'Children'),'Tag','LongTime');
set(h,'String',sprintf('%2.2f',IP.et{2}));
end
% Set EPI field map
if ~isempty(IP.epifm)
if IP.epifm
h = findobj(get(PM,'Children'),'Tag','EPI','UserData',1);
FieldMap('RadioOn',h);
IP.epifm = 1;
else
h = findobj(get(PM,'Children'),'Tag','EPI','UserData',2);
FieldMap('RadioOn',h);
IP.epifm = 0;
end
else % Default to yes
h = findobj(get(PM,'Children'),'Tag','EPI','UserData',1);
FieldMap('RadioOn',h);
IP.epifm = 1;
end
% Set apply jacobian
if ~isempty(IP.ajm)
if IP.ajm
h = findobj(get(PM,'Children'),'Tag','Jacobian','UserData',1);
FieldMap('RadioOn',h);
IP.ajm = 1;
else
h = findobj(get(PM,'Children'),'Tag','Jacobian','UserData',2);
FieldMap('RadioOn',h);
IP.ajm = 0;
end
else % Default to no
h = findobj(get(PM,'Children'),'Tag','Jacobian','UserData',2);
FieldMap('RadioOn',h);
IP.ajm = 0;
end
% Set blip direction
if ~isempty(IP.blipdir)
if IP.blipdir == 1
h = findobj(get(PM,'Children'),'Tag','BlipDir','UserData',1);
FieldMap('RadioOn',h);
IP.blipdir = 1;
elseif IP.blipdir == -1
h = findobj(get(PM,'Children'),'Tag','BlipDir','UserData',2);
FieldMap('RadioOn',h);
IP.blipdir = -1;
else
error('Invalid phase-encode direction');
end
else % Default to -1 = negative
h = findobj(get(PM,'Children'),'Tag','BlipDir','UserData',1);
FieldMap('RadioOn',h);
IP.blipdir = -1;
end
% Set total readout time
if ~isempty(IP.tert)
h = findobj(get(PM,'Children'),'Tag','ReadTime');
set(h,'String',sprintf('%2.2f',IP.tert));
end
%=======================================================================
%
% Input format was changed
%
%=======================================================================
case 'inputformat'
%
% Enforce radio behaviour.
%
index = get(gcbo,'UserData');
if index==1
partner = 2;
IP.uflags.iformat = 'RI';
else
partner = 1;
IP.uflags.iformat = 'PM';
end
h = findobj(get(PM,'Children'),'Tag','IFormat','UserData',partner);
maxv = get(gcbo,'Max');
value = get(gcbo,'Value');
if value == maxv
set(h,'Value',get(h,'Min'));
else
set(h,'Value',get(h,'Max'));
end
FieldMap('IFormat_Gui');
%=======================================================================
%
% A new default file has been chosen from the popup menu - gui version.
%
%=======================================================================
case 'defaultfile_gui'
m_file = get(gcbo,'UserData');
m_file = m_file(get(gcbo,'Value'));
m_file = m_file{1}(1:end-2);
IP = FieldMap('SetParams',m_file);
FieldMap('IFormat_Gui');
FieldMap('SynchroniseButtons');
%=======================================================================
%
% Load real or imaginary part of dual echo-time data - gui version.
%
%=======================================================================
case 'loadfile_gui'
FieldMap('Reset_Gui');
%
% File selection using gui
%
index = get(gcbo,'UserData');
FieldMap('LoadFile',index);
ypos = [445 420 385 360];
uicontrol(PM,'Style','Text','String',spm_str_manip(IP.P{index}.fname,['l',num2str(50)]),...
'Position',[220 ypos(index) 260 20].*WS,...
'ForegroundColor','k','BackgroundColor',spm('Colour'),...
'FontName',PF.times,...
'FontSize',FS(8));
FieldMap('Assert');
%=======================================================================
%
% Load phase and magnitude images - gui version.
%
%=======================================================================
case 'loadfilepm_gui'
FieldMap('Reset_Gui');
%
% File selection using gui
%
index = get(gcbo,'UserData');
FieldMap('LoadFilePM',index);
ypos = [445 420 385 360];
uicontrol(PM,'Style','Text','String',spm_str_manip(IP.P{index}.fname,['l',num2str(50)]),...
'Position',[220 ypos(index) 260 20].*WS,...
'ForegroundColor','k','BackgroundColor',spm('Colour'),...
'FontName',PF.times,...
'FontSize',FS(8));
FieldMap('Assert');
%=======================================================================
%
% Create unwrapped phase-map - gui version
%
%=======================================================================
case 'createfieldmap_gui'
%
% Create fieldmap from complex images...
%
status=FieldMap('CreateFieldMap',IP);
if ~isempty(status)
FieldMap('DisplayImage',FieldMap('MakedP'),[.05 .75 .95 .2],1);
% Toggle relevant buttons
FieldMap('ToggleGUI','Off','CreateFieldMap');
FieldMap('ToggleGUI','On',char('LoadFieldMap','WriteFieldMap'));
%
% Check that have correct parameters ready before allowing
% an image to be loaded for unwarping and hence conversion of
% fieldmap to voxel shift map.
%
if (FieldMap('GatherVDMData'))
FieldMap('FM2VDM',IP);
FieldMap('ToggleGUI','On',char('LoadEpi','EPI',...
'BlipDir','Jacobian','ReadTime'));
end
end
%=======================================================================
%
% Load already prepared fieldmap (in Hz).
%
%=======================================================================
case 'loadfieldmap_gui'
%
% Reset all previously loaded field maps and images to unwarp
%
FieldMap('Reset_gui');
%
% Select a precalculated phase map
%
FieldMap('LoadFieldMap');
uicontrol(PM,'Style','Text','String',spm_str_manip(IP.pP.fname,['l',num2str(50)]),...
'Position',[220 307 260 20].*WS,...
'ForegroundColor','k','BackgroundColor',spm('Colour'),...
'FontName',PF.times,...
'FontSize',FS(8));
FieldMap('DisplayImage',FieldMap('MakedP'),[.05 .75 .95 .2],1);
FieldMap('ToggleGUI','Off',char('CreateFieldMap','WriteFieldMap',...
'MatchVDM','WriteUnwarped',...
'LoadStructural', 'MatchStructural'));
% Check that have correct parameters ready before allowing
% an image to be loaded for unwarping and hence conversion of
% fieldmap to voxel shift map.
%
if (FieldMap('GatherVDMData'))
FieldMap('FM2VDM',IP);
FieldMap('ToggleGUI','On',char('LoadEpi','EPI',...
'BlipDir','Jacobian','ReadTime'));
end
%=======================================================================
%
% Write out field map in Hz - using GUI
%
%=======================================================================
case 'writefieldmap_gui'
FieldMap('Write',IP.P{1},IP.fm.fpm,'fpm_',64,'Fitted phase map in Hz');
%=======================================================================
%
% Load sample EPI image using gui, unwarp and display result
%
%=======================================================================
case 'loadepi_gui'
%
% Select and display EPI image
%
FieldMap('LoadEPI');
FieldMap('DisplayImage',IP.epiP,[.05 .5 .95 .2],2);
% The fm2vdm parameters may have been changed so must calculate
% the voxel shift map with current parameters.
if (FieldMap('GatherVDMData'))
FieldMap('FM2VDM',IP);
FieldMap('UnwarpEPI',IP);
FieldMap('DisplayImage',IP.uepiP,[.05 .25 .95 .2],3);
% Once EPI has been unwarped can enable unwarp checks and structural stuff
FieldMap('ToggleGUI','On',char('MatchVDM','WriteUnwarped','LoadStructural'));
end
%
% Redisplay phasemap in case .mat file associated with
% EPI image different from images that filadmap was
% estimated from.
%
FieldMap('DisplayImage',FieldMap('MakedP'),[.05 .75 .95 .2],1);
%=======================================================================
%
% Coregister fieldmap magnitude image to EPI to unwarp using GUI
%
%=======================================================================
case 'matchvdm_gui'
if (FieldMap('GatherVDMData'))
FieldMap('MatchVDM',IP);
FieldMap('DisplayImage',FieldMap('MakedP'),[.05 .75 .95 .2],1)
FieldMap('UnwarpEPI',IP);
FieldMap('DisplayImage',IP.epiP,[.05 .5 .95 .2],2);
FieldMap('DisplayImage',IP.uepiP,[.05 .25 .95 .2],3);
% Once EPI has been unwarped can enable unwarp checks
FieldMap('ToggleGUI','On',char('MatchVDM','WriteUnwarped','LoadStructural'));
end
%=======================================================================
%
% Load structural image
%
%=======================================================================
case 'loadstructural_gui'
FieldMap('LoadStructural');
FieldMap('DisplayImage',IP.nwarp,[.05 0.0 .95 .2],4);
%
% Redisplay the other images to allow for recalculation
% of size of display.
%
FieldMap('DisplayImage',FieldMap('MakedP'),[.05 .75 .95 .2],1);
FieldMap('DisplayImage',IP.epiP,[.05 .5 .95 .2],2);
FieldMap('DisplayImage',IP.uepiP,[.05 .25 .95 .2],3);
FieldMap('ToggleGUI','On','MatchStructural');
%=======================================================================
%
% Match structural image to unwarped EPI
%
%=======================================================================
case 'matchstructural_gui'
FieldMap('MatchStructural',IP);
FieldMap('DisplayImage',IP.nwarp,[.05 0.0 .95 .2],4);
%=======================================================================
%
% Write out unwarped EPI
%
%=======================================================================
case 'writeunwarped_gui'
unwarp_info=sprintf('Unwarped EPI:echo time difference=%2.2fms, EPI readout time=%2.2fms, Jacobian=%d',IP.uflags.etd, IP.tert,IP.ajm);
IP.uepiP = FieldMap('Write',IP.epiP,IP.uepiP.dat,'u',IP.epiP.dt(1),unwarp_info);
FieldMap('ToggleGUI','On', 'LoadStructural');
FieldMap('ToggleGUI','Off', 'WriteUnwarped');
%=======================================================================
%
% Help using spm_help
%
%=======================================================================
case 'help_gui'
FieldMap('help');
%=======================================================================
%
% Quit Toolbox
%
%=======================================================================
case 'quit'
Fgraph=spm_figure('FindWin','Graphics');
if ~isempty(Fgraph)
if DGW
delete(Fgraph);
Fgraph=[];
DGW = 0;
else
spm_figure('Clear','Graphics');
end
end
PM=spm_figure('FindWin','FieldMap');
if ~isempty(PM)
delete(PM);
PM=[];
end
%=======================================================================
%
% The following functions are GUI related functions that go on behind
% the scenes.
%=======================================================================
%
%=======================================================================
%
% Reset gui inputs when a new field map is to be calculated
%
%=======================================================================
case 'reset_gui'
% Clear any precalculated fieldmap name string
uicontrol(PM,'Style','Text','String','',...
'Position',[230 307 260 20].*WS,...
'ForegroundColor','k','BackgroundColor',spm('Colour'));
% Clear Fieldmap values
uicontrol(PM,'Style','Text',...
'Position',[350 280 50 020].*WS,...
'HorizontalAlignment','left',...
'String','');
% Disable input routes to make sure
% a new fieldmap is calculated.
%
FieldMap('ToggleGUI','Off',char('CreateFieldMap','WriteFieldMap',...
'LoadEpi','WriteUnwarped','MatchVDM',...
'LoadStructural','MatchStructural',...
'EPI','BlipDir',...
'Jacobian','ReadTime'));
%
% A new input image implies all processed data is void.
%
IP.fm = [];
IP.vdm = [];
IP.jim = [];
IP.pP = [];
IP.epiP = [];
IP.uepiP = [];
IP.vdmP = [];
IP.fmagP = [];
IP.wfmagP = [];
ID = cell(4,1);
spm_orthviews('Reset');
spm_figure('Clear','Graphics');
%=======================================================================
%
% Use gui for Real and Imaginary or Phase and Magnitude.
%
%=======================================================================
case 'iformat_gui'
FieldMap('Reset_Gui');
% Load Real and Imaginary or Phase and Magnitude Buttons
if IP.uflags.iformat=='PM'
h=findobj('Tag','LoadRI');
set(h,'Visible','Off');
uicontrol(PM,'String','Load Phase',...
'Position',[125 450 90 022].*WS,...
'ToolTipString','Load Analyze image containing first phase image',...
'CallBack','FieldMap(''LoadFilePM_Gui'');',...
'UserData',1,...
'Tag','LoadPM');
uicontrol(PM,'String','Load Mag.',...
'Position',[125 425 90 022].*WS,...
'ToolTipString','Load Analyze image containing first magnitude image',...
'CallBack','FieldMap(''LoadFilePM_Gui'');',...
'UserData',2,...
'Tag','LoadPM');
uicontrol(PM,'String','Load Phase',...
'Position',[125 390 90 022].*WS,...
'ToolTipString','Load Analyze image containing second phase image',...
'CallBack','FieldMap(''LoadFilePM_Gui'');',...
'UserData',3,...
'Tag','LoadPM');
uicontrol(PM,'String','Load Mag.',...
'Position',[125 365 90 022].*WS,...
'ToolTipString','Load Analyze image containing second magnitudeimage',...
'CallBack','FieldMap(''LoadFilePM_Gui'');',...
'UserData',4,...
'Tag','LoadPM');
else
% make the objects we don't want invisible
h=findobj('Tag','LoadPM');
set(h,'Visible','Off');
uicontrol(PM,'String','Load Real',...
'Position',[125 450 90 022].*WS,...
'ToolTipString','Load Analyze image containing real part of short echo-time image',...
'CallBack','FieldMap(''LoadFile_Gui'');',...
'UserData',1,...
'Tag','LoadRI');
uicontrol(PM,'String','Load Imag',...
'Position',[125 425 90 022].*WS,...
'ToolTipString','Load Analyze image containing imaginary part of short echo-time image',...
'CallBack','FieldMap(''LoadFile_Gui'');',...
'UserData',2,...
'Tag','LoadRI');
uicontrol(PM,'String','Load Real',...
'Position',[125 390 90 022].*WS,...
'ToolTipString','Load Analyze image containing real part of long echo-time image',...
'CallBack','FieldMap(''LoadFile_Gui'');',...
'UserData',3,...
'Tag','LoadRI');
uicontrol(PM,'String','Load Imag',...
'Position',[125 365 90 022].*WS,...
'ToolTipString','Load Analyze image containing imaginary part of long echo-time image',...
'CallBack','FieldMap(''LoadFile_Gui'');',...
'UserData',4,...
'Tag','LoadRI');
end
%=======================================================================
%
% Brain masking or not
%
%=======================================================================
case 'maskbrain'
FieldMap('Reset_Gui');
%
% Enforce radio behaviour.
%
index = get(gcbo,'UserData');
if index==1
partner=2;
IP.maskbrain=1;
else
partner=1;
IP.maskbrain=0;
end
tag = get(gcbo,'Tag');
value = get(gcbo,'Value');
maxv = get(gcbo,'Max');
h = findobj(get(PM,'Children'),'Tag',tag,'UserData',partner);
if value == maxv
set(h,'Value',get(h,'Min'));
else
set(h,'Value',get(h,'Max'));
end
FieldMap('Assert');
%=======================================================================
%
% Echo time was changed or entered
%
%=======================================================================
case 'echotime'
FieldMap('Assert');
%=======================================================================
%
% Check if inputs are correct for calculating new phase map
%
%=======================================================================
case 'assert'
if ~isempty(IP.pP) % If we're using precalculated fieldmap.
go = 0;
else
go = 1;
for i=1:2
if isempty(IP.P{i}) go = 0; end
end
for i=3:4
if (isempty(IP.P{i}) & IP.uflags.iformat=='RI') go = 0; end
end
h = findobj(get(PM,'Children'),'Tag','ShortTime');
IP.et{1} = str2num(get(h,'String'));
h = findobj(get(PM,'Children'),'Tag','LongTime');
IP.et{2} = str2num(get(h,'String'));
if isempty(IP.et{1}) | isempty(IP.et{2}) | IP.et{2} < IP.et{1}
go = 0;
end
end
if go
FieldMap('ToggleGui','On','CreateFieldMap');
else % Switch off fieldmap creation
FieldMap('ToggleGui','Off','CreateFieldMap');
end
%=======================================================================
%
% Enable or disable specified buttons or parameters in GUI
%
%=======================================================================
case 'togglegui'
h = get(PM,'Children');
tags=varargin{3};
for n=1:size(varargin{3},1)
set(findobj(h,'Tag',deblank(tags(n,:))),'Enable',varargin{2});
end
%=======================================================================
%
% A radiobutton was pressed.
%
%=======================================================================
case 'radiobutton'
%
% Enforce radio behaviour.
%
index = get(gcbo,'UserData');
if index==1
partner=2;
else
partner=1;
end
tag = get(gcbo,'Tag');
value = get(gcbo,'Value');
maxv = get(gcbo,'Max');
h = findobj(get(PM,'Children'),'Tag',tag,'UserData',partner);
if value == maxv
set(h,'Value',get(h,'Min'));
else
set(h,'Value',get(h,'Max'));
end
% Update Hz to voxel displacement map if the input parameters are ok
if (FieldMap('GatherVDMData'))
FieldMap('FM2VDM',IP);
%
% Update unwarped EPI if one is loaded
%
if ~isempty(IP.epiP)
IP.uepiP = FieldMap('UnwarpEPI',IP);
FieldMap('DisplayImage',IP.uepiP,[.05 .25 .95 .2],3);
FieldMap('ToggleGUI','On',char('WriteUnwarped'));
end
end
%=======================================================================
%
% Enforce radio-button behaviour
%
%=======================================================================
case 'radioon'
my_gcbo = varargin{2};
index = get(my_gcbo,'UserData');
if index==1
partner=2;
else
partner=1;
end
set(my_gcbo,'Value',get(my_gcbo,'Max'));
h = findobj(get(PM,'Children'),'Tag',get(my_gcbo,'Tag'),'UserData',partner);
set(h,'Value',get(h,'Min'));
%=======================================================================
%
% Total readout-time was changed or entered
%
%=======================================================================
case 'readouttime'
%
% Update unwarped EPI
%
% This means the transformation phase-map to voxel displacement-map
% has changed, which means the inversion will have to be redone,
% which means (in the case of flash-based field map) coregistration
% between field-map and sample EPI image should be redone. Phew!
%
if (FieldMap('GatherVDMData'))
FieldMap('FM2VDM',IP);
% Update unwarped EPI if one is loaded
if ~isempty(IP.epiP)
IP.uepiP = FieldMap('UnwarpEPI',IP);
FieldMap('DisplayImage',IP.uepiP,[.05 .25 .95 .2],3);
FieldMap('ToggleGUI','On',char('WriteUnwarped',...
'LoadStructural'));
end
FieldMap('ToggleGUI','On',char('LoadEpi','EPI','BlipDir',...
'Jacobian','ReadTime'));
else
% If readtime is missing switch everything off...
FieldMap('ToggleGUI','Off',char('LoadEpi','EPI',...
'BlipDir','Jacobian',...
'WriteUnwarped','LoadStructural',...
'MatchStructural', 'MatchVDM'));
end
%=======================================================================
%
% Sample UIControls pertaining to information needed for transformation
% phase-map -> voxel displacement-map
%
%=======================================================================
case 'gathervdmdata'
h = findobj(get(PM,'Children'),'Tag','EPI','UserData',1);
v = get(h,{'Value','Max'});
if v{1} == 1
IP.epifm = 1;
else
IP.epifm = 0;
end
h = findobj(get(PM,'Children'),'Tag','BlipDir','UserData',1);
v = get(h,{'Value','Max'});
if v{1} == 1 %% CHLOE: Changed
IP.blipdir = 1;
else
IP.blipdir = -1;
end
h = findobj(get(PM,'Children'),'Tag','Jacobian','UserData',1);
v = get(h,{'Value','Max'});
if v{1} == 1 %% CHLOE: Changed
IP.ajm = 1;
else
IP.ajm = 0;
end
h = findobj(get(PM,'Children'),'Tag','ReadTime');
IP.tert = str2num(get(h,'String'));
if isempty(IP.tert) | isempty(IP.fm) | isempty(IP.fm.fpm)
varargout{1} = 0;
FieldMap('ToggleGui','On','ReadTime');
else
varargout{1} = 1;
end
%=======================================================================
%
% Draw transversal and sagittal image.
%
%=======================================================================
case 'redrawimages'
global curpos;
for i=1:length(ID)
if ~isempty(ID{i}) & ~isempty(st.vols{i})
set(st.vols{i}.ax{2}.ax,'Visible','Off'); % Disable event delivery in Coronal
set(st.vols{i}.ax{2}.d,'Visible','Off'); % Make Coronal invisible
set(st.vols{i}.ax{1}.ax,'Position',ID{i}.tra_pos);
set(st.vols{i}.ax{1}.ax,'ButtonDownFcn',['FieldMap(''Orthviews'');']);
set(get(st.vols{i}.ax{1}.ax,'YLabel'),'String',ID{i}.label);
set(st.vols{i}.ax{3}.ax,'Position',ID{i}.sag_pos);
set(st.vols{i}.ax{3}.ax,'ButtonDownFcn',['FieldMap(''Orthviews'');']);
end
end
%=======================================================================
%
% Callback for orthviews
%
%=======================================================================
case 'orthviews'
if strcmp(get(gcf,'SelectionType'),'normal')
spm_orthviews('Reposition');,...
%spm_orthviews('set_pos2cm');,...
elseif strcmp(get(gcf,'SelectionType'),'extend')
spm_orthviews('Reposition');,...
%spm_orthviews('set_pos2cm');,...
spm_orthviews('context_menu','ts',1);
end;
curpos = spm_orthviews('pos',1);
set(st.in, 'String',sprintf('%3.3f',spm_sample_vol(st.vols{1},curpos(1),curpos(2),curpos(3),st.hld)));
%=======================================================================
%
% Display image.
%
%=======================================================================
case 'displayimage'
Fgraph=spm_figure('FindWin','Graphics');
% if isempty(Fgraph)
% st.fig=spm_figure('Create','Graphics','Graphics');
% DGW = 1;
% end
% Only open Graphics window if one has been found
if isempty(Fgraph)
return;
else
if ~isempty(ID{varargin{4}})
spm_orthviews('Delete',ID{varargin{4}}.h);
ID{varargin{4}} = [];
end
h = spm_orthviews('Image',varargin{2},[.01 .01 .01 .01]);
% Set bounding box to allow display of all images
spm_orthviews('MaxBB');
% Put everything in space of original EPI image.
if varargin{4} == 2
%spm_orthviews('Space',h); % This was deleted for some reason
end
%
% Get best possible positioning and scaling for
% transversal and sagittal views.
%
tra_pos = get(st.vols{varargin{4}}.ax{1}.ax,'Position');
sag_pos = get(st.vols{varargin{4}}.ax{3}.ax,'Position');
field_pos = varargin{3};
x_scale = field_pos(3) / (tra_pos(3) + sag_pos(3));
height = max([tra_pos(4) sag_pos(4)]);
y_scale = field_pos(4) / height;
if x_scale > y_scale % Height limiting
scale = y_scale;
dx = (field_pos(3) - scale*(tra_pos(3) + sag_pos(3))) / 3;
dy = 0;
else % Width limiting
scale = x_scale;
dx = 0;
dy = (field_pos(4) - scale*height) / 2;
end
tra_pos = [field_pos(1)+dx field_pos(2)+dy scale*tra_pos([3 4])];
sag_pos = [field_pos(1)+tra_pos(3)+2*dx field_pos(2)+dy scale*sag_pos([3 4])];
label = {'Fieldmap in Hz',...
'Warped EPI',...
'Unwarped EPI',...
'Structural'};
ID{varargin{4}} = struct('tra_pos', tra_pos,...
'sag_pos', sag_pos,...
'h', h,...
'label', label{varargin{4}});
FieldMap('RedrawImages');
st.in = uicontrol(PM,'Style','Text',...
'Position',[340 280 50 020].*WS,...
'HorizontalAlignment','left',...
'String','');
end
%=======================================================================
%=======================================================================
%
% The functions below are called by the various gui buttons but are
% not dependent on the gui to work. These functions can therefore also
% be called from a script bypassing the gui and can return updated
% variables.
%
%=======================================================================
%=======================================================================
%
%=======================================================================
%
% Create and initialise parameters for FieldMap toolbox
%
%=======================================================================
case 'initialise'
%
% Initialise parameters
%
ID = cell(4,1);
IP.P = cell(1,4);
IP.pP = [];
IP.fmagP = [];
IP.wfmagP = [];
IP.epiP = [];
IP.uepiP = [];
IP.nwarp = [];
IP.fm = [];
IP.vdm = [];
IP.et = cell(1,2);
IP.epifm = [];
IP.blipdir = [];
IP.ajm = [];
IP.tert = [];
IP.vdmP = []; %% Check that this should be there %%
IP.maskbrain = [];
IP.uflags = struct('iformat','','method','','fwhm',[],'bmask',[],'pad',[],'etd',[],'ws',[]);
IP.mflags = struct('template',[],'fwhm',[],'nerode',[],'ndilate',[],'thresh',[],'reg',[],'graphics',0);
% Initially set brain mask to be empty
IP.uflags.bmask = [];
% Set parameter values according to defaults
FieldMap('SetParams');
varargout{1}= IP;
%=======================================================================
%
% Sets parameters according to the defaults file that is being passed
%
%=======================================================================
case 'setparams'
if nargin == 1
pm_defaults; % "Default" default file
else
%eval(varargin{2}); % Scanner or sequence specific default file
run(varargin{2}); % Scanner or sequence specific default file
end
% Define parameters for fieldmap creation
IP.et{1} = pm_def.SHORT_ECHO_TIME;
IP.et{2} = pm_def.LONG_ECHO_TIME;
IP.maskbrain = pm_def.MASKBRAIN;
% Set parameters for unwrapping
IP.uflags.iformat = pm_def.INPUT_DATA_FORMAT;
IP.uflags.method = pm_def.UNWRAPPING_METHOD;
IP.uflags.fwhm = pm_def.FWHM;
IP.uflags.pad = pm_def.PAD;
IP.uflags.ws = pm_def.WS;
IP.uflags.etd = pm_def.LONG_ECHO_TIME - pm_def.SHORT_ECHO_TIME;
% Set parameters for brain masking
IP.mflags.template = pm_def.MFLAGS.TEMPLATE;
IP.mflags.fwhm = pm_def.MFLAGS.FWHM;
IP.mflags.nerode = pm_def.MFLAGS.NERODE;
IP.mflags.ndilate = pm_def.MFLAGS.NDILATE;
IP.mflags.thresh = pm_def.MFLAGS.THRESH;
IP.mflags.reg = pm_def.MFLAGS.REG;
IP.mflags.graphics = pm_def.MFLAGS.GRAPHICS;
% Set parameters for unwarping
IP.ajm = pm_def.DO_JACOBIAN_MODULATION;
IP.blipdir = pm_def.K_SPACE_TRAVERSAL_BLIP_DIR;
IP.tert = pm_def.TOTAL_EPI_READOUT_TIME;
IP.epifm = pm_def.EPI_BASED_FIELDMAPS;
varargout{1}= IP;
%=======================================================================
%
% Get a list of all the default files that are present
%
%=======================================================================
case 'getdefaultfiles'
fmdir = fullfile(spm('Dir'),'toolbox','FieldMap');
defdir = dir(fullfile(fmdir,'pm_defaults*.m'));
for i=1:length(defdir)
if defdir(i).name(12) ~= '.' & defdir(i).name(12) ~= '_'
error(sprintf('Error in default file spec: %s',defdir(i).name));
end
defnames{i} = defdir(i).name;
end
varargout{1} = defnames;
%=======================================================================
%
% Get list of menuitems from list of default files
%
%=======================================================================
case 'deffiles2menuitems'
for i=1:length(varargin{2})
if strcmp(varargin{2}{i},'pm_defaults.m');
menit{i} = 'Default';
else
endindx = strfind(varargin{2}{i},'.m');
menit{i} = varargin{2}{i}(13:(endindx-1));
end
end
varargout{1} = menit;
%=======================================================================
%
% Scale a phase map so that max = pi and min =-pi radians.
%
%=======================================================================
case 'scale'
F=varargin{2};
V=spm_vol(F);
vol=spm_read_vols(V);
mn=min(vol(:));
mx=max(vol(:));
vol=-pi+(vol-mn)*2*pi/(mx-mn);
V.dt(1)=4;
varargout{1} = FieldMap('Write',V,vol,'sc',V.dt(1),V.descrip);
%=======================================================================
%
% Load real or imaginary part of dual echo-time data - NO gui.
%
%=======================================================================
case 'loadfile'
index=varargin{2};
prompt_string = {'Select short echo-time real',...
'Select short echo-time imaginary',...
'Select long echo-time real',...
'Select long echo-time imaginary'};
%IP.P{index} = spm_vol(spm_get(1,'*.img',prompt_string{index}));
% SPM
IP.P{index} = spm_vol(spm_select(1,'image',prompt_string{index}));
if isfield(IP,'pP') & ~isempty(IP.pP)
IP.pP = [];
end
varargout{1} = IP.P{index};
%=======================================================================
%
% Load phase or magnitude part of dual (possibly) echo-time data - NO gui.
%
%=======================================================================
case 'loadfilepm'
index=varargin{2};
prompt_string = {'Select phase image',...
'Select magnitude image',...
'Select second phase image or press done',...
'Select magnitude image or press done'};
if index<3
%IP.P{index} = spm_vol(spm_get(1,'*.img',prompt_string{index}));
% SPM5 Update
IP.P{index} = spm_vol(spm_select(1,'image',prompt_string{index}));
if index==1
do=spm_input('Scale this to radians?',1,'b','Yes|No',[1,0]);
Finter=spm_figure('FindWin','Interactive');
close(Finter);
if do==1
tmp=FieldMap('Scale',IP.P{index}.fname);
IP.P{index} = spm_vol(tmp.fname);
end
end
else
%IP.P{index} = spm_vol(spm_get([0 1],'*.img',prompt_string{index}));
% SPM5 Update
IP.P{index} = spm_vol(spm_select([0 1],'image',prompt_string{index}));
if index==3 & ~isempty(IP.P{index})
do=spm_input('Scale this to radians?',1,'b','Yes|No',[1,0]);
Finter=spm_figure('FindWin','Interactive');
close(Finter);
if do==1
tmp=FieldMap('Scale',IP.P{index}.fname);
IP.P{index} = spm_vol(tmp.fname);
end
end
end
if isfield(IP,'pP') & ~isempty(IP.pP)
IP.pP = [];
end
varargout{1} = IP.P{index};
%=======================================================================
%
% Load already prepared fieldmap (in Hz) - no gui
%
%=======================================================================
case 'loadfieldmap'
%
% Select field map
%
% 24/03/04 - Chloe change below to spm_get(1,'fpm_*.img')...
% IP.pP = spm_vol(spm_get(1,'fpm_*.img','Select field map'));
% SPM5 Update
IP.pP = spm_vol(spm_select(1,'^fpm.*\.img$','Select field map'));
IP.fm.fpm = spm_read_vols(IP.pP);
IP.fm.jac = pm_diff(IP.fm.fpm,2);
if isfield(IP,'P') & ~isempty(IP.P{1})
IP.P = cell(1,4);
end
varargout{1} = IP.fm;
varargout{2} = IP.pP;
%=======================================================================
%
% Create unwrapped phase-map - NO gui
%
%=======================================================================
case 'createfieldmap'
IP=varargin{2};
% First check that images are in same space
if size([IP.P{1} IP.P{2} IP.P{3} IP.P{4}],2)==4
ip_dim=cat(1,[IP.P{1}.dim' IP.P{2}.dim' IP.P{3}.dim' IP.P{4}.dim']');
%ip_mat=cat(2,[IP.P{1}.mat(:) IP.P{2}.mat(:) IP.P{3}.mat(:) IP.P{4}.mat(:)]');
ip_mat=cat(2,single([IP.P{1}.mat(:) IP.P{2}.mat(:) IP.P{3}.mat(:) IP.P{4}.mat(:)]'));
else
ip_dim=cat(1,[IP.P{1}.dim' IP.P{2}.dim']');
%ip_mat=cat(2,[IP.P{1}.mat(:) IP.P{2}.mat(:)]');
ip_mat=cat(2,single([IP.P{1}.mat(:) IP.P{2}.mat(:)]'));
end
if any(any(diff(ip_dim,1,1),1)&[1,1,1])
errordlg({'Images don''t all have same dimensions'});
drawnow;
varargout{1}=[];
elseif any(any(diff(ip_mat,1,1),1))
errordlg({'Images don''t all have same orientation & voxel size'});
drawnow;
varargout{1}=[];
else
% Update flags for unwarping (in case TEs have been adjusted
IP.uflags.etd = IP.et{2}-IP.et{1};
% Clear any brain mask
IP.uflags.bmask = [];
% SPM5 Update
% If flag selected to mask brain and the field map is not based on EPI
if IP.maskbrain==1
IP.fmagP = FieldMap('Magnitude',IP);
IP.uflags.bmask = pm_brain_mask(IP.fmagP,IP.mflags);
varargout{2} = IP.fmagP;
end
IP.fm = pm_make_fieldmap([IP.P{1} IP.P{2} IP.P{3} IP.P{4}],IP.uflags);
varargout{1} = IP.fm;
end
%=======================================================================
%
% Convert field map to voxel displacement map and
% do necessary inversions of displacement fields.
%
%=======================================================================
case 'fm2vdm'
IP=varargin{2};
%
% If we already have memory mapped image pointer to voxel
% displacement map let's reuse it (so not to void possible
% realignment). If field-map is non-EPI based the previous
% realignment (based on different parameters) will be non-
% optimal and we should advice user to redo it.
%
% If no pointer already exist we'll make one.
%
if isfield(IP,'vdmP') & ~isempty(IP.vdmP)
msgbox({'Changing this parameter means that if previously',...
'you matched VDM to EPI, this result may no longer',...
'be optimal. In this case we recommend you redo the',...
'Match VDM to EPI.'},...
'Coregistration notice','warn','modal');
else
if ~isempty(IP.pP)
IP.vdmP = struct('dim', IP.pP.dim(1:3),...
'dt',[4 spm_platform('bigend')],...
'mat', IP.pP.mat);
IP.vdmP.fname=fullfile(spm_str_manip(IP.pP.fname, 'h'),['vdm5_' deblank(spm_str_manip(IP.pP.fname,'t'))]);
else
IP.vdmP = struct('dim', IP.P{1}.dim(1:3),...
'dt',[4 spm_platform('bigend')],...
'mat', IP.P{1}.mat);
IP.vdmP.fname=fullfile(spm_str_manip(IP.P{1}.fname, 'h'),['vdm5_' deblank(spm_str_manip(IP.P{1}.fname,'t'))]);
end
end
% Scale field map and jacobian by total EPI readout time
IP.vdm.vdm = IP.blipdir*IP.tert*1e-3*IP.fm.fpm;
IP.vdm.jac = IP.blipdir*IP.tert*1e-3*IP.fm.jac;
% Chloe added this: 26/02/05
% Put fieldmap parameters in descrip field of vdm
vdm_info=sprintf('Voxel Displacement Map:echo time difference=%2.2fms, EPI readout time=%2.2fms',IP.uflags.etd, IP.tert);
if IP.epifm ==1
spm_progress_bar('Init',3,'Inverting displacement map','');
spm_progress_bar('Set',1);
% Invert voxel shift map and multiply by -1...
IP.vdm.ivdm = pm_invert_phasemap(-1*IP.vdm.vdm);
IP.vdm.ijac = pm_diff(IP.vdm.ivdm,2);
spm_progress_bar('Set',2);
spm_progress_bar('Clear');
FieldMap('Write',IP.vdmP,IP.vdm.ivdm,'',IP.vdmP.dt(1),vdm_info);
else
FieldMap('Write',IP.vdmP,IP.vdm.vdm,'',IP.vdmP.dt(1),vdm_info);
end
varargout{1} = IP.vdm;
varargout{2} = IP.vdmP;
%=======================================================================
%
% Write out image
%
%=======================================================================
case 'write'
V=varargin{2};
vol=varargin{3};
name=varargin{4};
% Write out image
img=struct('dim', V.dim(1:3),...
'dt', [varargin{5} spm_platform('bigend')],...
'mat', V.mat);
img.fname=fullfile(spm_str_manip(V.fname, 'h'),[name deblank(spm_str_manip(V.fname,'t'))]);
img.descrip=varargin{6};
img=spm_write_vol(img,vol);
varargout{1}=img;
%=======================================================================
%
% Create fieldmap (Hz) struct for use when displaying image.
%
%=======================================================================
case 'makedp'
if isfield(IP,'vdmP') & ~isempty(IP.vdmP);
dP = struct('dim', IP.vdmP.dim,...
'dt',[64 spm_platform('bigend')],...
'pinfo', [1 0]',...
'mat', IP.vdmP.mat,...
'dat', reshape(IP.fm.fpm,IP.vdmP.dim),...
'fname', 'display_image');
else
if isfield(IP,'P') & ~isempty(IP.P{1})
dP = struct('dim', IP.P{1}.dim,...
'dt',[64 spm_platform('bigend')],...
'pinfo', [1 0]',...
'mat', IP.P{1}.mat,...
'dat', reshape(IP.fm.fpm,IP.P{1}.dim),...
'fname', 'display_image');
elseif isfield(IP,'pP') & ~isempty(IP.pP)
dP = struct('dim', IP.pP.dim,...
'dt',[64 spm_platform('bigend')],...
'pinfo', [1 0]',...
'mat', IP.pP.mat,...
'dat', reshape(IP.fm.fpm,IP.pP.dim),...
'fname', 'display_image');
end
end
varargout{1} = dP;
%=======================================================================
%
% Load sample EPI image - NO gui
%
%=======================================================================
case 'loadepi'
%
% Select EPI
%
%IP.epiP = spm_vol(spm_get(1,'*.img','Select sample EPI image'));
% SPM5 Update
IP.epiP = spm_vol(spm_select(1,'image','Select sample EPI image'));
varargout{1} = IP.epiP;
%=======================================================================
%
% Create unwarped epi - NO gui
%
%=======================================================================
case 'unwarpepi'
%
% Update unwarped EPI
%
IP=varargin{2};
IP.uepiP = struct('fname', 'Image in memory',...
'dim', IP.epiP.dim,...
'dt',[64 spm_platform('bigend')],...
'pinfo', IP.epiP.pinfo(1:2),...
'mat', IP.epiP.mat);
% Need to sample EPI and voxel shift map in space of EPI...
[x,y,z] = ndgrid(1:IP.epiP.dim(1),1:IP.epiP.dim(2),1:IP.epiP.dim(3));
xyz = [x(:) y(:) z(:)];
% Space of EPI is IP.epiP{1}.mat and space of
% voxel shift map is IP.vdmP{1}.mat
tM = inv(IP.epiP.mat\IP.vdmP.mat);
x2 = tM(1,1)*x + tM(1,2)*y + tM(1,3)*z + tM(1,4);
y2 = tM(2,1)*x + tM(2,2)*y + tM(2,3)*z + tM(2,4);
z2 = tM(3,1)*x + tM(3,2)*y + tM(3,3)*z + tM(3,4);
xyz2 = [x2(:) y2(:) z2(:)];
%
% Make mask since it is only meaningful to calculate undistorted
% image in areas where we have information about distortions.
%
msk = reshape(double(xyz2(:,1)>=1 & xyz2(:,1)<=IP.vdmP.dim(1) &...
xyz2(:,2)>=1 & xyz2(:,2)<=IP.vdmP.dim(2) &...
xyz2(:,3)>=1 & xyz2(:,3)<=IP.vdmP.dim(3)),IP.epiP.dim(1:3));
% Read in voxel displacement map in correct space
tvdm = reshape(spm_sample_vol(spm_vol(IP.vdmP.fname),xyz2(:,1),...
xyz2(:,2),xyz2(:,3),1),IP.epiP.dim(1:3));
% Voxel shift map must be added to the y-coordinates.
uepi = reshape(spm_sample_vol(IP.epiP,xyz(:,1),...
xyz(:,2)+tvdm(:),xyz(:,3),1),IP.epiP.dim(1:3));% TEMP CHANGE
% Sample Jacobian in correct space and apply if required
if IP.ajm==1
if IP.epifm==1 % If EPI, use inverted jacobian
IP.jim = reshape(spm_sample_vol(IP.vdm.ijac,xyz2(:,1),...
xyz2(:,2),xyz2(:,3),1),IP.epiP.dim(1:3));
else
IP.jim = reshape(spm_sample_vol(IP.vdm.jac,xyz2(:,1),...
xyz2(:,2),xyz2(:,3),1),IP.epiP.dim(1:3));
end
uepi = uepi.*(1+IP.jim);
end
IP.uepiP.dat=uepi.*msk;
varargout{1}=IP.uepiP;
%=======================================================================
%
% Create unwarped epi - NO gui ***FOR XY***
%
%=======================================================================
case 'unwarpepixy'
%
% Update unwarped EPI
%
IP=varargin{2};
IP.uepiP = struct('fname', 'Image in memory',...
'dim', IP.epiP.dim,...
'dt',[64 spm_platform('bigend')],...
'pinfo', IP.epiP.pinfo(1:2),...
'mat', IP.epiP.mat);
% Need to sample EPI and voxel shift map in space of EPI...
[x,y,z] = ndgrid(1:IP.epiP.dim(1),1:IP.epiP.dim(2),1:IP.epiP.dim(3));
xyz = [x(:) y(:) z(:)];
% Space of EPI is IP.epiP{1}.mat and space of
% voxel shift map is IP.vdmP{1}.mat
tM = inv(IP.epiP.mat\IP.vdmP.mat);
x2 = tM(1,1)*x + tM(1,2)*y + tM(1,3)*z + tM(1,4);
y2 = tM(2,1)*x + tM(2,2)*y + tM(2,3)*z + tM(2,4);
z2 = tM(3,1)*x + tM(3,2)*y + tM(3,3)*z + tM(3,4);
xyz2 = [x2(:) y2(:) z2(:)];
%
% Make mask since it is only meaningful to calculate undistorted
% image in areas where we have information about distortions.
%
msk = reshape(double(xyz2(:,1)>=1 & xyz2(:,1)<=IP.vdmP.dim(1) &...
xyz2(:,2)>=1 & xyz2(:,2)<=IP.vdmP.dim(2) &...
xyz2(:,3)>=1 & xyz2(:,3)<=IP.vdmP.dim(3)),IP.epiP.dim(1:3));
% Read in voxel displacement map in correct space
tvdm = reshape(spm_sample_vol(spm_vol(IP.vdmP.fname),xyz2(:,1),...
xyz2(:,2),xyz2(:,3),1),IP.epiP.dim(1:3));
% Voxel shift map must be added to the x-coordinates.
uepi = reshape(spm_sample_vol(IP.epiP,xyz(:,1)+tvdm(:),...
xyz(:,2),xyz(:,3),1),IP.epiP.dim(1:3));% TEMP CHANGE
% Sample Jacobian in correct space and apply if required
if IP.ajm==1
if IP.epifm==1 % If EPI, use inverted jacobian
IP.jim = reshape(spm_sample_vol(IP.vdm.ijac,xyz2(:,1),...
xyz2(:,2),xyz2(:,3),1),IP.epiP.dim(1:3));
else
IP.jim = reshape(spm_sample_vol(IP.vdm.jac,xyz2(:,1),...
xyz2(:,2),xyz2(:,3),1),IP.epiP.dim(1:3));
end
uepi = uepi.*(1+IP.jim);
end
IP.uepiP.dat=uepi.*msk;
varargout{1}=IP.uepiP;
%=======================================================================
%
% Coregister fieldmap magnitude image to EPI to unwarp
%
%=======================================================================
case 'matchvdm'
IP=varargin{2};
%
% Need a fieldmap magnitude image
%
if isempty(IP.pP) & ~isempty(IP.P{1})
IP.fmagP=struct('dim', IP.P{1}.dim,...
'dt',IP.P{1}.dt,...
'pinfo', IP.P{1}.pinfo,...
'mat', IP.P{1}.mat);
IP.fmagP.fname=fullfile(spm_str_manip(IP.P{1}.fname, 'h'),['mag_' deblank(spm_str_manip(IP.P{1}.fname,'t'))]);
% If using real and imaginary data, calculate using sqrt(i1.^2 + i2.^2).
% If using phase and magnitude, use magnitude image.
if IP.uflags.iformat=='RI'
IP.fmagP = spm_imcalc(spm_vol([IP.P{1}.fname;IP.P{2}.fname]),IP.fmagP,'sqrt(i1.^2 + i2.^2)');
else
IP.fmagP = IP.P{2};
end
elseif ~isempty(IP.pP) & ~isempty(IP.fmagP)
msg=sprintf('Using %s for matching\n',IP.fmagP.fname);
disp(msg);
else
%IP.fmagP = spm_vol(spm_get(1,'*.img','Select field map magnitude image'));
% SPM5 Update
IP.fmagP = spm_vol(spm_select(1,'image','Select field map magnitude image'));
end
% Now we have field map magnitude image, we want to coregister it to the
% EPI to be unwarped.
% If using an EPI field map:
% 1) Coregister magnitude image to EPI.
% 2) Apply resulting transformation matrix to voxel shift map
% If using a non-EPI field map:
% 1) Forward warp magnitude image
% 2) Coregister warped magnitude image to EPI.
% 3) Apply resulting transformation matrix to voxel shift map
if IP.epifm==1
[mi,M] = FieldMap('Coregister',IP.epiP,IP.fmagP);
MM = IP.fmagP.mat;
else
% Need to sample magnitude image in space of EPI to be unwarped...
[x,y,z] = ndgrid(1:IP.epiP.dim(1),1:IP.epiP.dim(2),1:IP.epiP.dim(3));
xyz = [x(:) y(:) z(:)];
% Space of EPI is IP.epiP{1}.mat and space of fmagP is IP.fmagP.mat
tM = inv(IP.epiP.mat\IP.fmagP.mat);
x2 = tM(1,1)*x + tM(1,2)*y + tM(1,3)*z + tM(1,4);
y2 = tM(2,1)*x + tM(2,2)*y + tM(2,3)*z + tM(2,4);
z2 = tM(3,1)*x + tM(3,2)*y + tM(3,3)*z + tM(3,4);
xyz2 = [x2(:) y2(:) z2(:)];
wfmag = reshape(spm_sample_vol(IP.fmagP,xyz2(:,1),...
xyz2(:,2),xyz2(:,3),1),IP.epiP.dim(1:3));
% Need to sample voxel shift map in space of EPI to be unwarped
tvdm = reshape(spm_sample_vol(IP.vdm.vdm,xyz2(:,1),...
xyz2(:,2),xyz2(:,3),0),IP.epiP.dim(1:3));
% Now apply warps to resampled forward warped magnitude image...
wfmag = reshape(spm_sample_vol(wfmag,xyz(:,1),xyz(:,2)-tvdm(:),...
xyz(:,3),1),IP.epiP.dim(1:3));
% Write out forward warped magnitude image
IP.wfmagP = struct('dim', IP.epiP.dim,...
'dt',[64 spm_platform('bigend')],...
'pinfo', IP.epiP.pinfo,...
'mat', IP.epiP.mat);
IP.wfmagP = FieldMap('Write',IP.epiP,wfmag,'wfmag_',4,'Voxel shift map');
% Now coregister warped magnitude field map to EPI
[mi,M] = FieldMap('Coregister',IP.epiP,IP.wfmagP);
% Update the .mat file of the forward warped mag image
spm_get_space(deblank(IP.wfmagP.fname),M*IP.wfmagP.mat);
% Get the original space of the fmap magnitude
MM = IP.fmagP.mat;
end
% Update .mat file for voxel displacement map
IP.vdmP.mat=M*MM;
spm_get_space(deblank(IP.vdmP.fname),M*MM);
varargout{1} = IP.vdmP;
%=======================================================================
%
% Coregister fieldmap magnitude image to EPI to do unwarpxy
%
%=======================================================================
case 'matchvdmxy'
IP=varargin{2};
%
% Need a fieldmap magnitude image
%
if isempty(IP.pP) & ~isempty(IP.P{1})
IP.fmagP=struct('dim', IP.P{1}.dim,...
'dt',IP.P{1}.dt,...
'pinfo', IP.P{1}.pinfo,...
'mat', IP.P{1}.mat);
IP.fmagP.fname=fullfile(spm_str_manip(IP.P{1}.fname, 'h'),['mag_' deblank(spm_str_manip(IP.P{1}.fname,'t'))]);
% If using real and imaginary data, calculate using sqrt(i1.^2 + i2.^2).
% If using phase and magnitude, use magnitude image.
if IP.uflags.iformat=='RI'
IP.fmagP = spm_imcalc(spm_vol([IP.P{1}.fname;IP.P{2}.fname]),IP.fmagP,'sqrt(i1.^2 + i2.^2)');
else
IP.fmagP = IP.P{2};
end
elseif ~isempty(IP.pP) & ~isempty(IP.fmagP)
msg=sprintf('Using %s for matching\n',IP.fmagP.fname);
disp(msg);
else
%IP.fmagP = spm_vol(spm_get(1,'*.img','Select field map magnitude image'));
% SPM5 Update
IP.fmagP = spm_vol(spm_select(1,'image','Select field map magnitude image'));
end
% Now we have field map magnitude image, we want to coregister it to the
% EPI to be unwarped.
% If using an EPI field map:
% 1) Coregister magnitude image to EPI.
% 2) Apply resulting transformation matrix to voxel shift map
% If using a non-EPI field map:
% 1) Forward warp magnitude image
% 2) Coregister warped magnitude image to EPI.
% 3) Apply resulting transformation matrix to voxel shift map
if IP.epifm==1
[mi,M] = FieldMap('Coregister',IP.epiP,IP.fmagP);
MM = IP.fmagP.mat;
else
% Need to sample magnitude image in space of EPI to be unwarped...
[x,y,z] = ndgrid(1:IP.epiP.dim(1),1:IP.epiP.dim(2),1:IP.epiP.dim(3));
xyz = [x(:) y(:) z(:)];
% Space of EPI is IP.epiP{1}.mat and space of fmagP is IP.fmagP.mat
tM = inv(IP.epiP.mat\IP.fmagP.mat);
x2 = tM(1,1)*x + tM(1,2)*y + tM(1,3)*z + tM(1,4);
y2 = tM(2,1)*x + tM(2,2)*y + tM(2,3)*z + tM(2,4);
z2 = tM(3,1)*x + tM(3,2)*y + tM(3,3)*z + tM(3,4);
xyz2 = [x2(:) y2(:) z2(:)];
wfmag = reshape(spm_sample_vol(IP.fmagP,xyz2(:,1),...
xyz2(:,2),xyz2(:,3),1),IP.epiP.dim(1:3));
% Need to sample voxel shift map in space of EPI to be unwarped
tvdm = reshape(spm_sample_vol(IP.vdm.vdm,xyz2(:,1),...
xyz2(:,2),xyz2(:,3),0),IP.epiP.dim(1:3));
% Now apply warps to resampled forward warped magnitude image...
wfmag = reshape(spm_sample_vol(wfmag,xyz(:,1)-tvdm(:),xyz(:,2),...
xyz(:,3),1),IP.epiP.dim(1:3));
% Write out forward warped magnitude image
IP.wfmagP = struct('dim', IP.epiP.dim,...
'dt',[64 spm_platform('bigend')],...
'pinfo', IP.epiP.pinfo,...
'mat', IP.epiP.mat);
IP.wfmagP = FieldMap('Write',IP.epiP,wfmag,'wfmag_',4,'Voxel shift map');
% Now coregister warped magnitude field map to EPI
[mi,M] = FieldMap('Coregister',IP.epiP,IP.wfmagP);
% Update the .mat file of the forward warped mag image
spm_get_space(deblank(IP.wfmagP.fname),M*IP.wfmagP.mat);
% Get the original space of the fmap magnitude
MM = IP.fmagP.mat;
end
% Update .mat file for voxel displacement map
IP.vdmP.mat=M*MM;
spm_get_space(deblank(IP.vdmP.fname),M*MM);
varargout{1} = IP.vdmP;
%=======================================================================
%
% Invert voxel displacement map
%
%=======================================================================
case 'invert'
vdm = pm_invert_phasemap(IP.vdm.vdm);
varargout{1} = vdm;
%=======================================================================
%
% Get fieldmap magnitude image
%
%=======================================================================
case 'magnitude'
IP=varargin{2};
if isempty(IP.fmagP)
%
% Get fieldmap magnitude image
%
if isempty(IP.pP) & ~isempty(IP.P{1})
IP.fmagP=struct('dim', IP.P{1}.dim,...
'dt', IP.P{1}.dt,...
'pinfo', IP.P{1}.pinfo,...
'mat', IP.P{1}.mat);
IP.fmagP.fname=fullfile(spm_str_manip(IP.P{1}.fname, 'h'),['mag_' deblank(spm_str_manip(IP.P{1}.fname,'t'))]);
% If using real and imaginary data, calculate using sqrt(i1.^2 + i2.^2).
% If using phase and magnitude, use magnitude image.
if IP.uflags.iformat=='RI'
IP.fmagP = spm_imcalc(spm_vol([IP.P{1}.fname;IP.P{2}.fname]),IP.fmagP,'sqrt(i1.^2 + i2.^2)');
else
IP.fmagP = IP.P{2};
end
% else
% IP.fmagP = spm_vol(spm_get(1,'*.img','Select field map magnitude image'));
else
do_f = ~isfield(IP, 'fmagP');
if ~do_f, do_f = isempty(IP.fmagP); end
if do_f
IP.fmagP = spm_vol(spm_select(1,'image','Select field map magnitude image'));
end
end
end
varargout{1} = IP.fmagP;
%=======================================================================
%
% Load structural image
%
%=======================================================================
case 'loadstructural'
%IP.nwarp = spm_vol(spm_get(1,'*.img','Select structural image'));
% SPM5 Update
IP.nwarp = spm_vol(spm_select(1,'image','Select structural image'));
varargout{1} = IP.nwarp;
%=======================================================================
%
% Coregister structural image to unwarped EPI
%
%=======================================================================
case 'matchstructural'
IP = varargin{2};
[mi,M] = FieldMap('Coregister',IP.uepiP,IP.nwarp);
MM = IP.nwarp.mat;
IP.nwarp.mat=M*MM;
spm_get_space(deblank(IP.nwarp.fname),IP.nwarp.mat);
varargout{1}=mi;
%=======================================================================
%
% Coregister two images - NO gui
%
%=======================================================================
case 'coregister'
%
% Coregisters image VF to image VG (use VF and VG like in SPM code)
%
VG = varargin{2};
VF = varargin{3};
% Define flags for coregistration...
IP.cflags.cost_fun = spm_get_defaults('coreg.estimate.cost_fun');
IP.cflags.sep = spm_get_defaults('coreg.estimate.sep');
IP.cflags.tol = spm_get_defaults('coreg.estimate.tol');
IP.cflags.fwhm = spm_get_defaults('coreg.estimate.fwhm');
IP.cflags.graphics = 0;
% Voxel sizes (mm)
vxg = sqrt(sum(VG.mat(1:3,1:3).^2));
vxf = sqrt(sum(VF.mat(1:3,1:3).^2));
% Smoothnesses
fwhmg = sqrt(max([1 1 1]*IP.cflags.sep(end)^2 - vxg.^2, [0 0 0]))./vxg;
fwhmf = sqrt(max([1 1 1]*IP.cflags.sep(end)^2 - vxf.^2, [0 0 0]))./vxf;
% Need to load data smoothed in unit8 format (as in spm_coreg_ui)
% if isfield(VG,'dat')
% VG=rmfield(VG,'dat');
% end
if ~isfield(VG,'uint8')
VG.uint8 = loaduint8(VG);
VG = smooth_uint8(VG,fwhmg); % Note side effects
end
% if isfield(VF,'dat')
% VF=rmfield(VF,'dat');
% end
if ~isfield(VF,'uint8')
VF.uint8 = loaduint8(VF);
VF = smooth_uint8(VF,fwhmf); % Note side effects
end
x=spm_coreg(VG,VF,IP.cflags);
M = inv(spm_matrix(x));
MM = spm_get_space(deblank(VF.fname));
varargout{1}=spm_coreg(x,VG,VF,2,IP.cflags.cost_fun,IP.cflags.fwhm);
varargout{2}=M;
%=======================================================================
%
% Use spm_help to display help for FieldMap toolbox
%
%=======================================================================
case 'help'
spm_help('FieldMap.man');
return
end
%=======================================================================
%
% Smoothing functions required for spm_coreg
%
%=======================================================================
function V = smooth_uint8(V,fwhm)
% Convolve the volume in memory (fwhm in voxels).
lim = ceil(2*fwhm);
s = fwhm/sqrt(8*log(2));
x = [-lim(1):lim(1)]; x = smoothing_kernel(fwhm(1),x); x = x/sum(x);
y = [-lim(2):lim(2)]; y = smoothing_kernel(fwhm(2),y); y = y/sum(y);
z = [-lim(3):lim(3)]; z = smoothing_kernel(fwhm(3),z); z = z/sum(z);
i = (length(x) - 1)/2;
j = (length(y) - 1)/2;
k = (length(z) - 1)/2;
spm_conv_vol(V.uint8,V.uint8,x,y,z,-[i j k]);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function krn = smoothing_kernel(fwhm,x)
% Variance from FWHM
s = (fwhm/sqrt(8*log(2)))^2+eps;
% The simple way to do it. Not good for small FWHM
% krn = (1/sqrt(2*pi*s))*exp(-(x.^2)/(2*s));
% For smoothing images, one should really convolve a Gaussian
% with a sinc function. For smoothing histograms, the
% kernel should be a Gaussian convolved with the histogram
% basis function used. This function returns a Gaussian
% convolved with a triangular (1st degree B-spline) basis
% function.
% Gaussian convolved with 0th degree B-spline
% int(exp(-((x+t))^2/(2*s))/sqrt(2*pi*s),t= -0.5..0.5)
% w1 = 1/sqrt(2*s);
% krn = 0.5*(erf(w1*(x+0.5))-erf(w1*(x-0.5)));
% Gaussian convolved with 1st degree B-spline
% int((1-t)*exp(-((x+t))^2/(2*s))/sqrt(2*pi*s),t= 0..1)
% +int((t+1)*exp(-((x+t))^2/(2*s))/sqrt(2*pi*s),t=-1..0)
w1 = 0.5*sqrt(2/s);
w2 = -0.5/s;
w3 = sqrt(s/2/pi);
krn = 0.5*(erf(w1*(x+1)).*(x+1) + erf(w1*(x-1)).*(x-1) - 2*erf(w1*x ).* x)...
+w3*(exp(w2*(x+1).^2) + exp(w2*(x-1).^2) - 2*exp(w2*x.^2));
krn(krn<0) = 0;
return;
%=======================================================================
%
% Load data function required for spm_coreg
%
%=======================================================================
function udat = loaduint8(V)
% Load data from file indicated by V into an array of unsigned bytes.
if size(V.pinfo,2)==1 & V.pinfo(1) == 2,
mx = 255*V.pinfo(1) + V.pinfo(2);
mn = V.pinfo(2);
else,
spm_progress_bar('Init',V.dim(3),...
['Computing max/min of ' spm_str_manip(V.fname,'t')],...
'Planes complete');
mx = -Inf; mn = Inf;
for p=1:V.dim(3),
img = spm_slice_vol(V,spm_matrix([0 0 p]),V.dim(1:2),1);
mx = max([max(img(:))+paccuracy(V,p) mx]);
mn = min([min(img(:)) mn]);
spm_progress_bar('Set',p);
end;
end;
spm_progress_bar('Init',V.dim(3),...
['Loading ' spm_str_manip(V.fname,'t')],...
'Planes loaded');
udat = uint8(0);
udat(V.dim(1),V.dim(2),V.dim(3))=0;
rand('state',100);
for p=1:V.dim(3),
img = spm_slice_vol(V,spm_matrix([0 0 p]),V.dim(1:2),1);
acc = paccuracy(V,p);
if acc==0,
udat(:,:,p) = uint8(round((img-mn)*(255/(mx-mn))));
else,
% Add random numbers before rounding to reduce aliasing artifact
r = rand(size(img))*acc;
udat(:,:,p) = uint8(round((img+r-mn)*(255/(mx-mn))));
end;
spm_progress_bar('Set',p);
end;
spm_progress_bar('Clear');
return;
function acc = paccuracy(V,p)
if ~spm_type(V.dt(1),'intt'),
acc = 0;
else,
if size(V.pinfo,2)==1,
acc = abs(V.pinfo(1,1));
else,
acc = abs(V.pinfo(1,p));
end;
end;
%_______________________________________________________________________
|
github
|
philippboehmsturm/antx-master
|
tbx_cfg_fieldmap.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/FieldMap/tbx_cfg_fieldmap.m
| 42,259 |
utf_8
|
8319c4da246db18dcc1d188a72a84d01
|
function fieldmap = tbx_cfg_fieldmap
% MATLABBATCH Configuration file for toolbox 'FieldMap'
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% $Id: tbx_cfg_fieldmap.m 4571 2011-11-23 17:34:12Z chloe $
addpath(fullfile(spm('dir'),'toolbox','FieldMap'));
% ---------------------------------------------------------------------
% ---------------------------------------------------------------------
% Default values that are common to all fieldmap jobs
% ---------------------------------------------------------------------
%
% ---------------------------------------------------------------------
% et Echo times [short TE long TE]
% ---------------------------------------------------------------------
et = cfg_entry;
et.tag = 'et';
et.name = 'Echo times [short TE long TE]';
et.help = {'Enter the short and long echo times (in ms) of the data used to acquire the field map.'};
et.strtype = 'e';
et.num = [1 2];
% ---------------------------------------------------------------------
% maskbrain Mask brain
% ---------------------------------------------------------------------
maskbrain = cfg_menu;
maskbrain.tag = 'maskbrain';
maskbrain.name = 'Mask brain';
maskbrain.help = {
'Select masking or no masking of the brain. If masking is selected,'
'the magnitude image is used to generate a mask of the brain.'
}';
maskbrain.labels = {
'Mask brain'
'No brain masking'
}';
maskbrain.values{1} = 1;
maskbrain.values{2} = 0;
% ---------------------------------------------------------------------
% blipdir Blip direction
% ---------------------------------------------------------------------
blipdir = cfg_menu;
blipdir.tag = 'blipdir';
blipdir.name = 'Blip direction';
blipdir.help = {'Enter the blip direction. This is the polarity of the phase-encode blips describing the direction in which k-space is traversed along the y-axis during EPI acquisition with respect to the coordinate system used in SPM. In this coordinate system, the phase encode direction corresponds with the y-direction and is defined as positive from the posterior to the anterior of the head.'};
blipdir.labels = {
'-1'
'1'
}';
blipdir.values{1} = -1;
blipdir.values{2} = 1;
% ---------------------------------------------------------------------
% tert Total EPI readout time
% ---------------------------------------------------------------------
tert = cfg_entry;
tert.tag = 'tert';
tert.name = 'Total EPI readout time';
tert.help = {
'Enter the total EPI readout time (in ms). This is the time taken to '
'acquire all of the phase encode steps required to cover k-space (ie one image slice). '
'For example, if the EPI sequence has 64 phase encode steps, the total readout time is '
'the time taken to acquire 64 echoes, e.g. '
'total readout time = number of echoes × echo spacing. '
'This time does not include i) the duration of the excitation, ii) the delay between, '
'the excitation and the start of the acquisition or iii) time for fat saturation etc.'
}';
tert.strtype = 'e';
tert.num = [1 1];
% ---------------------------------------------------------------------
% epifm EPI-based field map?
% ---------------------------------------------------------------------
epifm = cfg_menu;
epifm.tag = 'epifm';
epifm.name = 'EPI-based field map?';
epifm.help = {'Select non-EPI or EPI based field map. The field map data may be acquired using a non-EPI sequence (typically a gradient echo sequence) or an EPI sequence. The processing will be slightly different for the two cases. If using an EPI-based field map, the resulting Voxel Displacement Map will be inverted since the field map was acquired in distorted space.'};
epifm.labels = {
'non-EPI'
'EPI'
}';
epifm.values{1} = 0;
epifm.values{2} = 1;
% ---------------------------------------------------------------------
% ajm Jacobian modulation?
% ---------------------------------------------------------------------
ajm = cfg_menu;
ajm.tag = 'ajm';
ajm.name = 'Jacobian modulation?';
ajm.help = {'Select whether or not to use Jacobian modulation. This will adjust the intensities of voxels that have been stretched or compressed but in general is not recommended for EPI distortion correction'};
ajm.labels = {
'Do not use'
'Use'
}';
ajm.values{1} = 0;
ajm.values{2} = 1;
ajm.def = @(val)pm_get_defaults('DO_JACOBIAN_MODULATION', val{:});
% ---------------------------------------------------------------------
% method Unwrapping method
% ---------------------------------------------------------------------
method = cfg_menu;
method.tag = 'method';
method.name = 'Unwrapping method';
method.help = {'Select method for phase unwrapping'};
method.labels = {
'Mark3D'
'Mark2D'
'Huttonish'
}';
method.values = {
'Mark3D'
'Mark2D'
'Huttonish'
}';
method.def = @(val)pm_get_defaults('UNWRAPPING_METHOD', val{:});
% ---------------------------------------------------------------------
% fwhm FWHM
% ---------------------------------------------------------------------
fwhm = cfg_entry;
fwhm.tag = 'fwhm';
fwhm.name = 'FWHM';
fwhm.help = {'FWHM of Gaussian filter used to implement weighted smoothing of unwrapped maps.'};
fwhm.strtype = 'e';
fwhm.num = [1 1];
fwhm.def = @(val)pm_get_defaults('FWHM', val{:});
% ---------------------------------------------------------------------
% pad pad
% ---------------------------------------------------------------------
pad = cfg_entry;
pad.tag = 'pad';
pad.name = 'pad';
pad.help = {'Size of padding kernel if required.'};
pad.strtype = 'e';
pad.num = [1 1];
pad.def = @(val)pm_get_defaults('PAD', val{:});
% ---------------------------------------------------------------------
% ws Weighted smoothing
% ---------------------------------------------------------------------
ws = cfg_menu;
ws.tag = 'ws';
ws.name = 'Weighted smoothing';
ws.help = {'Select normal or weighted smoothing.'};
ws.labels = {
'Weighted Smoothing'
'No weighted smoothing'
}';
ws.values{1} = 1;
ws.values{2} = 0;
ws.def = @(val)pm_get_defaults('WS', val{:});
% ---------------------------------------------------------------------
% uflags uflags
% ---------------------------------------------------------------------
uflags = cfg_branch;
uflags.tag = 'uflags';
uflags.name = 'uflags';
uflags.val = {method fwhm pad ws };
uflags.help = {'Different options for phase unwrapping and field map processing'};
% ---------------------------------------------------------------------
% template Template image for brain masking
% ---------------------------------------------------------------------
template = cfg_files;
template.tag = 'template';
template.name = 'Template image for brain masking';
template.help = {'Select template file for segmentation to create brain mask'};
template.filter = 'nii';
template.ufilter = '.*';
template.num = [1 1];
template.def = @(val)pm_get_defaults('MFLAGS.TEMPLATE', val{:});
% ---------------------------------------------------------------------
% fwhm FWHM
% ---------------------------------------------------------------------
fwhm = cfg_entry;
fwhm.tag = 'fwhm';
fwhm.name = 'FWHM';
fwhm.help = {'FWHM of Gaussian filter for smoothing brain mask.'};
fwhm.strtype = 'e';
fwhm.num = [1 1];
fwhm.def = @(val)pm_get_defaults('MFLAGS.FWHM', val{:});
% ---------------------------------------------------------------------
% nerode Number of erosions
% ---------------------------------------------------------------------
nerode = cfg_entry;
nerode.tag = 'nerode';
nerode.name = 'Number of erosions';
nerode.help = {'Number of erosions used to create brain mask.'};
nerode.strtype = 'e';
nerode.num = [1 1];
nerode.def = @(val)pm_get_defaults('MFLAGS.NERODE', val{:});
% ---------------------------------------------------------------------
% ndilate Number of dilations
% ---------------------------------------------------------------------
ndilate = cfg_entry;
ndilate.tag = 'ndilate';
ndilate.name = 'Number of dilations';
ndilate.help = {'Number of dilations used to create brain mask.'};
ndilate.strtype = 'e';
ndilate.num = [1 1];
ndilate.def = @(val)pm_get_defaults('MFLAGS.NDILATE', val{:});
% ---------------------------------------------------------------------
% thresh Threshold
% ---------------------------------------------------------------------
thresh = cfg_entry;
thresh.tag = 'thresh';
thresh.name = 'Threshold';
thresh.help = {'Threshold used to create brain mask from segmented data.'};
thresh.strtype = 'e';
thresh.num = [1 1];
thresh.def = @(val)pm_get_defaults('MFLAGS.THRESH', val{:});
% ---------------------------------------------------------------------
% reg Regularization
% ---------------------------------------------------------------------
reg = cfg_entry;
reg.tag = 'reg';
reg.name = 'Regularization';
reg.help = {'Regularization value used in the segmentation. A larger value helps the segmentation to converge.'};
reg.strtype = 'e';
reg.num = [1 1];
reg.def = @(val)pm_get_defaults('MFLAGS.REG', val{:});
% ---------------------------------------------------------------------
% mflags mflags
% ---------------------------------------------------------------------
mflags = cfg_branch;
mflags.tag = 'mflags';
mflags.name = 'mflags';
mflags.val = {template fwhm nerode ndilate thresh reg };
mflags.help = {'Different options used for the segmentation and creation of the brain mask.'};
% ---------------------------------------------------------------------
% defaultsval Defaults values
% ---------------------------------------------------------------------
defaultsval = cfg_branch;
defaultsval.tag = 'defaultsval';
defaultsval.name = 'Defaults values';
defaultsval.val = {et maskbrain blipdir tert epifm ajm uflags mflags };
defaultsval.help = {'Defaults values'};
% ---------------------------------------------------------------------
% defaultsfile Defaults File
% ---------------------------------------------------------------------
defaultsfile = cfg_files;
defaultsfile.tag = 'defaultsfile';
defaultsfile.name = 'Defaults File';
defaultsfile.help = {'Select the ''pm_defaults*.m'' file containing the parameters for the field map data. Please make sure that the parameters defined in the defaults file are correct for your field map and EPI sequence. To create your own customised defaults file, either edit the distributed version and/or save it with the name ''pm_defaults_yourname.m''.'};
defaultsfile.filter = 'm';
[deffilepath, tmp] = fileparts(mfilename('fullpath'));
defaultsfile.dir = deffilepath;
defaultsfile.ufilter = '^pm_defaults.*\.m$';
defaultsfile.num = [1 1];
defaultsfile.def = @(val)pm_get_defaults('defaultsfilename', val{:});
% ---------------------------------------------------------------------
% defaults FieldMap defaults
% ---------------------------------------------------------------------
defaults = cfg_choice;
defaults.tag = 'defaults';
defaults.name = 'FieldMap defaults';
defaults.help = {'FieldMap default values can be entered as a file or set of values.'};
defaults.values = {defaultsval defaultsfile };
% ---------------------------------------------------------------------
% epi Select EPI to Unwarp
% ---------------------------------------------------------------------
epi = cfg_files;
epi.tag = 'epi';
epi.name = 'Select EPI to Unwarp';
epi.help = {'Select a single image to distortion correct. The corrected image will be saved with the prefix u. Note that this option is mainly for quality control of correction so that the original and distortion corrected images can be displayed for comparison. To unwarp multiple images please use either Realign & Unwarp or Apply VDM.'};
epi.filter = 'image';
epi.ufilter = '.*';
epi.num = [1 1];
% ---------------------------------------------------------------------
% session Session
% ---------------------------------------------------------------------
session = cfg_branch;
session.tag = 'session';
session.name = 'Session';
session.val = {epi };
session.help = {'Data for this session.'};
% ---------------------------------------------------------------------
% generic EPI Sessions
% ---------------------------------------------------------------------
generic1 = cfg_repeat;
generic1.tag = 'generic1';
generic1.name = 'EPI Sessions';
generic1.help = {'If a single set of field map data will be used for multiple EPI runs/sessions, select the first EPI in each run/session. A VDM file will created for each run/session, matched to the first EPI in each run/session and saved with a unique name extension.'};
generic1.values = {session };
generic1.num = [1 Inf];
% ---------------------------------------------------------------------
% matchvdm Match VDM to EPI?
% ---------------------------------------------------------------------
matchvdm = cfg_menu;
matchvdm.tag = 'matchvdm';
matchvdm.name = 'Match VDM to EPI?';
matchvdm.help = {'Match VDM file to EPI image. This will coregister the field map data to the selected EPI for each run/session.'};
matchvdm.labels = {
'match VDM'
'none'
}';
matchvdm.values{1} = 1;
matchvdm.values{2} = 0;
% ---------------------------------------------------------------------
% sessname Name extension for session specific vdm files
% ---------------------------------------------------------------------
sessname = cfg_entry;
sessname.tag = 'sessname';
sessname.name = 'VDM filename extension';
sessname.help = {'Filename extension for run/session specific VDM files. The extension will be followed by an incremented integer for run/session number.'};
sessname.strtype = 's';
sessname.num = [1 Inf];
sessname.def = @(val)pm_get_defaults('sessname', val{:});
% ---------------------------------------------------------------------
% writeunwarped Write unwarped EPI?
% ---------------------------------------------------------------------
writeunwarped = cfg_menu;
writeunwarped.tag = 'writeunwarped';
writeunwarped.name = 'Write unwarped EPI?';
writeunwarped.help = {'Write out distortion corrected EPI image. The image is saved with the prefix u. Note that this option is mainly for quality control of correction so that the original and distortion corrected images can be displayed for comparison. To unwarp multiple images please use either Realign & Unwarp or Apply VDM.'};
writeunwarped.labels = {
'write unwarped EPI'
'none'
}';
writeunwarped.values{1} = 1;
writeunwarped.values{2} = 0;
% ---------------------------------------------------------------------
% anat Select anatomical image for comparison
% ---------------------------------------------------------------------
anat = cfg_files;
anat.tag = 'anat';
anat.name = 'Select anatomical image for comparison';
anat.help = {'Select an anatomical image for comparison with the distortion corrected EPI or leave empty. Note that this option is mainly for quality control of correction.'};
anat.filter = 'image';
anat.ufilter = '.*';
anat.num = [0 1];
anat.val = {''};
% ---------------------------------------------------------------------
% matchanat Match anatomical image to EPI?
% ---------------------------------------------------------------------
matchanat = cfg_menu;
matchanat.tag = 'matchanat';
matchanat.name = 'Match anatomical image to EPI?';
matchanat.help = {'Match the anatomical image to the distortion corrected EPI. Note that this option is mainly for quality control of correction allowing for visual inspection and comparison of the distortion corrected EPI.'};
matchanat.labels = {
'none'
'match anat'
}';
matchanat.values{1} = 0;
matchanat.values{2} = 1;
% ---------------------------------------------------------------------
% ---------------------------------------------------------------------
% Different kinds of input jobs
% ---------------------------------------------------------------------
% ---------------------------------------------------------------------
% 1) Presubtracted phase and magnitude data
% ---------------------------------------------------------------------
% phase Phase Image
% ---------------------------------------------------------------------
phase = cfg_files;
phase.tag = 'phase';
phase.name = 'Phase Image';
phase.help = {'Select a single phase image. This should be the result from the subtraction of two phase images (where the subtraction is usually done automatically by the scanner software). The phase image will be scaled between +/- PI.'};
phase.filter = 'image';
phase.ufilter = '.*';
phase.num = [1 1];
% ---------------------------------------------------------------------
% magnitude Magnitude Image
% ---------------------------------------------------------------------
magnitude = cfg_files;
magnitude.tag = 'magnitude';
magnitude.name = 'Magnitude Image';
magnitude.help = {'Select a single magnitude image. This is used for masking the phase information and coregistration with the EPI data. If two magnitude images are available, select the one acquired at the shorter echo time because it will have greater signal'};
magnitude.filter = 'image';
magnitude.ufilter = '.*';
magnitude.num = [1 1];
% ---------------------------------------------------------------------
% subj Subject
% ---------------------------------------------------------------------
subj = cfg_branch;
subj.tag = 'subj';
subj.name = 'Subject';
subj.val = {phase magnitude defaults generic1 matchvdm sessname writeunwarped anat matchanat };
subj.help = {'Data for this subject or field map session.'};
% ---------------------------------------------------------------------
% generic Data
% ---------------------------------------------------------------------
generic = cfg_repeat;
generic.tag = 'generic';
generic.name = 'Data';
generic.help = {'Subjects or sessions for which individual field map data has been acquired.'};
generic.values = {subj };
generic.num = [1 Inf];
% ---------------------------------------------------------------------
% presubphasemag Presubtracted Phase and Magnitude Data
% ---------------------------------------------------------------------
presubphasemag = cfg_exbranch;
presubphasemag.tag = 'presubphasemag';
presubphasemag.name = 'Presubtracted Phase and Magnitude Data';
presubphasemag.val = {generic };
presubphasemag.help = {'Calculate a voxel displacement map (VDM) from presubtracted phase and magnitude field map data. This option expects a single magnitude image and a single phase image resulting from the subtraction of two phase images (where the subtraction is usually done automatically by the scanner software). The phase image will be scaled between +/- PI.'};
presubphasemag.prog = @fieldmap_presubphasemag;
presubphasemag.vout = @vout;
% ---------------------------------------------------------------------
% 2) Real and imaginary data
% ---------------------------------------------------------------------
% shortreal Short Echo Real Image
% ---------------------------------------------------------------------
shortreal = cfg_files;
shortreal.tag = 'shortreal';
shortreal.name = 'Short Echo Real Image';
shortreal.help = {'Select short echo real image'};
shortreal.filter = 'image';
shortreal.ufilter = '.*';
shortreal.num = [1 1];
% ---------------------------------------------------------------------
% shortimag Short Echo Imaginary Image
% ---------------------------------------------------------------------
shortimag = cfg_files;
shortimag.tag = 'shortimag';
shortimag.name = 'Short Echo Imaginary Image';
shortimag.help = {'Select short echo imaginary image'};
shortimag.filter = 'image';
shortimag.ufilter = '.*';
shortimag.num = [1 1];
% ---------------------------------------------------------------------
% longreal Long Echo Real Image
% ---------------------------------------------------------------------
longreal = cfg_files;
longreal.tag = 'longreal';
longreal.name = 'Long Echo Real Image';
longreal.help = {'Select long echo real image'};
longreal.filter = 'image';
longreal.ufilter = '.*';
longreal.num = [1 1];
% ---------------------------------------------------------------------
% longimag Long Echo Imaginary Image
% ---------------------------------------------------------------------
longimag = cfg_files;
longimag.tag = 'longimag';
longimag.name = 'Long Echo Imaginary Image';
longimag.help = {'Select long echo imaginary image'};
longimag.filter = 'image';
longimag.ufilter = '.*';
longimag.num = [1 1];
% ---------------------------------------------------------------------
% subj Subject
% ---------------------------------------------------------------------
subj = cfg_branch;
subj.tag = 'subj';
subj.name = 'Subject';
subj.val = {shortreal shortimag longreal longimag defaults generic1 matchvdm sessname writeunwarped anat matchanat };
subj.help = {'Data for this subject or field map session.'};
% ---------------------------------------------------------------------
% generic Data
% ---------------------------------------------------------------------
generic = cfg_repeat;
generic.tag = 'generic';
generic.name = 'Data';
generic.help = {'Subjects or sessions for which individual field map data has been acquired.'};
generic.values = {subj };
generic.num = [1 Inf];
% ---------------------------------------------------------------------
% realimag Real and Imaginary Data
% ---------------------------------------------------------------------
realimag = cfg_exbranch;
realimag.tag = 'realimag';
realimag.name = 'Real and Imaginary Data';
realimag.val = {generic };
realimag.help = {'Calculate a voxel displacement map (VDM) from real and imaginary field map data. This option expects two real and imaginary pairs of data of two different echo times. The phase images will be scaled between +/- PI.'};
realimag.prog = @fieldmap_realimag;
realimag.vout = @vout;
% ---------------------------------------------------------------------
% 3) Phase and magnitude (4 files)
% ---------------------------------------------------------------------
% shortphase Short Echo Phase Image
% ---------------------------------------------------------------------
shortphase = cfg_files;
shortphase.tag = 'shortphase';
shortphase.name = 'Short Echo Phase Image';
shortphase.help = {'Select short echo phase image'};
shortphase.filter = 'image';
shortphase.ufilter = '.*';
shortphase.num = [1 1];
% ---------------------------------------------------------------------
% shortmag Short Echo Magnitude Image
% ---------------------------------------------------------------------
shortmag = cfg_files;
shortmag.tag = 'shortmag';
shortmag.name = 'Short Echo Magnitude Image';
shortmag.help = {'Select short echo magnitude image'};
shortmag.filter = 'image';
shortmag.ufilter = '.*';
shortmag.num = [1 1];
% ---------------------------------------------------------------------
% longphase Long Echo Phase Image
% ---------------------------------------------------------------------
longphase = cfg_files;
longphase.tag = 'longphase';
longphase.name = 'Long Echo Phase Image';
longphase.help = {'Select long echo phase image'};
longphase.filter = 'image';
longphase.ufilter = '.*';
longphase.num = [1 1];
% ---------------------------------------------------------------------
% longmag Long Echo Magnitude Image
% ---------------------------------------------------------------------
longmag = cfg_files;
longmag.tag = 'longmag';
longmag.name = 'Long Echo Magnitude Image';
longmag.help = {'Select long echo magnitude image'};
longmag.filter = 'image';
longmag.ufilter = '.*';
longmag.num = [1 1];
% ---------------------------------------------------------------------
% subj Subject
% ---------------------------------------------------------------------
subj = cfg_branch;
subj.tag = 'subj';
subj.name = 'Subject';
subj.val = {shortphase shortmag longphase longmag defaults generic1 matchvdm sessname writeunwarped anat matchanat };
subj.help = {'Data for this subject or field map session.'};
% ---------------------------------------------------------------------
% generic Data
% ---------------------------------------------------------------------
generic = cfg_repeat;
generic.tag = 'generic';
generic.name = 'Data';
generic.help = {'Subjects or sessions for which individual field map data has been acquired.'};
generic.values = {subj };
generic.num = [1 Inf];
% ---------------------------------------------------------------------
% phasemag Phase and Magnitude Data
% ---------------------------------------------------------------------
phasemag = cfg_exbranch;
phasemag.tag = 'phasemag';
phasemag.name = 'Phase and Magnitude Data';
phasemag.val = {generic };
phasemag.help = {'Calculate a voxel displacement map (VDM) from double phase and magnitude field map data. This option expects two phase and magnitude pairs of data of two different echo times.'};
phasemag.prog = @fieldmap_phasemag;
phasemag.vout = @vout;
% ---------------------------------------------------------------------
% 4) Precalculated fieldmap
% ---------------------------------------------------------------------
% precalcfieldmap Precalculated field map
% ---------------------------------------------------------------------
precalcfieldmap1 = cfg_files;
precalcfieldmap1.tag = 'precalcfieldmap';
precalcfieldmap1.name = 'Precalculated field map';
precalcfieldmap1.help = {'Select a precalculated field map. This should be a processed field map (ie phase unwrapped, masked if necessary and scaled to Hz) , for example as generated by the FieldMap toolbox and are stored with fpm_* prefix.'};
precalcfieldmap1.filter = 'image';
precalcfieldmap1.ufilter = '.*';
precalcfieldmap1.num = [1 1];
% ---------------------------------------------------------------------
% magfieldmap Select magnitude image in same space as fieldmap
% ---------------------------------------------------------------------
magfieldmap = cfg_files;
magfieldmap.tag = 'magfieldmap';
magfieldmap.name = 'Select magnitude image in same space as fieldmap';
magfieldmap.help = {'Select magnitude image which is in the same space as the field map to do matching to EPI.'};
magfieldmap.filter = 'image';
magfieldmap.ufilter = '.*';
magfieldmap.num = [0 1];
% ---------------------------------------------------------------------
% subj Subject
% ---------------------------------------------------------------------
subj = cfg_branch;
subj.tag = 'subj';
subj.name = 'Subject';
subj.val = {precalcfieldmap1 magfieldmap defaults generic1 matchvdm sessname writeunwarped anat matchanat };
subj.help = {'Data for this subject or field map session.'};
% ---------------------------------------------------------------------
% generic Data
% ---------------------------------------------------------------------
generic = cfg_repeat;
generic.tag = 'generic';
generic.name = 'Data';
generic.help = {'Subjects or sessions for which individual field map data has been acquired.'};
generic.values = {subj };
generic.num = [1 Inf];
% ---------------------------------------------------------------------
% precalcfieldmap Precalculated FieldMap (in Hz)
% ---------------------------------------------------------------------
precalcfieldmap = cfg_exbranch;
precalcfieldmap.tag = 'precalcfieldmap';
precalcfieldmap.name = 'Precalculated FieldMap (in Hz)';
precalcfieldmap.val = {generic };
precalcfieldmap.help = {'Calculate a voxel displacement map (VDM) from a precalculated field map. This option expects a processed field map (ie phase unwrapped, masked if necessary and scaled to Hz). Precalculated field maps can be generated by the FieldMap toolbox and stored as fpm_* files.'};
precalcfieldmap.prog = @fieldmap_precalcfieldmap;
precalcfieldmap.vout = @vout;
% ---------------------------------------------------------------------
% 5) Apply vdm* file
% ---------------------------------------------------------------------
% scans Images
% ---------------------------------------------------------------------
scans = cfg_files;
scans.tag = 'scans';
scans.name = 'Images';
scans.help = {
'Select scans for this session. These are assumed to be realigned to the first in the time series (e.g. using Realign: Estimate) but do not need to be resliced'
};
scans.filter = 'image';
scans.ufilter = '.*';
scans.num = [1 Inf];
% ---------------------------------------------------------------------
% vdmfile selected vdm files
% ---------------------------------------------------------------------
vdmfile = cfg_files;
vdmfile.tag = 'vdmfile';
vdmfile.name = 'Fieldmap (vdm* file)';
vdmfile.help = {'Select VDM (voxel displacement map) for this session (e.g. created via FieldMap toolbox). This is assumed to be in alignment with the images selected for resampling (note this can be achieved via the FieldMap toolbox).'};
vdmfile.filter = 'image';
vdmfile.ufilter = '.*';
vdmfile.num = [1 1];
% ---------------------------------------------------------------------
% vdmapply session Session
% ---------------------------------------------------------------------
data = cfg_branch;
data.tag = 'data';
data.name = 'Session';
data.val = {scans vdmfile};
data.help = {'Data for this session.'};
% ---------------------------------------------------------------------
% generic Data
% ---------------------------------------------------------------------
generic2 = cfg_repeat;
generic2.tag = 'generic2';
generic2.name = 'Data';
generic2.help = {'Subjects or sessions for which VDM file is being applied to images.'};
generic2.values = {data};
generic2.num = [1 Inf];
% ---------------------------------------------------------------------
% Reslice options for applyvdm
% ---------------------------------------------------------------------
% ---------------------------------------------------------------------
% wrap Wrapping
% ---------------------------------------------------------------------
pedir = cfg_menu;
pedir.tag = 'pedir';
pedir.name = 'Distortion direction';
pedir.help = {
'In which direction are the distortions? Any single dimension can be corrected therefore input data may have been acquired with phase encode directions in Y (most typical), X or Z'};
pedir.labels = {
'Posterior-Anterior (Y)'
'Right-Left (X)'
'Foot-Head (Z)'}';
pedir.values = {[2] [1] [3]};
pedir.def = @(val)pm_get_defaults('pedir', val{:});
% ---------------------------------------------------------------------
% Which images to reslice?
% ---------------------------------------------------------------------
applyvdmwhich = cfg_menu;
applyvdmwhich.tag = 'which';
applyvdmwhich.name = 'Reslice which images ?';
applyvdmwhich.help = {
'All Images (1..n) '
' This applies the VDM and reslices all the images. '
'All Images + Mean Image '
' This applies the VDM reslices all the images and creates a mean of the resliced images.'
}';
applyvdmwhich.labels = {
' All Images (1..n)'
' All Images + Mean Image'
}';
applyvdmwhich.values = {[2 0] [2 1]};
applyvdmwhich.def = @(val)spm_get_defaults('realign.write.which', val{:});
% ---------------------------------------------------------------------
% rinterp Interpolation
% ---------------------------------------------------------------------
rinterp = cfg_menu;
rinterp.tag = 'rinterp';
rinterp.name = 'Interpolation';
rinterp.help = {'The method by which the images are sampled when being written in a different space. Nearest Neighbour is fastest, but not recommended for image realignment. Bilinear Interpolation is probably OK for PET, but not so suitable for fMRI because higher degree interpolation generally gives better results/* \cite{thevenaz00a,unser93a,unser93b}*/. Although higher degree methods provide better interpolation, but they are slower because they use more neighbouring voxels.'};
rinterp.labels = {
'Nearest neighbour'
'Trilinear'
'2nd Degree B-spline '
'3rd Degree B-Spline'
'4th Degree B-Spline'
'5th Degree B-Spline '
'6th Degree B-Spline'
'7th Degree B-Spline'
}';
rinterp.values = {0 1 2 3 4 5 6 7};
rinterp.def = @(val)spm_get_defaults('realign.write.interp', val{:});
% ---------------------------------------------------------------------
% wrap Wrapping
% ---------------------------------------------------------------------
wrap = cfg_menu;
wrap.tag = 'wrap';
wrap.name = 'Wrapping';
wrap.help = {
'This indicates which directions in the volumes the values should wrap around in. For example, in MRI scans, the images wrap around in the phase encode direction, so (e.g.) the subject''s nose may poke into the back of the subject''s head. These are typically:'
' No wrapping - for PET or images that have already been spatially transformed. Also the recommended option if you are not really sure.'
' Wrap in Y - for (un-resliced) MRI where phase encoding is in the Y direction (voxel space) etc.'
}';
wrap.labels = {
'No wrap'
'Wrap X'
'Wrap Y'
'Wrap X & Y'
'Wrap Z '
'Wrap X & Z'
'Wrap Y & Z'
'Wrap X, Y & Z'
}';
wrap.values = {[0 0 0] [1 0 0] [0 1 0] [1 1 0] [0 0 1] [1 0 1] [0 1 1]...
[1 1 1]};
wrap.def = @(val)spm_get_defaults('realign.write.wrap', val{:});
% ---------------------------------------------------------------------
% mask Masking
% ---------------------------------------------------------------------
mask = cfg_menu;
mask.tag = 'mask';
mask.name = 'Masking';
mask.help = {'Because of subject motion, different images are likely to have different patterns of zeros from where it was not possible to sample data. With masking enabled, the program searches through the whole time series looking for voxels which need to be sampled from outside the original images. Where this occurs, that voxel is set to zero for the whole set of images (unless the image format can represent NaN, in which case NaNs are used where possible).'};
mask.labels = {
'Mask images'
'Dont mask images'
}';
mask.values = {1 0};
mask.def = @(val)spm_get_defaults('realign.write.mask', val{:});
% ---------------------------------------------------------------------
% prefix Filename Prefix
% ---------------------------------------------------------------------
prefix = cfg_entry;
prefix.tag = 'prefix';
prefix.name = 'Filename Prefix';
prefix.help = {'Specify the string to be prepended to the filenames of the distortion corrected image file(s). Default prefix is ''u''.'};
prefix.strtype = 's';
prefix.num = [1 Inf];
prefix.def = @(val)spm_get_defaults('unwarp.write.prefix', val{:});
% ---------------------------------------------------------------------
% applyvdmroptions Reslicing Options
% ---------------------------------------------------------------------
applyvdmroptions = cfg_branch;
applyvdmroptions.tag = 'roptions';
applyvdmroptions.name = 'Reslice Options';
applyvdmroptions.val = {pedir applyvdmwhich rinterp wrap mask prefix };
applyvdmroptions.help = {'Apply VDM reslice options'};
% ---------------------------------------------------------------------
% applyvdm Apply vdm* file to EPI files
% ---------------------------------------------------------------------
applyvdm = cfg_exbranch;
applyvdm.tag = 'applyvdm';
applyvdm.name = 'Apply VDM ';
applyvdm.val = {generic2 applyvdmroptions};
applyvdm.help = {'Apply VDM (voxel displacement map) to resample voxel values in selected image(s). This allows a VDM to be applied to any images which are assumed to be already realigned (e.g. including EPI fMRI time series and DTI data).'
'The VDM can be been created from a field map acquisition using the FieldMap toolbox and comprises voxel shift values which describe geometric distortions occuring as a result of magnetic susceptbility artefacts. Distortions along any single dimension can be corrected therefore input data may have been acquired with phase encode directions in X, Y (most typical) and Z.'
'The selected images are assumed to be realigned to the first in the time series (e.g. using Realign: Estimate) but do not need to be resliced. The VDM is assumed to be in alignment with the images selected for resampling (note this can be achieved via the FieldMap toolbox). The resampled images are written to the input subdirectory with the same (prefixed) filename.'
'e.g. The typical processing steps for fMRI time series would be 1) Realign: Estimate, 2) FieldMap to create VDM, 3) Apply VDM.'
'Note that this routine is a general alternative to using the VDM in combination with Realign & Unwarp which estimates and corrects for the combined effects of static and movement-related susceptibility induced distortions. Apply VDM can be used when dynamic distortions are not (well) modelled by Realign & Unwarp (e.g. for fMRI data acquired with R->L phase-encoding direction, high field fMRI data or DTI data).'
}';
applyvdm.prog = @fieldmap_applyvdm;
applyvdm.vout = @vout_applyvdm;
% ---------------------------------------------------------------------
% fieldmap FieldMap
% ---------------------------------------------------------------------
fieldmap = cfg_choice;
fieldmap.tag = 'fieldmap';
fieldmap.name = 'FieldMap';
fieldmap.help = {
'The FieldMap toolbox generates unwrapped field maps which are converted to voxel displacement maps (VDM) that can be used to unwarp geometrically distorted EPI images. For references and an explantion of the theory behind the field map based unwarping, see FieldMap_principles.man. The resulting VDM files are saved with the prefix vdm and can be applied to images using Apply VDM or in combination with Realign & Unwarp to calculate and correct for the combined effects of static and movement-related susceptibility induced distortions.'
''
}';
fieldmap.values = {presubphasemag realimag phasemag precalcfieldmap applyvdm};
%------------------------------------------------------------------------
function out=fieldmap_presubphasemag(job)
for i=1:numel(job.subj),
out(i)=FieldMap_Run(job.subj(i));
end
%------------------------------------------------------------------------
function out=fieldmap_realimag(job)
for i=1:numel(job.subj),
out(i)=FieldMap_Run(job.subj(i));
end
%------------------------------------------------------------------------
function out=fieldmap_phasemag(job)
for i=1:numel(job.subj),
out(i)=FieldMap_Run(job.subj(i));
end
%------------------------------------------------------------------------
function out=fieldmap_precalcfieldmap(job)
for i=1:numel(job.subj),
out(i)=FieldMap_Run(job.subj(i));
end
%------------------------------------------------------------------------
function out=fieldmap_applyvdm(job)
out=FieldMap_applyvdm(job);
%------------------------------------------------------------------------
function dep = vout(job)
depnum=1;
for k=1:numel(job.subj)
for l=1:numel(job.subj(k).session)
dep(depnum) = cfg_dep;
dep(depnum).sname = sprintf('Voxel displacement map (Subj %d, Session %d)',k,l);
dep(depnum).src_output = substruct('()',{k},'.','vdmfile','{}',{l});
dep(depnum).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
depnum=depnum+1;
end
end;
%------------------------------------------------------------------------
function dep = vout_applyvdm(job)
for k=1:numel(job.data)
if job.roptions.which(1) > 0
cdep(1) = cfg_dep;
cdep(1).sname = sprintf('VDM corrected images (Sess %d)', k);
cdep(1).src_output = substruct('.','sess', '()',{k}, '.','rfiles');
cdep(1).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
end;
if k == 1
dep = cdep;
else
dep = [dep cdep];
end;
end
if ~strcmp(job.roptions.which,'<UNDEFINED>') && job.roptions.which(2),
if exist('dep','var')
dep(end+1) = cfg_dep;
else
dep = cfg_dep;
end;
dep(end).sname = 'Mean Image';
dep(end).src_output = substruct('.','rmean');
dep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
end;
|
github
|
philippboehmsturm/antx-master
|
spmmouse.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/spmmouse/spmmouse.m
| 14,273 |
utf_8
|
d9d85092bf19b02c78ec7c433004ca7b
|
function spmmouse(varargin)
%SPMMouse - toolbox for SPM for animal brains
%Stephen Sawiak - http://www.wbic.cam.ac.uk/~sjs80/spmmouse.html
global spmmouseset
fg = spm_figure('FindWin','Menu');
if isempty(fg)
spm('PET');
end
% what should we do
if nargin == 0
showinfo;
return;
end
str = varargin{1};
switch lower(str)
case {'load','loadpreset'}
loadpreset(varargin{2:end});
case 'unload'
unload;
case 'createpreset'
createpreset;
case 'loadimage'
loadimage;
case 'autochk'
autochk;
case 'slideru'
slideru;
case 'sliderl'
sliderl;
case 'slidert'
slidert;
case 'createmip'
createmip;
case 'priors'
priors;
case 'savepreset'
savepreset;
case 'applypreset'
applypreset;
end
%------------------------------
function initspmmouseset
global spmmouseset
mypath = mfilename('fullpath');
spmmouseset.oldpath = path;
spmmouseset.path = fileparts(mypath);
spmmouseset.title = 'SPMMouse v1.0';
spmmouseset.margin = 15;
spmmouseset.size = [400 364];
%------------------------------
function showinfo
global spmmouseset;
if isempty(spmmouseset)
initspmmouseset;
end;
try
gfig = spm_figure('FindWin','Graphics');
figure(gfig);
catch
fprintf(1,'Could not find SPM graphics window ! Is SPM loaded ?\n');
return;
end
% clear everything visible from graphics window
delete(findobj(get(gfig,'Children'),'flat','HandleVisibility','on'));
% clear callbacks
set(gfig,'KeyPressFcn','','WindowButtonDownFcn','','WindowButtonMotionFcn','','WindowButtonUpFcn','');
winscale = spm('WinScale');
tTitle = uicontrol(gfig,'Style','Text','Position',[20 800 560 40].*winscale,'String',spmmouseset.title,'FontSize',24,'BackgroundColor','w');
tInfo = uicontrol(gfig,'Style','Edit','Position',[20 180 560 560].*winscale,...
'FontSize',14,'FontWeight','normal','BackgroundColor',[1 1 0.5],'Min',0,'Max',2,'Enable','on','Value',0,'Enable','inactive');
newl = sprintf('\n');
set(tInfo,'String', ...
{'SPMMouse is a series of modifications to SPM making it easy to use non-human brains. It includes templates for the mouse brain but is generally applicable, and an interface is provided to make a ''glass brain'' from any brain-extracted image.',newl,...
'Modifications to default settings allow realign, coregister, normalise, segment, etc to work with non-human images. A new option appears in Display allowing an overlay to be displayed on the image, easing initial manual registration.',newl,...
'Use of VBM in the mouse brain is described in',...
'S.J. Sawiak et al. "Voxel-based Morphometry Reveals Changes Not Seen with Manual 2D Volumetry in the R6/2 Huntingdon''s disease mouse brain. Neurobiol. Dis. (2009) 33(1) p20-27',newl,...
'Please cite this paper if you use this toolbox. Sample data, updates and tutorials are available from',...
' http://www.wbic.cam.ac.uk/~sjs80/spmmouse.html','',...
'Bug reports and suggestions should be sent to','','Stephen Sawiak','[email protected]'});
set(tInfo,'Listboxtop',1)
uicontrol('Position',[20 760 148 30].*winscale,'String','Load Animal Preset',...
'Callback','spmmouse(''loadpreset'');');
uicontrol('Position',[180 760 148 30].*winscale,'String','Create Animal Preset',...
'Callback','spmmouse(''createpreset'');');
uicontrol('Position',[340 760 148 30].*winscale,'String','Unload SPMMouse',...
'Callback','spmmouse(''unload'');');
try
im=imread('mouse.jpg');
axes('Position',[0.8 0.01 0.2 0.2]);
imagesc(im);axis image off;
catch
% it doesn't matter if the mouse can't be displayed ;)
end
%--------------------------
function unload
global spmmouseset
if ~isempty(spmmouseset)
adjustdefaults('unset');
spmmouseset=[];
end
%--------------------------
function loadpreset(filename)
% If no filename given, use GUI to ask for details & print summary. With
% a filename, work silently.
global spmmouseset;
if isempty(spmmouseset)
initspmmouseset;
end;
if nargin == 0
%
% ask user for a preset file
filename = spm_select(1,'mat','Select preset...',[], ...
spmmouseset.path);
end
try
preset = load(char(filename));
catch
fprintf(1,'Couldn''t open file, or file is corrupt / not preset file! Aborting.\n');
return;
end
%load things about the glass brain and scaling factors
try
spmmouseset.animal.name = preset.name;
spmmouseset.animal.mipmat= preset.mipmat;
load(char(preset.mipmat),'scale');
spmmouseset.animal.scale = 1./scale(1);
catch
fprintf(1,'Critical fields missing from preset file - aborting\n.');
return;
end
if(isfield(preset,'isig')) % does the file have any priors in it?
% will be read by replaced/spm_affine_priors.m
spmmouseset.animal.isig = preset.isig;
spmmouseset.animal.mu = preset.mu(:);
end
if(isfield(preset,'grey'))
% can we open the file?
if ~spm_existfile(preset.grey)
% no - is it in the spmmouse tpm directory?
[gpth,gnm,gext,gfr] = spm_fileparts(preset.grey);
[wpth,wnm,wext,wfr] = spm_fileparts(preset.white);
[cpth,cnm,cext,cfr] = spm_fileparts(preset.csf);
% best just pretend we have nothing
preset = rmfield(preset,{'grey','white','csf'});
% try to find tpms
if spm_existfile(fullfile(spmmouseset.path,'tpm',[gnm gext]))
% yes - let's just update it
preset.grey = fullfile(spmmouseset.path,'tpm',[gnm gext gfr]);
% white and csf files probably in same place, let's
% take a chance ...
preset.white= fullfile(spmmouseset.path,'tpm',[wnm wext wfr]);
preset.csf = fullfile(spmmouseset.path,'tpm',[cnm cext cfr]);
elseif nargin == 0
% no - ask the user
if strcmpi(questdlg(sprintf('Couldn''t find \n"%s"\n\nWould you like to locate tissue probability maps now?', preset.grey), preset.name, 'Yes', 'No', 'Yes'),'yes')
[files,sts] = spm_select(3,'image','Select grey, white, csf TPMs');
if sts
preset.grey = deblank(files(1,:));
preset.white = deblank(files(2,:));
preset.csf = deblank(files(3,:));
% user will probably want to save this,
% let's just do it
try
save(filename, '-v6', '-struct', 'preset');
catch
warning('Couldn''t save amended preset file');
end
end
end
end
end
end
if isfield(preset,'grey')
spmmouseset.animal.tpm = char(...
preset.grey,...
preset.white,...
preset.csf); % Prior probability maps
end
adjustdefaults;
if nargin == 0
try
gfig = findobj('Tag','Graphics');
figure(gfig);
catch
fprintf(1,'Could not find SPM graphics window ! Is SPM loaded ?\n');
return;
end
% clear everything visible from graphics window
delete(findobj(get(gfig,'Children'),'flat','HandleVisibility','on'));
% clear callbacks
set(gfig,'KeyPressFcn','','WindowButtonDownFcn','','WindowButtonMotionFcn','','WindowButtonUpFcn','');
winscale = spm('WinScale');
tTitle = uicontrol(gfig,'Style','Text','Position',[20 800 560 40].*winscale,'String',spmmouseset.title,'FontSize',24,'BackgroundColor','w');
tName = uicontrol(gfig,'Style','Text','Position',[20 700 560 40].*winscale,'String',spmmouseset.animal.name,'FontSize',14,'BackgroundColor','w','FontWeight','bold','ForegroundColor','b');
uicontrol('Position',[20 760 148 30].*winscale,'String','Show Welcome Screen',...
'Callback','spmmouse;');
%uicontrol('Position',[180 760 148 30].*winscale,'String','Edit Preset',...
% 'Callback','spmmouse(''editpreset'');');
% display details of the loaded preset
axmip = axes('Position',[0.1 0.4 0.4 0.4]);
mip=load(char(preset.mipmat));
imagesc(rot90(mip.mask_all)); axis image off; colormap gray;
title('Preview of MIP template');
if(isfield(preset,'grey'))
strtpms = sprintf('TPMs:\n%s\n%s\n%s\n',preset.grey,preset.white,preset.csf);
else
strtpms = sprintf('No TPMs specified in preset.\n');
end
tInfo = uicontrol(gfig,'Style','Text','Position',[20 50 560 250].*winscale,'String','','FontSize',12,'BackgroundColor','w','FontWeight','bold');
set(tInfo, 'String', ...
{sprintf('CX %i CY %i CZ %i DX %i DY %i DZ %i scale %f %f %f', ...
mip.CXYZ, mip.DXYZ, mip.scale), ...
'',strtpms,'','preset file:',filename,'','Ready to go, use SPM as normal.',''});
end
%----------------------------------
function adjustdefaults(cmd)
% Set and unset small animal specific defaults for spatial processing
% FORMAT adjustdefaults('set')
% Override SPM (human brain sized) defaults with values suitable for
% images with smaller FOV. Previous defaults will be saved.
% FORMAT adjustdefaults('unset')
% Reset defaults to values before the last call to
% adjustdefaults('set'). Usually, this will be human brain sized
% defaults, except if adjustdefaults('set') has been called more than
% once.
persistent olddefs
global spmmouseset;
if nargin == 0
cmd = 'set';
end
% Defaults sections to be modified
%=======================================================================
defnames = {'realign','unwarp','coreg','normalise','preproc','smooth','stats'};
switch cmd,
case 'set'
try
for cdef = 1:numel(defnames)
olddefs.(defnames{cdef}) = spm_get_defaults(defnames{cdef});
end
newdefs = olddefs;
animal = spmmouseset.animal;
% now adjust all settings based on scale - all these numbers can be
% adjusted in the particular interfaces for each function, they are
% reasonable enough but not really worth adding a further fudge-factor
% modifying interface...
fixedscale = 0.01 * round(animal.scale * 100);
newdefs.realign.estimate.sep = 3*fixedscale;
newdefs.realign.estimate.fwhm = 4*fixedscale;
newdefs.unwarp.estimate.fwhm = 4*fixedscale;
newdefs.unwarp.estimate.basfcn = [12 12]*fixedscale;
newdefs.coreg.estimate.sep = fixedscale*[4 2];
newdefs.coreg.estimate.tol = [0.02 0.02 0.02 0.001 0.001 0.001 0.01 0.01 0.01 0.001 0.001 0.001];
newdefs.coreg.estimate.fwhm = 7*[fixedscale fixedscale]; % bug fix 22/7/09
newdefs.normalise.estimate.smosrc = 8*fixedscale;
newdefs.normalise.estimate.smoref = 0;
newdefs.normalise.estimate.regtype = 'none';
newdefs.normalise.estimate.cutoff = 25*fixedscale;
newdefs.normalise.write.bb = [[-6 -10 -10];[6 7 1]];
newdefs.normalise.write.vox = fixedscale*[2 2 2];
% for bias correction
allowedvals = [1,2,5,10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,Inf];
newdefs.preproc.ngaus = [3 2 2 4]'; % Gaussians per class
newdefs.preproc.warpco = 25*fixedscale;
newdefs.preproc.biasfwhm = allowedvals(find(allowedvals>=(60*fixedscale),1,'first'));
newdefs.preproc.fudge = .5;
newdefs.preproc.samp = 3*fixedscale;
newdefs.preproc.regtype = 'animal';
if(isfield(animal,'tpm'))
newdefs.preproc.tpm = cellstr(animal.tpm);
end
newdefs.smooth.fwhm = [8 8 8].*fixedscale;
newdefs.stats.results.volume.distmin = 8*fixedscale;
newdefs.stats.results.svc.distmin = 4*fixedscale;
newdefs.stats.results.mipmat = animal.mipmat;
catch
fprintf(1,'Error occured setting defaults in spmmouse :(\n');
return;
end
spm_get_defaults('animal', spmmouseset.animal);
for cdef = 1:numel(defnames)
spm_get_defaults(defnames{cdef},newdefs.(defnames{cdef}));
end
% Zoom defaults
%===============================================================
[olddefs.orthviews.zoom.fov olddefs.orthviews.zoom.res] = ...
spm_orthviews('ZoomMenu');
newdefs.orthviews.zoom.fov = [Inf 20 10 5 2 1];
newdefs.orthviews.zoom.res = [ .1 .05 .05 .025 .01 .01];
spm_orthviews('ZoomMenu',newdefs.orthviews.zoom.fov, newdefs.orthviews.zoom.res);
% VBM8 defaults
%===============================================================
try
olddefs.vbm8.opts = cg_vbm8_get_defaults('opts');
newdefs.vbm8.opts = olddefs.vbm8.opts;
newdefs.vbm8.opts.tpm = {fullfile(spm('dir'),'toolbox','Seg','TPM.nii')}; % TPM.nii
newdefs.vbm8.opts.ngaus = [3 2 2 3 4 2]; % Gaussians per class
newdefs.vbm8.opts.affreg = 'animal'; % Affine regularisation
newdefs.vbm8.opts.biasfwhm = allowedvals(find(allowedvals>=(60*fixedscale),1,'first')); % Bias FWHM
newdefs.vbm8.opts.samp = 3*fixedscale; % Sampling distance
cg_vbm8_get_defaults('opts',newdefs.vbm8.opts);
end
addpath(fullfile(spmmouseset.path,'replaced'),'-begin');
case 'unset',
if ~isempty(olddefs)
for cdef = 1:numel(defnames)
spm_get_defaults(defnames{cdef},olddefs.(defnames{cdef}));
end
spm_orthviews('ZoomMenu',olddefs.orthviews.zoom.fov, olddefs.orthviews.zoom.res);
if isfield(olddefs,'vbm8')
cg_vbm8_get_defaults('opts',olddefs.vbm8.opts);
end
end
spm_get_defaults('animal',[]);
rmpath(fullfile(spmmouseset.path,'replaced'));
end
|
github
|
philippboehmsturm/antx-master
|
tbx_cfg_spmmouse.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/spmmouse/tbx_cfg_spmmouse.m
| 4,675 |
utf_8
|
b22be77a04d0c4a276ccaf167b8ddb45
|
function cfg = tbx_cfg_spmmouse
% Adapted GUI for SPM Segment, New Segment and VBM8 including modified
% choices for bias regularisation and affine registration options. Although
% computation is done by standard SPM functions and the defaults are
% changed in the global defaults variable, the cfg_menu GUIs can not
% be altered in-place.
% No configurable defaults or paths will be adjusted here. This has to be
% done manually after SPM is started by calling spmmouse from MATLAB.
cfg = cfg_choice;
cfg.tag = 'animal';
cfg.name = 'Spatial processing (animals)';
cfg.help = {'This toolbox contains modified GUIs for SPM spatial processing of animal sized brains.'
'SPM functions that are not listed in this toolbox can be used from the normal menu.'};
% SPM Segment
cpreproc = spm_cfg_preproc;
cpreproc = cfg_menu_replace(cpreproc, 'biasfwhm',{...
'1mm cutoff', '2mm cutoff', '5mm cutoff', '10mm cutoff', '20mm cutoff',...
'30mm cutoff','40mm cutoff','50mm cutoff','60mm cutoff','70mm cutoff',...
'80mm cutoff','90mm cutoff','100mm cutoff','110mm cutoff','120mm cutoff',...
'130mm cutoff','140mm cutoff','150mm cutoff','No correction'},...
{1,2,5,10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,Inf});
cpreproc = cfg_menu_replace(cpreproc, 'regtype', ...
{
'No Affine Registration'
'ICBM space template - European brains'
'ICBM space template - East Asian brains'
'Average sized template'
'Animal template'
'No regularisation'
}', ...
{
''
'mni'
'eastern'
'subj'
'animal'
'none'
}');
cfg.values = {cpreproc};
% try New Segment
% Note: New Segment does not (yet) have configurable defaults
if exist(fullfile(spm('dir'),'toolbox','Seg'),'dir')
opwd = pwd;
try
cd(fullfile(spm('dir'),'toolbox','Seg'));
cpreproc8 = tbx_cfg_preproc8;
cpreproc8 = cfg_menu_replace(cpreproc8, 'biasfwhm',{...
'1mm cutoff', '2mm cutoff', '5mm cutoff', '10mm cutoff', '20mm cutoff',...
'30mm cutoff','40mm cutoff','50mm cutoff','60mm cutoff','70mm cutoff',...
'80mm cutoff','90mm cutoff','100mm cutoff','110mm cutoff','120mm cutoff',...
'130mm cutoff','140mm cutoff','150mm cutoff','No correction'},...
{1,2,5,10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,Inf});
cpreproc8 = cfg_menu_replace(cpreproc8, 'affreg', ...
{
'No Affine Registration'
'ICBM space template - European brains'
'ICBM space template - East Asian brains'
'Average sized template'
'Animal template'
'No regularisation'
}', ...
{
''
'mni'
'eastern'
'subj'
'animal'
'none'
}');
cfg.values = [cfg.values {cpreproc8}];
end
cd(opwd);
end
% try VBM8 New Segment
if exist(fullfile(spm('dir'),'toolbox','vbm8'),'dir')
opwd = pwd;
try
cd(fullfile(spm('dir'),'toolbox','Seg'));
cvbm8 = tbx_cfg_vbm8;
% Only want to copy estwrite branch
tropts = cfg_tropts([], 0, inf, 0, inf, true);
id = list(cvbm8,cfg_findspec({{'tag','estwrite'}}),tropts);
cvbm8 = subsref(cvbm8,id{1});
cvbm8 = cfg_menu_replace(cvbm8, 'biasfwhm',{...
'1mm cutoff', '2mm cutoff', '5mm cutoff', '10mm cutoff', '20mm cutoff',...
'30mm cutoff','40mm cutoff','50mm cutoff','60mm cutoff','70mm cutoff',...
'80mm cutoff','90mm cutoff','100mm cutoff','110mm cutoff','120mm cutoff',...
'130mm cutoff','140mm cutoff','150mm cutoff','No correction'},...
{1,2,5,10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,Inf});
cvbm8 = cfg_menu_replace(cvbm8, 'affreg', ...
{
'No Affine Registration'
'ICBM space template - European brains'
'ICBM space template - East Asian brains'
'Average sized template'
'Animal template'
'No regularisation'
}', ...
{
''
'mni'
'eastern'
'subj'
'animal'
'none'
}');
cfg.values = [cfg.values {cvbm8}];
end
cd(opwd);
end
function cfg = cfg_menu_replace(cfg, tag, labels, values)
tropts = cfg_tropts([], 0, inf, 0, inf, true);
id = list(cfg,cfg_findspec({{'tag',tag}}),tropts);
citem = subsref(cfg,id{1});
citem.labels = labels;
citem.values = values;
cfg = subsasgn(cfg, id{1}, citem);
|
github
|
philippboehmsturm/antx-master
|
spm_klaff.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/DARTEL/spm_klaff.m
| 8,314 |
utf_8
|
0f0299ab4f49e2fbfa31b23c2f939ae1
|
function M = spm_klaff(Nf, Ng)
% Affine registration by minimising Kullback-Leibler Divergence
% FORMAT M = spm_klaff(Nf,Ng)
% Nf - NIfTI handle for one image
% Ng - Nifti handle for the other. If not passed, then
% spm*/toolbox/Seg/TPM.nii is used.
% M - The voxel-for-voxel affine transform
%
% The images that are matched are tissue probability maps, in the
% same form as spm/toolbox/Seg/TPM.nii or the Template files
% generated by DARTEL. To save some memory, no more than three
% (GM, WM and other) classes are matched together.
%
% Note that the code is very memory hungry because it stores a
% load of image gradients. If it doesn't work because of this,
% the recommandation is to buy a more powerful computer.
%________________________________________________________
% (c) Wellcome Trust Centre for NeuroImaging (2009)
% John Ashburner
% $Id: spm_klaff.m 4148 2011-01-04 16:49:23Z guillaume $
if nargin<2, Ng = fullfile(spm('Dir'),'toolbox','Seg','TPM.nii'); end
if ischar(Nf), Nf = nifti(Nf); end
if ischar(Ng), Ng = nifti(Ng); end
deg = [2 2 2 1 1 1]; % Degree of interpolation to use
df = [size(Nf.dat),1,1]; % Dimensions of data
dg = [size(Ng.dat),1,1]; % Dimensions of data
nd = min([df(4)+1,dg(4)]); % Use the first nd volumes.
nd = min(nd,3); % Just use GM, WM & other
g0 = loaddat(Ng,nd);
% Data structure for template
c = cell(1,nd);
for k=1:nd,
c{k} = zeros(dg(1:3),'single');
end
g = struct('g',c,'dx',c,'dy',c,'dz',c);
clear c
[x,y,zz] = ndgrid(1:dg(1),1:dg(2),0);
for k=1:nd,
c = spm_bsplinc(g0{k},deg);
for z=1:dg(3),
[tmp,dx,dy,dz] = spm_bsplins(c,x,y,z+zz,deg);
g(k).g(:,:,z) = single(exp(tmp));
g(k).dx(:,:,z) = single(dx);
g(k).dy(:,:,z) = single(dy);
g(k).dz(:,:,z) = single(dz);
end
clear c tmp dx dy dz
end
clear g0
% Compute derivatives (see Eqn 12 of Ashburner & Friston (2009)).
for z=1:dg(3),
sx = zeros(dg(1:2),'single');
sy = zeros(dg(1:2),'single');
sz = zeros(dg(1:2),'single');
for k=1:nd,
tmp = g(k).g(:,:,z);
sx = sx + g(k).dx(:,:,z).*tmp;
sy = sy + g(k).dy(:,:,z).*tmp;
sz = sz + g(k).dz(:,:,z).*tmp;
end
for k=1:nd,
tmp = g(k).g(:,:,z);
g(k).dx(:,:,z) = (g(k).dx(:,:,z) - sx).*tmp;
g(k).dy(:,:,z) = (g(k).dy(:,:,z) - sy).*tmp;
g(k).dz(:,:,z) = (g(k).dz(:,:,z) - sz).*tmp;
end
clear tmp sx sy sz
drawnow
end
f = loaddat(Nf,nd);
for k=1:nd,
f{k} = spm_bsplinc(double(f{k}),deg);
end
M = Nf.mat\Ng.mat;
spm_plot_convergence('Init','KL Divergence Affine Registration',...
'RMS Change', 'Iteration');
for it=1:64,
% if it==1,
AA = zeros(12); % Fisher Information matrix
% end
Ab = zeros(12,1); % 1st derivatives
kl = 0;
nv = 0;
for z=1:dg(3), % Loop over slices
% Coordinates to sample f from
x1 = M(1,1)*x + M(1,2)*y + M(1,3)*z + M(1,4);
y1 = M(2,1)*x + M(2,2)*y + M(2,3)*z + M(2,4);
z1 = M(3,1)*x + M(3,2)*y + M(3,3)*z + M(3,4);
% These need to be in range, so create a mask
msk = x1>=1 & x1<=df(1) &...
y1>=1 & y1<=df(2) &...
z1>=1 & z1<=df(3);
if any(msk(:)),
x1 = x1(msk);
y1 = y1(msk);
z1 = z1(msk);
% Original coordinates, for use later
X = {x(msk);y(msk);z*ones(size(x1));ones(size(x1))};
G = cell(nd,1); % Masked g
D = cell(nd,3); % Masked gradients of g
F = cell(nd,1); % Masked f
for k=1:nd,
F{k} = exp(spm_bsplins(f{k},x1,y1,z1,deg));
tmp = g(k).g(:,:,z); G{k} = tmp(msk);
tmp = g(k).dx(:,:,z); D{k,1} = tmp(msk);
tmp = g(k).dy(:,:,z); D{k,2} = tmp(msk);
tmp = g(k).dz(:,:,z); D{k,3} = tmp(msk);
end
% Re-normalise so that values sum to 1.
sf = zeros(size(F{1}));
for k=1:nd, sf = sf + F{k}; end
for k=1:nd, F{k} = F{k}./sf; end
for k=1:nd,
DG = cell(3,4); % dg/dm = dg/dx * dx/dm
for i=1:3,
for j=1:4,
DG{i,j} = X{j}.*D{k,i};
end
end
DG = DG(:);
% Derivatives were derived using MATLAB symbolic toolbox.
% First derivatives:
% maple diff(f1(x1,x2)*log(f1(x1,x2)/g1) + g1*log(g1/f1(x1,x2)),x1)
% This gives...
% diff(f1(x1,x2),x1)*log(f1(x1,x2)/g1)
% +diff(f1(x1,x2),x1)
% -g1*diff(f1(x1,x2),x1)/f1(x1,x2)
% Because the gradients sum to zero at each point, the first
% derivatives can be simplified to...
% -diff(f1(x1,x2),x1)*(log(g1/f1(x1,x2))+g1/f1(x1,x2))
%
% Expectation of second derivatives:
% maple diff(f1(x1,x2)*log(f1(x1,x2)/g1) + g1*log(g1/f1(x1,x2)),x1,x2)
% This gives...
% diff(f1(x1,x2),x1,x2)*log(f1(x1,x2)/g1)...
% +diff(f1(x1,x2),x1)*diff(f1(x1,x2),x2)/f1(x1,x2)...
% +diff(f1(x1,x2),x1,x2)...
% -g1*diff(f1(x1,x2),x1,x2)/f1(x1,x2)...
% +g1*diff(f1(x1,x2),x1)/f1(x1,x2)^2*diff(f1(x1,x2),x2)
% For computing expectations, g1/f1(x1,x2) was set to 1.
% This simplification loses terms requiring diff(f1(x1,x2),x1,x2)
% giving nicely positive definite second derivatives.
% 2*diff(f1(x1,x2),x1)*diff(f1(x1,x2),x2)/f1(x1,x2)
%
% Note that the workings in maple swapped around g and f.
tmp = F{k}./G{k};
ltmp = log(tmp);
tmp = -(ltmp + tmp);
kl = kl + sum((F{k}-G{k}).*ltmp);
nv = nv + numel(ltmp);
for i=1:12,
Ab(i) = Ab(i) + sum(DG{i}.*tmp);
% if it==1,
% Fisher information matrix could use the same data
% (irrespective of iteration number), so theoretically
% only needs to be computed the once. However, the
% amount of overlap changes from iteration to iteration
% so I have chosen to recompute it each time.
for j=1:12,
AA(i,j) = AA(i,j) + 2*sum(DG{i}.*DG{j}./G{k});
end
% end
drawnow;
end
end
end
end
% The derivatives are for an optimisation that minimises
% D_{KL}(g(M x))||f'(x)) + D_{KL}(f'(x)||g(M x)))
% The actual transform update we want is to match
% f'(M^{-1} x)) with g(x), so an inverse is needed.
% That was for the increment, whereby f'(x) = f(M_o x).
% Therefore, for the whole thing, we are matching
% f(M_o M^{-1} x) with g(x), so M_n = M_o M^{-1}, where
% M = I - dM. In the MATLAB code, M_n = M_o (I-dM) is
% by M = M/(eye(4) - dM);
dM = [reshape(AA\Ab,[3,4]); 0 0 0 0];
%M = M/(eye(4) - dM); % Theoretically correct according to LM-algorithm
%M = M*(eye(4) + dM); % Another possibility
M = M*real(expm(dM)); % Forces the transform to have non-neg Jacobian
fprintf('%3d %15g %15g\n', it, sqrt(sum(dM(:).^2)), kl/nv);
spm_plot_convergence('Set', sqrt(sum(dM(:).^2)));
if sum(dM(:).^2) < 1e-7, break; end
end
spm_plot_convergence('Clear');
%________________________________________________________
%________________________________________________________
function f = loaddat(N,d4)
% Load the first nd-1 volumes of the image, and create the
% last volume by subtracting the sum of the others from 1.
% Then take the logarithm.
d = size(N.dat);
d(4) = d4;
f = cell(1,d4);
fe = ones(d(1:3),'single');
tol = 1e-6;
for k=1:d(4)-1,
tmp = single(N.dat(:,:,:,k));
tmp = max(tmp,tol);
fe = fe - tmp;
f{k} = tmp;
end
fe = max(fe,tol);
f{end} = fe;
for k=1:d(4)-1, fe = fe + f{k}; end
for k=1:d(4), f{k} = log(f{k}./fe); end
%________________________________________________________
|
github
|
philippboehmsturm/antx-master
|
spm_dartel_norm_fun.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/DARTEL/spm_dartel_norm_fun.m
| 10,295 |
utf_8
|
63e79a297027d2f2790b757b50bede30
|
function out = spm_dartel_norm_fun(job)
% Spatially normalise and smooth fMRI/PET data to MNI space, using DARTEL flow fields
% FORMAT out = spm_dartel_norm_fun(job)
% job - a structure generated by the configuration file
% job.template - DARTEL template for aligning to MNI space
% job.subj(n) - Subject n
% subj(n).flowfield - DARTEL flow field
% subj(n).images - Images for this subject
% job.vox - Voxel sizes for spatially normalised images
% job.bb - Bounding box for spatially normalised images
% job.preserve - How to transform
% 0 = preserve concentrations
% 1 = preserve integral (cf "modulation")
%
% Normally, DARTEL generates warped images that align with the average-
% shaped template. This routine includes an initial affine regisration
% of the template (the final one generated by DARTEL), with the TPM data
% released with SPM.
%
% "Smoothed" (blurred) spatially normalised images are generated in such a
% way that the original signal is preserved. Normalised images are
% generated by a "pushing" rather than a "pulling" (the usual) procedure.
% Note that trilinear interpolation is used, and no masking is done. It
% is therefore essential that the images are realigned and resliced
% before they are spatially normalised. Alternatively, contrast images
% generated from unsmoothed native-space fMRI/PET data can be spatially
% normalised for a 2nd level analysis.
%
% Two "preserve" options are provided. One of them should do the
% equavalent of generating smoothed "modulated" spatially normalised
% images. The other does the equivalent of smoothing the modulated
% normalised fMRI/PET, and dividing by the smoothed Jacobian determinants.
%
%__________________________________________________________________________
% Copyright (C) 2009 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_dartel_norm_fun.m 4194 2011-02-05 18:08:06Z ged $
% Hard coded stuff, that should maybe be customisable
K = 6;
tpm = fullfile(spm('Dir'),'toolbox','Seg','TPM.nii');
Mmni = spm_get_space(tpm);
% DARTEL template
if ~isempty(job.template{1})
Nt = nifti(job.template{1});
do_aff = true;
else
Nt = nifti(tpm);
do_aff = false;
end
% Deal with desired bounding box and voxel sizes.
%--------------------------------------------------------------------------
bb = job.bb;
vox = job.vox;
Mt = Nt.mat;
dimt = size(Nt.dat);
if any(isfinite(bb(:))) || any(isfinite(vox)),
[bb0 vox0] = spm_get_bbox(Nt, 'old');
msk = ~isfinite(vox); vox(msk) = vox0(msk);
msk = ~isfinite(bb); bb(msk) = bb0(msk);
bb = sort(bb);
vox = abs(vox);
% Adjust bounding box slightly - so it rounds to closest voxel.
bb(:,1) = round(bb(:,1)/vox(1))*vox(1);
bb(:,2) = round(bb(:,2)/vox(2))*vox(2);
bb(:,3) = round(bb(:,3)/vox(3))*vox(3);
dim = round(diff(bb)./vox+1);
of = -vox.*(round(-bb(1,:)./vox)+1);
mat = [vox(1) 0 0 of(1) ; 0 vox(2) 0 of(2) ; 0 0 vox(3) of(3) ; 0 0 0 1];
if det(Mt(1:3,1:3)) < 0,
mat = mat*[-1 0 0 dim(1)+1; 0 1 0 0; 0 0 1 0; 0 0 0 1];
end
else
dim = dimt(1:3);
mat = Mt;
end
if isfield(job.data,'subj') || isfield(job.data,'subjs'),
if do_aff
[pth,nam,ext] = fileparts(Nt.dat.fname);
if exist(fullfile(pth,[nam '_2mni.mat']))
load(fullfile(pth,[nam '_2mni.mat']),'mni');
else
% Affine registration of DARTEL Template with MNI space.
%--------------------------------------------------------------------------
fprintf('** Affine registering "%s" with MNI space **\n', nam);
clear mni
mni.affine = Mmni/spm_klaff(Nt,tpm);
mni.code = 'MNI152';
save(fullfile(pth,[nam '_2mni.mat']),'mni');
end
M = mat\mni.affine/Mt;
%M = mat\Mmni*inv(spm_klaff(Nt,tpm))*inv(Mt);
mat_intent = mni.code;
else
M = mat\eye(4);
mat_intent = 'Aligned';
end
fprintf('\n');
if isfield(job.data,'subjs')
% Re-order data
%--------------------------------------------------------------------------
subjs = job.data.subjs;
subj = struct('flowfield',cell(numel(subjs.flowfields),1),...
'images', cell(numel(subjs.flowfields),1));
for i=1:numel(subj)
subj(i).flowfield = {subjs.flowfields{i}};
subj(i).images = cell(numel(subjs.images),1);
for j=1:numel(subjs.images),
subj(i).images{j} = subjs.images{j}{i};
end
end
else
subj = job.data.subj;
end
% Loop over subjects
%--------------------------------------------------------------------------
out = cell(1,numel(subj));
for i=1:numel(subj),
% Spatially normalise data from this subject
[pth,nam,ext] = fileparts(subj(i).flowfield{1});
fprintf('** "%s" **\n', nam);
out{i} = deal_with_subject(subj(i).flowfield,subj(i).images,K, mat,dim,M,job.preserve,job.fwhm,mat_intent);
end
if isfield(job.data,'subjs'),
out1 = out;
out = cell(numel(subj),numel(subjs.images));
for i=1:numel(subj),
for j=1:numel(subjs.images),
out{i,j} = out1{i}{j};
end
end
end
end
%__________________________________________________________________________
%__________________________________________________________________________
function out = deal_with_subject(Pu,PI,K,mat,dim,M,jactransf,fwhm,mat_intent)
% Generate deformation, which is the inverse of the usual one (it is for "pushing"
% rather than the usual "pulling"). This deformation is affine transformed to
% allow for different voxel sizes and bounding boxes, and also to incorporate
% the affine mapping between MNI space and the population average shape.
%--------------------------------------------------------------------------
NU = nifti(Pu{1});
M = M*NU.mat;
y0 = spm_dartel_integrate(NU.dat,[0 1], K);
y = zeros(size(y0),'single');
y(:,:,:,1) = M(1,1)*y0(:,:,:,1) + M(1,2)*y0(:,:,:,2) + M(1,3)*y0(:,:,:,3) + M(1,4);
y(:,:,:,2) = M(2,1)*y0(:,:,:,1) + M(2,2)*y0(:,:,:,2) + M(2,3)*y0(:,:,:,3) + M(2,4);
y(:,:,:,3) = M(3,1)*y0(:,:,:,1) + M(3,2)*y0(:,:,:,2) + M(3,3)*y0(:,:,:,3) + M(3,4);
y0 = y;
clear y
odm = zeros(1,3);
oM = zeros(4,4);
out = cell(1,numel(PI));
for m=1:numel(PI),
% Generate headers etc for output images
%----------------------------------------------------------------------
[pth,nam,ext,num] = spm_fileparts(PI{m});
NI = nifti(fullfile(pth,[nam ext]));
NO = NI;
if jactransf,
if fwhm==0,
NO.dat.fname=fullfile(pth,['mw' nam ext]);
else
NO.dat.fname=fullfile(pth,['smw' nam ext]);
end
NO.dat.scl_slope = 1.0;
NO.dat.scl_inter = 0.0;
NO.dat.dtype = 'float32-le';
else
if fwhm==0,
NO.dat.fname=fullfile(pth,['w' nam ext]);
else
NO.dat.fname=fullfile(pth,['sw' nam ext]);
end
end
NO.dat.dim = [dim NI.dat.dim(4:end)];
NO.mat = mat;
NO.mat0 = mat;
NO.mat_intent = mat_intent;
NO.mat0_intent = mat_intent;
if fwhm==0,
NO.descrip = 'DARTEL normed';
else
NO.descrip = sprintf('Smoothed (%gx%gx%g) DARTEL normed',fwhm);
end
out{m} = NO.dat.fname;
NO.extras = [];
create(NO);
% Smoothing settings
vx = sqrt(sum(mat(1:3,1:3).^2));
krn = max(fwhm./vx,0.1);
% Loop over volumes within the file
%----------------------------------------------------------------------
fprintf('%s',nam); drawnow;
for j=1:size(NI.dat,4),
% Check if it is a DARTEL "imported" image to normalise
if sum(sum((NI.mat - NU.mat ).^2)) < 0.0001 && ...
sum(sum((NI.mat0 - NU.mat0).^2)) < 0.0001,
% No affine transform necessary
M = eye(4);
dm = [size(NI.dat),1,1,1,1];
y = y0;
else
% Need to resample the mapping by an affine transform
% so that it maps from voxels in the native space image
% to voxels in the spatially normalised image.
%--------------------------------------------------------------
M0 = NI.mat;
if isfield(NI,'extras') && isfield(NI.extras,'mat'),
M1 = NI.extras.mat;
if size(M1,3) >= j && sum(sum(M1(:,:,j).^2)) ~=0,
M0 = M1(:,:,j);
end
end
M = NU.mat0\M0;
dm = [size(NI.dat),1,1,1,1];
if ~all(dm(1:3)==odm) || ~all(M(:)==oM(:)),
% Generate new deformation (if needed)
y = zeros([dm(1:3),3],'single');
for d=1:3,
yd = y0(:,:,:,d);
for x3=1:size(y,3),
y(:,:,x3,d) = single(spm_slice_vol(yd,M*spm_matrix([0 0 x3]),dm(1:2),[1 NaN]));
end
end
end
end
odm = dm(1:3);
oM = M;
% Write the warped data for this time point.
%------------------------------------------------------------------
for k=1:size(NI.dat,5),
for l=1:size(NI.dat,6),
f = single(NI.dat(:,:,:,j,k,l));
if ~jactransf,
% Unmodulated - note the slightly novel procedure
[f,c] = dartel3('push',f,y,dim);
spm_smooth(f,f,krn); % Side effects
spm_smooth(c,c,krn); % Side effects
f = f./(c+0.001); % I don't like it, but it may stop a few emails.
else
% Modulated, by pushing
scal = abs(det(NI.mat(1:3,1:3))/det(NO.mat(1:3,1:3))); % Account for vox sizes
f = dartel3('push',f,y,dim)*scal;
spm_smooth(f,f,krn); % Side effects
end
NO.dat(:,:,:,j,k,l) = f;
fprintf('\t%d,%d,%d', j,k,l); drawnow;
end
end
end
fprintf('\n'); drawnow;
end
%__________________________________________________________________________
|
github
|
philippboehmsturm/antx-master
|
tbx_cfg_dartel.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/DARTEL/tbx_cfg_dartel.m
| 65,076 |
utf_8
|
da29ad1825a2e216ba03f7c83d417021
|
function dartel = tbx_cfg_dartel
% Configuration file for toolbox 'DARTEL Tools'
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: tbx_cfg_dartel.m 4650 2012-02-09 08:14:54Z volkmar $
if ~isdeployed, addpath(fullfile(spm('dir'),'toolbox','DARTEL')); end
% ---------------------------------------------------------------------
% matnames Parameter Files
% ---------------------------------------------------------------------
matnames = cfg_files;
matnames.tag = 'matnames';
matnames.name = 'Parameter Files';
matnames.help = {'Select ''_sn.mat'' files containing the spatial transformation and segmentation parameters. Rigidly aligned versions of the image that was segmented will be generated. The image files used by the segmentation may have moved. If they have, then (so the import can find them) ensure that they are either in the output directory, or the current working directory.'};
matnames.filter = 'mat';
matnames.ufilter = '.*seg_sn\.mat$';
matnames.num = [1 Inf];
% ---------------------------------------------------------------------
% odir Output Directory
% ---------------------------------------------------------------------
odir = cfg_files;
odir.tag = 'odir';
odir.name = 'Output Directory';
odir.help = {'Select the directory where the resliced files should be written.'};
odir.filter = 'dir';
odir.ufilter = '.*';
odir.num = [1 1];
% ---------------------------------------------------------------------
% bb Bounding box
% ---------------------------------------------------------------------
bb = cfg_entry;
bb.tag = 'bb';
bb.name = 'Bounding box';
bb.val = {[NaN NaN NaN
NaN NaN NaN]};
bb.help = {'The bounding box (in mm) of the volume that is to be written (relative to the anterior commissure). Non-finite values will be replaced by the bounding box of the tissue probability maps used in the segmentation.'};
bb.strtype = 'e';
bb.num = [2 3];
% ---------------------------------------------------------------------
% vox Voxel size
% ---------------------------------------------------------------------
vox = cfg_entry;
vox.tag = 'vox';
vox.name = 'Voxel size';
vox.val = {1.5};
vox.help = {'The (isotropic) voxel sizes of the written images. A non-finite value will be replaced by the average voxel size of the tissue probability maps used by the segmentation.'};
vox.strtype = 'e';
vox.num = [1 1];
% ---------------------------------------------------------------------
% image Image option
% ---------------------------------------------------------------------
image = cfg_menu;
image.tag = 'image';
image.name = 'Image option';
image.val = {0};
image.help = {'A resliced version of the original image can be produced, which may have various procedures applied to it. All options will rescale the images so that the mean of the white matter intensity is set to one. The ``skull stripped'''' versions are the images simply scaled by the sum of the grey and white matter probabilities.'};
image.labels = {
'Original'
'Bias Corrected'
'Skull-Stripped'
'Bias Corrected and Skull-stripped'
'None'
}';
image.values = {1 3 5 7 0};
% ---------------------------------------------------------------------
% GM Grey Matter
% ---------------------------------------------------------------------
GM = cfg_menu;
GM.tag = 'GM';
GM.name = 'Grey Matter';
GM.val = {1};
GM.help = {'Produce a resliced version of this tissue class?'};
GM.labels = {
'Yes'
'No'
}';
GM.values = {1 0};
% ---------------------------------------------------------------------
% WM White Matter
% ---------------------------------------------------------------------
WM = cfg_menu;
WM.tag = 'WM';
WM.name = 'White Matter';
WM.val = {1};
WM.help = {'Produce a resliced version of this tissue class?'};
WM.labels = {
'Yes'
'No'
}';
WM.values = {1 0};
% ---------------------------------------------------------------------
% CSF CSF
% ---------------------------------------------------------------------
CSF = cfg_menu;
CSF.tag = 'CSF';
CSF.name = 'CSF';
CSF.val = {0};
CSF.help = {'Produce a resliced version of this tissue class?'};
CSF.labels = {
'Yes'
'No'
}';
CSF.values = {1 0};
% ---------------------------------------------------------------------
% initial Initial Import
% ---------------------------------------------------------------------
initial = cfg_exbranch;
initial.tag = 'initial';
initial.name = 'Initial Import';
initial.val = {matnames odir bb vox image GM WM CSF };
initial.help = {'Images first need to be imported into a form that DARTEL can work with. If the default segmentation is used (ie the Segment button), then this involves taking the results of the segmentation (*_seg_sn.mat)/* \cite{ashburner05} */, in order to have rigidly aligned tissue class images. Typically, there would be imported grey matter and white matter images, but CSF images can also be included. The subsequent DARTEL alignment will then attempt to nonlinearly register these tissue class images together. If the new segmentation routine is used (from the toolbox), then this includes the option to generate ``imported'''' tissue class images. This means that a seperate importing step is not needed for it.'};
initial.prog = @spm_dartel_import;
initial.vout = @vout_initial_import;
% ---------------------------------------------------------------------
% images Images
% ---------------------------------------------------------------------
images1 = cfg_files;
images1.tag = 'images';
images1.name = 'Images';
images1.help = {'Select a set of imported images of the same type to be registered by minimising a measure of difference from the template.'};
images1.filter = 'image';
images1.ufilter = '^r.*';
images1.num = [1 Inf];
% ---------------------------------------------------------------------
% images Images
% ---------------------------------------------------------------------
images = cfg_repeat;
images.tag = 'images';
images.name = 'Images';
images.help = {'Select the images to be warped together. Multiple sets of images can be simultaneously registered. For example, the first set may be a bunch of grey matter images, and the second set may be the white matter images of the same subjects.'};
images.values = {images1 };
images.num = [1 Inf];
% ---------------------------------------------------------------------
% template Template basename
% ---------------------------------------------------------------------
template = cfg_entry;
template.tag = 'template';
template.name = 'Template basename';
template.val = {'Template'};
template.help = {'Enter the base for the template name. Templates generated at each outer iteration of the procedure will be basename_1.nii, basename_2.nii etc. If empty, then no template will be saved. Similarly, the estimated flow-fields will have the basename appended to them.'};
template.strtype = 's';
template.num = [1 Inf];
% ---------------------------------------------------------------------
% rform Regularisation Form
% ---------------------------------------------------------------------
rform = cfg_menu;
rform.tag = 'rform';
rform.name = 'Regularisation Form';
rform.val = {0};
rform.help = {'The registration is penalised by some ``energy'''' term. Here, the form of this energy term is specified. Three different forms of regularisation can currently be used.'};
rform.labels = {
'Linear Elastic Energy'
'Membrane Energy'
'Bending Energy'
}';
rform.values = {0 1 2};
% ---------------------------------------------------------------------
% its Inner Iterations
% ---------------------------------------------------------------------
its = cfg_menu;
its.tag = 'its';
its.name = 'Inner Iterations';
its.val = {3};
its.help = {'The number of Gauss-Newton iterations to be done within this outer iteration. After this, new average(s) are created, which the individual images are warped to match.'};
its.labels = {
'1'
'2'
'3'
'4'
'5'
'6'
'7'
'8'
'9'
'10'
}';
its.values = {1 2 3 4 5 6 7 8 9 10};
% ---------------------------------------------------------------------
% rparam Reg params
% ---------------------------------------------------------------------
rparam = cfg_entry;
rparam.tag = 'rparam';
rparam.name = 'Reg params';
rparam.val = {[0.1 0.01 0.001]};
rparam.help = {
'For linear elasticity, the parameters are mu, lambda and id. For membrane energy, the parameters are lambda, unused and id.id is a term for penalising absolute displacements, and should therefore be small. For bending energy, the parameters are lambda, id1 and id2, and the regularisation is by (-lambda*Laplacian + id1)^2 + id2.'
'Use more regularisation for the early iterations so that the deformations are smooth, and then use less for the later ones so that the details can be better matched.'
}';
rparam.strtype = 'e';
rparam.num = [1 3];
% ---------------------------------------------------------------------
% K Time Steps
% ---------------------------------------------------------------------
K = cfg_menu;
K.tag = 'K';
K.name = 'Time Steps';
K.val = {6};
K.help = {'The number of time points used for solving the partial differential equations. A single time point would be equivalent to a small deformation model. Smaller values allow faster computations, but are less accurate in terms of inverse consistency and may result in the one-to-one mapping breaking down. Earlier iteration could use fewer time points, but later ones should use about 64 (or fewer if the deformations are very smooth).'};
K.labels = {
'1'
'2'
'4'
'8'
'16'
'32'
'64'
'128'
'256'
'512'
}';
K.values = {0 1 2 3 4 5 6 7 8 9};
% ---------------------------------------------------------------------
% slam Smoothing Parameter
% ---------------------------------------------------------------------
slam = cfg_menu;
slam.tag = 'slam';
slam.name = 'Smoothing Parameter';
slam.val = {1};
slam.help = {'A LogOdds parameterisation of the template is smoothed using a multi-grid scheme. The amount of smoothing is determined by this parameter.'};
slam.labels = {
'None'
'0.5'
'1'
'2'
'4'
'8'
'16'
'32'
}';
slam.values = {0 0.5 1 2 4 8 16 32};
% ---------------------------------------------------------------------
% param Outer Iteration
% ---------------------------------------------------------------------
param1 = cfg_branch;
param1.tag = 'param';
param1.name = 'Outer Iteration';
param1.val = {its rparam K slam };
param1.help = {'Different parameters can be specified for each outer iteration. Each of them warps the images to the template, and then regenerates the template from the average of the warped images. Multiple outer iterations should be used for more accurate results, beginning with a more coarse registration (more regularisation) then ending with the more detailed registration (less regularisation).'};
val = cell(1,6);
param = param1;
param.val{1}.val{1} = 3; % iits
param.val{2}.val{1} = [4 2 1e-6]; % rparam
param.val{3}.val{1} = 0; % K
param.val{4}.val{1} = 16;
val{1} = param;
param.val{1}.val{1} = 3; % iits
param.val{2}.val{1} = [2 1 1e-6]; % rparam
param.val{3}.val{1} = 0; % K
param.val{4}.val{1} = 8;
val{2} = param;
param.val{1}.val{1} = 3; % iits
param.val{2}.val{1} = [1 0.5 1e-6]; % rparam
param.val{3}.val{1} = 1; % K
param.val{4}.val{1} = 4;
val{3} = param;
param.val{1}.val{1} = 3; % iits
param.val{2}.val{1} = [0.5 0.25 1e-6]; % rparam
param.val{3}.val{1} = 2; % K
param.val{4}.val{1} = 2;
val{4} = param;
param.val{1}.val{1} = 3; % iits
param.val{2}.val{1} = [0.25 0.125 1e-6]; % rparam
param.val{3}.val{1} = 4; % K
param.val{4}.val{1} = 1;
val{5} = param;
param.val{1}.val{1} = 3; % iits
param.val{2}.val{1} = [0.25 0.125 1e-6]; % rparam
param.val{3}.val{1} = 6; % K
param.val{4}.val{1} = 0.5;
val{6} = param;
% ---------------------------------------------------------------------
% param Outer Iterations
% ---------------------------------------------------------------------
param = cfg_repeat;
param.tag = 'param';
param.name = 'Outer Iterations';
param.val = val;
param.help = {'The images are averaged, and each individual image is warped to match this average. This is repeated a number of times.'};
param.values = {param1};
param.num = [1 Inf];
% ---------------------------------------------------------------------
% lmreg LM Regularisation
% ---------------------------------------------------------------------
lmreg = cfg_entry;
lmreg.tag = 'lmreg';
lmreg.name = 'LM Regularisation';
lmreg.val = {0.01};
lmreg.help = {'Levenberg-Marquardt regularisation. Larger values increase the the stability of the optimisation, but slow it down. A value of zero results in a Gauss-Newton strategy, but this is not recommended as it may result in instabilities in the FMG.'};
lmreg.strtype = 'e';
lmreg.num = [1 1];
% ---------------------------------------------------------------------
% cyc Cycles
% ---------------------------------------------------------------------
cyc = cfg_menu;
cyc.tag = 'cyc';
cyc.name = 'Cycles';
cyc.val = {3};
cyc.help = {'Number of cycles used by the full multi-grid matrix solver. More cycles result in higher accuracy, but slow down the algorithm. See Numerical Recipes for more information on multi-grid methods.'};
cyc.labels = {
'1'
'2'
'3'
'4'
'5'
'6'
'7'
'8'
}';
cyc.values = {1 2 3 4 5 6 7 8};
% ---------------------------------------------------------------------
% its Iterations
% ---------------------------------------------------------------------
its = cfg_menu;
its.tag = 'its';
its.name = 'Iterations';
its.val = {3};
its.help = {'Number of relaxation iterations performed in each multi-grid cycle. More iterations are needed if using ``bending energy'''' regularisation, because the relaxation scheme only runs very slowly. See the chapter on solving partial differential equations in Numerical Recipes for more information about relaxation methods.'};
its.labels = {
'1'
'2'
'3'
'4'
'5'
'6'
'7'
'8'
}';
its.values = {1 2 3 4 5 6 7 8};
% ---------------------------------------------------------------------
% optim Optimisation Settings
% ---------------------------------------------------------------------
optim = cfg_branch;
optim.tag = 'optim';
optim.name = 'Optimisation Settings';
optim.val = {lmreg cyc its };
optim.help = {'Settings for the optimisation. If you are unsure about them, then leave them at the default values. Optimisation is by repeating a number of Levenberg-Marquardt iterations, in which the equations are solved using a full multi-grid (FMG) scheme. FMG and Levenberg-Marquardt are both described in Numerical Recipes (2nd edition).'};
% ---------------------------------------------------------------------
% settings Settings
% ---------------------------------------------------------------------
settings = cfg_branch;
settings.tag = 'settings';
settings.name = 'Settings';
settings.val = {template rform param optim };
settings.help = {'Various settings for the optimisation. The default values should work reasonably well for aligning tissue class images together.'};
% ---------------------------------------------------------------------
% warp Run DARTEL (create Templates)
% ---------------------------------------------------------------------
warp = cfg_exbranch;
warp.tag = 'warp';
warp.name = 'Run DARTEL (create Templates)';
warp.val = {images settings };
warp.check = @check_dartel_template;
warp.help = {'Run the DARTEL nonlinear image registration procedure. This involves iteratively matching all the selected images to a template generated from their own mean. A series of Template*.nii files are generated, which become increasingly crisp as the registration proceeds.'};
warp.prog = @spm_dartel_template;
warp.vout = @vout_dartel_template;
% ---------------------------------------------------------------------
% images Images
% ---------------------------------------------------------------------
images1 = cfg_files;
images1.tag = 'images';
images1.name = 'Images';
images1.help = {'Select a set of imported images of the same type to be registered by minimising a measure of difference from the template.'};
images1.filter = 'image';
images1.ufilter = '^r.*';
images1.num = [1 Inf];
% ---------------------------------------------------------------------
% images Images
% ---------------------------------------------------------------------
images = cfg_repeat;
images.tag = 'images';
images.name = 'Images';
images.help = {'Select the images to be warped together. Multiple sets of images can be simultaneously registered. For example, the first set may be a bunch of grey matter images, and the second set may be the white matter images of the same subjects.'};
images.values = {images1 };
images.num = [1 Inf];
% ---------------------------------------------------------------------
% rform Regularisation Form
% ---------------------------------------------------------------------
rform = cfg_menu;
rform.tag = 'rform';
rform.name = 'Regularisation Form';
rform.val = {0};
rform.help = {'The registration is penalised by some ``energy'''' term. Here, the form of this energy term is specified. Three different forms of regularisation can currently be used.'};
rform.labels = {
'Linear Elastic Energy'
'Membrane Energy'
'Bending Energy'
}';
rform.values = {0 1 2};
% ---------------------------------------------------------------------
% its Inner Iterations
% ---------------------------------------------------------------------
its = cfg_menu;
its.tag = 'its';
its.name = 'Inner Iterations';
its.val = {3};
its.help = {'The number of Gauss-Newton iterations to be done within this outer iteration.'};
its.labels = {
'1'
'2'
'3'
'4'
'5'
'6'
'7'
'8'
'9'
'10'
}';
its.values = {1 2 3 4 5 6 7 8 9 10};
% ---------------------------------------------------------------------
% rparam Reg params
% ---------------------------------------------------------------------
rparam = cfg_entry;
rparam.tag = 'rparam';
rparam.name = 'Reg params';
rparam.val = {[0.1 0.01 0.001]};
rparam.help = {
'For linear elasticity, the parameters are mu, lambda and id. For membrane energy, the parameters are lambda, unused and id.id is a term for penalising absolute displacements, and should therefore be small. For bending energy, the parameters are lambda, id1 and id2, and the regularisation is by (-lambda*Laplacian + id1)^2 + id2.'
'Use more regularisation for the early iterations so that the deformations are smooth, and then use less for the later ones so that the details can be better matched.'
}';
rparam.strtype = 'e';
rparam.num = [1 3];
% ---------------------------------------------------------------------
% K Time Steps
% ---------------------------------------------------------------------
K = cfg_menu;
K.tag = 'K';
K.name = 'Time Steps';
K.val = {6};
K.help = {'The number of time points used for solving the partial differential equations. A single time point would be equivalent to a small deformation model. Smaller values allow faster computations, but are less accurate in terms of inverse consistency and may result in the one-to-one mapping breaking down. Earlier iteration could use fewer time points, but later ones should use about 64 (or fewer if the deformations are very smooth).'};
K.labels = {
'1'
'2'
'4'
'8'
'16'
'32'
'64'
'128'
'256'
'512'
}';
K.values = {0 1 2 3 4 5 6 7 8 9};
% ---------------------------------------------------------------------
% template Template
% ---------------------------------------------------------------------
template = cfg_files;
template.tag = 'template';
template.name = 'Template';
template.help = {'Select template. Smoother templates should be used for the early iterations. Note that the template should be a 4D file, with the 4th dimension equal to the number of sets of images.'};
template.filter = 'nifti';
template.ufilter = '.*';
template.num = [1 1];
% ---------------------------------------------------------------------
% param Outer Iteration
% ---------------------------------------------------------------------
param1 = cfg_branch;
param1.tag = 'param';
param1.name = 'Outer Iteration';
param1.val = {its rparam K template };
param1.help = {'Different parameters and templates can be specified for each outer iteration.'};
val = cell(1,6);
param = param1;
param.val{1}.val{1} = 3; % iits
param.val{2}.val{1} = [4 2 1e-6]; % rparam
param.val{3}.val{1} = 0; % K
val{1} = param;
param.val{1}.val{1} = 3; % iits
param.val{2}.val{1} = [2 1 1e-6]; % rparam
param.val{3}.val{1} = 0; % K
val{2} = param;
param.val{1}.val{1} = 3; % iits
param.val{2}.val{1} = [1 0.5 1e-6]; % rparam
param.val{3}.val{1} = 1; % K
val{3} = param;
param.val{1}.val{1} = 3; % iits
param.val{2}.val{1} = [0.5 0.25 1e-6]; % rparam
param.val{3}.val{1} = 2; % K
val{4} = param;
param.val{1}.val{1} = 3; % iits
param.val{2}.val{1} = [0.25 0.125 1e-6]; % rparam
param.val{3}.val{1} = 4; % K
val{5} = param;
param.val{1}.val{1} = 3; % iits
param.val{2}.val{1} = [0.25 0.125 1e-6]; % rparam
param.val{3}.val{1} = 6; % K
val{6} = param;
% ---------------------------------------------------------------------
% param Outer Iterations
% ---------------------------------------------------------------------
param = cfg_repeat;
param.tag = 'param';
param.name = 'Outer Iterations';
param.val = val;
param.help = {'The images are warped to match a sequence of templates. Early iterations should ideally use smoother templates and more regularisation than later iterations.'};
param.values = {param1};
param.num = [1 Inf];
% ---------------------------------------------------------------------
% lmreg LM Regularisation
% ---------------------------------------------------------------------
lmreg = cfg_entry;
lmreg.tag = 'lmreg';
lmreg.name = 'LM Regularisation';
lmreg.val = {0.01};
lmreg.help = {'Levenberg-Marquardt regularisation. Larger values increase the the stability of the optimisation, but slow it down. A value of zero results in a Gauss-Newton strategy, but this is not recommended as it may result in instabilities in the FMG.'};
lmreg.strtype = 'e';
lmreg.num = [1 1];
% ---------------------------------------------------------------------
% cyc Cycles
% ---------------------------------------------------------------------
cyc = cfg_menu;
cyc.tag = 'cyc';
cyc.name = 'Cycles';
cyc.val = {3};
cyc.help = {'Number of cycles used by the full multi-grid matrix solver. More cycles result in higher accuracy, but slow down the algorithm. See Numerical Recipes for more information on multi-grid methods.'};
cyc.labels = {
'1'
'2'
'3'
'4'
'5'
'6'
'7'
'8'
}';
cyc.values = {1 2 3 4 5 6 7 8};
% ---------------------------------------------------------------------
% its Iterations
% ---------------------------------------------------------------------
its = cfg_menu;
its.tag = 'its';
its.name = 'Iterations';
its.val = {3};
its.help = {'Number of relaxation iterations performed in each multi-grid cycle. More iterations are needed if using ``bending energy'''' regularisation, because the relaxation scheme only runs very slowly. See the chapter on solving partial differential equations in Numerical Recipes for more information about relaxation methods.'};
its.labels = {
'1'
'2'
'3'
'4'
'5'
'6'
'7'
'8'
}';
its.values = {1 2 3 4 5 6 7 8};
% ---------------------------------------------------------------------
% optim Optimisation Settings
% ---------------------------------------------------------------------
optim = cfg_branch;
optim.tag = 'optim';
optim.name = 'Optimisation Settings';
optim.val = {lmreg cyc its };
optim.help = {'Settings for the optimisation. If you are unsure about them, then leave them at the default values. Optimisation is by repeating a number of Levenberg-Marquardt iterations, in which the equations are solved using a full multi-grid (FMG) scheme. FMG and Levenberg-Marquardt are both described in Numerical Recipes (2nd edition).'};
% ---------------------------------------------------------------------
% settings Settings
% ---------------------------------------------------------------------
settings = cfg_branch;
settings.tag = 'settings';
settings.name = 'Settings';
settings.val = {rform param optim };
settings.help = {'Various settings for the optimisation. The default values should work reasonably well for aligning tissue class images together.'};
% ---------------------------------------------------------------------
% warp1 Run DARTEL (existing Templates)
% ---------------------------------------------------------------------
warp1 = cfg_exbranch;
warp1.tag = 'warp1';
warp1.name = 'Run DARTEL (existing Templates)';
warp1.val = {images settings };
warp1.check = @check_dartel_template;
warp1.help = {'Run the DARTEL nonlinear image registration procedure to match individual images to pre-existing template data. Start out with smooth templates, and select crisp templates for the later iterations.'};
warp1.prog = @spm_dartel_warp;
warp1.vout = @vout_dartel_warp;
% ---------------------------------------------------------------------
% flowfields Flow fields
% ---------------------------------------------------------------------
flowfields = cfg_files;
flowfields.tag = 'flowfields';
flowfields.name = 'Flow fields';
flowfields.help = {'The flow fields store the deformation information. The same fields can be used for both forward or backward deformations (or even, in principle, half way or exaggerated deformations).'};
flowfields.filter = 'nifti';
flowfields.ufilter = '^u_.*';
flowfields.num = [1 Inf];
% ---------------------------------------------------------------------
% images Images
% ---------------------------------------------------------------------
images1 = cfg_files;
images1.tag = 'images';
images1.name = 'Images';
images1.help = {'Select images to be warped. Note that there should be the same number of images as there are flow fields, such that each flow field warps one image.'};
images1.filter = 'nifti';
images1.ufilter = '.*';
images1.num = [1 Inf];
% ---------------------------------------------------------------------
% images Images
% ---------------------------------------------------------------------
images = cfg_repeat;
images.tag = 'images';
images.name = 'Images';
images.help = {'The flow field deformations can be applied to multiple images. At this point, you are choosing how many images each flow field should be applied to.'};
images.values = {images1 };
images.num = [1 Inf];
% ---------------------------------------------------------------------
% See later
% ---------------------------------------------------------------------
many_subj = cfg_branch;
many_subj.tag = 'subjs';
many_subj.name = 'Many Subjects';
many_subj.val = {flowfields,images};
many_subj.help = {[...
'Select this option if you have many subjects to spatially normalise, ',...
'but there are a small and fixed number of scans for each subject.']};
% ---------------------------------------------------------------------
% jactransf Modulation
% ---------------------------------------------------------------------
jactransf = cfg_menu;
jactransf.tag = 'jactransf';
jactransf.name = 'Modulation';
jactransf.val = {0};
jactransf.help = {'This allows the spatially normalised images to be rescaled by the Jacobian determinants of the deformations. Note that the rescaling is only approximate for deformations generated using smaller numbers of time steps.'};
jactransf.labels = {
'Pres. Concentration (No "modulation")'
'Pres. Amount ("Modulation")'
}';
jactransf.values = {0 1};
% ---------------------------------------------------------------------
% K Time Steps
% ---------------------------------------------------------------------
K = cfg_menu;
K.tag = 'K';
K.name = 'Time Steps';
K.val = {6};
K.help = {'The number of time points used for solving the partial differential equations. Note that Jacobian determinants are not very accurate for very small numbers of time steps (less than about 16).'};
K.labels = {
'1'
'2'
'4'
'8'
'16'
'32'
'64'
'128'
'256'
'512'
}';
K.values = {0 1 2 3 4 5 6 7 8 9};
% ---------------------------------------------------------------------
% interp Interpolation
% ---------------------------------------------------------------------
interp = cfg_menu;
interp.tag = 'interp';
interp.name = 'Interpolation';
interp.val = {1};
interp.help = {
['The method by which the images are sampled when ',...
'being written in a different space. ',...
'(Note that Inf or NaN values are treated as zero, ',...
'rather than as missing data)']
' Nearest Neighbour:'
' - Fastest, but not normally recommended.'
' Bilinear Interpolation:'
' - OK for PET, realigned fMRI, or segmentations'
' B-spline Interpolation:'
[' - Better quality (but slower) interpolation',...
'/* \cite{thevenaz00a}*/, especially with higher ',...
'degree splines. Can produce values outside the ',...
'original range (e.g. small negative values from an ',...
'originally all positive image).']
}';
interp.labels = {
'Nearest neighbour'
'Trilinear'
'2nd Degree B-spline'
'3rd Degree B-Spline '
'4th Degree B-Spline '
'5th Degree B-Spline'
'6th Degree B-Spline'
'7th Degree B-Spline'
}';
interp.values = {0 1 2 3 4 5 6 7};
% ---------------------------------------------------------------------
% crt_warped Create Warped
% ---------------------------------------------------------------------
crt_warped = cfg_exbranch;
crt_warped.tag = 'crt_warped';
crt_warped.name = 'Create Warped';
crt_warped.val = {flowfields images jactransf K interp };
crt_warped.check = @check_norm;
crt_warped.help = {'This allows spatially normalised images to be generated. Note that voxel sizes and bounding boxes can not be adjusted, and that there may be strange effects due to the boundary conditions used by the warping. Also note that the warped images are not in Talairach or MNI space. The coordinate system is that of the average shape and size of the subjects to which DARTEL was applied. In order to have MNI-space normalised images, then the Deformations Utility can be used to compose the individual DARTEL warps, with a deformation field that matches (e.g.) the Template grey matter generated by DARTEL, with one of the grey matter volumes released with SPM.'};
crt_warped.prog = @spm_dartel_norm;
crt_warped.vout = @vout_norm;
% ---------------------------------------------------------------------
% flowfields Flow fields
% ---------------------------------------------------------------------
flowfields = cfg_files;
flowfields.tag = 'flowfields';
flowfields.name = 'Flow fields';
flowfields.help = {'The flow fields store the deformation information. The same fields can be used for both forward or backward deformations (or even, in principle, half way or exaggerated deformations).'};
flowfields.filter = 'nifti';
flowfields.ufilter = '^u_.*';
flowfields.num = [1 Inf];
% ---------------------------------------------------------------------
% K Time Steps
% ---------------------------------------------------------------------
K = cfg_menu;
K.tag = 'K';
K.name = 'Time Steps';
K.val = {6};
K.help = {'The number of time points used for solving the partial differential equations. Note that Jacobian determinants are not very accurate for very small numbers of time steps (less than about 16).'};
K.labels = {
'1'
'2'
'4'
'8'
'16'
'32'
'64'
'128'
'256'
'512'
}';
K.values = {0 1 2 3 4 5 6 7 8 9};
% ---------------------------------------------------------------------
% jacdet Jacobian determinants
% ---------------------------------------------------------------------
jacdet = cfg_exbranch;
jacdet.tag = 'jacdet';
jacdet.name = 'Jacobian determinants';
jacdet.val = {flowfields K };
jacdet.help = {'Create Jacobian determinant fields from flowfields.'};
jacdet.prog = @spm_dartel_jacobian;
jacdet.vout = @vout_jacdet;
% ---------------------------------------------------------------------
% flowfields Flow fields
% ---------------------------------------------------------------------
flowfields = cfg_files;
flowfields.tag = 'flowfields';
flowfields.name = 'Flow fields';
flowfields.help = {'The flow fields store the deformation information. The same fields can be used for both forward or backward deformations (or even, in principle, half way or exaggerated deformations).'};
flowfields.filter = 'nifti';
flowfields.ufilter = '^u_.*';
flowfields.num = [1 Inf];
% ---------------------------------------------------------------------
% images Images
% ---------------------------------------------------------------------
images = cfg_files;
images.tag = 'images';
images.name = 'Images';
images.help = {'Select the image(s) to be inverse normalised. These should be in alignment with the template image generated by the warping procedure.'};
images.filter = 'nifti';
images.ufilter = '.*';
images.num = [1 Inf];
% ---------------------------------------------------------------------
% K Time Steps
% ---------------------------------------------------------------------
K = cfg_menu;
K.tag = 'K';
K.name = 'Time Steps';
K.val = {6};
K.help = {'The number of time points used for solving the partial differential equations. Note that Jacobian determinants are not very accurate for very small numbers of time steps (less than about 16).'};
K.labels = {
'1'
'2'
'4'
'8'
'16'
'32'
'64'
'128'
'256'
'512'
}';
K.values = {0 1 2 3 4 5 6 7 8 9};
% ---------------------------------------------------------------------
% crt_iwarped Create Inverse Warped
% ---------------------------------------------------------------------
crt_iwarped = cfg_exbranch;
crt_iwarped.tag = 'crt_iwarped';
crt_iwarped.name = 'Create Inverse Warped';
crt_iwarped.val = {flowfields images K interp };
crt_iwarped.help = {'Create inverse normalised versions of some image(s). The image that is inverse-normalised should be in alignment with the template (generated during the warping procedure). Note that the results have the same dimensions as the ``flow fields'''', but are mapped to the original images via the affine transformations in their headers.'};
crt_iwarped.prog = @spm_dartel_invnorm;
crt_iwarped.vout = @vout_invnorm;
% ---------------------------------------------------------------------
%
% ---------------------------------------------------------------------
flowfield = cfg_files;
flowfield.tag = 'flowfield';
flowfield.name = 'Flow Field';
flowfield.filter = 'nifti';
flowfield.ufilter = '^u_.*\.nii$';
flowfield.num = [1 1];
flowfield.help = {'DARTEL flow field for this subject.'};
% ---------------------------------------------------------------------
%
% ---------------------------------------------------------------------
images = cfg_files;
images.tag = 'images';
images.name = 'Images';
images.filter = 'nifti';
images.num = [1 Inf];
images.help = {'Images for this subject to spatially normalise.'};
% ---------------------------------------------------------------------
%
% ---------------------------------------------------------------------
subj = cfg_branch;
subj.tag = 'subj';
subj.name = 'Subject';
subj.val = {flowfield,images};
subj.help = {'Subject to be spatially normalized.'};
% ---------------------------------------------------------------------
%
% ---------------------------------------------------------------------
few_subj = cfg_repeat;
few_subj.tag = 'few_subj';
few_subj.name = 'Few Subjects';
few_subj.values = {subj};
few_subj.help = {[...
'Select this option if there are only a few subjects, each with many or ' ...
'a variable number of scans each. You will then need to specify a series of subjects, and the flow field and images of each of them.']};
% ---------------------------------------------------------------------
%
% ---------------------------------------------------------------------
way = cfg_choice;
way.tag = 'data';
way.name = 'Select according to';
way.values = {few_subj,many_subj};
way.help = {...
['You may wish to spatially normalise only a few subjects, '...
'but have many scans per subject (eg for fMRI), '...
'or you may have lots of subjects, but with a small and fixed number '...
'of scans for each of them (eg for VBM). The idea is to chose the way of '...
'selecting files that is easier.']};
% ---------------------------------------------------------------------
%
% ---------------------------------------------------------------------
template = cfg_files;
template.tag = 'template';
template.name = 'DARTEL Template';
template.filter = 'nifti';
template.num = [0 1];
template.help = {...
['Select the final Template file generated by DARTEL. This will be affine '...
'registered with a TPM file, such that the resulting spatially normalised '...
'images are closer aligned to MNI space. Leave empty if you do not wish to '...
'incorporate a transform to MNI space '...
'(ie just click ``done'' on the file selector, without selecting any images).']};
% ---------------------------------------------------------------------
%
% ---------------------------------------------------------------------
fwhm = cfg_entry;
fwhm.tag = 'fwhm';
fwhm.name = 'Gaussian FWHM';
fwhm.val = {[8 8 8]};
fwhm.strtype = 'e';
fwhm.num = [1 3];
fwhm.help = {'Specify the full-width at half maximum (FWHM) of the Gaussian blurring kernel in mm. Three values should be entered, denoting the FWHM in the x, y and z directions. Note that you can also specify [0 0 0], but any ``modulated'' data will show aliasing (see eg Wikipedia), which occurs because of the way the warped images are generated.'};
% ---------------------------------------------------------------------
%
% ---------------------------------------------------------------------
preserve = cfg_menu;
preserve.tag = 'preserve';
preserve.name = 'Preserve';
preserve.help = {
'Preserve Concentrations (no "modulation"): Smoothed spatially normalised images (sw*) represent weighted averages of the signal under the smoothing kernel, approximately preserving the intensities of the original images. This option is currently suggested for eg fMRI.'
''
'Preserve Amount ("modulation"): Smoothed and spatially normalised images preserve the total amount of signal from each region in the images (smw*). Areas that are expanded during warping are correspondingly reduced in intensity. This option is suggested for VBM.'
}';
preserve.labels = {
'Preserve Concentrations'
'Preserve Amount'
}';
preserve.values = {0 1};
preserve.val = {0};
% ---------------------------------------------------------------------
%
% ---------------------------------------------------------------------
vox = cfg_entry;
vox.tag = 'vox';
vox.name = 'Voxel sizes';
vox.num = [1 3];
vox.strtype = 'e';
vox.val = {[NaN NaN NaN]};
vox.help = {[...
'Specify the voxel sizes of the deformation field to be produced. ',...
'Non-finite values will default to the voxel sizes of the template image',...
'that was originally used to estimate the deformation.']};
% ---------------------------------------------------------------------
%
% ---------------------------------------------------------------------
bb = cfg_entry;
bb.tag = 'bb';
bb.name = 'Bounding box';
bb.strtype = 'e';
bb.num = [2 3];
bb.val = {[NaN NaN NaN; NaN NaN NaN]};
bb.help = {[...
'Specify the bounding box of the deformation field to be produced. ',...
'Non-finite values will default to the bounding box of the template image',...
'that was originally used to estimate the deformation.']};
% ---------------------------------------------------------------------
%
% ---------------------------------------------------------------------
nrm = cfg_exbranch;
nrm.tag = 'mni_norm';
nrm.name = 'Normalise to MNI Space';
nrm.val = {template,way,vox,bb,preserve,fwhm};
nrm.prog = @spm_dartel_norm_fun;
nrm.vout = @vout_norm_fun;
nrm.check = @check_norm_fun;
nrm.help = {[...
'Normally, DARTEL generates warped images that align with the average-shaped template. ',...
'This routine includes an initial affine regisration of the template (the final one ',...
'generated by DARTEL), with the TPM data released with SPM.'],[...
'``Smoothed'''' (blurred) spatially normalised images are generated in such a ',...
'way that the original signal is preserved. Normalised images are ',...
'generated by a ``pushing'''' rather than a ``pulling'''' (the usual) procedure. ',...
'Note that a procedure related to trilinear interpolation is used, and no masking is done. It ',...
'is therefore recommended that the images are realigned and resliced ',...
'before they are spatially normalised, in order to benefit from motion correction using higher order interpolation. Alternatively, contrast images ',...
'generated from unsmoothed native-space fMRI/PET data can be spatially ',...
'normalised for a 2nd level analysis.'],[...
'Two ``preserve'''' options are provided. One of them should do the ',...
'equavalent of generating smoothed ``modulated'''' spatially normalised ',...
'images. The other does the equivalent of smoothing the modulated ',...
'normalised fMRI/PET, and dividing by the smoothed Jacobian determinants.']};
% ---------------------------------------------------------------------
% images Images
% ---------------------------------------------------------------------
images1 = cfg_files;
images1.tag = 'images';
images1.name = 'Images';
images1.help = {'Select tissue class images (one per subject).'};
images1.filter = 'nifti';
images1.ufilter = '^r.*c';
images1.num = [1 Inf];
% ---------------------------------------------------------------------
% images Images
% ---------------------------------------------------------------------
images = cfg_repeat;
images.tag = 'images';
images.name = 'Images';
images.help = {'Multiple sets of images are used here. For example, the first set may be a bunch of grey matter images, and the second set may be the white matter images of the same subjects. The number of sets of images must be the same as was used to generate the template.'};
images.values = {images1 };
images.num = [1 Inf];
% ---------------------------------------------------------------------
% flowfields Flow fields
% ---------------------------------------------------------------------
flowfields = cfg_files;
flowfields.tag = 'flowfields';
flowfields.name = 'Flow fields';
flowfields.help = {'Select the flow fields for each subject.'};
flowfields.filter = 'nifti';
flowfields.ufilter = '^u_.*';
flowfields.num = [1 Inf];
% ---------------------------------------------------------------------
% template Template
% ---------------------------------------------------------------------
template = cfg_files;
template.tag = 'template';
template.name = 'Template';
template.help = {'Residual differences are computed between the warped images and template.'};
template.filter = 'nifti';
template.ufilter = '^Template.*';
template.num = [0 1];
% ---------------------------------------------------------------------
% K Time Steps
% ---------------------------------------------------------------------
K = cfg_menu;
K.tag = 'K';
K.name = 'Time Steps';
K.val = {6};
K.help = {'The number of time points used for solving the partial differential equations. Note that Jacobian determinants are not very accurate for very small numbers of time steps (less than about 16).'};
K.labels = {
'1'
'2'
'4'
'8'
'16'
'32'
'64'
'128'
'256'
'512'
}';
K.values = {0 1 2 3 4 5 6 7 8 9};
% ---------------------------------------------------------------------
% fwhm Smoothing
% ---------------------------------------------------------------------
fwhm = cfg_menu;
fwhm.tag = 'fwhm';
fwhm.name = 'Smoothing';
fwhm.val = {4};
fwhm.help = {'The residuals can be smoothed with a Gaussian to reduce dimensionality. More smoothing is recommended if there are fewer training images.'};
fwhm.labels = {
'None'
' 2mm'
' 4mm'
' 6mm'
' 8mm'
'10mm'
'12mm'
'14mm'
'16mm'
}';
fwhm.values = {0 2 4 6 8 10 12 14 16};
% ---------------------------------------------------------------------
% resids Generate Residuals
% ---------------------------------------------------------------------
resids = cfg_exbranch;
resids.tag = 'resids';
resids.name = 'Generate Residuals';
resids.val = {images flowfields template K fwhm };
resids.check = @check_resids;
resids.help = {'Generate residual images in a form suitable for computing a Fisher kernel. In principle, a Gaussian Process model can be used to determine the optimal (positive) linear combination of kernel matrices. The idea would be to combine the kernel from the residuals, with a kernel derived from the flow-fields. Such a combined kernel should then encode more relevant information than the individual kernels alone.'};
resids.prog = @spm_dartel_resids;
resids.vout = @vout_resids;
% ---------------------------------------------------------------------
% images Data
% ---------------------------------------------------------------------
images = cfg_files;
images.tag = 'images';
images.name = 'Data';
images.help = {'Select images to generate dot-products from.'};
images.filter = 'nifti';
images.ufilter = '.*';
images.num = [1 Inf];
% ---------------------------------------------------------------------
% weight Weighting image
% ---------------------------------------------------------------------
weight = cfg_files;
weight.tag = 'weight';
weight.name = 'Weighting image';
weight.val = {{}};
weight.help = {'The kernel can be generated so that some voxels contribute to the similarity measures more than others. This is achieved by supplying a weighting image, which each of the component images are multiplied before the dot-products are computed. This image needs to have the same dimensions as the component images, but orientation information (encoded by matrices in the headers) is ignored. If left empty, then all voxels are weighted equally.'};
weight.filter = 'image';
weight.ufilter = '.*';
weight.num = [0 1];
% ---------------------------------------------------------------------
% dotprod Dot-product Filename
% ---------------------------------------------------------------------
dotprod = cfg_entry;
dotprod.tag = 'dotprod';
dotprod.name = 'Dot-product Filename';
dotprod.help = {'Enter a filename for results (it will be prefixed by ``dp_'''' and saved in the current directory).'};
dotprod.strtype = 's';
dotprod.num = [1 Inf];
% ---------------------------------------------------------------------
% reskern Kernel from Resids
% ---------------------------------------------------------------------
reskern = cfg_exbranch;
reskern.tag = 'reskern';
reskern.name = 'Kernel from Images';
reskern.val = {images weight dotprod };
reskern.help = {'Generate a kernel matrix from images. In principle, this same function could be used for generating kernels from any image data (e.g. ``modulated'''' grey matter). If there is prior knowledge about some region providing more predictive information (e.g. the hippocampi for AD), then it is possible to weight the generation of the kernel accordingly. The matrix of dot-products is saved in a variable ``Phi'''', which can be loaded from the dp_*.mat file. The ``kernel trick'''' can be used to convert these dot-products into distance measures for e.g. radial basis-function approaches.'};
reskern.prog = @spm_dartel_dotprods;
% ---------------------------------------------------------------------
% flowfields Flow fields
% ---------------------------------------------------------------------
flowfields = cfg_files;
flowfields.tag = 'flowfields';
flowfields.name = 'Flow fields';
flowfields.help = {'Select the flow fields for each subject.'};
flowfields.filter = 'nifti';
flowfields.ufilter = '^u_.*';
flowfields.num = [1 Inf];
% ---------------------------------------------------------------------
% rform Regularisation Form
% ---------------------------------------------------------------------
rform = cfg_menu;
rform.tag = 'rform';
rform.name = 'Regularisation Form';
rform.val = {0};
rform.help = {'The registration is penalised by some ``energy'''' term. Here, the form of this energy term is specified. Three different forms of regularisation can currently be used.'};
rform.labels = {
'Linear Elastic Energy'
'Membrane Energy'
'Bending Energy'
}';
rform.values = {0 1 2};
% ---------------------------------------------------------------------
% rparam Reg params
% ---------------------------------------------------------------------
rparam = cfg_entry;
rparam.tag = 'rparam';
rparam.name = 'Reg params';
rparam.val = {[0.25 0.125 1e-06]};
rparam.help = {'For linear elasticity, the parameters are `mu'', `lambda'' and `id''. For membrane and bending energy, the parameters are `lambda'', unused and `id''. The term `id'' is for penalising absolute displacements, and should therefore be small.'};
rparam.strtype = 'e';
rparam.num = [1 3];
% ---------------------------------------------------------------------
% dotprod Dot-product Filename
% ---------------------------------------------------------------------
dotprod = cfg_entry;
dotprod.tag = 'dotprod';
dotprod.name = 'Dot-product Filename';
dotprod.help = {'Enter a filename for results (it will be prefixed by ``dp_'''' and saved in the current directory.'};
dotprod.strtype = 's';
dotprod.num = [1 Inf];
% ---------------------------------------------------------------------
% flokern Kernel from Flows
% ---------------------------------------------------------------------
flokern = cfg_exbranch;
flokern.tag = 'flokern';
flokern.name = 'Kernel from Flows';
flokern.val = {flowfields rform rparam dotprod };
flokern.help = {'Generate a kernel from flow fields. The dot-products are saved in a variable ``Phi'''' in the resulting dp_*.mat file.'};
flokern.prog = @spm_dartel_kernel;
% ---------------------------------------------------------------------
% kernfun Kernel Utilities
% ---------------------------------------------------------------------
kernfun = cfg_choice;
kernfun.tag = 'kernfun';
kernfun.name = 'Kernel Utilities';
kernfun.help = {
'DARTEL can be used for generating matrices of dot-products for various kernel pattern-recognition procedures.'
'The idea of applying pattern-recognition procedures is to obtain a multi-variate characterisation of the anatomical differences among groups of subjects. These characterisations can then be used to separate (eg) healthy individuals from particular patient populations. There is still a great deal of methodological work to be done, so the types of kernel that can be generated here are unlikely to be the definitive ways of proceeding. They are only just a few ideas that may be worth trying out. The idea is simply to attempt a vaguely principled way to combine generative models with discriminative models (see the ``Pattern Recognition and Machine Learning'''' book by Chris Bishop for more ideas). Better ways (higher predictive accuracy) will eventually emerge.'
'Various pattern recognition algorithms are available freely over the Internet. Possible approaches include Support-Vector Machines, Relevance-Vector machines and Gaussian Process Models. Gaussian Process Models probably give the most accurate probabilistic predictions, and allow kernels generated from different pieces of data to be most easily combined.'
}';
kernfun.values = {reskern flokern};
% ---------------------------------------------------------------------
% dartel DARTEL Tools
% ---------------------------------------------------------------------
dartel = cfg_choice;
dartel.tag = 'dartel';
dartel.name = 'DARTEL Tools';
dartel.help = {
'This toolbox is based around the ``A Fast Diffeomorphic Registration Algorithm'''' paper/* \cite{ashburner07} */. The idea is to register images by computing a ``flow field'''', which can then be ``exponentiated'''' to generate both forward and backward deformations. Currently, the software only works with images that have isotropic voxels, identical dimensions and which are in approximate alignment with each other. One of the reasons for this is that the approach assumes circulant boundary conditions, which makes modelling global rotations impossible. Another reason why the images should be approximately aligned is because there are interactions among the transformations that are minimised by beginning with images that are already almost in register. This problem could be alleviated by a time varying flow field, but this is currently computationally impractical.'
'Because of these limitations, images should first be imported. This involves taking the ``*_seg_sn.mat'''' files produced by the segmentation code of SPM5, and writing out rigidly transformed versions of the tissue class images, such that they are in as close alignment as possible with the tissue probability maps. Rigidly transformed original images can also be generated, with the option to have skull-stripped versions.'
'The next step is the registration itself. This can involve matching single images together, or it can involve the simultaneous registration of e.g. GM with GM, WM with WM and 1-(GM+WM) with 1-(GM+WM) (when needed, the 1-(GM+WM) class is generated implicitly, so there is no need to include this class yourself). This procedure begins by creating a mean of all the images, which is used as an initial template. Deformations from this template to each of the individual images are computed, and the template is then re-generated by applying the inverses of the deformations to the images and averaging. This procedure is repeated a number of times.'
'Finally, warped versions of the images (or other images that are in alignment with them) can be generated. '
''
'This toolbox is not yet seamlessly integrated into the SPM package. Eventually, the plan is to use many of the ideas here as the default strategy for spatial normalisation. The toolbox may change with future updates. There will also be a number of other (as yet unspecified) extensions, which may include a variable velocity version (related to LDDMM). Note that the Fast Diffeomorphism paper only describes a sum of squares objective function. The multinomial objective function is an extension, based on a more appropriate model for aligning binary data to a template.'
}';
dartel.values = {initial warp warp1 nrm crt_warped jacdet crt_iwarped kernfun };
%dartel.num = [0 Inf];
%_______________________________________________________________________
%
%_______________________________________________________________________
function dep = vout_initial_import(job)
cls = {'GM', 'WM', 'CSF'};
kk = 1;
for k=1:3,
if isnumeric(job.(cls{k})) && job.(cls{k})
dep(kk) = cfg_dep;
dep(kk).sname = sprintf('Imported Tissue (%s)', cls{k});
dep(kk).src_output = substruct('.','cfiles','()',{':',k});
dep(kk).tgt_spec = cfg_findspec({{'filter','nifti'}});
kk = kk + 1;
end
end
if isnumeric(job.image) && job.image
dep(kk) = cfg_dep;
dep(kk).sname = sprintf('Resliced Original Images');
dep(kk).src_output = substruct('.','files');
dep(kk).tgt_spec = cfg_findspec({{'filter','nifti'}});
end
%_______________________________________________________________________
%_______________________________________________________________________
function chk = check_dartel_template(job)
n1 = numel(job.images);
n2 = numel(job.images{1});
chk = '';
for i=1:n1,
if numel(job.images{i}) ~= n2,
chk = 'Incompatible number of images';
break;
end;
end;
%_______________________________________________________________________
%_______________________________________________________________________
function dep = vout_dartel_template(job)
if isa(job.settings.template,'cfg_dep') || ~ ...
isempty(deblank(job.settings.template))
for it=0:numel(job.settings.param),
tdep(it+1) = cfg_dep;
tdep(it+1).sname = sprintf('Template (Iteration %d)', it);
tdep(it+1).src_output = substruct('.','template','()',{it+1});
tdep(it+1).tgt_spec = cfg_findspec({{'filter','nifti'}});
end
else
tdep = cfg_dep;
tdep = tdep(false);
end
fdep = cfg_dep;
fdep.sname = 'Flow Fields';
fdep.src_output = substruct('.','files','()',{':'});
fdep.tgt_spec = cfg_findspec({{'filter','nifti'}});
dep = [tdep fdep];
%_______________________________________________________________________
%_______________________________________________________________________
function dep = vout_dartel_warp(job)
dep = cfg_dep;
dep.sname = 'Flow Fields';
dep.src_output = substruct('.','files','()',{':'});
dep.tgt_spec = cfg_findspec({{'filter','nifti'}});
%_______________________________________________________________________
%_______________________________________________________________________
function chk = check_norm(job)
chk = '';
PU = job.flowfields;
PI = job.images;
n1 = numel(PU);
for i=1:numel(PI),
if numel(PI{i}) ~= n1,
chk = 'Incompatible number of images';
break;
end
end
%_______________________________________________________________________
%_______________________________________________________________________
function chk = check_norm_fun(job)
chk = '';
if isfield(job.data,'subjs')
PU = job.data.subjs.flowfields;
PI = job.data.subjs.images;
n1 = numel(PU);
for i=1:numel(PI),
if numel(PI{i}) ~= n1,
chk = 'Incompatible number of images';
break;
end
end
end
%_______________________________________________________________________
%_______________________________________________________________________
function dep = vout_norm(job)
if job.jactransf,
sname = 'Warped Images - Jacobian Transformed';
else
sname = 'Warped Images';
end
PU = job.flowfields;
PI = job.images;
for m=1:numel(PI),
dep(m) = cfg_dep;
dep(m).sname = sprintf('%s (Image %d)',sname,m);
dep(m).src_output = substruct('.','files','()',{':',m});
dep(m).tgt_spec = cfg_findspec({{'filter','nifti'}});
end
%_______________________________________________________________________
%_______________________________________________________________________
function dep = vout_invnorm(job)
PU = job.flowfields;
PI = job.images;
for m=1:numel(PI),
dep(m) = cfg_dep;
dep(m).sname = sprintf('Inverse Warped Images (Image %d)',m);
dep(m).src_output = substruct('.','files','()',{':',m});
dep(m).tgt_spec = cfg_findspec({{'filter','nifti'}});
end
n = numel(PI);
for m=1:numel(PU),
dep(m+n) = cfg_dep;
dep(m+n).sname = sprintf('Inverse Warped Images (Deformation %d)',m);
dep(m+n).src_output = substruct('.','files','()',{m,':'});
dep(m+n).tgt_spec = cfg_findspec({{'filter','nifti'}});
end
%_______________________________________________________________________
%_______________________________________________________________________
function dep = vout_jacdet(job)
dep = cfg_dep;
dep.sname = 'Jacobian Determinant Fields';
dep.src_output = substruct('.','files','()',{':'});
dep.tgt_spec = cfg_findspec({{'filter','nifti'}});
%_______________________________________________________________________
%_______________________________________________________________________
function dep = vout_norm_fun(job)
if job.preserve,
sname = 'MNI Smo. Warped - Amount';
else
sname = 'MNI Smo. Warped - Concentrations';
end
dep = cfg_dep;
if isfield(job.data,'subj')
for m=1:numel(job.data.subj)
dep(m) = cfg_dep;
dep(m).sname = sprintf('%s (Deformation %d)',sname,m);
dep(m).src_output = substruct('{}',{m},'()',{':'});
dep(m).tgt_spec = cfg_findspec({{'filter','nifti'}});
end
end
if isfield(job.data,'subjs')
for m=1:numel(job.data.subjs.images),
dep(m) = cfg_dep;
dep(m).sname = sprintf('%s (Image %d)',sname,m);
dep(m).src_output = substruct('()',{':',m});
dep(m).tgt_spec = cfg_findspec({{'filter','nifti'}});
end
end
%_______________________________________________________________________
%_______________________________________________________________________
function chk = check_resids(job)
chk = '';
PU = job.flowfields;
PI = job.images;
n1 = numel(PU);
for i=1:numel(PI),
if numel(PI{i}) ~= n1,
chk = 'Incompatible number of images';
break;
end
end
%_______________________________________________________________________
%_______________________________________________________________________
function dep = vout_resids(job)
dep = cfg_dep;
dep.sname = 'Residual Files';
dep.src_output = substruct('.','files','()',{':'});
dep.tgt_spec = cfg_findspec({{'filter','nifti'}});
%_______________________________________________________________________
|
github
|
philippboehmsturm/antx-master
|
spm_dartel_smooth.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/DARTEL/spm_dartel_smooth.m
| 1,773 |
utf_8
|
b7c32a058585a98c2722f80112a61f05
|
function [sig,a] = spm_dartel_smooth(t,lam,its,vx,a)
% A function for smoothing tissue probability maps
% FORMAT [sig,a_new] = spm_dartel_smooth(t,lam,its,vx,a_old)
%________________________________________________________
% (c) Wellcome Centre for NeuroImaging (2007)
% John Ashburner
% $Id: spm_dartel_smooth.m 3102 2009-05-08 11:29:34Z john $
if nargin<5, a = zeros(size(t),'single'); end
if nargin<4, vx = [1 1 1]; end;
if nargin<3, its = 16; end;
if nargin<2, lam = 1; end;
d = size(t);
W = zeros([d(1:3) round((d(4)*(d(4)+1))/2)],'single');
s = max(sum(t,4),eps('single'));
for k=1:d(4),
t(:,:,:,k) = max(min(t(:,:,:,k)./s,1-eps('single')),eps('single'));
end
for i=1:its,
%trnc= -log(eps('single'));
%a = max(min(a,trnc),-trnc);
sig = softmax(a);
gr = sig - t;
for k=1:d(4),
gr(:,:,:,k) = gr(:,:,:,k).*s;
end
gr = gr + optimNn('vel2mom',a,[2 vx lam lam*1e-4 0]);
jj = d(4)+1;
reg = 2*sqrt(eps('single'))*d(4)^2;
for j1=1:d(4),
W(:,:,:,j1) = (sig(:,:,:,j1).*(1-sig(:,:,:,j1)) + reg).*s;
for j2=(j1+1):d(4),
W(:,:,:,jj) = -sig(:,:,:,j1).*sig(:,:,:,j2).*s;
jj = jj+1;
end
end
a = a - optimNn(W,gr,[2 vx lam lam*1e-4 0 1 1]);
%a = a - mean(a(:)); % unstable
%a = a - sum(sum(sum(sum(a))))/numel(a);
fprintf(' %g,', sum(gr(:).^2)/numel(gr));
drawnow
end;
fprintf('\n');
sig = softmax(a);
return;
function sig = softmax(a)
sig = zeros(size(a),'single');
for j=1:size(a,3),
aj = double(squeeze(a(:,:,j,:)));
trunc = log(realmax*(1-eps));
aj = min(max(aj-mean(aj(:)),-trunc),trunc);
sj = exp(aj);
s = sum(sj,3);
for i=1:size(a,4),
sig(:,:,j,i) = single(sj(:,:,i)./s);
end
end;
|
github
|
philippboehmsturm/antx-master
|
spm_dartel_import.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/DARTEL/spm_dartel_import.m
| 11,025 |
utf_8
|
b77410a96c6ed6cad8a8077f59075ab7
|
function out = spm_dartel_import(job)
% Import subjects' data for use with DARTEL
% FORMAT spm_dartel_import(job)
% job.matnames - Names of *_seg_sn.mat files to use
% job.odir - Output directory
% job.bb - Bounding box
% job.vox - Voxel sizes
% job.GM/WM/CSF - Options fo different tissue classes
% job.image - Options for resliced original image
%
% Rigidly aligned images are generated using info from the seg_sn.mat
% files. These can be resliced GM, WM or CSF, but also various resliced
% forms of the original image (skull-stripped, bias corrected etc).
%____________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_dartel_import.m 4194 2011-02-05 18:08:06Z ged $
matnames = job.matnames;
for i=1:numel(matnames),
p(i) = load(matnames{i});
end;
if numel(p)>0,
tmp = strvcat(p(1).VG.fname);
p(1).VG = spm_vol(tmp);
b0 = spm_load_priors(p(1).VG);
end;
odir = job.odir{1};
bb = job.bb;
vox = job.vox;
iopt = job.image;
opt = [job.GM, job.WM, job.CSF];
for i=1:numel(p),
preproc_apply(p(i),odir,b0,bb,vox,iopt,opt,matnames{i});
end;
out.cfiles = cell(numel(matnames),numel(opt));
if job.image,
out.files = cell(numel(matnames),1);
end
for i=1:numel(matnames),
[pth,nam,ext] = fileparts(matnames{i});
nam = nam(1:(numel(nam)-7));
if job.image,
fname = fullfile(odir,['r',nam, '.nii']);
out.files{i} = fname;
end
for k1=1:numel(opt),
if opt(k1),
fname = fullfile(odir,['r','c', num2str(k1), nam, '.nii']);
out.cfiles{i,k1} = fname;
end
end
end
return;
%=======================================================================
%=======================================================================
function preproc_apply(p,odir,b0,bb,vx,iopt,opt,matname)
[pth0,nam,ext,num] = spm_fileparts(matname);
[pth ,nam,ext,num] = spm_fileparts(p.VF(1).fname);
P = path_search([nam,ext],{pth,odir,pwd,pth0});
if isempty(P),
fprintf('Could not find "%s"\n', [nam,ext]);
return;
end;
p.VF.fname = P;
T = p.flags.Twarp;
bsol = p.flags.Tbias;
d2 = [size(T) 1];
d = p.VF.dim(1:3);
[x1,x2,o] = ndgrid(1:d(1),1:d(2),1);
x3 = 1:d(3);
d3 = [size(bsol) 1];
B1 = spm_dctmtx(d(1),d2(1));
B2 = spm_dctmtx(d(2),d2(2));
B3 = spm_dctmtx(d(3),d2(3));
bB3 = spm_dctmtx(d(3),d3(3),x3);
bB2 = spm_dctmtx(d(2),d3(2),x2(1,:)');
bB1 = spm_dctmtx(d(1),d3(1),x1(:,1));
mg = p.flags.mg;
mn = p.flags.mn;
vr = p.flags.vr;
K = length(p.flags.mg);
Kb = length(p.flags.ngaus);
lkp = []; for k=1:Kb, lkp = [lkp ones(1,p.flags.ngaus(k))*k]; end;
spm_progress_bar('init',length(x3),['Working on ' nam],'Planes completed');
M = p.VG(1).mat\p.flags.Affine*p.VF.mat;
if iopt, idat = zeros(d(1:3),'single'); end;
dat = {zeros(d(1:3),'uint8'),zeros(d(1:3),'uint8'),zeros(d(1:3),'uint8')};
for z=1:length(x3),
% Bias corrected image
f = spm_sample_vol(p.VF,x1,x2,o*x3(z),0);
msk = (f==0) | ~isfinite(f);
if ~isempty(bsol),
cr = exp(transf(bB1,bB2,bB3(z,:),bsol)).*f;
else
cr = f;
end
if iopt,
if bitand(iopt,2),
idat(:,:,z) = cr;
else
idat(:,:,z) = f;
end;
end;
[t1,t2,t3] = defs(T,z,B1,B2,B3,x1,x2,x3,M);
q = zeros([d(1:2) Kb]);
bg = ones(d(1:2));
bt = zeros([d(1:2) Kb]);
for k1=1:Kb,
bt(:,:,k1) = spm_sample_priors(b0{k1},t1,t2,t3,k1==Kb);
end;
b = zeros([d(1:2) K]);
for k=1:K,
b(:,:,k) = bt(:,:,lkp(k))*mg(k);
end;
s = sum(b,3);
for k=1:K,
p1 = exp((cr-mn(k)).^2/(-2*vr(k)))/sqrt(2*pi*vr(k)+eps);
q(:,:,lkp(k)) = q(:,:,lkp(k)) + p1.*b(:,:,k)./s;
end;
sq = sum(q,3)+eps;
for k1=1:3,
tmp = q(:,:,k1);
tmp = tmp./sq;
tmp(msk) = 0;
dat{k1}(:,:,z) = uint8(round(255 * tmp));
end;
spm_progress_bar('set',z);
end;
spm_progress_bar('clear');
%[dat{1},dat{2},dat{3}] = clean_gwc(dat{1},dat{2},dat{3}, 2);
if iopt,
if bitand(iopt,2),
nwm = 0;
swm = 0;
for z=1:numel(x3),
nwm = nwm + sum(sum(double(dat{2}(:,:,z))));
swm = swm + sum(sum(double(dat{2}(:,:,z)).*idat(:,:,z)));
end;
idat = idat*(double(nwm)/double(swm));
end;
if bitand(iopt,4),
for z=1:numel(x3),
%msk = double(dat{1}(:,:,z)) ...
% + double(dat{2}(:,:,z)) ...
% + 0.5*double(dat{3}(:,:,z));
%msk = msk<128;
%tmp = idat(:,:,z);
%tmp(msk) = 0;
%idat(:,:,z) = tmp;
wt = (double(dat{1}(:,:,z))+double(dat{2}(:,:,z)))/255;
idat(:,:,z) = idat(:,:,z).*wt;
end;
end;
for z=1:numel(x3),
tmp = idat(:,:,z);
tmp(~isfinite(double(tmp))) = 0;
idat(:,:,z) = tmp;
end;
end;
% Sort out bounding box etc
[bb1,vx1] = spm_get_bbox(p.VG(1), 'old');
bb(~isfinite(bb)) = bb1(~isfinite(bb));
if ~isfinite(vx), vx = abs(prod(vx1))^(1/3); end;
bb(1,:) = vx*ceil(bb(1,:)/vx);
bb(2,:) = vx*floor(bb(2,:)/vx);
% Figure out the mapping from the volumes to create to the original
mm = [
bb(1,1) bb(1,2) bb(1,3)
bb(2,1) bb(1,2) bb(1,3)
bb(1,1) bb(2,2) bb(1,3)
bb(2,1) bb(2,2) bb(1,3)
bb(1,1) bb(1,2) bb(2,3)
bb(2,1) bb(1,2) bb(2,3)
bb(1,1) bb(2,2) bb(2,3)
bb(2,1) bb(2,2) bb(2,3)]';
vx2 = inv(p.VG(1).mat)*[mm ; ones(1,8)];
odim = abs(round((bb(2,:)-bb(1,:))/vx))+1;
%dimstr = sprintf('%dx%dx%d',odim);
dimstr = '';
vx1 = [
1 1 1
odim(1) 1 1
1 odim(2) 1
odim(1) odim(2) 1
1 1 odim(3)
odim(1) 1 odim(3)
1 odim(2) odim(3)
odim(1) odim(2) odim(3)]';
M = p.Affine*vx2/[vx1 ; ones(1,8)];
mat0 = p.VF.mat*M;
mat = [mm ; ones(1,8)]/[vx1 ; ones(1,8)];
fwhm = max(vx./sqrt(sum(p.VF.mat(1:3,1:3).^2))-1,0.01);
for k1=1:numel(opt),
if opt(k1),
dat{k1} = decimate(dat{k1},fwhm);
VT = struct('fname',fullfile(odir,['r',dimstr,'c', num2str(k1), nam, '.nii']),...
'dim', odim,...
'dt', [spm_type('uint8') spm_platform('bigend')],...
'pinfo',[1/255 0]',...
'mat',mat);
VT = spm_create_vol(VT);
Ni = nifti(VT.fname);
Ni.mat0 = mat0;
Ni.mat_intent = 'Aligned';
Ni.mat0_intent = 'Aligned';
create(Ni);
for i=1:odim(3),
tmp = spm_slice_vol(dat{k1},M*spm_matrix([0 0 i]),odim(1:2),1)/255;
VT = spm_write_plane(VT,tmp,i);
end;
end;
end;
if iopt,
%idat = decimate(idat,fwhm);
VT = struct('fname',fullfile(odir,['r',dimstr,nam, '.nii']),...
'dim', odim,...
'dt', [spm_type('float32') spm_platform('bigend')],...
'pinfo',[1 0]',...
'mat',mat);
VT.descrip = 'Resliced';
if bitand(iopt,2), VT.descrip = [VT.descrip ', bias corrected']; end;
if bitand(iopt,4), VT.descrip = [VT.descrip ', skull stripped']; end;
VT = spm_create_vol(VT);
Ni = nifti(VT.fname);
Ni.mat0 = mat0;
Ni.mat_intent = 'Aligned';
Ni.mat0_intent = 'Aligned';
create(Ni);
for i=1:odim(3),
tmp = spm_slice_vol(idat,M*spm_matrix([0 0 i]),odim(1:2),1);
VT = spm_write_plane(VT,tmp,i);
end;
end;
return;
%=======================================================================
%=======================================================================
function [x1,y1,z1] = defs(sol,z,B1,B2,B3,x0,y0,z0,M)
x1a = x0 + transf(B1,B2,B3(z,:),sol(:,:,:,1));
y1a = y0 + transf(B1,B2,B3(z,:),sol(:,:,:,2));
z1a = z0(z) + transf(B1,B2,B3(z,:),sol(:,:,:,3));
x1 = M(1,1)*x1a + M(1,2)*y1a + M(1,3)*z1a + M(1,4);
y1 = M(2,1)*x1a + M(2,2)*y1a + M(2,3)*z1a + M(2,4);
z1 = M(3,1)*x1a + M(3,2)*y1a + M(3,3)*z1a + M(3,4);
return;
%=======================================================================
%=======================================================================
function t = transf(B1,B2,B3,T)
d2 = [size(T) 1];
t1 = reshape(reshape(T, d2(1)*d2(2),d2(3))*B3', d2(1), d2(2));
t = B1*t1*B2';
return;
%=======================================================================
%=======================================================================
function dat = decimate(dat,fwhm)
% Convolve the volume in memory (fwhm in voxels).
lim = ceil(2*fwhm);
s = fwhm/sqrt(8*log(2));
x = -lim(1):lim(1); x = spm_smoothkern(fwhm(1),x); x = x/sum(x);
y = -lim(2):lim(2); y = spm_smoothkern(fwhm(2),y); y = y/sum(y);
z = -lim(3):lim(3); z = spm_smoothkern(fwhm(3),z); z = z/sum(z);
i = (length(x) - 1)/2;
j = (length(y) - 1)/2;
k = (length(z) - 1)/2;
spm_conv_vol(dat,dat,x,y,z,-[i j k]);
return;
%=======================================================================
%=======================================================================
function [g,w,c] = clean_gwc(g,w,c, level)
if nargin<4, level = 1; end;
b = w;
b(1) = w(1);
% Build a 3x3x3 seperable smoothing kernel
%-----------------------------------------------------------------------
kx=[0.75 1 0.75];
ky=[0.75 1 0.75];
kz=[0.75 1 0.75];
sm=sum(kron(kron(kz,ky),kx))^(1/3);
kx=kx/sm; ky=ky/sm; kz=kz/sm;
th1 = 0.15;
if level==2, th1 = 0.2; end;
% Erosions and conditional dilations
%-----------------------------------------------------------------------
niter = 32;
spm_progress_bar('Init',niter,'Extracting Brain','Iterations completed');
for j=1:niter,
if j>2, th=th1; else th=0.6; end; % Dilate after two its of erosion.
for i=1:size(b,3),
gp = double(g(:,:,i));
wp = double(w(:,:,i));
bp = double(b(:,:,i))/255;
bp = (bp>th).*(wp+gp);
b(:,:,i) = uint8(round(bp));
end;
spm_conv_vol(b,b,kx,ky,kz,-[1 1 1]);
spm_progress_bar('Set',j);
end;
th = 0.05;
for i=1:size(b,3),
gp = double(g(:,:,i))/255;
wp = double(w(:,:,i))/255;
cp = double(c(:,:,i))/255;
bp = double(b(:,:,i))/255;
bp = ((bp>th).*(wp+gp))>th;
g(:,:,i) = uint8(round(255*gp.*bp./(gp+wp+cp+eps)));
w(:,:,i) = uint8(round(255*wp.*bp./(gp+wp+cp+eps)));
c(:,:,i) = uint8(round(255*(cp.*bp./(gp+wp+cp+eps)+cp.*(1-bp))));
end;
spm_progress_bar('Clear');
return;
%=======================================================================
%=======================================================================
function pthnam = path_search(nam,pth)
pthnam = '';
for i=1:numel(pth),
if exist(fullfile(pth{i},nam),'file'),
pthnam = fullfile(pth{i},nam);
return;
end;
end;
|
github
|
philippboehmsturm/antx-master
|
stat_thresh.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/ns/stat_thresh.m
| 16,232 |
utf_8
|
d2613cd524b47b58778eae21cddbf866
|
function [peak_threshold, extent_threshold, peak_threshold_1, extent_threshold_1] = ...
stat_thres(search_volume, num_voxels, fwhm, df, p_val_peak, ...
cluster_threshold, p_val_extent, nconj, nvar, EC_file, expr)
%
% stat_thresh.m
% Modified version of STAT_THRESHOLD function by Keith Worsley. The original
% STAT_THRESHOLD function is part of the FMRISTAT packgage. The main use of the
% original version is to calculate peak and cluster thresholds, both corrected
% and uncorrected. Details on input and output arguments are found in the
% original STAT_THRESHOLD function available from Keith Worsley's web site
% at McGill University's Math & Stat department.
%
% This stat_thresh.m function is a customized version to be called by a function
% spm_list_nS for non-stationarity correction of RFT-based cluster size test.
% The input and output of this function is therefore modified for producing cluster
% p-values (corrected) under non-stationarity. The modification includes:
% -supressing the output from being displayed.
% -the number of cluster p-values it can calculate has been increased to 500 clusters
% (the default in the original version was 5).
% -the p_val_extent is treated as extent, no matter how small it is.
%
% stat_thresh is called by spm_list_nS in the following format:
% [PEAK_P CLUSTER_P PEAK_P_1 CLUSTER_P_1] =
% stat_thresh(V_RESEL,NUM_VOX,1,[DF_ER;DF_RPV],ALPHA,CL_DEF_TH,CL_RESEL);
% PARAMETERS:
% V_RESEL: The seach volume in terms of resels. It is a 1x4 vector
% describing the topological characteristic of the search
% volume.
% NUM_VOX: The number of voxels in the search volume.
% DF_ER: Degrees of freedom of error
% DF_RPV: Degrees of freedom of RPV image estimation. Usually the same
% as the error df.
% ALPHA: The significance level of the peak (arbitrarily set to 0.05)
% CL_DEF_TH: The cluster defining threshold. Can be entered in terms of
% a p-value (uncorrected) or a t-value.
% CL_RESEL: The cluster size in terms of resel
%
% PEAK_P: Peak p-value (FWE corrected). Not used for our purpose.
% PEAK_P_1: Peak p-value (uncorrected). Not used for our purpose.
% CLUSTER_P: Cluster p-value (FWE corrected)
% CLUSTER_P_1: Cluster p-value (uncorrected)
%
% ----------------
%
% More etails on non-stationary cluster size test can be found in
%
% Worsley K J, Andermann M, Koulis T, MacDonald D and Evans A C
% Detecting Changes in Nonisotropic Images
% Human Brain Mapping 8: 98-101 (1999)
%
% Hayasaka S, Phan K L, Liberzon I, Worsley K J, and Nichols T E
% Nonstationary cluster size inference with random-field and permutation methods
% NeuroImage 22: 676-687 (2004)
%
%
%-----------------------------------------------------------------------------------
% Version 0.76b Feb 19, 2007 by Satoru Hayasaka
%
%############################################################################
% COPYRIGHT: Copyright 2003 K.J. Worsley
% Department of Mathematics and Statistics,
% McConnell Brain Imaging Center,
% Montreal Neurological Institute,
% McGill University, Montreal, Quebec, Canada.
% [email protected] , www.math.mcgill.ca/keith
%
% Permission to use, copy, modify, and distribute this
% software and its documentation for any purpose and without
% fee is hereby granted, provided that this copyright
% notice appears in all copies. The author and McGill University
% make no representations about the suitability of this
% software for any purpose. It is provided "as is" without
% express or implied warranty.
%############################################################################
%############################################################################
% UPDATES:
%
% Variable nvar is rounded so that it is recognized as an integer.
% Feb 19, 2007 by Satoru Hayasaka
%############################################################################
% Defaults:
if nargin<1; search_volume=[]; end
if nargin<2; num_voxels=[]; end
if nargin<3; fwhm=[]; end
if nargin<4; df=[]; end
if nargin<5; p_val_peak=[]; end
if nargin<6; cluster_threshold=[]; end
if nargin<7; p_val_extent=[]; end
if nargin<8; nconj=[]; end
if nargin<9; nvar=[]; end
if nargin<10; EC_file=[]; end
if nargin<11; expr=[]; end
if isempty(search_volume); search_volume=1000000; end
if isempty(num_voxels); num_voxels=1000000; end
if isempty(fwhm); fwhm=0.0; end
if isempty(df); df=Inf; end
if isempty(p_val_peak); p_val_peak=0.05; end
if isempty(cluster_threshold); cluster_threshold=0.001; end
if isempty(p_val_extent); p_val_extent=0.05; end
if isempty(nconj); nconj=1; end
if isempty(nvar); nvar=1; end
if size(fwhm,1)==1; fwhm(2,:)=fwhm; end
if size(fwhm,2)==1; scale=1; else scale=fwhm(1,2)/fwhm(1,1); fwhm=fwhm(:,1); end;
isscale=(scale>1);
if length(num_voxels)==1; num_voxels(2,1)=1; end
if size(search_volume,2)==1
radius=(search_volume/(4/3*pi)).^(1/3);
search_volume=[ones(length(radius),1) 4*radius 2*pi*radius.^2 search_volume];
end
if size(search_volume,1)==1
search_volume=[search_volume; [1 zeros(1,size(search_volume,2)-1)]];
end
lsv=size(search_volume,2);
fwhm_inv=all(fwhm>0)./(fwhm+any(fwhm<=0));
resels=search_volume.*repmat(fwhm_inv,1,lsv).^repmat(0:lsv-1,2,1);
invol=resels.*(4*log(2)).^(repmat(0:lsv-1,2,1)/2);
for k=1:2
D(k,1)=max(find(invol(k,:)))-1;
end
% determines which method was used to estimate fwhm (see fmrilm or multistat):
df_limit=4;
% max number of pvalues or thresholds to print:
% it can print out a ton of stuff! (the original default was 5)
nprint=500;
if length(df)==1; df=[df 0]; end
if size(df,1)==1; df=[df; Inf Inf]; end
if size(df,2)==1; df=[df [0; df(2,1)]]; end
% is_tstat=1 if it is a t statistic
is_tstat=(df(1,2)==0);
if is_tstat
df1=1;
df2=df(1,1);
else
df1=df(1,1);
df2=df(1,2);
end
if df2 >= 1000; df2=Inf; end
df0=df1+df2;
dfw1=df(2,1);
dfw2=df(2,2);
if dfw1 >= 1000; dfw1=Inf; end
if dfw2 >= 1000; dfw2=Inf; end
if length(nvar)==1; nvar(2,1)=df1; end
nvar = round(nvar); %-to make sure that nvar is integer!
if isscale & (D(2)>1 | nvar(1,1)>1 | df2<Inf)
D
nvar
df2
fprintf('Cannot do scale space.');
return
end
Dlim=D+[scale>1; 0];
DD=Dlim+nvar-1;
% Values of the F statistic:
t=((1000:-1:1)'/100).^4;
% Find the upper tail probs cumulating the F density using Simpson's rule:
if df2==Inf
u=df1*t;
b=exp(-u/2-log(2*pi)/2+log(u)/4)*df1^(1/4)*4/100;
else
u=df1*t/df2;
b=exp(-df0/2*log(1+u)+log(u)/4-betaln(1/2,(df0-1)/2))*(df1/df2)^(1/4)*4/100;
end
t=[t; 0];
b=[b; 0];
n=length(t);
sb=cumsum(b);
sb1=cumsum(b.*(-1).^(1:n)');
pt1=sb+sb1/3-b/3;
pt2=sb-sb1/3-b/3;
tau=zeros(n,DD(1)+1,DD(2)+1);
tau(1:2:n,1,1)=pt1(1:2:n);
tau(2:2:n,1,1)=pt2(2:2:n);
tau(n,1,1)=1;
tau(:,1,1)=min(tau(:,1,1),1);
% Find the EC densities:
u=df1*t;
for d=1:max(DD)
for e=0:min(min(DD),d)
s1=0;
cons=-((d+e)/2+1)*log(pi)+gammaln(d)+gammaln(e+1);
for k=0:(d-1+e)/2
[i,j]=ndgrid(0:k,0:k);
if df2==Inf
q1=log(pi)/2-((d+e-1)/2+i+j)*log(2);
else
q1=(df0-1-d-e)*log(2)+gammaln((df0-d)/2+i)+gammaln((df0-e)/2+j) ...
-gammalni(df0-d-e+i+j+k)-((d+e-1)/2-k)*log(df2);
end
q2=cons-gammalni(i+1)-gammalni(j+1)-gammalni(k-i-j+1) ...
-gammalni(d-k-i+j)-gammalni(e-k-j+i+1);
s2=sum(sum(exp(q1+q2)));
if s2>0
s1=s1+(-1)^k*u.^((d+e-1)/2-k)*s2;
end
end
if df2==Inf
s1=s1.*exp(-u/2);
else
s1=s1.*exp(-(df0-2)/2*log(1+u/df2));
end
if DD(1)>=DD(2)
tau(:,d+1,e+1)=s1;
if d<=min(DD)
tau(:,e+1,d+1)=s1;
end
else
tau(:,e+1,d+1)=s1;
if d<=min(DD)
tau(:,d+1,e+1)=s1;
end
end
end
end
% For multivariate statistics, add a sphere to the search region:
a=zeros(2,max(nvar));
for k=1:2
j=(nvar(k)-1):-2:0;
a(k,j+1)=exp(j*log(2)+j/2*log(pi) ...
+gammaln((nvar(k)+1)/2)-gammaln((nvar(k)+1-j)/2)-gammaln(j+1));
end
rho=zeros(n,Dlim(1)+1,Dlim(2)+1);
for k=1:nvar(1)
for l=1:nvar(2)
rho=rho+a(1,k)*a(2,l)*tau(:,(0:Dlim(1))+k,(0:Dlim(2))+l);
end
end
if is_tstat
t=[sqrt(t(1:(n-1))); -flipdim(sqrt(t),1)];
rho=[rho(1:(n-1),:,:); flipdim(rho,1)]/2;
for i=0:D(1)
for j=0:D(2)
rho(n-1+(1:n),i+1,j+1)=-(-1)^(i+j)*rho(n-1+(1:n),i+1,j+1);
end
end
rho(n-1+(1:n),1,1)=rho(n-1+(1:n),1,1)+1;
n=2*n-1;
end
% For scale space:
if scale>1
kappa=D(1)/2;
tau=zeros(n,D(1)+1);
for d=0:D(1)
s1=0;
for k=0:d/2
s1=s1+(-1)^k/(1-2*k)*exp(gammaln(d+1)-gammaln(k+1)-gammaln(d-2*k+1) ...
+(1/2-k)*log(kappa)-k*log(4*pi))*rho(:,d+2-2*k,1);
end
if d==0
cons=log(scale);
else
cons=(1-1/scale^d)/d;
end
tau(:,d+1)=rho(:,d+1,1)*(1+1/scale^d)/2+s1*cons;
end
rho(:,1:(D(1)+1),1)=tau;
end
if D(2)==0
d=D(1);
if nconj>1
% Conjunctions:
b=gamma(((0:d)+1)/2)/gamma(1/2);
for i=1:d+1
rho(:,i,1)=rho(:,i,1)/b(i);
end
m1=zeros(n,d+1,d+1);
for i=1:d+1
j=i:d+1;
m1(:,i,j)=rho(:,j-i+1,1);
end
for k=2:nconj
for i=1:d+1
for j=1:d+1
m2(:,i,j)=sum(rho(:,1:d+2-i,1).*m1(:,i:d+1,j),2);
end
end
m1=m2;
end
for i=1:d+1
rho(:,i,1)=m1(:,1,i)*b(i);
end
end
if ~isempty(EC_file)
if d<3
rho(:,(d+2):4,1)=zeros(n,4-d-2+1);
end
fid=fopen(EC_file,'w');
% first 3 are dimension sizes as 4-byte integers:
fwrite(fid,[n max(d+2,5) 1],'int');
% next 6 are bounding box as 4-byte floats:
fwrite(fid,[0 0 0; 1 1 1],'float');
% rest are the data as 4-byte floats:
if ~isempty(expr)
eval(expr);
end
fwrite(fid,t,'float');
fwrite(fid,rho,'float');
fclose(fid);
end
end
if all(fwhm>0)
pval_rf=zeros(n,1);
for i=1:D(1)+1
for j=1:D(2)+1
pval_rf=pval_rf+invol(1,i)*invol(2,j)*rho(:,i,j);
end
end
else
pval_rf=Inf;
end
% Bonferroni
pt=rho(:,1,1);
pval_bon=abs(prod(num_voxels))*pt;
% Minimum of the two:
pval=min(pval_rf,pval_bon);
tlim=1;
if p_val_peak(1) <= tlim
peak_threshold=minterp1(pval,t,p_val_peak);
if length(p_val_peak)<=nprint
peak_threshold;
end
else
% p_val_peak is treated as a peak value:
P_val_peak=interp1(t,pval,p_val_peak);
peak_threshold=P_val_peak;
if length(p_val_peak)<=nprint
P_val_peak;
end
end
if fwhm<=0 | any(num_voxels<0)
peak_threshold_1=p_val_peak+NaN;
extent_threshold=p_val_extent+NaN;
extent_threshold_1=extent_threshold;
return
end
% Cluster_threshold:
%###-Changed so that cluster_threshold is considered as cluster extent no matter what.
if cluster_threshold > eps
tt=cluster_threshold;
else
% cluster_threshold is treated as a probability:
tt=minterp1(pt,t,cluster_threshold);
Cluster_threshold=tt;
end
d=D(1);
rhoD=interp1(t,rho(:,d+1,1),tt);
p=interp1(t,pt,tt);
% Pre-selected peak:
pval=rho(:,d+1,1)./rhoD;
if p_val_peak(1) <= tlim
peak_threshold_1=minterp1(pval,t, p_val_peak);
if length(p_val_peak)<=nprint
peak_threshold_1;
end
else
% p_val_peak is treated as a peak value:
P_val_peak_1=interp1(t,pval,p_val_peak);
peak_threshold_1=P_val_peak_1;
if length(p_val_peak)<=nprint
P_val_peak_1;
end
end
if D(1)==0 | nconj>1 | nvar(1)>1 | D(2)>0 | scale>1
extent_threshold=p_val_extent+NaN;
extent_threshold_1=extent_threshold;
if length(p_val_extent)<=nprint
extent_threshold;
extent_threshold_1;
end
return
end
% Expected number of clusters:
%###-Change tlim to a small number so that p_val_extent is considered as cluster extent
tlim = eps;
EL=invol(1,d+1)*rhoD;
cons=gamma(d/2+1)*(4*log(2))^(d/2)/fwhm(1)^d*rhoD/p;
if df2==Inf & dfw1==Inf
if p_val_extent(1) <= tlim
pS=-log(1-p_val_extent)/EL;
extent_threshold=(-log(pS)).^(d/2)/cons;
pS=-log(1-p_val_extent);
extent_threshold_1=(-log(pS)).^(d/2)/cons;
if length(p_val_extent)<=nprint
extent_threshold;
extent_threshold_1;
end
else
% p_val_extent is now treated as a spatial extent:
pS=exp(-(p_val_extent*cons).^(2/d));
P_val_extent=1-exp(-pS*EL);
extent_threshold=P_val_extent;
P_val_extent_1=1-exp(-pS);
extent_threshold_1=P_val_extent_1;
if length(p_val_extent)<=nprint
P_val_extent;
P_val_extent_1;
end
end
else
% Find dbn of S by taking logs then using fft for convolution:
ny=2^12;
a=d/2;
b2=a*10*max(sqrt(2/(min(df1+df2,dfw1))),1);
if df2<Inf
b1=a*log((1-(1-0.000001)^(2/(df2-d)))*df2/2);
else
b1=a*log(-log(1-0.000001));
end
dy=(b2-b1)/ny;
b1=round(b1/dy)*dy;
y=((1:ny)'-1)*dy+b1;
numrv=1+(d+1)*(df2<Inf)+d*(dfw1<Inf)+(dfw2<Inf);
f=zeros(ny,numrv);
mu=zeros(1,numrv);
if df2<Inf
% Density of log(Beta(1,(df2-d)/2)^(d/2)):
yy=exp(y./a)/df2*2;
yy=yy.*(yy<1);
f(:,1)=(1-yy).^((df2-d)/2-1).*((df2-d)/2).*yy/a;
mu(1)=exp(gammaln(a+1)+gammaln((df2-d+2)/2)-gammaln((df2+2)/2)+a*log(df2/2));
else
% Density of log(exp(1)^(d/2)):
yy=exp(y./a);
f(:,1)=exp(-yy).*yy/a;
mu(1)=exp(gammaln(a+1));
end
nuv=[];
aav=[];
if df2<Inf
nuv=[df1+df2-d df2+2-(1:d)];
aav=[a repmat(-1/2,1,d)];
end
if dfw1<Inf
if dfw1>df_limit
nuv=[nuv dfw1-dfw1/dfw2-(0:(d-1))];
else
nuv=[nuv repmat(dfw1-dfw1/dfw2,1,d)];
end
aav=[aav repmat(1/2,1,d)];
end
if dfw2<Inf
nuv=[nuv dfw2];
aav=[aav -a];
end
for i=1:(numrv-1)
nu=nuv(i);
aa=aav(i);
yy=y/aa+log(nu);
% Density of log((chi^2_nu/nu)^aa):
f(:,i+1)=exp(nu/2*yy-exp(yy)/2-(nu/2)*log(2)-gammaln(nu/2))/abs(aa);
mu(i+1)=exp(gammaln(nu/2+aa)-gammaln(nu/2)-aa*log(nu/2));
end
% Check: plot(y,f); sum(f*dy,1) should be 1
omega=2*pi*((1:ny)'-1)/ny/dy;
shift=complex(cos(-b1*omega),sin(-b1*omega))*dy;
prodfft=prod(fft(f),2).*shift.^(numrv-1);
% Density of Y=log(B^(d/2)*U^(d/2)/sqrt(det(Q))):
ff=real(ifft(prodfft));
% Check: plot(y,ff); sum(ff*dy) should be 1
mu0=prod(mu);
% Check: plot(y,ff.*exp(y)); sum(ff.*exp(y)*dy.*(y<10)) should equal mu0
alpha=p/rhoD/mu0*fwhm(1)^d/(4*log(2))^(d/2);
% Integrate the density to get the p-value for one cluster:
pS=cumsum(ff(ny:-1:1))*dy;
pS=pS(ny:-1:1);
% The number of clusters is Poisson with mean EL:
pSmax=1-exp(-pS*EL);
if p_val_extent(1) <= tlim
yval=minterp1(-pSmax,y,-p_val_extent);
% Spatial extent is alpha*exp(Y) -dy/2 correction for mid-point rule:
extent_threshold=alpha*exp(yval-dy/2);
% For a single cluster:
yval=minterp1(-pS,y,-p_val_extent);
extent_threshold_1=alpha*exp(yval-dy/2);
if length(p_val_extent)<=nprint
extent_threshold;
extent_threshold_1;
end
else
% p_val_extent is now treated as a spatial extent:
P_val_extent=interp1(y,pSmax,log(p_val_extent/alpha)+dy/2);
extent_threshold=P_val_extent;
% For a single cluster:
P_val_extent_1=interp1(y,pS,log(p_val_extent/alpha)+dy/2);
extent_threshold_1=P_val_extent_1;
if length(p_val_extent)<=nprint
P_val_extent;
P_val_extent_1;
end
end
end
return
function x=gammalni(n);
i=find(n>=0);
x=Inf+n;
if ~isempty(i)
x(i)=gammaln(n(i));
end
return
function iy=minterp1(x,y,ix);
% interpolates only the monotonically increasing values of x at ix
n=length(x);
mx=x(1);
my=y(1);
xx=x(1);
for i=2:n
if x(i)>xx
xx=x(i);
mx=[mx xx];
my=[my y(i)];
end
end
iy=interp1(mx,my,ix);
return
|
github
|
philippboehmsturm/antx-master
|
tbx_cfg_hdw.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/HDW/tbx_cfg_hdw.m
| 9,492 |
utf_8
|
f45f5115b3ab70be34ef72399f52ff5d
|
function hdw = tbx_cfg_hdw
% Configuration file for toolbox 'High-Dimensional Warping'
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: tbx_cfg_hdw.m 3960 2010-06-30 17:41:24Z ged $
% ---------------------------------------------------------------------
% ref Reference Image
% ---------------------------------------------------------------------
ref = cfg_files;
ref.tag = 'ref';
ref.name = 'Reference Image';
ref.help = {'This is the reference image, which remains stationary.'};
ref.filter = 'image';
ref.ufilter = '.*';
ref.num = [1 1];
% ---------------------------------------------------------------------
% mov Moved Image
% ---------------------------------------------------------------------
mov = cfg_files;
mov.tag = 'mov';
mov.name = 'Moved Image';
mov.help = {'This is the moved image, which is warped to match the reference.'};
mov.filter = 'image';
mov.ufilter = '.*';
mov.num = [1 1];
% ---------------------------------------------------------------------
% data Subject
% ---------------------------------------------------------------------
data1 = cfg_branch;
data1.tag = 'data';
data1.name = 'Subject';
data1.val = {ref mov};
data1.help = {'Two images of the same subject, which are to be registered together. Prior to nonlinear high-dimensional warping, the images should be rigidly registered with each other.'};
% ---------------------------------------------------------------------
% data Subjects
% ---------------------------------------------------------------------
data = cfg_repeat;
data.tag = 'data';
data.name = 'Subjects';
data.help = {'Specify pairs of images to match together.'};
data.values = {data1};
data.num = [0 Inf];
% ---------------------------------------------------------------------
% nits Iterations
% ---------------------------------------------------------------------
nits = cfg_entry;
nits.tag = 'nits';
nits.name = 'Iterations';
nits.help = {'Number of iterations for the bias correction'};
nits.val = {8};
nits.strtype = 'n';
nits.num = [1 1];
% ---------------------------------------------------------------------
% fwhm Bias FWHM
% ---------------------------------------------------------------------
fwhm = cfg_menu;
fwhm.tag = 'fwhm';
fwhm.name = 'Bias FWHM';
fwhm.help = {'FWHM of Gaussian smoothness of bias. If your intensity nonuniformity is very smooth, then choose a large FWHM. This will prevent the algorithm from trying to model out intensity variation due to different tissue types. The model for intensity nonuniformity is one of i.i.d. Gaussian noise that has been smoothed by some amount, before taking the exponential. Note also that smoother bias fields need fewer parameters to describe them. This means that the algorithm is faster for smoother intensity nonuniformities.'};
fwhm.val = {60};
fwhm.labels = {'30mm cutoff'
'40mm cutoff'
'50mm cutoff'
'60mm cutoff'
'70mm cutoff'
'80mm cutoff'
'90mm cutoff'
'100mm cutoff'
'110mm cutoff'
'120mm cutoff'
'130mm cutoff'
'140mm cutoff'
'150mm cutoff'
'No correction'}';
fwhm.values = {30 40 50 60 70 80 90 100 110 120 130 140 150 Inf};
% ---------------------------------------------------------------------
% reg Bias regularisation
% ---------------------------------------------------------------------
reg = cfg_menu;
reg.tag = 'reg';
reg.name = 'Bias regularisation';
reg.help = {'We know a priori that intensity variations due to MR physics tend to be spatially smooth, whereas those due to different tissue types tend to contain more high frequency information. A more accurate estimate of a bias field can be obtained by including prior knowledge about the distribution of the fields likely to be encountered by the correction algorithm. For example, if it is known that there is little or no intensity non-uniformity, then it would be wise to penalise large values for the intensity nonuniformity parameters. This regularisation can be placed within a Bayesian context, whereby the penalty incurred is the negative logarithm of a prior probability for any particular pattern of nonuniformity.'};
reg.val = {1e-6};
reg.labels = {'no regularisation'
'extremely light regularisation'
'very light regularisation'
'light regularisation'
'medium regularisation'
'heavy regularisation'
'very heavy regularisation'
'extremely heavy regularisation'}';
reg.values = {0, 1e-9, 1e-8, 1e-7, 1e-6, 1e-5, 1e-4, 1e-3};
% ---------------------------------------------------------------------
% lmreg Levenberg-Marquardt regularisation
% ---------------------------------------------------------------------
lmreg = cfg_menu;
lmreg.tag = 'lmreg';
lmreg.name = 'Levenberg-Marquardt regularisation';
lmreg.help = {'Levenberg-Marquardt regularisation keeps the bias correction part stable. Higher values means more stability, but slower convergence.'};
lmreg.val = {1e-6};
lmreg.labels ={'no regularisation'
'extremely light regularisation'
'very light regularisation'
'light regularisation'
'medium regularisation'
'heavy regularisation'
'very heavy regularisation'
'extremely heavy regularisation'
}';
lmreg.values = {0, 1e-9, 1e-8, 1e-7, 1e-6, 1e-5, 1e-4, 1e-3};
% ---------------------------------------------------------------------
% bias_opts Bias Correction Options
% ---------------------------------------------------------------------
bias_opts = cfg_branch;
bias_opts.tag = 'bias_opts';
bias_opts.name = 'Bias Correction Options';
bias_opts.val = {nits fwhm reg lmreg };
bias_opts.help = {'MR images are usually corrupted by a smooth, spatially varying artifact that modulates the intensity of the image (bias). These artifacts, although not usually a problem for visual inspection, can impede automated processing of the images.'
'Before registering the images, an approximate bias correction is estimated for the moved image. This is based on minimising the difference between the images an a symmetric way. Prior to registering the images, they should be rigidly aligned together. The bias correction is estimated once for these aligned images.'}';
% ---------------------------------------------------------------------
% nits Iterations
% ---------------------------------------------------------------------
nitsw = cfg_entry;
nitsw.tag = 'nits';
nitsw.name = 'Iterations';
nitsw.help = {'Number of iterations for the warping.'};
nitsw.val = {8};
nitsw.strtype = 'n';
nitsw.num = [1 1];
% ---------------------------------------------------------------------
% reg Warping regularisation
% ---------------------------------------------------------------------
regw = cfg_entry;
regw.tag = 'reg';
regw.name = 'Warping regularisation';
regw.help = {'There is a tradeoff between the smoothness of the estimated warps, and the difference between the registered images. Higher values mean smoother warps, at the expense of a lower mean squared difference between the images.'};
regw.val = {4};
regw.strtype = 'e';
regw.num = [1 1];
% ---------------------------------------------------------------------
% warp_opts Warping Options
% ---------------------------------------------------------------------
warp_opts = cfg_branch;
warp_opts.tag = 'warp_opts';
warp_opts.name = 'Warping Options';
warp_opts.val = {nitsw regw};
warp_opts.help = {'There are a couple of user-customisable warping options.'};
% ---------------------------------------------------------------------
% hdw High-Dimensional Warping
% ---------------------------------------------------------------------
hdw = cfg_exbranch;
hdw.tag = 'hdw';
hdw.name = 'High-Dimensional Warping';
hdw.val = {data bias_opts warp_opts};
hdw.help = {'This toolbox is a Bayesian method for three dimensional registration of brain images/* \cite{ashburner00a} */. A finite element approach is used to obtain a maximum a posteriori (MAP) estimate of the deformation field at every voxel of a template volume. The priors used by the MAP estimate penalize unlikely deformations and enforce a continuous one-to-one mapping. The deformations are assumed to have some form of symmetry, in that priors describing the probability distribution of the deformations should be identical to those for the inverses (i.e., warping brain A to brain B should not be different probablistically from warping B to A). A gradient descent algorithm is used to estimate the optimum deformations.'
'Deformation fields are written with the same name as the moved image, but with "y_" prefixed on to the filename. Jacobian determinant images are also written (prefixed by "jy_").'}';
hdw.prog = @spm_local_hdw;
%======================================================================
function spm_local_hdw(job)
if ~isdeployed, addpath(fullfile(spm('Dir'),'toolbox','HDW')); end
spm_hdw(job);
|
github
|
philippboehmsturm/antx-master
|
spm_hdw.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/HDW/spm_hdw.m
| 10,972 |
utf_8
|
40c05cd670bad0c86a761d18e32f7811
|
function spm_hdw(job)
% Warp a pair of same subject images together
%
% Very little support can be provided for the warping routine, as it
% involves optimising a very nonlinear objective function.
% Also, don't ask what the best value for the regularisation is.
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_hdw.m 4148 2011-01-04 16:49:23Z guillaume $
for i=1:numel(job.data),
run_warping(job.data(i).mov{1},job.data(i).ref{1},job.warp_opts,job.bias_opts);
end;
%_______________________________________________________________________
%_______________________________________________________________________
function run_warping(PF,PG,warp_opts,bias_opts)
VG = spm_vol(PG);
VF = spm_vol(PF);
reg = warp_opts.reg;
nit = warp_opts.nits;
% Load the image pair as 8 bit.
%-----------------------------------------------------------------------
bo = bias_opts;
[VG.uint8,sf] = loaduint8(VG); % Template
VF.uint8 = bias_correction(VF,VG,bo.nits,bo.fwhm,bo.reg,bo.lmreg,sf);
% Try loading pre-existing deformation fields. Otherwise, create
% deformation fields from uniform affine transformations.
%-----------------------------------------------------------------------
[pth,nme,ext,num] = spm_fileparts(VF.fname);
ofname = fullfile(pth,['y_' nme '.nii']);
Def = cell(3,1);
if exist(ofname)==2,
P = [repmat(ofname,3,1), [',1,1';',1,2';',1,3']];
VT = spm_vol(P);
if any(abs(VT(1).mat\VG.mat - eye(4))>0.00001),
error('Incompatible affine transformation matrices.');
end;
Def{1} = spm_load_float(VT(1));
Def{2} = spm_load_float(VT(2));
Def{3} = spm_load_float(VT(3));
spm_affdef(Def{:},inv(VF.mat));
else,
fprintf('Generating uniform affine transformation field\n');
Def{1} = single(1:VG.dim(1))';
Def{1} = Def{1}(:,ones(VG.dim(2),1),ones(VG.dim(3),1));
Def{2} = single(1:VG.dim(2));
Def{2} = Def{2}(ones(VG.dim(1),1),:,ones(VG.dim(3),1));
Def{3} = reshape(single(1:VG.dim(3)),1,1,VG.dim(3));
Def{3} = Def{3}(ones(VG.dim(1),1),ones(VG.dim(2),1),:);
spm_affdef(Def{:},VF.mat\VG.mat);
end;
% Voxel sizes
%-----------------------------------------------------------------------
vxg = sqrt(sum(VG.mat(1:3,1:3).^2))';if det(VG.mat(1:3,1:3))<0, vxg(1) = -vxg(1); end;
vxf = sqrt(sum(VF.mat(1:3,1:3).^2))';if det(VF.mat(1:3,1:3))<0, vxf(1) = -vxf(1); end;
% Do warping
%-----------------------------------------------------------------------
fprintf('Warping (iterations=%d regularisation=%g)\n', nit, reg);
spm_warp(VG.uint8,VF.uint8,Def{:},[vxg vxf],[nit,reg,1,0]);
% Convert mapping from voxels to mm
%-----------------------------------------------------------------------
spm_affdef(Def{:},VF.mat);
% Write the deformations
%-----------------------------------------------------------------------
save_def(Def,VG.mat,ofname)
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [udat,sf] = loaduint8(V)
% Load data from file indicated by V into an array of unsigned bytes.
spm_progress_bar('Init',V.dim(3),...
['Computing max/min of ' spm_str_manip(V.fname,'t')],...
'Planes complete');
mx = -Inf;
for p=1:V.dim(3),
img = spm_slice_vol(V,spm_matrix([0 0 p]),V.dim(1:2),1);
mx = max([max(img(:)) mx]);
spm_progress_bar('Set',p);
end;
spm_progress_bar('Init',V.dim(3),...
['Loading ' spm_str_manip(V.fname,'t')],...
'Planes loaded');
sf = 255/mx;
udat = uint8(0);
udat(V.dim(1),V.dim(2),V.dim(3))=0;
for p=1:V.dim(3),
img = spm_slice_vol(V,spm_matrix([0 0 p]),V.dim(1:2),1);
udat(:,:,p) = round(max(min(img*sf,255),0));
spm_progress_bar('Set',p);
end;
spm_progress_bar('Clear');
return;
%_______________________________________________________________________
%_______________________________________________________________________
function t = transf(B1,B2,B3,T)
d2 = [size(T) 1];
t1 = reshape(reshape(T, d2(1)*d2(2),d2(3))*B3', d2(1), d2(2));
t = B1*t1*B2';
return;
%_______________________________________________________________________
%_______________________________________________________________________
function udat = bias_correction(VF,VG,nits,fwhm,reg1,reg2,sf)
% This function is intended for doing bias correction prior
% to high-dimensional intra-subject registration. Begin by
% coregistering, then run the bias correction, and then do
% the high-dimensional warping. A version of the first image
% is returned out, that has the same bias as that of the second
% image. This allows warping of the corrected first image, to
% match the uncorrected second image.
%
% Ideally, it would all be combined into the same model, but
% that would require quite a lot of extra work. I should really
% sort out a good convergence criterion, and make it a proper
% Levenberg-Marquardt optimisation.
vx = sqrt(sum(VF.mat(1:3,1:3).^2));
d = VF.dim(1:3);
sd = vx(1)*VF.dim(1)/fwhm; d3(1) = ceil(sd*2); krn_x = exp(-(0:(d3(1)-1)).^2/sd.^2)/sqrt(vx(1));
sd = vx(2)*VF.dim(2)/fwhm; d3(2) = ceil(sd*2); krn_y = exp(-(0:(d3(2)-1)).^2/sd.^2)/sqrt(vx(2));
sd = vx(3)*VF.dim(3)/fwhm; d3(3) = ceil(sd*2); krn_z = exp(-(0:(d3(3)-1)).^2/sd.^2)/sqrt(vx(3));
Cbias = kron(krn_z,kron(krn_y,krn_x)).^(-2)*prod(d)*reg1;
Cbias = sparse(1:length(Cbias),1:length(Cbias),Cbias,length(Cbias),length(Cbias));
B3bias = spm_dctmtx(d(3),d3(3));
B2bias = spm_dctmtx(d(2),d3(2));
B1bias = spm_dctmtx(d(1),d3(1));
lmRb = speye(size(Cbias))*prod(d)*reg2;
Tbias = zeros(d3);
ll = Inf;
spm_plot_convergence('Init','Bias Correction','- Log-likelihood','Iteration');
for subit=1:nits,
% Compute objective function and its 1st and second derivatives
Alpha = zeros(prod(d3),prod(d3)); % Second derivatives
Beta = zeros(prod(d3),1); % First derivatives
oll = ll;
ll = 0.5*Tbias(:)'*Cbias*Tbias(:);
for z=1:VF.dim(3),
M1 = spm_matrix([0 0 z]);
M2 = VG.mat\VF.mat*M1;
f1o = spm_slice_vol(VF,M1,VF.dim(1:2),0);
f2o = spm_slice_vol(VG,M2,VF.dim(1:2),0);
msk = (f1o==0) & (f2o==0);
f1o(msk) = 0;
f2o(msk) = 0;
ro = transf(B1bias,B2bias,B3bias(z,:),Tbias);
msk = abs(ro)>0.01; % false(d(1:2));
% Use the form based on an integral for bias that is
% far from uniform.
f1 = f1o(msk);
f2 = f2o(msk);
r = ro(msk);
e = exp(r);
t1 = (f2.*e-f1);
t2 = (f1./e-f2);
ll = ll + 1/4*sum(sum((t1.^2-t2.^2)./r));
wt1 = zeros(size(f1o));
wt2 = zeros(size(f1o));
wt1(msk) = (2*(t1.*f2.*e+t2.*f1./e)./r + (t2.^2-t1.^2)./r.^2)/4;
wt2(msk) = ((f2.^2.*e.^2-f1.^2./e.^2+t1.*f2.*e-t2.*f1./e)./r/2 ...
- (t1.*f2.*e+t2.*f1./e)./r.^2 + (t1.^2-t2.^2)./r.^3/2);
% Use the simple symmetric form for bias close to uniform
f1 = f1o(~msk);
f2 = f2o(~msk);
r = ro(~msk);
e = exp(r);
t1 = (f2.*e-f1);
t2 = (f1./e-f2);
ll = ll + (sum(t1.^2)+sum(t2.^2))/4;
wt1(~msk) = (t1.*f2.*e-t2.*f1./e)/2;
wt2(~msk) = ((f2.*e).^2+t1.*f2.*e + (f1./e).^2+t2.*f1./e)/2;
b3 = B3bias(z,:)';
Beta = Beta + kron(b3,spm_krutil(wt1,B1bias,B2bias,0));
Alpha = Alpha + kron(b3*b3',spm_krutil(wt2,B1bias,B2bias,1));
end;
spm_plot_convergence('Set',ll/prod(d));
if subit > 1 && ll>oll,
% Hasn't improved, so go back to previous solution
Tbias = oTbias;
ll = oll;
lmRb = lmRb*10;
else
% Accept new solution
oTbias = Tbias;
Tbias = Tbias(:);
Tbias = Tbias - (Alpha + Cbias + lmRb)\(Beta + Cbias*Tbias);
Tbias = reshape(Tbias,d3);
end;
end;
udat = uint8(0);
udat(VF.dim(1),VF.dim(2),VF.dim(3)) = 0;
for z=1:VF.dim(3),
M1 = spm_matrix([0 0 z]);
f1 = spm_slice_vol(VF,M1,VF.dim(1:2),0);
r = transf(B1bias,B2bias,B3bias(z,:),Tbias);
f1 = f1./exp(r);
udat(:,:,z) = round(max(min(f1*sf,255),0));
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function save_def(Def,mat,fname)
% Save a deformation field as an image
dim = [size(Def{1},1) size(Def{1},2) size(Def{1},3) 1 3];
dtype = 'FLOAT32';
off = 0;
scale = 1;
inter = 0;
dat = file_array(fname,dim,dtype,off,scale,inter);
N = nifti;
N.dat = dat;
N.mat = mat;
N.mat0 = mat;
N.mat_intent = 'Aligned';
N.mat0_intent = 'Aligned';
N.intent.code = 'VECTOR';
N.intent.name = 'Mapping';
N.descrip = 'Deformation field';
create(N);
N.dat(:,:,:,1,1) = Def{1};
N.dat(:,:,:,1,2) = Def{2};
N.dat(:,:,:,1,3) = Def{3};
% Write Jacobian determinants
[pth,nme,ext,num] = spm_fileparts(fname);
jfname = fullfile(pth,['j' nme '.nii'])
dt = spm_def2det(Def{:},N.mat);
dat = file_array(jfname,dim(1:3),dtype,off,scale,inter);
N = nifti;
N.dat = dat;
N.mat = mat;
N.mat0 = mat;
N.mat_intent = 'Aligned';
N.mat0_intent = 'Aligned';
N.intent.code = 'NONE';
N.intent.name = 'Det';
N.descrip = 'Jacobian Determinant';
create(N);
N.dat(:,:,:) = dt;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function theory
% This function is never called. It simply contains my derivation of the
% objective function and its first and second derivatives for the LM
% optimisation. Note that this would simply be summed over all voxels.
% An estimate of the variance should maybe have been included, but I'll
% leave that for a future version.
% These will be used to simplify expressions
r = x1*p1+x2*p2;
e = exp(r);
t1 = (f2*e-f1)
t2 = (f1/e-f2)
% This is the actual objective function
maple int((exp(-(x1*p1+x2*p2)*(1-t))*f1-exp((x1*p1+x2*p2)*t)*f2)^2/2,t=0..1)
f = 1/4*(t1^2-t2^2)/r
% These are the first derivatives
maple diff(1/4*((f1-f2*exp(x1*p1+x2*p2))^2-(f2-f1/exp(x1*p1+x2*p2))^2)/(x1*p1+x2*p2),x1)
d1 = p1*1/4*(2*(t1*f2*e+t2*f1/e)/r + (t2^2-t1^2)/r^2)
% These are the second derivatives
maple diff(diff(1/4*((f1-f2*exp(x1*p1+x2*p2))^2-(f2-f1/exp(x1*p1+x2*p2))^2)/(x1*p1+x2*p2),x1),x2)
d2 = p1*p2*(1/2*(f2^2*e^2-f1^2/e^2+t1*f2*e-t2*f1/e)/r - (t1*f2*e+t2*f1/e)/r^2 + 1/2*(t1^2-t2^2)/r^3)
% However, the above formulation has problems in limiting case of zero bias,
% so this objective function is used for these regions
f = (t1^2+t2^2)/4
% First derivs
maple diff((f1-exp(x1*p1+x2*p2)*f2)^2/4 + (f1/exp(x1*p1+x2*p2)-f2)^2/4,x1)
d1 = (p1*t1*f2*e - p1*t2*f1/e)/2
% Second derivatives
maple diff(diff((f1-exp(x1*p1+x2*p2)*f2)^2/4 + (f1/exp(x1*p1+x2*p2)-f2)^2/4,x1),x2)
d2 = p1*p2*(f2^2*e^2+t1*f2*e + f1^2/e^2+t2*f1/e)/2
|
github
|
philippboehmsturm/antx-master
|
run_correction.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/physiotools/run_correction.m
| 6,131 |
utf_8
|
f3e5799b94a4622ea9d01182fc9c113d
|
function varargout = run_correction(cmd, varargin)
% Template function to implement callbacks for an cfg_exbranch. The calling
% syntax is
% varargout = run_correction(cmd, varargin)
% where cmd is one of
% 'run' - out = run_correction('run', job)
% Run a job, and return its output argument
% 'vout' - dep = run_correction('vout', job)
% Examine a job structure with all leafs present and return an
% array of cfg_dep objects.
% 'check' - str = run_correction('check', subcmd, subjob)
% Examine a part of a fully filled job structure. Return an empty
% string if everything is ok, or a string describing the check
% error. subcmd should be a string that identifies the part of
% the configuration to be checked.
% 'defaults' - defval = run_correction('defaults', key)
% Retrieve defaults value. key must be a sequence of dot
% delimited field names into the internal def struct which is
% kept in function local_def. An error is returned if no
% matching field is found.
% run_correction('defaults', key, newval)
% Set the specified field in the internal def struct to a new
% value.
% Application specific code needs to be inserted at the following places:
% 'run' - main switch statement: code to compute the results, based on
% a filled job
% 'vout' - main switch statement: code to compute cfg_dep array, based
% on a job structure that has all leafs, but not necessarily
% any values filled in
% 'check' - create and populate switch subcmd switchyard
% 'defaults' - modify initialisation of defaults in subfunction local_defs
% Callbacks can be constructed using anonymous function handles like this:
% 'run' - @(job)run_correction('run', job)
% 'vout' - @(job)run_correction('vout', job)
% 'check' - @(job)run_correction('check', 'subcmd', job)
% 'defaults' - @(val)run_correction('defaults', 'defstr', val{:})
% Note the list expansion val{:} - this is used to emulate a
% varargin call in this function handle.
%
% This code is part of a batch job configuration system for MATLAB. See
% help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging
% Volkmar Glauche
% $Id: run_correction.m 7 2009-07-31 07:34:19Z glauche $
rev = '$Rev: 7 $'; %#ok
if ischar(cmd)
switch lower(cmd)
case 'run'
job = local_getjob(varargin{1});
% Sort out input arguments
if isfield(job.corrdata,'matfile')
% read and merge saved estimation output
var = load(job.corrdata.matfile{1});
job.corrdata.var = var;
end
WhichPhysioStr = char(fieldnames(job.corrdata.var.which));
switch WhichPhysioStr
case 'cardiac'
WhichPhysio = 0;
case 'resp'
WhichPhysio = 1;
case 'pulse'
WhichPhysio = 2;
case 'respcard'
WhichPhysio = 3;
case 'cardresp'
WhichPhysio = 4;
case 'resppulse'
WhichPhysio = 5;
case 'pulseresp'
WhichPhysio = 6;
end
% do computation, return results in variable out
out.images = TimeSerieImagePhysioCorrection1(job.images, job.corrdata.var.PhasesOfSlices, job.corrdata.var.CyclesOfSlices, WhichPhysio, job.corrdata.var.which.(WhichPhysioStr).corr, job.fitmethod, job.fitorder, job.sorder, job.prefix);
if nargout > 0
varargout{1} = out;
end
case 'vout'
job = local_getjob(varargin{1});
dep = cfg_dep;
dep.sname = 'Corrected Time Series';
dep.src_output = substruct('.','images');
dep.tgt_spec = cfg_findspec({{'filter','image'}});
% determine outputs, return cfg_dep array in variable dep
varargout{1} = dep;
case 'check'
if ischar(varargin{1})
subcmd = lower(varargin{1});
subjob = varargin{2};
str = '';
switch subcmd
% implement checks, return status string in variable str
otherwise
cfg_message('unknown:check', ...
'Unknown check subcmd ''%s''.', subcmd);
end
varargout{1} = str;
else
cfg_message('ischar:check', 'Subcmd must be a string.');
end
case 'defaults'
if nargin == 2
varargout{1} = local_defs(varargin{1});
else
local_defs(varargin{1:2});
end
otherwise
cfg_message('unknown:cmd', 'Unknown command ''%s''.', cmd);
end
else
cfg_message('ischar:cmd', 'Cmd must be a string.');
end
function varargout = local_defs(defstr, defval)
persistent defs;
if isempty(defs)
% initialise defaults
end
if ischar(defstr)
% construct subscript reference struct from dot delimited tag string
tags = textscan(defstr,'%s', 'delimiter','.');
subs = struct('type','.','subs',tags{1}');
try
cdefval = subsref(local_def, subs);
catch
cdefval = [];
cfg_message('defaults:noval', ...
'No matching defaults value ''%s'' found.', defstr);
end
if nargin == 1
varargout{1} = cdefval;
else
defs = subsasgn(defs, subs, defval);
end
else
cfg_message('ischar:defstr', 'Defaults key must be a string.');
end
function job = local_getjob(job)
if ~isstruct(job)
cfg_message('isstruct:job', 'Job must be a struct.');
end
|
github
|
philippboehmsturm/antx-master
|
run_phases_and_cycles.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/physiotools/run_phases_and_cycles.m
| 9,577 |
utf_8
|
1e141800f7c7283857f0e5c97d9643cd
|
function varargout = run_phases_and_cycles(cmd, varargin)
% Run the physiotool functions from SPM8 batch system
% varargout = run_phases_and_cycles(cmd, varargin)
% where cmd is one of
% 'run' - out = run_phases_and_cycles('run', job)
% Run a job, and return its output argument
% 'vout' - dep = run_phases_and_cycles('vout', job)
% Examine a job structure with all leafs present and return an
% array of cfg_dep objects.
% 'check' - str = run_phases_and_cycles('check', subcmd, subjob)
% Examine a part of a fully filled job structure. Return an empty
% string if everything is ok, or a string describing the check
% error. subcmd should be a string that identifies the part of
% the configuration to be checked.
% 'defaults' - defval = run_phases_and_cycles('defaults', key)
% Retrieve defaults value. key must be a sequence of dot
% delimited field names into the internal def struct which is
% kept in function local_def. An error is returned if no
% matching field is found.
% run_phases_and_cycles('defaults', key, newval)
% Set the specified field in the internal def struct to a new
% value.
% Application specific code needs to be inserted at the following places:
% 'run' - main switch statement: code to compute the results, based on
% a filled job
% 'vout' - main switch statement: code to compute cfg_dep array, based
% on a job structure that has all leafs, but not necessarily
% any values filled in
% 'check' - create and populate switch subcmd switchyard
% 'defaults' - modify initialisation of defaults in subfunction local_defs
% Callbacks can be constructed using anonymous function handles like this:
% 'run' - @(job)run_phases_and_cycles('run', job)
% 'vout' - @(job)run_phases_and_cycles('vout', job)
% 'check' - @(job)run_phases_and_cycles('check', 'subcmd', job)
% 'defaults' - @(val)run_phases_and_cycles('defaults', 'defstr', val{:})
% Note the list expansion val{:} - this is used to emulate a
% varargin call in this function handle.
%
% This code is part of a batch job configuration system for MATLAB. See
% help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging
% Volkmar Glauche
% $Id: run_phases_and_cycles.m 7 2009-07-31 07:34:19Z glauche $
rev = '$Rev: 7 $'; %#ok
if ischar(cmd)
switch lower(cmd)
case 'run'
job = local_getjob(varargin{1});
% do computation, return results in variable out
% combined estimation of phases&cycles and correction
% estimation of phases&cycles
out = struct('PhasesOfSlices', [], 'CyclesOfSlices', [], 'SIGNALS', [],'matfile','');
% Sort out input arguments
WhichPhysioStr = char(fieldnames(job.which));
ChanNames = fieldnames(job.which.(WhichPhysioStr));
ChanNames = ChanNames(1:end-1); % skip 'corr' field
physiofiles = cellfun(@(Chan)subsref(job.which.(WhichPhysioStr),substruct('.',Chan,'.','datafile')),ChanNames);
bandwidth = cellfun(@(Chan)subsref(job.which.(WhichPhysioStr),substruct('.',Chan,'.','bandwidth')),ChanNames);
signalyflip = cellfun(@(Chan)subsref(job.which.(WhichPhysioStr),substruct('.',Chan,'.','flip')),ChanNames);
switch WhichPhysioStr
case 'cardiac'
WhichPhysio = 0;
corrext = {'','Global','Cyclic'}; % dummy for corr == -1
channel = job.which.(WhichPhysioStr).cardiac.channel;
case 'resp'
WhichPhysio = 1;
corrext = {'Hist','Global','Cyclic'};
channel = 1; % dummy
case 'pulse'
WhichPhysio = 2;
corrext = {'','Global','Cyclic'}; % dummy for corr == -1
channel = 1; % dummy
case 'respcard'
WhichPhysio = 3;
corrext = {'GlobalHist','GlobalGlobal','GlobalCyclic','CyclicCyclic'};
channel = job.which.(WhichPhysioStr).cardiac.channel;
case 'cardresp'
WhichPhysio = 4;
corrext = {'HistGlobal','GlobalGlobal','CyclicGlobal','CyclicCyclic'};
channel = job.which.(WhichPhysioStr).cardiac.channel;
case 'resppulse'
WhichPhysio = 5;
corrext = {'GlobalHist','GlobalGlobal','GlobalCyclic','CyclicCyclic'};
channel = 1; % dummy
case 'pulseresp'
WhichPhysio = 6;
corrext = {'HistGlobal','GlobalGlobal','CyclicGlobal','CyclicCyclic'};
channel = 1; % dummy
end
% compute phases & cycles
[out.PhasesOfSlices, out.CyclesOfSlices, out.SIGNALS] = PhysioSignal_Plot_PhasesAndCyclesOfSlices23(physiofiles, job.TR, job.nslices, [1 job.nscans], WhichPhysio, job.which.(WhichPhysioStr).corr, [0;0], [0;0], bandwidth, job.TR*job.ndummy, channel, signalyflip);
% construct output filename based on input and correction
% method and save results
if numel(physiofiles) == 1
[p n e v] = fileparts(physiofiles{1});
else
[p n1 e v] = fileparts(physiofiles{1});
[p n2 e v] = fileparts(physiofiles{2});
if isequal(n1,n2)
n = n1;
else
n = [n1 n2];
end
end
out.which.(WhichPhysioStr).corr = job.which.(WhichPhysioStr).corr; % save info for reference during correction
out.matfile = {fullfile(p, [n corrext{job.which.(WhichPhysioStr).corr+2} WhichPhysioStr '.mat'])};
save(out.matfile{1},'-struct','out');
if nargout > 0
varargout{1} = out;
end
case 'vout'
job = local_getjob(varargin{1});
% initialise empty cfg_dep array
dep = cfg_dep;
dep = dep(false);
% determine outputs, return cfg_dep array in variable dep
% output structure
% out.matfile = filename with correction parameters - cell
% strings
% out.PhasesOfSlices
% out.CyclesOfSlices
% out.Signals
dep(1) = cfg_dep;
dep(1).sname = 'Correction parameters';
dep(1).src_output = substruct('.','matfile');
dep(1).tgt_spec = cfg_findspec({{'type','mat','strtype','e'}});
WhichPhysioStr = char(fieldnames(job.which));
switch WhichPhysioStr
case {'cardiac','pulse','resp'}
dep(2) = cfg_dep;
dep(2).sname = sprintf('PhasesOfSlices - %s(1)', WhichPhysioStr);
dep(2).src_output = substruct('.','PhasesOfSlices','()',{1,':'});
dep(2).tgt_spec = cfg_findspec({{'strtype','r'}});
dep(3) = cfg_dep;
dep(3).sname = sprintf('CyclesOfSlices - %s(1)', WhichPhysioStr);
dep(3).src_output = substruct('.','PhasesOfSlices','()',{1,':'});
dep(3).tgt_spec = cfg_findspec({{'strtype','r'}});
end
varargout{1} = dep;
case 'check'
if ischar(varargin{1})
subcmd = lower(varargin{1});
subjob = varargin{2};
str = '';
switch subcmd
% implement checks, return status string in variable str
otherwise
cfg_message('unknown:check', ...
'Unknown check subcmd ''%s''.', subcmd);
end
varargout{1} = str;
else
cfg_message('ischar:check', 'Subcmd must be a string.');
end
case 'defaults'
if nargin == 2
varargout{1} = local_defs(varargin{1});
else
local_defs(varargin{1:2});
end
otherwise
cfg_message('unknown:cmd', 'Unknown command ''%s''.', cmd);
end
else
cfg_message('ischar:cmd', 'Cmd must be a string.');
end
function varargout = local_defs(defstr, defval)
persistent defs;
if isempty(defs)
% initialise defaults
end
if ischar(defstr)
% construct subscript reference struct from dot delimited tag string
tags = textscan(defstr,'%s', 'delimiter','.');
subs = struct('type','.','subs',tags{1}');
try
cdefval = subsref(local_def, subs);
catch
cdefval = [];
cfg_message('defaults:noval', ...
'No matching defaults value ''%s'' found.', defstr);
end
if nargin == 1
varargout{1} = cdefval;
else
defs = subsasgn(defs, subs, defval);
end
else
cfg_message('ischar:defstr', 'Defaults key must be a string.');
end
function job = local_getjob(job)
if ~isstruct(job)
cfg_message('isstruct:job', 'Job must be a struct.');
end
|
github
|
philippboehmsturm/antx-master
|
run_est_apply.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/physiotools/run_est_apply.m
| 5,573 |
utf_8
|
12e58502fd85bc798bfe0f7195391a9a
|
function varargout = run_est_apply(cmd, varargin)
% Template function to implement callbacks for an cfg_exbranch. The calling
% syntax is
% varargout = run_est_apply(cmd, varargin)
% where cmd is one of
% 'run' - out = run_est_apply('run', job)
% Run a job, and return its output argument
% 'vout' - dep = run_est_apply('vout', job)
% Examine a job structure with all leafs present and return an
% array of cfg_dep objects.
% 'check' - str = run_est_apply('check', subcmd, subjob)
% Examine a part of a fully filled job structure. Return an empty
% string if everything is ok, or a string describing the check
% error. subcmd should be a string that identifies the part of
% the configuration to be checked.
% 'defaults' - defval = run_est_apply('defaults', key)
% Retrieve defaults value. key must be a sequence of dot
% delimited field names into the internal def struct which is
% kept in function local_def. An error is returned if no
% matching field is found.
% run_est_apply('defaults', key, newval)
% Set the specified field in the internal def struct to a new
% value.
% Application specific code needs to be inserted at the following places:
% 'run' - main switch statement: code to compute the results, based on
% a filled job
% 'vout' - main switch statement: code to compute cfg_dep array, based
% on a job structure that has all leafs, but not necessarily
% any values filled in
% 'check' - create and populate switch subcmd switchyard
% 'defaults' - modify initialisation of defaults in subfunction local_defs
% Callbacks can be constructed using anonymous function handles like this:
% 'run' - @(job)run_est_apply('run', job)
% 'vout' - @(job)run_est_apply('vout', job)
% 'check' - @(job)run_est_apply('check', 'subcmd', job)
% 'defaults' - @(val)run_est_apply('defaults', 'defstr', val{:})
% Note the list expansion val{:} - this is used to emulate a
% varargin call in this function handle.
%
% This code is part of a batch job configuration system for MATLAB. See
% help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging
% Volkmar Glauche
% $Id: run_est_apply.m 7 2009-07-31 07:34:19Z glauche $
rev = '$Rev: 7 $'; %#ok
if ischar(cmd)
switch lower(cmd)
case 'run'
job = local_getjob(varargin{1});
% augment estimation job with information from job.images
V = spm_vol(job.images{1});
job.nslices = V.dim(3);
job.nscans = numel(job.images);
% run estimation job
out = run_phases_and_cycles('run',job);
job.corrdata.var = out;
% run correction job, add images to output
out1 = run_correction('run',job);
out.images = out1.images;
if nargout > 0
varargout{1} = out;
end
case 'vout'
job = local_getjob(varargin{1});
% augment estimation job with information from job.images
if iscellstr(job.images) && ~isempty(job.images)
V = spm_vol(job.images{1});
job.nslices = V.dim(3);
job.nscans = numel(job.images);
else
job.nslices = '<UNDEFINED>';
job.nscans = '<UNDEFINED>';
end
% get estimation outputs
dep1 = run_phases_and_cycles('vout',job);
% get correction outputs
dep2 = run_correction('vout',job);
varargout{1} = [dep1 dep2];
case 'check'
if ischar(varargin{1})
subcmd = lower(varargin{1});
subjob = varargin{2};
str = '';
switch subcmd
% implement checks, return status string in variable str
otherwise
cfg_message('unknown:check', ...
'Unknown check subcmd ''%s''.', subcmd);
end
varargout{1} = str;
else
cfg_message('ischar:check', 'Subcmd must be a string.');
end
case 'defaults'
if nargin == 2
varargout{1} = local_defs(varargin{1});
else
local_defs(varargin{1:2});
end
otherwise
cfg_message('unknown:cmd', 'Unknown command ''%s''.', cmd);
end
else
cfg_message('ischar:cmd', 'Cmd must be a string.');
end
function varargout = local_defs(defstr, defval)
persistent defs;
if isempty(defs)
% initialise defaults
end
if ischar(defstr)
% construct subscript reference struct from dot delimited tag string
tags = textscan(defstr,'%s', 'delimiter','.');
subs = struct('type','.','subs',tags{1}');
try
cdefval = subsref(local_def, subs);
catch
cdefval = [];
cfg_message('defaults:noval', ...
'No matching defaults value ''%s'' found.', defstr);
end
if nargin == 1
varargout{1} = cdefval;
else
defs = subsasgn(defs, subs, defval);
end
else
cfg_message('ischar:defstr', 'Defaults key must be a string.');
end
function job = local_getjob(job)
if ~isstruct(job)
cfg_message('isstruct:job', 'Job must be a struct.');
end
|
github
|
philippboehmsturm/antx-master
|
tbx_run_fbi_dicom.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/FBIDicom/tbx_run_fbi_dicom.m
| 4,924 |
utf_8
|
07da3d668a76b3d2908774b7c8e5f7ae
|
function out = tbx_run_fbi_dicom(job)
% SPM job execution function
% takes a harvested job data structure and call SPM functions to perform
% computations on the data.
% Input:
% job - harvested job data structure (see matlabbatch help)
% Output:
% out - computation results, usually a struct variable.
% tbx_run_fbi_dicom.m,v 1.3 2008/05/21 11:43:30 vglauche Exp
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging
% Volkmar Glauche
% $Id: $
rev = '$Rev: 218 $'; %#ok<NASGU>
switch char(fieldnames(job.data))
case 'files'
files = {job.data.files};
case 'dirs'
files1 = cell(size(job.data.dirs));
for k = 1:numel(job.data.dirs)
files1{k} = recurse_dirs(deblank(job.data.dirs{k}),{});
end;
files = [files1{:}];
if numel(files) == 0
dstr = sprintf('%s\n', job.data.dirs{:});
error('tbx_fbi_dicom:failed', ...
['DICOM import failed:\n' ...
'No files/directories to convert.\n' ...
'Check that you have read permissions on the directories.\n%s'], dstr);
end;
case 'dicomdirs'
files1 = cell(size(job.data.dicomdirs));
for k = 1:numel(job.data.dicomdirs)
files1{k} = read_dicomdirs(job.data.dicomdirs{k});
end;
files = [files1{:}];
if numel(files) == 0
dstr = sprintf('%s\n', job.data.dirs{:});
error('tbx_fbi_dicom:failed', ...
['DICOM import failed:\n' ...
'No files/directories to convert.\n' ...
'Check that you have read permissions on the directories.\n%s'], dstr);
end;
end;
out.files = {};
rjob = cell(size(files));
switch spm('ver')
case 'SPM5'
for k = 1:numel(files)
rjob{k}.util{1}.dicom = job;
rjob{k}.util{1}.dicom.data = files{k};
end
% no detection of failed jobs
spm_jobman('run',rjob);
case {'SPM8','SPM8b'}
for k = 1:numel(files)
rjob{k}.spm.util.dicom = job;
rjob{k}.spm.util.dicom.data = files{k};
end
cjob = cfg_util('initjob', rjob);
cfg_util('run', cjob);
jout = cfg_util('getalloutputs', cjob);
cfg_util('deljob', cjob);
for k = 1:numel(jout)
if isfield(jout{k},'files')
out.files = [out.files(:); jout{k}.files(:)];
end
end
end
%______________________________________________________________________
% Recursively get all files from a directory and all its subdirectories
function pp = recurse_dirs(cdir,pp)
pp1 = {};
if exist(cdir, 'dir')
ad = dir(cdir);
for i=1:length(ad)
if ad(i).isdir
if ~strcmp(ad(i).name,'.') && ~strcmp(ad(i).name,'..')
pp = recurse_dirs([cdir filesep ad(i).name],pp);
end;
else
pp1{end+1} = fullfile(cdir, ad(i).name);
end;
end;
if ~isempty(pp1)
pp{end+1} = pp1;
end
else
warning('tbx_run_fbi_dicom:recurse_dirs', 'Can not access folder ''%s''. Data from this folder may be archived already.', cdir);
end
%______________________________________________________________________
% Read a dicomdirs file and parse its contents to get a series-wise list
% of files
function files = read_dicomdirs(dicomdirs)
p = fileparts(dicomdirs);
hdcmdirs = spm_dicom_headers(dicomdirs);
drs = hdcmdirs{1}.DirectoryRecordSequence;
% Get directory record types
hdrt = deblank(cellfun(@(item)subsref(item,substruct('.','DirectoryRecordType')), ...
drs,'UniformOutput', ...
false));
% Get start and end of series lists
% Assume that DirectoryRecordSequence is a linear listing of all items on
% CD and no files are listed "outside" of a SERIES
isseries = find(strcmp(hdrt, 'SERIES'));
files = cell(size(isseries));
if ~isempty(isseries)
ieseries = [isseries(2:end)-1 numel(hdrt)];
for cs = 1:numel(isseries)
files{cs} = {};
for ce = isseries(cs):ieseries(cs)
if isfield(drs{ce}, 'ReferencedFileID')
% canonicalise file names, assume filenames relative to
% dicomdir file location
cf = fullfile(p, ...
strrep(lower(deblank(drs{ce}.ReferencedFileID)),'\',filesep));
if exist(cf, 'file')
files{cs}{end+1} = cf;
else
cf = fullfile(p, ...
strrep(deblank(drs{ce}.ReferencedFileID),'\',filesep));
if exist(cf, 'file')
files{cs}{end+1} = cf;
end
end
end
end
end
% prune empty series
files = files(~cellfun(@isempty,files));
end
|
github
|
philippboehmsturm/antx-master
|
spm_dicom_query.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/FBIDicom/spm_dicom_query.m
| 19,806 |
utf_8
|
73257342ab7e797a1d6d9fdb52a49fb1
|
function spm_dicom_query
f=findobj(0,'tag',mfilename);
if ishandle(f)
clf(f,'reset');
set(f,'units','normalized','tag',mfilename, 'position',[.1 .25 .8 .5]);
else
f=figure('units','normalized','tag',mfilename, 'position',[.1 .25 ...
.8 .7], 'name',[spm('ver') ': DICOM query'], ...
'numbertitle','off', 'resize','off');
end;
l=uicontrol('style','listbox', 'units','normalized', ...
'position',[.1 .55 .8 .4], 'tag',[mfilename 'patbox'], 'max',2,...
'fontname','bitstream vera sans mono', 'callback',@addto_selbox);
l=uicontrol('style','text', 'string','PatName Filter', 'units','normalized', ...
'position',[.1 .50 .1 .04]);
l=uicontrol('style','edit', 'string','.*', 'units','normalized', ...
'position',[.2 .50 .1 .04], 'tag',[mfilename 'PatNamefilt'], ...
'callback',@filter_fill_patbox);
l=uicontrol('style','text', 'string','PatID Filter', 'units','normalized', ...
'position',[.3 .50 .1 .04]);
l=uicontrol('style','edit', 'string','.*', 'units','normalized', ...
'position',[.4 .50 .1 .04], 'tag',[mfilename 'PatIDfilt'], ...
'callback',@filter_fill_patbox);
l=uicontrol('style','text', 'string','StudyName Filter', 'units','normalized', ...
'position',[.1 .45 .1 .04]);
l=uicontrol('style','edit', 'string','.*', 'units','normalized', ...
'position',[.2 .45 .1 .04], 'tag',[mfilename 'StuNamefilt'], 'enable','off', ...
'callback',@filter_fill_patbox);
l=uicontrol('style','text', 'string','StudyDate Filter', 'units','normalized', ...
'position',[.3 .45 .1 .04]);
l=uicontrol('style','edit', 'string','.*', 'units','normalized', ...
'position',[.4 .45 .1 .04], 'tag',[mfilename 'StuDatefilt'], 'enable','off', ...
'callback',@filter_fill_patbox);
l=uicontrol('style','text', 'string','StudyTime Filter', 'units','normalized', ...
'position',[.5 .45 .1 .04]);
l=uicontrol('style','edit', 'string','.*', 'units','normalized', ...
'position',[.6 .45 .1 .04], 'tag',[mfilename 'StuTimefilt'], 'enable','off', ...
'callback',@filter_fill_patbox);
l=uicontrol('style','text', 'string','SequenceName Filter', 'units','normalized', ...
'position',[.1 .4 .1 .04]);
l=uicontrol('style','edit', 'string','.*', 'units','normalized', ...
'position',[.2 .4 .1 .04], 'tag',[mfilename 'SeqNamefilt'], 'enable','off', ...
'callback',@filter_fill_patbox);
l=uicontrol('style','text', 'string','ProtocolName Filter', 'units','normalized', ...
'position',[.3 .4 .1 .04]);
l=uicontrol('style','edit', 'string','.*', 'units','normalized', ...
'position',[.4 .4 .1 .04], 'tag',[mfilename 'ProNamefilt'], 'enable','off', ...
'callback',@filter_fill_patbox);
l=uibuttongroup('Title','Detail Level', 'units','normalized', ...
'position',[.1 .31 .6 .07], 'tag',[mfilename 'level'], ...
'SelectionChangeFcn',@update_fill_patbox);
lpat=uicontrol('parent',l, 'style','radio', 'string','Subject/Project', ...
'units','normalized', 'position',[0 .05 1/3 .95]);
lpat=uicontrol('parent',l, 'style','radio', 'string','Study/Examination', ...
'units','normalized', 'position',[1/3 .05 1/3 .95]);
lpat=uicontrol('parent',l, 'style','radio', 'string','Series', ...
'units','normalized', 'position',[2/3 .05 1/3 .95]);
l=uicontrol('style','pushbutton', 'string','Update List', 'callback', ...
@update_fill_patbox, 'units','normalized', 'position',[.7 .31 .2 .07]);
l=uicontrol('style','listbox', 'units','normalized', ...
'position',[.1 .1 .8 .2], 'tag',[mfilename 'selbox'], 'max',2,...
'fontname','bitstream vera sans mono', 'callback',@rmfrom_selbox, ...
'string',{}, 'userdata',{});
l=uicontrol('style','popup', 'string',{'SPM DICOM import (Fast)', 'SPM DICOM import (Expert)'}, 'callback', ...
@get_selected_files, 'units','normalized', 'position',[.1 .05 ...
.15 .05], 'tag',[mfilename 'button']);
l=uicontrol('style','popup', 'string',{'DTI DICOM import (Fast)', 'DTI DICOM import (Expert)', 'DICOM Copy Tool'}, 'callback', ...
@get_selected_files, 'units','normalized', 'position',[.3 .05 ...
.15 .05], 'tag',[mfilename 'button']);
l=uicontrol('style','pushbutton', 'string','Export dirnames', 'callback', ...
@get_selected_files, 'units','normalized', 'position',[.5 .05 ...
.15 .05], 'tag',[mfilename 'button']);
l=uicontrol('style','pushbutton', 'string','Cancel', 'callback', ...
@cancel, 'units','normalized', 'position',[.7 .05 ...
.2 .05], 'tag',[mfilename 'button']);
update_fill_patbox;
function update_fill_patbox(varargin)
spm('pointer','watch');
query_database;
filter_patbox;
fill_patbox;
spm('pointer','arrow');
function filter_fill_patbox(varargin)
spm('pointer','watch');
filter_patbox;
fill_patbox;
spm('pointer','arrow');
function filter_patbox(varargin)
set(findobj(0, 'tag',[mfilename 'patbox']),'value',1, ...
'string',{'Filtering results', 'Please wait...'});
drawnow;
ud =get(findobj(0, 'tag',[mfilename 'patbox']),'userdata');
lvls=get(get(findobj(0, 'tag',[mfilename 'level']),'children'));
lvl =find(cat(1,lvls.Value));
hser = [findobj(0,'tag',[mfilename 'SeqNamefilt']),...
findobj(0,'tag',[mfilename 'ProNamefilt'])];
hstu = [findobj(0,'tag',[mfilename 'StuNamefilt']),...
findobj(0,'tag',[mfilename 'StuDatefilt']),...
findobj(0,'tag',[mfilename 'StuTimefilt'])];
hpat = [findobj(0,'tag',[mfilename 'PatNamefilt']),...
findobj(0,'tag',[mfilename 'PatIDfilt'])];
IDCOLS=ud.PATIDCOLS+ud.STUIDCOLS+ud.SERIDCOLS;
ud.sel = ~cellfun(@isempty,regexp(ud.vals(:,IDCOLS+1),get(hpat(1),'string'),'once')) & ...
~cellfun(@isempty,regexp(ud.vals(:,IDCOLS+2),get(hpat(2),'string'),'once'));
if lvl < 3
ud.sel = ud.sel & ...
~cellfun(@isempty,regexp(ud.vals(:,IDCOLS+ud.PATCOLS+1), get(hstu(1),'string'), 'once')) & ...
~cellfun(@isempty,regexp(ud.vals(:,IDCOLS+ud.PATCOLS+2), get(hstu(2),'string'), 'once')) & ...
~cellfun(@isempty,regexp(ud.vals(:,IDCOLS+ud.PATCOLS+3), get(hstu(3), 'string'),'once'));
if lvl < 2
ud.sel = ud.sel & ...
~cellfun(@isempty,regexp(ud.vals(:,IDCOLS+ud.PATCOLS+ud.STUCOLS+2), get(hser(1),'string'), 'once')) & ...
~cellfun(@isempty,regexp(ud.vals(:,IDCOLS+ud.PATCOLS+ud.STUCOLS+3), get(hser(2),'string'), 'once'));
end
end
set(findobj(0, 'tag',[mfilename 'patbox']),'userdata',ud);
function query_database(varargin)
set(findobj(0,'tag',[mfilename 'patbox']), 'value',1,...
'string',{'Database query in progress', 'Please wait...'});
drawnow;
level={'--serieslevel','--studylevel','--patientlevel'}; % Level uis are read out in
% order opposite to creation
query_util='/apps/ctn-dicom/scripts/dicom_query';
lvls=get(get(findobj(0, 'tag',[mfilename 'level']),'children'));
lvl = logical(cat(1,lvls.Value));
[s result]=system(sprintf('%s %s --all',query_util,level{lvl}));
% get column numbers
ud.PATIDCOLS=0;
ud.PATCOLS=0;
ud.STUIDCOLS=0;
ud.STUCOLS=0;
ud.SERIDCOLS=0;
ud.SERCOLS=0;
ud.IMACOLS=0;
[tok result] = strtok(result,char(10));
while ~isempty(strfind(tok,'COLS='))
try
eval(['ud.' tok ';']);
[tok result] = strtok(result,char(10));
catch
break;
end
end
fmtstr=['|' repmat('%s',1,ud.PATIDCOLS+ud.PATCOLS+...
ud.STUIDCOLS+ud.STUCOLS+ud.SERIDCOLS+ud.SERCOLS+ud.IMACOLS)];
[tok result] = strtok(result,char(10));
ud.vals = textscan(result, fmtstr, 'delimiter','|', 'whitespace','');
ud.vals = deblank(cat(2,ud.vals{:}));
% trim vals to equal length per column
for k = (ud.PATIDCOLS+ud.STUIDCOLS+ud.SERIDCOLS+1):size(ud.vals,2)
tmp = strvcat(strcat(ud.vals(:,k),'.'));
for l = 1:size(ud.vals,1)
ud.vals{l,k} = strrep(tmp(l,:),' ','.');
end;
end;
ud.sel = true(size(ud.vals,1),1);
set(findobj(0,'tag',[mfilename 'patbox']),'userdata',ud);
function fill_patbox(varargin)
set(findobj(0,'tag',[mfilename 'patbox']),...
'string',{'Formatting results', 'Please wait...'});
drawnow;
stuindent='->';
serindent='--->';
imaindent='----->';
lvls=get(get(findobj(0, 'tag',[mfilename 'level']),'children'));
lvl =find(cat(1,lvls.Value));
hser = [findobj(0,'tag',[mfilename 'SeqNamefilt']) findobj(0,'tag',[mfilename 'ProNamefilt'])];
hstu = [findobj(0,'tag',[mfilename 'StuNamefilt']),...
findobj(0,'tag',[mfilename 'StuDatefilt']),...
findobj(0,'tag',[mfilename 'StuTimefilt'])];
switch lvl
case 1
set(hser,'enable','on');
set(hstu,'enable','on');
case 2
set(hser,'enable','off');
set(hstu,'enable','on');
case 3
set(hser,'enable','off');
set(hstu,'enable','off');
end;
ud = get(findobj(0,'tag',[mfilename 'patbox']),'userdata');
set(findobj(0,'tag',[mfilename 'patbox']), 'value',[]);
cstr = 1;
patlast=0;
stulast=0;
serlast=0;
vals = ud.vals(ud.sel,:);
ud.str=cell(4*size(vals,1),1);
ud.uid=cell(4*size(vals,1),1);
ud.valind=zeros(4*size(vals,1),1);
for k=1:size(vals,1)
if patlast == 0 || ~all(cellfun(@isequal,...
vals(k,ud.PATIDCOLS+ud.STUIDCOLS+ud.SERIDCOLS+(1:ud.PATCOLS)),...
vals(patlast,ud.PATIDCOLS+ud.STUIDCOLS+ud.SERIDCOLS+(1:ud.PATCOLS))))
ud.str{cstr} = strrep(sprintf('%s ', vals{k,ud.PATIDCOLS+ud.STUIDCOLS+ud.SERIDCOLS+...
(1:ud.PATCOLS)}),char(65533),'_');
ud.uid(cstr) = {vals(k,1:ud.PATIDCOLS)};
ud.valind(cstr) = k;
patlast = k;
cstr = cstr+1;
end;
if ud.STUCOLS
if stulast == 0 || ~all(cellfun(@isequal,...
vals(k,ud.PATIDCOLS+ud.STUIDCOLS+ud.SERIDCOLS+...
ud.PATCOLS+(1:ud.STUCOLS)),...
vals(stulast,ud.PATIDCOLS+ud.STUIDCOLS+ud.SERIDCOLS+...
ud.PATCOLS+(1:ud.STUCOLS))))
cval = vals(k,:);
timeval=str2double(regexprep(cval{ud.PATIDCOLS+ud.STUIDCOLS+ud.SERIDCOLS+...
ud.PATCOLS+3},'^(\.*)([0-9].*[0-9])(\.*)$','$2'));
timestr=sprintf('%02d:%02d',floor(timeval/3600),floor(rem(timeval/60,60)));
cval{ud.PATIDCOLS+ud.STUIDCOLS+ud.SERIDCOLS+ud.PATCOLS+3}=timestr;
ud.str{cstr} = strrep(sprintf('%s ', stuindent,...
cval{ud.PATIDCOLS+ud.STUIDCOLS+ud.SERIDCOLS+...
ud.PATCOLS+(1:ud.STUCOLS)}),char(65533),'_');
ud.uid(cstr) = {vals(k,1:(ud.PATIDCOLS+ud.STUIDCOLS))};
ud.valind(cstr) = k;
stulast = k;
cstr = cstr+1;
end;
end;
if ud.SERCOLS
if serlast == 0 || ~all(cellfun(@isequal,...
vals(k,ud.PATIDCOLS+ud.STUIDCOLS+ud.SERIDCOLS+...
ud.PATCOLS+ud.STUCOLS+(1:ud.SERCOLS)),...
vals(serlast,ud.PATIDCOLS+ud.STUIDCOLS+ud.SERIDCOLS+...
ud.PATCOLS+ud.STUCOLS+(1:ud.SERCOLS))))
ud.str{cstr} = strrep(sprintf('%s ', serindent,...
vals{k,ud.PATIDCOLS+ud.STUIDCOLS+ud.SERIDCOLS+...
ud.PATCOLS+ud.STUCOLS+(1:ud.SERCOLS)}),char(65533),'_');
ud.uid(cstr) = {vals(k,1:(ud.PATIDCOLS+ud.STUIDCOLS+ ...
ud.SERIDCOLS))};
ud.valind(cstr) = k;
serlast = k;
cstr = cstr+1;
end;
end;
if ud.IMACOLS
tmpstr=sprintf('%s ', imaindent, ...
vals{k,ud.PATIDCOLS+ud.STUIDCOLS+ud.SERIDCOLS+...
ud.PATCOLS+ud.STUCOLS+ud.SERCOLS+(1:ud.IMACOLS)});
ud.str{cstr} = strrep(tmpstr,char(65533),'_');
ud.uid(cstr) = {vals(k,1:(ud.PATIDCOLS+ud.STUIDCOLS+ud.SERIDCOLS))};
ud.valind(cstr) = k;
cstr = cstr+1;
end;
end;
if cstr == 1
ud.str = {'No hits in database.'};
ud.uid = {};
ud.valind = [];
else
ud.str = ud.str(1:(cstr-1));
ud.uid = ud.uid(1:(cstr-1));
ud.valind = ud.valind(1:(cstr-1));
end
set(findobj(0,'tag',[mfilename 'patbox']), 'string',ud.str,'userdata',ud);
function addto_selbox(varargin)
ud =get(findobj(0,'tag',[mfilename 'patbox']),'userdata');
sel2=get(findobj(0,'tag',[mfilename 'patbox']),'value');
uid1=get(findobj(0,'tag',[mfilename 'selbox']),'userdata');
str1=get(findobj(0,'tag',[mfilename 'selbox']),'string');
uid=[uid1(:); ud.uid(sel2)]';
str=[str1(:); ud.str(sel2)]';
set(findobj(0,'tag',[mfilename 'selbox']),'string',str, 'userdata',uid, 'value',[]);
function rmfrom_selbox(varargin)
sel=get(findobj(0,'tag',[mfilename 'selbox']),'value');
uid=get(findobj(0,'tag',[mfilename 'selbox']),'userdata');
str=get(findobj(0,'tag',[mfilename 'selbox']),'string');
set(findobj(0,'tag',[mfilename 'selbox']),'value',[]);
nsel=setdiff(1:numel(uid),sel);
if ~isempty(nsel)
set(findobj(0,'tag',[mfilename 'selbox']),'userdata',uid(nsel), 'string',str(nsel));
else
set(findobj(0,'tag',[mfilename 'selbox']),'userdata',{}, 'string',{});
end
function get_selected_files(varargin)
set(findobj(0,'tag',[mfilename 'button']),'Enable','off');
spm('pointer','watch');
uid=get(findobj(0,'tag',[mfilename 'selbox']),'userdata');
cmd = get(gcbo,'string');
if iscell(cmd)
% popup menu
cmd = cmd{get(gcbo, 'value')};
end;
patidstr='';
stuinsuidstr='';
serinsuidstr='';
for k=1:numel(uid)
switch numel(uid{k})
case 1,
patidstr=sprintf('PatientLevel.PatID="%s" OR %s', ...
deblank(uid{k}{1}), patidstr);
case 2,
stuinsuidstr=sprintf('StudyLevel.StuInsUID="%s" OR %s', ...
deblank(uid{k}{2}), stuinsuidstr);
case 3,
serinsuidstr=sprintf('SeriesLevel.SerInsUID="%s" OR %s', ...
deblank(uid{k}{3}), serinsuidstr);
end;
end;
querystr = ['select distinct SerPath='...
'substring(InstanceTable.Path, 1, char_length(InstanceTable.Path) -'...
' charindex( ''/'', reverse(InstanceTable.Path))) from InstanceTable, ImageLevel, SeriesLevel ' ...
'%s where SeriesLevel.SerInsUID = ImageLevel.SerParent and '...
'ImageLevel.SOPInsUID = InstanceTable.ImageUID and (%s)'];
isqlstr = ['export LANG=C\n'...
'export LC_ALL=C\n'...
'export SYBASE=/apps/sybase\n'...
'cat <<EOF|/apps/sybase/OCS-12_5/bin/isql -U fbidicom -P fbidicom -S FBIDICOM -H fbidicom -w 10000 -D DicomImage\n'...
'set nocount on\n%s\ngo\nEOF\n'];
dirs={};
if ~isempty(patidstr)
patidstr=sprintf(['(%s) and StudyLevel.PatParent=PatientLevel.PatID and '...
'SeriesLevel.StuParent=StudyLevel.StuInsUID'],patidstr(1:end-3));
patidtables=', StudyLevel, PatientLevel';
querypatid=sprintf(querystr, patidtables, patidstr);
[s w]=system(sprintf(isqlstr,querypatid));
tmp=textscan(w,'%s','delimiter',char(10));
dirs=[dirs(:); tmp{1}(3:end)]';
end;
if ~isempty(stuinsuidstr)
stuinsuidstr=sprintf(['(%s) and '...
'SeriesLevel.StuParent=' ...
'StudyLevel.StuInsUID'],stuinsuidstr(1:end-3));
stuinsuidtables=', StudyLevel';
querystuinsuid=sprintf(querystr, stuinsuidtables, stuinsuidstr);
[s w]=system(sprintf(isqlstr,querystuinsuid));
tmp=textscan(w,'%s','delimiter',char(10));
dirs=[dirs(:); tmp{1}(3:end)]';
end;
if ~isempty(serinsuidstr)
queryserinsuid=sprintf(querystr,'',serinsuidstr(1:end-3));
[s w]=system(sprintf(isqlstr,queryserinsuid));
tmp=textscan(w,'%s','delimiter',char(10));
dirs=[dirs(:); tmp{1}(3:end)]';
end;
dirs=deblank(dirs);
close(findobj(0,'tag',mfilename));
spm('pointer','arrow');
switch lower(cmd)
case {'spm dicom import (fast)','spm dicom import (expert)'}
switch lower(spm('ver'))
case {'spm5','spm8','spm8b'}
jtmp.fbi_dicom=struct('data',struct('dirs',{dirs}), ...
'outdir','<UNDEFINED>');
jobs{1}.tools={jtmp};
fg = spm_figure('findwin','Graphics');
if ~isempty(fg) && ishandle(fg)
figure(fg);
end
if strcmpi(cmd,'spm dicom import (fast)') == 1 && any(strcmpi(spm('ver'),{'spm8','spm8b'}))
spm_jobman('serial',jobs);
else
spm_jobman('interactive',jobs);
end;
case 'spm2'
addpath(fullfile(spm('dir'),'toolbox','DICOM'));
fg = spm_figure('findwin','Interactive');
if ~isempty(fg) && ishandle(fg)
figure(fg);
end
spm_DICOM(dirs);
end;
case {'dti dicom import (fast)','dti dicom import (expert)'}
switch lower(spm('ver'))
case {'spm8','spm8b'}
jobs = cell(1,numel(dirs)+3);
jobs{1}.cfg_basicio.cfg_named_dir.name = 'Output Directory';
jobs{1}.cfg_basicio.cfg_named_dir.dirs = {'<UNDEFINED>'};
jobs{2}.cfg_basicio.cfg_named_input.name = 'Save Hardi (1 = yes, 0 = no)';
jobs{2}.cfg_basicio.cfg_named_input.input = '<UNDEFINED>';
outdir(1) = cfg_dep;
outdir(1).sname = 'Named Directory Selector: Output Directory(1)';
outdir(1).src_exbranch = substruct('.','val', '{}',{1}, '.','val', '{}',{1});
outdir(1).src_output = substruct('.','dirs', '{}',{1});
shardi(1) = cfg_dep;
shardi(1).sname = 'Named Input: Save Hardi (1 = yes, 0 = no)';
shardi(1).src_exbranch = substruct('.','val', '{}',{2}, '.','val', '{}',{1});
shardi(1).src_output = substruct('.','input');
for k = 1:numel(dirs)
jobs{2*k-1+2}.spm.tools.fbi_dicom_dti=struct('dirs',{dirs(k)}, ...
'outdir',outdir);
rawdep(k) = cfg_dep;
rawdep(k).src_exbranch = substruct('.','val', '{}',{2*k-1+2}, '.','val', '{}',{1}, '.','val', '{}',{1});
rawdep(k).src_output = substruct('.','files');
jobs{2*k+2}.dtijobs.tensor.filename = rawdep(k);
jobs{2*k+2}.dtijobs.tensor.hardi = shardi;
end
jobs{end+1}.cfg_basicio.file_move.files = rawdep;
jobs{end}.cfg_basicio.file_move.action.delete = false;
if strcmpi(cmd,'dti dicom import (fast)') == 1
spm_jobman('serial',jobs);
else
spm_jobman('interactive',jobs);
end;
otherwise
error('Unsupported SPM version');
end
case 'dicom copy tool'
% need to run one dicom_copy_tool per subject
subj = cell(size(dirs));
stud = cell(size(dirs));
for k=1:numel(dirs)
[subj{k} n e] = fileparts(dirs{k});
stud{k} = [n e];
end;
[usubj unused ind] = unique(subj);
if numel(usubj)>1
sts=questdlg(sprintf(['You have selected %d subjects. DICOM Copy Tool ' ...
'has to be called for each subject separately. ' ...
'Do you want to proceed?'],numel(usubj)), ...
'Multiple subjects selected', 'Copy', 'Cancel', 'Copy');
if strcmp(sts,'Cancel')
assignin('base','dcmdirs',dirs);
fprintf('\nNames of data directories saved into workspace variable ''dcmdirs''.\n');
fprintf('DICOM Copy Tool will not be started.\n');
return;
end
end;
for k=1:numel(usubj)
dicom_copy_tool;
dicom_copy_model('set', 'makeDir', 1);
dicom_copy_model('set', 'efilmDir', usubj{k});
cstud = stud(ind==k);
for l=1:numel(cstud)
dicom_copy_model('set', 'setSourceDir', cstud{l})
end;
dicom_copy_model('set','ATsorting',1);
waitfor(findobj('tag','dicom_copy_figure'));
end;
case 'export dirnames'
assignin('base','dcmdirs',dirs);
fprintf('\nNames of data directories saved into workspace variable ''dcmdirs''.\n');
end;
function cancel(varargin)
close(findobj(0,'tag',mfilename));
|
github
|
philippboehmsturm/antx-master
|
tbx_run_fbi_ima.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/FBIDicom/tbx_run_fbi_ima.m
| 8,880 |
UNKNOWN
|
6885a91a97bcd2487e1df40d70e9e9dc
|
function out = tbx_run_fbi_ima(cmd, job)
%
% (c) Sebastian Thees 17.2.2001, email: [email protected]
%
% Dept. of Neurologie, Charite, Berlin, Germany
%
switch lower(cmd)
case 'run'
params.file = detImaParams(job.imaFileList{1});
order = genSliceOrder( params.file.nSlices, job.interleaved);
[p n e v] = spm_fileparts(job.imgFilename);
if ~any(strcmp(e,{'.img','.nii'}))
e = '.nii';
end
if params.file.isMosaic == 0
imgFilename = [n e];
img = zeros(params.file.matrix(1), params.file.matrix(2), numel(job.imaFileList), ...
'uint16');
for i = 1 : numel(job.imaFileList)
imaFid = fopen(job.imaFileList{order(i)}, 'r', 'ieee-be');
fseek( imaFid, 6144, 'bof');
[img(:,:,i), n]= fread( imaFid, params.file.matrix(1:2), 'uint16');
if n ~= params.file.imaSize
fclose('all');
error('Unable to read image %s completely. %2.4f %% read => terminating !',...
job.imaFileList{order(i)}, n/params.file.imaSize);
end
fclose( imaFid);
end
V = imaToImg_geometrie(imgFilename, job.odir{1}, params);
spm_write_vol(V, double(img));
out.outimgs{1} = V.fname;
else
xSize = params.file.matrix(1); ySize = params.file.matrix(2);
nX = params.file.nX; nY = params.file.nY; % mosaic-dimensions (1x1,2x2,4x4,8x8, ...)
oimg = zeros( xSize, ySize, nX*nY, 'uint16');
for i = 1 : numel(job.imaFileList)
imgFilename = sprintf('%s-%0*d%s', n, ceil(log10(numel(job.imaFileList)+1)), ...
i, e);
imaFid = fopen(job.imaFileList{i}, 'r', 'ieee-be');
fseek( imaFid, 6144, 'bof');
img = uint16( fread( imaFid, [nX*xSize nY*ySize], 'uint16'));
if size( img, 1)*size(img,2) ~= nX*xSize*nY*ySize % check for possible error
fclose('all');
error('Unable to read image completly. %2.4f %% read => terminating !\n\n', ...
size( img, 1)*size(img,2)/nX*xSize*nY*ySize);
end
%
% begin: image extraction
for j = 0 : nY - 1
for k = 0 : nX - 1
oimg(:,:, 1+k+j*nX) = img( 1 + k*xSize : (k+1)*xSize, 1 + j*xSize : (j+1)*xSize);
end
end
% end: image extraction
fclose( imaFid);
V = imaToImg_geometrie(imgFilename, job.odir{1}, params);
spm_write_vol(V, double(oimg));
out.outimgs{i} = V.fname;
end
end
case 'vout'
out = cfg_dep;
out.sname = 'Converted IMA images';
out.src_output = substruct('.','outimgs');
out.tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
end
function V = imaToImg_geometrie( imgFilename, path, params)
%
% Sebastian Thees 17.2.2001, email: [email protected]
%
% Dept. of Neurologie, Charite, Berlin, Germany
%
% calculate the rotations / translations and fix them in a .mat file
%
% intro / remember:
% coord in scanner: x => horizontal, to left is +
% y => vertical, up is +, therefor: z => to the feets is +
%
% coord in spm (neurological world ...): rot about 180� versus y.
%
M = eye( 4);
Tspm = eye( 3); % transformation from MRT Koord to SPM world.
Tspm(1,1) = -1;
Tspm(3,3) = -1;
Zoom = zeros( 3); % scaling in row, col and norm direction (Units == [mm]).
Zoom( 1, 1) = params.file.FoV(1) / params.file.matrix(1);
Zoom( 2, 2) = params.file.FoV(2) / params.file.matrix(2);
Zoom( 3, 3) = params.file.sliceThickness*(1+params.file.distFactor);
Tmrt = zeros( 3); % tranformation from native to scanned plot-orientation in MRT-KoordSys
Tmrt(1:3,1) = params.file.rowVect;
Tmrt(1:3,2) = params.file.colVect;
Tmrt(1:3,3) = params.file.normVect;
M(1:3,1:3) = Tspm * Tmrt * Zoom; % total transformation
% vector in MRT coord-sys to the voxel 1 1 1.
MRT_BBorigin = params.file.centerPoint - Zoom( 3, 3)/2*params.file.normVect - ...
(params.file.matrix(1)+1)/2*Zoom( 1, 1) * params.file.rowVect - ...
(params.file.matrix(2)+1)/2*Zoom( 2, 2) * params.file.colVect;
% this vector tells SPM where to locate the Voxel 1 1 1 (Units == [mm]).
M(1:3,4) = Tspm * MRT_BBorigin;
V.fname = fullfile(path, imgFilename);
V.dim = [params.file.matrix params.file.nSlices];
V.dt = [spm_type('uint16') spm_platform('bigend')];
V.mat = M;
V.pinfo = [Inf;Inf;0];
function order = genSliceOrder( n, type)
%
% Matthias Moosmann -Moosoft-
%
order = zeros(1,n);
switch type
case 1, %verschachtelt
%n gerade
if n/2==round(n/2),
for i=1:n,
if i/2==round(i/2),
order(i)=(n-i+2)/2 ;
else
order(i)= (2*n-i+1)/2;
end
end
%n ungerade
else
for i=1:n,
if i/2==round(i/2),
order(i)=(2*n-i+2)/2;
else
order(i)=(n-i+2)/2;
end
end
end
order = fliplr( order);
case 0, % ascending( MRT: first slice top)
order = 1 : n;
end
function params = detImaParams( filename)
%
% Sebastian Thees 17.2.2001, email: [email protected]
%
% Dept. of Neurologie, Charite, Berlin, Germany
%
% params = struct(
% name: string
% date: string
% time: string
% seqType: string
% acquisitionTime: double
% normVect: [3x1 double]
% colVect: [3x1 double]
% rowVect: [3x1 double]
% centerPoint: [3x1 double]
% distFromIsoCenter: double
% FoV: [2x1 double]
% sliceThickness: double
% distFactor: double
% repTime: double
% scanIndex: double
% angletype: [7x1 char]
% angle: [4x1 char]
% matrix: [2x1 douuble]
% nSlices: double
% isMosaic: int
% imaSize: int
% )
fid = fopen( filename, 'r', 's');
% who and when
fseek( fid, 768, 'bof');
params.name = sscanf( fread( fid, 25, 'uchar=>char'), '%s');
fseek( fid, 12, 'bof');
date = fread( fid, 3, 'uint32');
params.date = sprintf( '%d.%d.%d', date(3),date(2),date(1));
fseek( fid, 52, 'bof');
time = fread( fid, 3, 'uint32');
params.time = sprintf( '%d:%d:%d', time(1),time(2),time(3));
%scan stuff
fseek( fid, 3083, 'bof'); %sequenzeType
params.seqType = sscanf( fread( fid, 8, 'uchar=>char'), '%s');
fseek( fid, 2048, 'bof'); % acquisition Time
params.acquisitionTime = fread( fid, 1, 'double');
%geometrical stuff
fseek( fid, 3792, 'bof');
params.normVect = fread( fid, 3, 'double');
fseek( fid, 3856, 'bof');
params.colVect = fread( fid, 3, 'double');
fseek( fid, 3832, 'bof');
params.rowVect = fread( fid, 3, 'double');
fseek( fid, 3768, 'bof');
params.centerPoint = fread( fid, 3, 'double');
fseek( fid, 3816, 'bof');
params.distFromIsoCenter = fread( fid, 1, 'double');
% sliceParams ...
fseek( fid, 3744, 'bof');
params.FoV = fread( fid, 2, 'double');
%fseek( fid, 5000, 'bof');
%params.pixelSize = fread( fid, 2, 'double');
fseek( fid, 1544, 'bof');
params.sliceThickness = fread( fid, 1, 'double');
fseek( fid, 1560, 'bof');
params.repTime = fread( fid, 1, 'double');
fseek( fid, 5726, 'bof');
params.scanIndex = str2double( sscanf( fread( fid, 3, 'uchar=>char'), '%s'));
fseek( fid, 5814, 'bof');
params.angletype = fread( fid, 7, 'uchar=>char');
fseek( fid, 5821, 'bof');
params.angle = fread( fid, 4, 'uchar=>char');
%
% fourier transform MRI leeds to a squared image matrix:
fseek(fid, 2864, 'bof');
params.matrix(1) = fread( fid, 1, 'uint32');
params.matrix(2) = params.matrix(1);
%
fseek(fid, 1948, 'bof');
params.imaSize=fread( fid, 1, 'int32')/2;
% total imageSize
fseek(fid, 4994, 'bof'); params.imaDim = fread( fid, 2, 'short');
fseek(fid, 3984, 'bof'); p=fread(fid, 1, 'uint32');
if p~=0 % number of partitions not zero (-> 3D dataset)
params.nSlices=p;
params.distFactor = 0;
else
fseek( fid, 4004, 'bof'); params.nSlices = fread( fid, 1, 'uint32');
fseek( fid, 4136, 'bof'); params.distFactor = fread( fid, 1, 'double');
end
% estimate if file is mosaic or not
params.isMosaic=0; params.nX=1; params.nY=1;
% calculation of mosaic format assumes a "squared" format !!!
n = sqrt( params.imaSize/(params.matrix(1)*params.matrix(2)));
if (n>1) && (int32(n)==n)
params.isMosaic=1;
params.nX = params.imaDim(1)/params.matrix(1);
params.nY = params.imaDim(2)/params.matrix(2);
end
fclose( fid);
|
github
|
philippboehmsturm/antx-master
|
tbx_cfg_fbi_dicom_dti.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/FBIDicom/tbx_cfg_fbi_dicom_dti.m
| 4,637 |
utf_8
|
175dcc76897ab728ac7945dc7dff3290
|
function dicom = tbx_cfg_fbi_dicom_dti
% SPM Configuration file
% automatically generated by the MATLABBATCH utility function GENCODE
% Modified version for FBIDicom conversion for DTI data - needs to be
% kept in sync with tbx_cfg_fbi_dicom.m
%_______________________________________________________________________
% Copyright (C) 2008 Freiburg Brain Imaging
% $Id: tbx_cfg_fbi_dicom_dti.m 20 2008-10-20 09:39:12Z volkmar $
rev = '$Rev: 20 $';
% add path to toolbox
p = fileparts(mfilename('fullpath'));
addpath(p);
% ---------------------------------------------------------------------
% dirs DICOM directorie(s)
% ---------------------------------------------------------------------
dirs = cfg_files;
dirs.name = 'DICOM directorie(s)';
dirs.tag = 'dirs';
dirs.filter = 'dir';
dirs.num = [1 Inf];
dirs.help = {['Select the DICOM directory to convert. If multiple directories '...
'are specified, their data will be averaged into one DTD.mat.']};
% ---------------------------------------------------------------------
% root Directory structure for converted files
% ---------------------------------------------------------------------
root = cfg_menu;
root.tag = 'root';
root.name = 'Directory structure for converted files';
root.help = {
'Choose root directory of converted file tree. The options are:'
''
'* /projects/<ProjectName>/<StudyDate-StudyTime>: Automatically determine the project name from the DICOM patient name and try to convert into the projects directory.'
''
'* Output directory: ./<ProjectName>/<StudyDate-StudyTime>: Automatically determine the project name and try to convert into the output directory, starting with a ProjectName subdirectory.'
''
'* Output directory: ./<StudyDate-StudyTime>: Automatically determine the project name and try to convert into the output directory, starting with a StudyDate-StudyTime subdirectory. This option is useful if automatic project recognition fails and one wants to convert data into a project directory.'
''
'* Output directory: ./<PatientID>: Convert into the output directory, starting with a PatientID subdirectory.'
''
'* Output directory: ./<PatientName>: Convert into the output directory, starting with a PatientName subdirectory.'
'* No directory hierarchy: Convert all files into the output directory, without sequence/series subdirectories'
}';
root.labels = {
'Output directory: ./<StudyDate-StudyTime>'
'Output directory: ./<PatientID>'
'Output directory: ./<PatientID>/<StudyDate-StudyTime>'
'Output directory: ./<PatientName>'
'No directory hierarchy'
}';
root.values = {
'date_time'
'patid'
'patid_date'
'patname'
'flat'
}';
root.def = @(val)spm_get_defaults('dicom.root', val{:});
% ---------------------------------------------------------------------
% outdir Output directory
% ---------------------------------------------------------------------
outdir = cfg_files;
outdir.tag = 'outdir';
outdir.name = 'Output directory';
outdir.help = {'Select a directory where files are written. Default is current directory.'};
outdir.filter = 'dir';
outdir.ufilter = '.*';
outdir.num = [1 1];
% ---------------------------------------------------------------------
% dicom DICOM Import
% ---------------------------------------------------------------------
dicom = cfg_exbranch;
dicom.tag = 'fbi_dicom_dti';
dicom.name = 'FBI DICOM Import (DTI)';
dicom.val = {dirs root outdir};
dicom.help = {'DICOM Conversion. Most scanners produce data in DICOM format. This routine attempts to convert DICOM files into SPM compatible image volumes, which are written into the current directory by default. Note that not all flavours of DICOM can be handled, as DICOM is a very complicated format, and some scanner manufacturers use their own fields, which are not in the official documentation at http://medical.nema.org/'};
dicom.prog = @tbx_run_fbi_dicom_dti;
dicom.vout = @vout;
% ---------------------------------------------------------------------
% ---------------------------------------------------------------------
function dep = vout(job)
dep = cfg_dep;
dep.sname = 'Raw diffusion binary file';
dep.src_output = substruct('.','files');
dep.tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
|
github
|
philippboehmsturm/antx-master
|
tbx_cfg_fbi_dicom.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/toolbox/FBIDicom/tbx_cfg_fbi_dicom.m
| 10,299 |
utf_8
|
3cd48e1bd7669f5b1d12bfa4e8a3ff53
|
function dicom = tbx_cfg_fbi_dicom
% SPM Configuration file
% automatically generated by the MATLABBATCH utility function GENCODE
% Modified version for FBIDicom conversion - needs to be kept in sync
% with spm_cfg_dicom.m
%_______________________________________________________________________
% Copyright (C) 2008 Freiburg Brain Imaging
% $Id: tbx_cfg_fbi_dicom.m,v 1.8 2008-06-02 11:40:50 vglauche Exp $
rev = '$Rev: 1517 $';
% add path to toolbox
p = fileparts(mfilename('fullpath'));
addpath(p);
% ---------------------------------------------------------------------
% files DICOM files
% ---------------------------------------------------------------------
files = cfg_files;
files.tag = 'files';
files.name = 'DICOM files';
files.help = {'Select the DICOM files to convert.'};
files.filter = '.*';
files.ufilter = '.*';
files.num = [1 Inf];
% ---------------------------------------------------------------------
% dirs DICOM directory tree(s)
% ---------------------------------------------------------------------
dirs = cfg_files;
dirs.name = 'DICOM directory tree(s)';
dirs.tag = 'dirs';
dirs.filter = 'dir';
dirs.num = [1 Inf];
dirs.help = {['Select the root(s) of the DICOM directory tree(s) to convert. '...
'The conversion will recursively search each directory for ' ...
'files to convert.']};
% ---------------------------------------------------------------------
% dicomdirs DICOMDIR files
% ---------------------------------------------------------------------
dicomdirs = cfg_files;
dicomdirs.tag = 'dicomdirs';
dicomdirs.name = 'DICOMDIR files';
dicomdirs.help = {'Select the DICOMDIR file(s) to read.'};
dicomdirs.filter = '.*';
dicomdirs.ufilter = '^dicomdir$';
dicomdirs.num = [1 Inf];
% ---------------------------------------------------------------------
% data Select what (files or directories)?
% ---------------------------------------------------------------------
data = cfg_choice;
data.name = 'Select what (files or directories)?';
data.tag = 'data';
data.values = {files dirs dicomdirs};
data.help = {['Choose ''DICOM directory tree(s)'' if your DICOM data is organised ' ...
'in a directory tree. The conversion will then look recursively ' ...
'in each subdirectory to collect the files.'],...
'Alternatively, select the individual DICOM files to convert.'};
% ---------------------------------------------------------------------
% root Directory structure for converted files
% ---------------------------------------------------------------------
root = cfg_menu;
root.tag = 'root';
root.name = 'Directory structure for converted files';
root.help = {
'Choose root directory of converted file tree. The options are:'
''
'* /projects/<ProjectName>/<StudyDate-StudyTime>: Automatically determine the project name from the DICOM patient name and try to convert into the projects directory.'
''
'* Output directory: ./<ProjectName>/<StudyDate-StudyTime>: Automatically determine the project name and try to convert into the output directory, starting with a ProjectName subdirectory.'
''
'* Output directory: ./<StudyDate-StudyTime>: Automatically determine the project name and try to convert into the output directory, starting with a StudyDate-StudyTime subdirectory. This option is useful if automatic project recognition fails and one wants to convert data into a project directory.'
''
'* Output directory: ./<PatientID>: Convert into the output directory, starting with a PatientID subdirectory.'
''
'* Output directory: ./<PatientName>: Convert into the output directory, starting with a PatientName subdirectory.'
'* No directory hierarchy: Convert all files into the output directory, without sequence/series subdirectories'
}';
root.labels = {
'Output directory: ./<StudyDate-StudyTime>/<ProtocolName>'
'Output directory: ./<PatientID>/<ProtocolName>'
'Output directory: ./<PatientID>/<StudyDate-StudyTime>/<ProtocolName>'
'Output directory: ./<PatientName>/<ProtocolName>'
'Output directory: ./<ProtocolName>'
'No directory hierarchy'
}';
root.values = {
'date_time'
'patid'
'patid_date'
'patname'
'series'
'flat'
}';
root.def = @(val)spm_get_defaults('dicom.root', val{:});
% ---------------------------------------------------------------------
% outdir Output directory
% ---------------------------------------------------------------------
outdir = cfg_files;
outdir.tag = 'outdir';
outdir.name = 'Output directory';
outdir.help = {'Select a directory where files are written. Default is current directory.'};
outdir.filter = 'dir';
outdir.ufilter = '.*';
outdir.num = [1 1];
% ---------------------------------------------------------------------
% protfilter Protocol name filter
% ---------------------------------------------------------------------
protfilter = cfg_entry;
protfilter.tag = 'protfilter';
protfilter.name = 'Protocol name filter';
protfilter.help = {'A regular expression to filter protocol names. DICOM images whose protocol names do not match this filter will not be converted.'};
protfilter.strtype = 's';
protfilter.num = [0 Inf];
protfilter.val = {'.*'};
% ---------------------------------------------------------------------
% format Output image format
% ---------------------------------------------------------------------
format = cfg_menu;
format.tag = 'format';
format.name = 'Output image format';
format.help = {
'DICOM conversion can create separate img and hdr files or combine them in one file. The single file option will help you save space on your hard disk, but may be incompatible with programs that are not NIfTI-aware.'
'In any case, only 3D image files will be produced.'
}';
format.labels = {
'Two file (img+hdr) NIfTI'
'Single file (nii) NIfTI'
}';
format.values = {
'img'
'nii'
}';
format.def = @(val)spm_get_defaults('images.format', val{:});
% ---------------------------------------------------------------------
% icedims Use ICEDims in filename
% ---------------------------------------------------------------------
icedims = cfg_menu;
icedims.tag = 'icedims';
icedims.name = 'Use ICEDims in filename';
icedims.help = {'If image sorting fails, one can try using the additional SIEMENS ICEDims information to create unique filenames. Use this only if there would be multiple volumes with exactly the same file names.'};
icedims.labels = {
'No'
'Yes'
}';
icedims.values = {false true};
icedims.val = {false};
% ---------------------------------------------------------------------
% convopts Conversion options
% ---------------------------------------------------------------------
convopts = cfg_branch;
convopts.tag = 'convopts';
convopts.name = 'Conversion options';
convopts.val = {format icedims };
convopts.help = {''};
% ---------------------------------------------------------------------
% dicom DICOM Import
% ---------------------------------------------------------------------
dicom = cfg_exbranch;
dicom.tag = 'fbi_dicom';
dicom.name = 'FBI DICOM Import (SPM)';
dicom.val = {data root outdir protfilter convopts };
dicom.help = {'DICOM Conversion. Most scanners produce data in DICOM format. This routine attempts to convert DICOM files into SPM compatible image volumes, which are written into the current directory by default. Note that not all flavours of DICOM can be handled, as DICOM is a very complicated format, and some scanner manufacturers use their own fields, which are not in the official documentation at http://medical.nema.org/'};
dicom.prog = @tbx_run_fbi_dicom;
dicom.vout = @vout;
% ---------------------------------------------------------------------
% ---------------------------------------------------------------------
function dep = vout(job)
dep = cfg_dep;
dep.sname = 'Converted Images';
dep.src_output = substruct('.','files');
dep.tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
%% Currently unused configuration for tbxmp_convert_rp
function unused
% ---------------------------------------------------------------------
% srcimg Text file with image comments
% ---------------------------------------------------------------------
srcimg = cfg_files;
srcimg.tag = 'srcimg';
srcimg.name = 'Text file with image comments';
srcimg.help = {''};
srcimg.filter = '*.txt';
srcimg.ufilter = '.*';
srcimg.num = [1 1];
% ---------------------------------------------------------------------
% convert_rp Convert realignment parameters
% ---------------------------------------------------------------------
convert_rp = cfg_exbranch;
convert_rp.tag = 'convert_rp';
convert_rp.name = 'Convert realignment parameters';
convert_rp.val = {srcimg };
convert_rp.help = {
'Import realignment parameters documented by the Freiburg spm_dicom_convert'
'FORMAT tbxvol_import_rp(bch)'
'======'
'Two input files are necessary: one listing the filenames, the other'
'listing the image comments'
''
'This function is part of the volumes toolbox for SPM5. For general help about this toolbox, bug reports, licensing etc. type'
'spm_help vgtbx_config_Volumes'
'in the matlab command window after the toolbox has been launched.'
'_______________________________________________________________________'
''
'@(#) $Id: tbx_cfg_vgtbx_MedPhysConvert.m,v 1.1 2008-04-14 08:53:15 vglauche Exp $'
}';
convert_rp.prog = @tbxmp_convert_rp;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.