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
|
spm_get_bf.m
|
.m
|
antx-master/xspm8/spm_get_bf.m
| 5,655 |
utf_8
|
4a302f12929f57bbbe0fc6127fdd7bba
|
function [xBF] = spm_get_bf(xBF)
% fills in basis function structure
% FORMAT [xBF] = spm_get_bf(xBF);
%
% xBF.dt - time bin length {seconds}
% xBF.name - description of basis functions specified
% xBF.length - window length (seconds)
% xBF.order - order
% xBF.bf - Matrix of basis functions
%
% xBF.name 'hrf'
% 'hrf (with time derivative)'
% 'hrf (with time and dispersion derivatives)'
% 'Fourier set'
% 'Fourier set (Hanning)'
% 'Gamma functions'
% 'Finite Impulse Response'};
%
% (any other specification will default to hrf)
%__________________________________________________________________________
%
% spm_get_bf prompts for basis functions to model event or epoch-related
% responses. The basis functions returned are unitary and orthonormal
% when defined as a function of peri-stimulus time in time-bins.
% It is at this point that the distinction between event and epoch-related
% responses enters.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Karl Friston
% $Id: spm_get_bf.m 3934 2010-06-17 14:58:25Z guillaume $
% length of time bin
%--------------------------------------------------------------------------
if ~nargin
str = 'time bin for basis functions {secs}';
xBF.dt = spm_input(str,'+1','r',1/16,1);
end
dt = xBF.dt;
% assemble basis functions
%==========================================================================
% model event-related responses
%--------------------------------------------------------------------------
if ~isfield(xBF,'name')
spm_input('Hemodynamic Basis functions...',1,'d')
Ctype = {
'hrf',...
'hrf (with time derivative)',...
'hrf (with time and dispersion derivatives)',...
'Fourier set',...
'Fourier set (Hanning)',...
'Gamma functions',...
'Finite Impulse Response'};
str = 'Select basis set';
Sel = spm_input(str,2,'m',Ctype);
xBF.name = Ctype{Sel};
end
% get order and length parameters
%--------------------------------------------------------------------------
switch xBF.name
case { 'Fourier set','Fourier set (Hanning)',...
'Gamma functions','Finite Impulse Response'}
%----------------------------------------------------------------------
try, l = xBF.length;
catch, l = spm_input('window length {secs}',3,'e',32);
xBF.length = l;
end
try, h = xBF.order;
catch, h = spm_input('order',4,'e',4);
xBF.order = h;
end
end
% create basis functions
%--------------------------------------------------------------------------
switch xBF.name
case {'Fourier set','Fourier set (Hanning)'}
%----------------------------------------------------------------------
pst = [0:dt:l]';
pst = pst/max(pst);
% hanning window
%----------------------------------------------------------------------
if strcmp(xBF.name,'Fourier set (Hanning)')
g = (1 - cos(2*pi*pst))/2;
else
g = ones(size(pst));
end
% zeroth and higher Fourier terms
%----------------------------------------------------------------------
bf = g;
for i = 1:h
bf = [bf g.*sin(i*2*pi*pst)];
bf = [bf g.*cos(i*2*pi*pst)];
end
case {'Gamma functions'}
%----------------------------------------------------------------------
pst = [0:dt:l]';
bf = spm_gamma_bf(pst,h);
case {'Finite Impulse Response'}
%----------------------------------------------------------------------
bin = l/h;
bf = kron(eye(h),ones(round(bin/dt),1));
case {'NONE'}
%----------------------------------------------------------------------
bf = 1;
otherwise
% canonical hemodynamic response function
%----------------------------------------------------------------------
[bf p] = spm_hrf(dt);
% add time derivative
%----------------------------------------------------------------------
if strfind(xBF.name,'time')
dp = 1;
p(6) = p(6) + dp;
D = (bf(:,1) - spm_hrf(dt,p))/dp;
bf = [bf D(:)];
p(6) = p(6) - dp;
% add dispersion derivative
%------------------------------------------------------------------
if strfind(xBF.name,'dispersion')
dp = 0.01;
p(3) = p(3) + dp;
D = (bf(:,1) - spm_hrf(dt,p))/dp;
bf = [bf D(:)];
end
end
% length and order
%----------------------------------------------------------------------
xBF.length = size(bf,1)*dt;
xBF.order = size(bf,2);
end
% Orthogonalise and fill in basis function structure
%--------------------------------------------------------------------------
xBF.bf = spm_orth(bf);
%==========================================================================
%- S U B - F U N C T I O N S
%==========================================================================
% compute Gamma functions
%--------------------------------------------------------------------------
function bf = spm_gamma_bf(u,h)
% returns basis functions used for Volterra expansion
% FORMAT bf = spm_gamma_bf(u,h);
% u - times {seconds}
% h - order
% bf - basis functions (mixture of Gammas)
%__________________________________________________________________________
u = u(:);
bf = [];
for i = 2:(1 + h)
m = 2^i;
s = sqrt(m);
bf = [bf spm_Gpdf(u,(m/s)^2,m/s^2)];
end
|
github
|
philippboehmsturm/antx-master
|
spm_eeval.m
|
.m
|
antx-master/xspm8/spm_eeval.m
| 8,442 |
utf_8
|
e737ca615edb620ef652dad343579121
|
function [p,msg] = spm_eeval(str,Type,n,m)
% Expression evaluation
% FORMAT [p,msg] = spm_eeval(str,Type,n,m)
% Str - Expression to work with
%
% Type - type of evaluation
% - 's'tring
% - 'e'valuated string
% - 'n'atural numbers
% - 'w'hole numbers
% - 'i'ntegers
% - 'r'eals
% - 'c'ondition indicator vector
%
% n ('e', 'c' & 'p' types)
% - Size of matrix requred
% - NaN for 'e' type implies no checking - returns input as evaluated
% - length of n(:) specifies dimension - elements specify size
% - Inf implies no restriction
% - Scalar n expanded to [n,1] (i.e. a column vector)
% (except 'x' contrast type when it's [n,np] for np
% - E.g: [n,1] & [1,n] (scalar n) prompt for an n-vector,
% returned as column or row vector respectively
% [1,Inf] & [Inf,1] prompt for a single vector,
% returned as column or row vector respectively
% [n,Inf] & [Inf,n] prompts for any number of n-vectors,
% returned with row/column dimension n respectively.
% [a,b] prompts for an 2D matrix with row dimension a and
% column dimension b
% [a,Inf,b] prompt for a 3D matrix with row dimension a,
% page dimension b, and any column dimension.
% - 'c' type can only deal with single vectors
% - NaN for 'c' type treated as Inf
% - Defaults (missing or empty) to NaN
%
% m ('n', 'w', 'n1', 'w1', 'bn1' & 'bw1' types)
% - Maximum value (inclusive)
%
% m ('r' type)
% - Maximum and minimum values (inclusive)
%
% m ('c' type)
% - Number of unique conditions required by 'c' type
% - Inf implies no restriction
% - Defaults (missing or empty) to Inf - no restriction
%
% p - Result
%
% msg - Explanation of why it didn't work
%
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Andrew Holmes
% $Id: spm_eeval.m 3756 2010-03-05 18:43:37Z guillaume $
if nargin<4, m=[]; end
if nargin<3, n=[]; end
if nargin<2, Type='e'; end
if nargin<1, str=''; end
if isempty(str), p='!'; msg='empty input'; return, end
switch lower(Type)
case 's'
p = str; msg = '';
case 'e'
p = evalin('base',['[',str,']'],'''!''');
if ischar(p)
msg = 'evaluation error';
else
[p,msg] = sf_SzChk(p,n);
end
case 'n'
p = evalin('base',['[',str,']'],'''!''');
if ischar(p)
msg = 'evaluation error';
elseif any(floor(p(:))~=p(:)|p(:)<1) || ~isreal(p)
p='!'; msg='natural number(s) required';
elseif ~isempty(m) && any(p(:)>m)
p='!'; msg=['max value is ',num2str(m)];
else
[p,msg] = sf_SzChk(p,n);
end
case 'w'
p = evalin('base',['[',str,']'],'''!''');
if ischar(p)
msg = 'evaluation error';
elseif any(floor(p(:))~=p(:)|p(:)<0) || ~isreal(p)
p='!'; msg='whole number(s) required';
elseif ~isempty(m) && any(p(:)>m)
p='!'; msg=['max value is ',num2str(m)];
else
[p,msg] = sf_SzChk(p,n);
end
case 'i'
p = evalin('base',['[',str,']'],'''!''');
if ischar(p)
msg = 'evaluation error';
elseif any(floor(p(:))~=p(:)) || ~isreal(p)
p='!'; msg='integer(s) required';
else
[p,msg] = sf_SzChk(p,n);
end
case 'p'
p = evalin('base',['[',str,']'],'''!''');
if ischar(p)
msg = 'evaluation error';
elseif length(setxor(p(:)',m))
p='!'; msg='invalid permutation';
else
[p,msg] = sf_SzChk(p,n);
end
case 'r'
p = evalin('base',['[',str,']'],'''!''');
if ischar(p)
msg = 'evaluation error';
elseif ~isreal(p)
p='!'; msg='real number(s) required';
elseif ~isempty(m) && ( max(p)>max(m) || min(p)<min(m) )
p='!'; msg=sprintf('real(s) in [%g,%g] required',min(m),max(m));
else
[p,msg] = sf_SzChk(p,n);
end
case 'c'
if isempty(m), m=Inf; end
[p,msg] = icond(str,n,m);
otherwise
error('unrecognised type');
end
return;
function [i,msg] = icond(i,n,m)
if nargin<3, m=Inf; end
if nargin<2, n=NaN; end
if any(isnan(n(:)))
n=Inf;
elseif (length(n(:))==2 & ~any(n==1)) | length(n(:))>2
error('condition input can only do vectors')
end
if nargin<2, i=''; end
if isempty(i), varargout={[],'empty input'}; return, end
msg = ''; i=i(:)';
if ischar(i)
if i(1)=='0' & all(ismember(unique(i(:)),char(abs('0'):abs('9'))))
%-Leading zeros in a digit list
msg = sprintf('%s expanded',i);
z = min(find([diff(i=='0'),1]));
i = [zeros(1,z), icond(i(z+1:end))'];
else
%-Try an eval, for functions & string #s
i = evalin('base',['[',i,']'],'i');
end
end
if ischar(i)
%-Evaluation error from above: see if it's an 'abab' or 'a b a b' type:
[c,null,i] = unique(lower(i(~isspace(i))));
if all(ismember(c,char(abs('a'):abs('z'))))
%-Map characters a-z to 1-26, but let 'r' be zero (rest)
tmp = c-'a'+1; tmp(tmp=='r'-'a'+1)=0;
i = tmp(i);
msg = [sprintf('[%s] mapped to [',c),...
sprintf('%d,',tmp(1:end-1)),...
sprintf('%d',tmp(end)),']'];
else
i = '!'; msg = 'evaluation error';
end
elseif ~all(floor(i(:))==i(:))
i = '!'; msg = 'must be integers';
elseif length(i)==1 & prod(n)>1
msg = sprintf('%d expanded',i);
i = floor(i./10.^[floor(log10(i)+eps):-1:0]);
i = i-[0,10*i(1:end-1)];
end
%-Check size of i & #conditions
if ~ischar(i), [i,msg] = sf_SzChk(i,n,msg); end
if ~ischar(i) & isfinite(m) & length(unique(i))~=m
i = '!'; msg = sprintf('%d conditions required',m);
end
return;
function str = sf_SzStr(n,unused)
%=======================================================================
%-Size info string constuction
if nargin<2, l=0; else l=1; end
if nargin<1, error('insufficient arguments'); end;
if isempty(n), n=NaN; end
n=n(:); if length(n)==1, n=[n,1]; end; dn=length(n);
if any(isnan(n)) || (prod(n)==1 && dn<=2) || (dn==2 && min(n)==1 && isinf(max(n)))
str = ''; lstr = '';
elseif dn==2 && min(n)==1
str = sprintf('[%d]',max(n)); lstr = [str,'-vector'];
elseif dn==2 && sum(isinf(n))==1
str = sprintf('[%d]',min(n)); lstr = [str,'-vector(s)'];
else
str=''; for i = 1:dn
if isfinite(n(i)), str = sprintf('%s,%d',str,n(i));
else str = sprintf('%s,*',str); end
end
str = ['[',str(2:end),']']; lstr = [str,'-matrix'];
end
if l, str=sprintf('\t%s',lstr); else str=[str,' ']; end
function [p,msg] = sf_SzChk(p,n,msg)
%=======================================================================
%-Size checking
if nargin<3, msg=''; end
if nargin<2, n=[]; end; if isempty(n), n=NaN; else n=n(:)'; end
if nargin<1, error('insufficient arguments'), end
if ischar(p) || any(isnan(n(:))), return, end
if length(n)==1, n=[n,1]; end
dn = length(n);
sp = size(p);
if dn==2 && min(n)==1
%-[1,1], [1,n], [n,1], [1,Inf], [Inf,1] - vector - allow transpose
%---------------------------------------------------------------
i = min(find(n==max(n)));
if n(i)==1 && max(sp)>1
p='!'; msg='scalar required';
elseif ndims(p)~=2 || ~any(sp==1) || ( isfinite(n(i)) && max(sp)~=n(i) )
%-error: Not2D | not vector | not right length
if isfinite(n(i)), str=sprintf('%d-',n(i)); else str=''; end
p='!'; msg=[str,'vector required'];
elseif sp(i)==1 && n(i)~=1
p=p'; msg=[msg,' (input transposed)'];
end
elseif dn==2 && sum(isinf(n))==1
%-[n,Inf], [Inf,n] - n vector(s) required - allow transposing
%---------------------------------------------------------------
i = find(isfinite(n));
if ndims(p)~=2 || ~any(sp==n(i))
p='!'; msg=sprintf('%d-vector(s) required',min(n));
elseif sp(i)~=n
p=p'; msg=[msg,' (input transposed)'];
end
else
%-multi-dimensional matrix required - check dimensions
%---------------------------------------------------------------
if ndims(p)~=dn || ~all( size(p)==n | isinf(n) )
p = '!'; msg='';
for i = 1:dn
if isfinite(n(i)), msg = sprintf('%s,%d',msg,n(i));
else msg = sprintf('%s,*',msg); end
end
msg = ['[',msg(2:end),']-matrix required'];
end
end
|
github
|
philippboehmsturm/antx-master
|
spm_check_installation.m
|
.m
|
antx-master/xspm8/spm_check_installation.m
| 19,118 |
utf_8
|
18ee5f8c826ccf3542347a9828085c3c
|
function spm_check_installation(action)
% Check SPM installation
% FORMAT spm_check_installation('basic')
% Perform a superficial check of SPM installation [default].
%
% FORMAT spm_check_installation('full')
% Perform an in-depth diagnostic of SPM installation.
%
% FORMAT spm_check_installation('build')
% Build signature of SPM distribution as used by previous option.
% (for developers)
%__________________________________________________________________________
% Copyright (C) 2009 Wellcome Trust Centre for Neuroimaging
% Guillaume Flandin
% $Id: spm_check_installation.m 6155 2014-09-05 11:02:42Z guillaume $
if isdeployed, return; end
%-Select action
%--------------------------------------------------------------------------
if ~nargin, action = 'basic'; end
switch action
case 'basic'
check_basic;
case 'full'
check_full;
case 'build'
build_signature;
otherwise
error('Unknown action to perform.');
end
%==========================================================================
% FUNCTION check_basic
%==========================================================================
function check_basic
%-Minimal MATLAB version required
%--------------------------------------------------------------------------
try
v = spm_check_version('matlab','7.1');
catch
error('A problem occurred with spm_check_version.m.');
end
if v < 0
error([...
'SPM8 requires MATLAB 7.1 onwards in order to run.\n'...
'This MATLAB version is %s\n'], version);
end
%-Check installation
%--------------------------------------------------------------------------
spm('Ver','',1);
d = spm('Dir');
%-Check the search path
%--------------------------------------------------------------------------
p = textscan(path,'%s','delimiter',pathsep); p = p{1};
if ~ismember(lower(d),lower(p))
error(sprintf([...
'You do not appear to have the MATLAB search path set up\n'...
'to include your SPM8 distribution. This means that you\n'...
'can start SPM in this directory, but if your change to\n'...
'another directory then MATLAB will be unable to find the\n'...
'SPM functions. You can use the editpath command in MATLAB\n'...
'to set it up.\n'...
' addpath %s\n'...
'For more information, try typing the following:\n'...
' help path\n help editpath'],d));
end
%-Ensure that the original release - as well as the updates - was installed
%--------------------------------------------------------------------------
if ~exist(fullfile(d,'@nifti','create.m'),'file') % File that should not have changed
if isunix
error(sprintf([...
'There appears to be some problem with the installation.\n'...
'The original spm8.zip distribution should be installed\n'...
'and the updates installed on top of this. Unix commands\n'...
'to do this are:\n'...
' unzip spm8.zip\n'...
' unzip -o spm8_updates_r????.zip -d spm8']));
else
error(sprintf([...
'There appears to be some problem with the installation.\n'...
'The original spm8.zip distribution should be installed\n'...
'and the updates installed on top of this.']));
end
end
%-Ensure that the files were unpacked correctly
%--------------------------------------------------------------------------
if ispc
try
t = load(fullfile(d,'Split.mat'));
catch
error(sprintf([...
'There appears to be some problem reading the MATLAB .mat\n'...
'files from the SPM distribution. This is probably\n'...
'something to do with the way that the distribution was\n'...
'unpacked. If you used WinZip, then ensure that\n'...
'TAR file smart CR/LF conversion is disabled\n'...
'(under the Miscellaneous Configuration Options).']));
end
if ~exist(fullfile(d,'toolbox','DARTEL','diffeo3d.c'),'file'),
error(sprintf([...
'There appears to be some problem with the installation.\n'...
'This is probably something to do with the way that the\n'...
'distribution was unbundled from the original .zip files.\n'...
'Please ensure that the files are unpacked so that the\n'...
'directory structure is retained.']));
end
end
%-Check the MEX files
%--------------------------------------------------------------------------
try
feval(@spm_bsplinc,1,ones(1,6));
catch
error([...
'SPM uses a number of MEX files, which are compiled functions.\n'...
'These need to be compiled for the various platforms on which SPM\n'...
'is run. At the FIL, where SPM is developed, the number of\n'...
'computer platforms is limited. It is therefore not possible to\n'...
'release a version of SPM that will run on all computers. See\n'...
' %s%csrc%cMakefile and\n'...
' http://en.wikibooks.org/wiki/SPM#Installation\n'...
'for information about how to compile mex files for %s\n'...
'in MATLAB %s.'],...
d,filesep,filesep,computer,version);
end
%==========================================================================
% FUNCTION check_full
%==========================================================================
function check_full
%-Say Hello
%--------------------------------------------------------------------------
fprintf('\n');
disp( ' ___ ____ __ __ ' );
disp( '/ __)( _ \( \/ ) ' );
disp( '\__ \ )___/ ) ( Statistical Parametric Mapping ' );
disp(['(___/(__) (_/\/\_) SPM - http://www.fil.ion.ucl.ac.uk/spm/ ']);
fprintf('\n');
%-Detect SPM directory
%--------------------------------------------------------------------------
SPMdir = which('spm.m','-ALL');
if isempty(SPMdir)
fprintf('SPM is not in your MATLAB path.\n');
return;
elseif numel(SPMdir) > 1
fprintf('SPM seems to appear in several different folders:\n');
for i=1:numel(SPMdir)
fprintf(' * %s\n',SPMdir{i});
end
fprintf('Remove all but one with ''editpath'' or ''spm_rmpath''.\n');
return;
else
fprintf('SPM is installed in: %s\n',fileparts(SPMdir{1}));
end
SPMdir = fileparts(SPMdir{1});
%-Detect SPM version and revision number
%--------------------------------------------------------------------------
v = struct('Name','','Version','','Release','','Date','');
try
fid = fopen(fullfile(SPMdir,'Contents.m'),'rt');
if fid == -1
fprintf('Cannot open ''%s'' for reading.\n',fullfile(SPMdir,'Contents.m'));
return;
end
l1 = fgetl(fid); l2 = fgetl(fid);
fclose(fid);
l1 = strtrim(l1(2:end)); l2 = strtrim(l2(2:end));
t = textscan(l2,'%s','delimiter',' '); t = t{1};
v.Name = l1; v.Date = t{4};
v.Version = t{2}; v.Release = t{3}(2:end-1);
catch
fprintf('Cannot obtain SPM version & revision number.\n');
return;
end
fprintf('SPM version is %s (%s, %s)\n', ...
v.Release,v.Version,strrep(v.Date,'-',' '));
%-Detect SPM toolboxes
%--------------------------------------------------------------------------
officials = {'Beamforming', 'DARTEL', 'dcm_meeg', 'DEM', 'FieldMap', ...
'HDW', 'MEEGtools', 'mixture', 'Neural_Models', 'Seg', 'Shoot', ...
'spectral', 'SRender'};
dd = dir(fullfile(SPMdir,'toolbox'));
dd = {dd([dd.isdir]).name};
dd(strncmp('.',dd,1)) = [];
dd = setdiff(dd,officials);
fprintf('SPM toolboxes:');
for i=1:length(dd)
fprintf(' %s',dd{i});
end
if isempty(dd), fprintf(' none'); end
fprintf('\n');
%-Detect MATLAB & toolboxes
%--------------------------------------------------------------------------
fprintf('MATLAB is installed in: %s\n',matlabroot);
fprintf('MATLAB version is %s\n',version);
fprintf('MATLAB toolboxes: '); hastbx = false;
if license('test','signal_toolbox') && ~isempty(ver('signal'))
vtbx = ver('signal'); hastbx = true;
fprintf('signal (v%s) ',vtbx.Version);
end
if license('test','image_toolbox') && ~isempty(ver('images'))
vtbx = ver('images'); hastbx = true;
fprintf('images (v%s) ',vtbx.Version);
end
if license('test','statistics_toolbox') && ~isempty(ver('stats'))
vtbx = ver('stats'); hastbx = true;
fprintf('stats (v%s)',vtbx.Version);
end
if ~hastbx, fprintf('none.'); end
fprintf('\n');
%-Detect Platform and Operating System
%--------------------------------------------------------------------------
[C, maxsize] = computer;
fprintf('Platform: %s (maxsize=%d)\n', C, maxsize);
if ispc
platform = [system_dependent('getos'),' ',system_dependent('getwinsys')];
elseif exist('ismac') && ismac
[fail, input] = unix('sw_vers');
if ~fail
platform = strrep(input, 'ProductName:', '');
platform = strrep(platform, sprintf('\t'), '');
platform = strrep(platform, sprintf('\n'), ' ');
platform = strrep(platform, 'ProductVersion:', ' Version: ');
platform = strrep(platform, 'BuildVersion:', 'Build: ');
else
platform = system_dependent('getos');
end
else
platform = system_dependent('getos');
end
fprintf('OS: %s\n', platform);
%-Detect Java
%--------------------------------------------------------------------------
fprintf('%s\n', version('-java'));
fprintf('Java support: ');
level = {'jvm', 'awt', 'swing', 'desktop'};
for i=1:numel(level)
if isempty(javachk(level{i})), fprintf('%s ',level{i}); end
end
fprintf('\n');
%-Detect Monitor(s)
%--------------------------------------------------------------------------
M = get(0,'MonitorPositions');
fprintf('Monitor(s):');
for i=1:size(M,1)
fprintf(' [%d %d %d %d]',M(i,:));
end
fprintf(' (%dbit)\n', get(0,'ScreenDepth'));
%-Detect OpenGL rendering
%--------------------------------------------------------------------------
S = opengl('data');
fprintf('OpenGL version: %s',S.Version);
if S.Software, fprintf('(Software)\n'); else fprintf('(Hardware)\n'); end
fprintf('OpenGL renderer: %s (%s)\n',S.Vendor,S.Renderer);
%-Detect MEX setup
%--------------------------------------------------------------------------
fprintf('MEX extension: %s\n',mexext);
try
cc = mex.getCompilerConfigurations('C','Selected');
if ~isempty(cc)
cc = cc(1); % can be C or C++
fprintf('C Compiler: %s (%s).\n', cc.Name, cc.Version);
fprintf('C Compiler settings: %s (''%s'')\n', ...
cc.Details.CompilerExecutable, cc.Details.OptimizationFlags);
else
fprintf('No C compiler is selected (see mex -setup)\n');
end
end
try
[sts, m] = fileattrib(fullfile(SPMdir,'src'));
m = [m.UserRead m.UserWrite m.UserExecute ...
m.GroupRead m.GroupWrite m.GroupExecute ...
m.OtherRead m.OtherWrite m.OtherExecute];
r = 'rwxrwxrwx'; r(~m) = '-';
fprintf('C Source code permissions: dir %s, ', r);
[sts, m] = fileattrib(fullfile(SPMdir,'src','spm_resels_vol.c'));
m = [m.UserRead m.UserWrite m.UserExecute ...
m.GroupRead m.GroupWrite m.GroupExecute ...
m.OtherRead m.OtherWrite m.OtherExecute];
r = 'rwxrwxrwx'; r(~m) = '-';
fprintf('file %s\n',r);
end
%-Get file details for local SPM installation
%--------------------------------------------------------------------------
fprintf('%s\n',repmat('-',1,70));
l = generate_listing(SPMdir);
fprintf('%s %40s\n','Parsing local installation...','...done');
%-Get file details for most recent public version
%--------------------------------------------------------------------------
fprintf('Downloading SPM information...');
url = sprintf('http://www.fil.ion.ucl.ac.uk/spm/software/%s/%s.xml',...
lower(v.Release),lower(v.Release));
try
p = [tempname '.xml'];
urlwrite(url,p);
catch
fprintf('\nCannot access URL %s\n',url);
return;
end
fprintf('%40s\n','...done');
%-Parse it into a Matlab structure
%--------------------------------------------------------------------------
fprintf('Parsing SPM information...');
tree = xmlread(p);
delete(p);
r = struct([]); ind = 1;
if tree.hasChildNodes
for i=0:tree.getChildNodes.getLength-1
m = tree.getChildNodes.item(i);
if strcmp(m.getNodeName,'signature')
m = m.getChildNodes;
for j=0:m.getLength-1
if strcmp(m.item(j).getNodeName,'file')
n = m.item(j).getChildNodes;
for k=0:n.getLength-1
o = n.item(k);
if ~strcmp(o.getNodeName,'#text')
try
s = char(o.getChildNodes.item(0).getData);
catch
s = '';
end
switch char(o.getNodeName)
case 'name'
r(ind).file = s;
case 'id'
r(ind).id = str2num(s);
otherwise
r(ind).(char(o.getNodeName)) = s;
end
end
end
ind = ind + 1;
end
end
end
end
end
fprintf('%44s\n','...done');
%-Compare local and public versions
%--------------------------------------------------------------------------
fprintf('%s\n',repmat('-',1,70));
compare_versions(l,r);
fprintf('%s\n',repmat('-',1,70));
%==========================================================================
% FUNCTION compare_versions
%==========================================================================
function compare_versions(l,r)
%-Uniformise file names
%--------------------------------------------------------------------------
a = {r.file}; a = strrep(a,'\','/'); [r.file] = a{:};
a = {l.file}; a = strrep(a,'\','/'); [l.file] = a{:};
%-Look for missing or unknown files
%--------------------------------------------------------------------------
[x,ir,il] = setxor({r.file},{l.file});
if isempty(ir) && isempty(il)
fprintf('No missing or unknown files\n');
else
if ~isempty(ir)
fprintf('File(s) missing in your installation:\n');
end
for i=1:length(ir)
fprintf(' * %s\n', r(ir(i)).file);
end
if ~isempty(ir) && ~isempty(il), fprintf('%s\n',repmat('-',1,70)); end
if ~isempty(il)
fprintf('File(s) not part of the current version of SPM:\n');
end
for i=1:length(il)
fprintf(' * %s\n', l(il(i)).file);
end
end
fprintf('%s\n',repmat('-',1,70));
%-Look for local changes or out-of-date files
%--------------------------------------------------------------------------
[tf, ir] = ismember({r.file},{l.file});
dispc = true;
for i=1:numel(r)
if tf(i)
if ~isempty(r(i).id) && (isempty(l(ir(i)).id) || (r(i).id ~= l(ir(i)).id))
dispc = false;
fprintf('File %s is not up to date (r%d vs r%d)\n', ...
r(i).file, r(i).id, l(ir(i)).id);
end
if ~isempty(r(i).md5) && ~isempty(l(ir(i)).md5) && ~strcmp(r(i).md5,l(ir(i)).md5)
dispc = false;
fprintf('File %s has been edited (checksum mismatch)\n', r(i).file);
end
end
end
if dispc
fprintf('No local change or out-of-date files\n');
end
%==========================================================================
% FUNCTION build_signature
%==========================================================================
function build_signature
[v,r] = spm('Ver','',1);
d = spm('Dir');
l = generate_listing(d);
fprintf('Saving %s signature in %s\n',...
v, fullfile(pwd,sprintf('%s_signature.xml',v)));
fid = fopen(fullfile(pwd,sprintf('%s_signature.xml',v)),'wt');
fprintf(fid,'<?xml version="1.0"?>\n');
fprintf(fid,'<!-- Signature for %s r%s -->\n',v,r);
fprintf(fid,'<signature>\n');
for i=1:numel(l)
fprintf(fid,' <file>\n');
fprintf(fid,' <name>%s</name>\n',l(i).file);
fprintf(fid,' <id>%d</id>\n',l(i).id);
fprintf(fid,' <date>%s</date>\n',l(i).date);
fprintf(fid,' <md5>%s</md5>\n',l(i).md5);
fprintf(fid,' </file>\n');
end
fprintf(fid,'</signature>\n');
fclose(fid);
%==========================================================================
% FUNCTION generate_listing
%==========================================================================
function l = generate_listing(d,r,l)
if nargin < 2
r = '';
end
if nargin < 3
l = struct([]);
end
%-List content of folder
%--------------------------------------------------------------------------
ccd = fullfile(d,r);
fprintf('%-10s: %58s','Directory',ccd(max(1,length(ccd)-57):end));
dd = dir(ccd);
f = {dd(~[dd.isdir]).name};
dispw = false;
for i=1:length(f)
[p,name,ext] = fileparts(f{i});
info = struct('file','', 'id',[], 'date','', 'md5','');
if ismember(ext,{'.m','.man','.txt','.xml','.c','.h',''})
info = extract_info(fullfile(ccd,f{i}));
end
info.file = fullfile(r,f{i});
try
try
info.md5 = md5sum(fullfile(ccd,f{i}));
catch
%[s, info.md5] = system(['md5sum "' fullfile(ccd,f{i}) '"']);
%info.md5 = strtok(info.md5);
end
end
if isempty(l), l = info;
else l(end+1) = info;
end
if isempty(r) && strcmp(ext,'.m')
w = which(f{i},'-ALL');
if numel(w) > 1 && ~strcmpi(f{i},'Contents.m')
if ~dispw, fprintf('\n'); end
dispw = true;
fprintf('File %s appears %d times in your MATLAB path:\n',f{i},numel(w));
for j=1:numel(w)
if j==1 && ~strncmp(d,w{1},length(d))
fprintf(' %s (SHADOWING)\n',w{1});
else
fprintf(' %s\n',w{j});
end
end
end
end
end
if ~dispw, fprintf('%s',repmat(sprintf('\b'),1,70)); end
%-Recursively extract subdirectories
%--------------------------------------------------------------------------
dd = {dd([dd.isdir]).name};
dd(strncmp('.',dd,1)) = [];
for i=1:length(dd)
l = generate_listing(d,fullfile(r,dd{i}),l);
end
%==========================================================================
% FUNCTION extract_info
%==========================================================================
function svnprops = extract_info(f)
%Extract Subversion properties (Id tag)
svnprops = struct('file',f, 'id',[], 'date','', 'md5','');
fp = fopen(f,'rt');
str = fread(fp,Inf,'*uchar');
fclose(fp);
str = char(str(:)');
r = regexp(str,['\$Id: (?<file>\S+) (?<id>[0-9]+) (?<date>\S+) ' ...
'(\S+Z) (?<author>\S+) \$'],'names');
if isempty(r)
%fprintf('\n%s has no SVN Id.\n',f);
else
svnprops.file = r(1).file;
svnprops.id = str2num(r(1).id);
svnprops.date = r(1).date;
[p,name,ext] = fileparts(f);
if ~strcmp(svnprops.file,[name ext])
fprintf('\nSVN Id does not match filename for file:\n %s\n',f);
end
end
if numel(r) > 1
%fprintf('\n%s has several SVN Ids.\n',f);
end
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_history.m
|
.m
|
antx-master/xspm8/spm_eeg_history.m
| 7,083 |
utf_8
|
0d69e18b7d2f308ba43f7932b0f18cb7
|
function H = spm_eeg_history(S)
% Generate a MATLAB script from the history of an M/EEG SPM data file
% FORMAT H = spm_eeg_history(S)
%
% S - filename or input struct (optional)
% (optional) fields of S:
% history - history of M/EEG object (D.history)
% sname - filename of the to be generated MATLAB script
%
% H - cell array summary of history for review purposes
%__________________________________________________________________________
%
% In SPM for M/EEG, each preprocessing step enters its call and input
% arguments into an internal history. The sequence of function calls that
% led to a given file can be read by the history method (i.e. call
% 'D.history'). From this history this function generates a script (m-file)
% which can be run without user interaction and will repeat, if run, the
% exact sequence on the preprocessing steps stored in the history. Of
% course, the generated script can also be used as a template for a
% slightly different analysis or for different subjects.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Stefan Kiebel
% $Id: spm_eeg_history.m 5227 2013-02-03 15:35:03Z vladimir $
try
h = S.history;
catch
[D, sts] = spm_select(1, 'mat', 'Select M/EEG mat file');
if ~sts, H = {}; return; end
D = spm_eeg_load(D);
h = D.history;
end
if nargout
H = hist2cell(h);
else
try
S.sname; % not fname, as it means something else for MEEG object
catch
[filename, pathname] = uiputfile('*.m', ...
'Select the to be generated script file');
if isequal(filename,0) || isequal(pathname,0)
return;
end
S.sname = fullfile(pathname, filename);
end
hist2script(h,S.sname);
end
%==========================================================================
% function hist2script
%==========================================================================
function hist2script(h,fname)
histlist = convert2humanreadable(h);
[selection, ok]= listdlg('ListString', histlist, 'SelectionMode', 'multiple',...
'InitialValue', 1:numel(histlist) ,'Name', 'Select history entries', ...
'ListSize', [400 300]);
if ok, h = h(selection); else return; end
Nh = length(h);
fp = fopen(fname, 'wt');
if fp == -1
error('File %s cannot be opened for writing.', fname);
end
fprintf(fp, '%s\n\n', 'spm(''defaults'', ''eeg'');');
for i = 1:Nh
fprintf(fp, '%s\n', 'S = [];');
s = gencode(h(i).args(1), 'S');
for j = 1:length(s)
fprintf(fp, '%s\n', s{j});
end
fprintf(fp, '%s\n\n\n', ['D = ' h(i).fun '(S);']);
end
fclose(fp);
%==========================================================================
% function hist2cell
%==========================================================================
function H = hist2cell(h)
nf = length(h);
H = cell(nf,4);
for i=1:nf
try
H{i,1} = char(convert2humanreadable(h(i)));
catch
H{i,2} = h(i).fun;
end
H{i,2} = h(i).fun;
args = h(i).args;
try,args = args{1};end
switch h(i).fun
case 'spm_eeg_convert'
H{i,3} = args.dataset;
if i<nf
path = fileparts(H{i,3});
H{i,4} = fullfile(path,[args.outfile '.mat']);
else
H{i,4} = '[this file]';
end
case 'spm_eeg_prep'
Df = args.D;
try, Df = args.D.fname; end
H{i,2} = [H{i,2},' (',args.task,')'];
pth = fileparts(Df);
if isempty(pth)
try
pth = fileparts(H{i-1,4});
Df = fullfile(pth, Df);
end
end
H{i,3} = Df;
if i<nf
H{i,4} = Df;
else
H{i,4} = '[this file]';
end
otherwise
Df = args.D;
try,Df = args.D.fname;end
H{i,3} = Df;
if i<nf
try
args2 = h(i+1).args;
try,args2 = args2{1};end
Df2 = args2.D;
try,Df2 = args2.D.fname;end
H{i,4} = Df2;
catch
H{i,4} = '?';
end
else
H{i,4} = '[this file]';
end
end
end
%==========================================================================
% function convert2humanreadable
%==========================================================================
function hh = convert2humanreadable(h)
hh = cell(numel(h),1);
for i=1:numel(h)
switch h(i).fun
case 'spm_eeg_convert'
hh{i} = 'Convert';
case 'spm_eeg_epochs'
hh{i} = 'Epoch';
case 'spm_eeg_filter'
if length(h(i).args.filter.PHz) == 2
hh{i} = [upper(h(i).args.filter.band(1)) h(i).args.filter.band(2:end)...
' filter ' num2str(h(i).args.filter.PHz(:)', '%g %g') ' Hz'];
else
hh{i} = [upper(h(i).args.filter.band(1)) h(i).args.filter.band(2:end)...
' filter ' num2str(h(i).args.filter.PHz, '%g') ' Hz'];
end
case 'spm_eeg_downsample'
hh{i} = ['Downsample to ' num2str(h(i).args.fsample_new) ' Hz'];
case 'spm_eeg_bc'
hh{i} = ['Baseline correction ' mat2str(h(i).args.time(:)') ' ms'];
case 'spm_eeg_copy'
hh{i} = 'Copy dataset';
case 'spm_eeg_montage'
hh{i} = 'Change montage';
case 'spm_eeg_artefact'
hh{i} = 'Detect artefacts';
case 'spm_eeg_average'
hh{i} = 'Average';
case 'spm_eeg_average_TF'
hh{i} = 'Average time-frequency';
case 'spm_eeg_grandmean'
hh{i} = 'Grand mean';
case 'spm_eeg_merge'
hh{i} = 'Merge';
case 'spm_eeg_tf'
hh{i} = 'Compute time-frequency';
case 'spm_eeg_weight_epochs'
hh{i} = 'Compute contrast';
case 'spm_eeg_sort_conditions'
hh{i} = 'Sort conditions';
case 'spm_eeg_prep'
switch h(i).args.task
case 'settype'
hh{i} = 'Set channel type';
case {'loadtemplate', 'setcoor2d', 'project3D'}
hh{i} = 'Set 2D coordinates';
case 'loadeegsens'
hh{i} = 'Load EEG sensor locations';
case 'defaulteegsens'
hh{i} = 'Set EEG sensor locations to default';
case 'sens2chan'
hh{i} = 'Specify initial montage';
case 'headshape'
hh{i} = 'Load fiducials/headshape';
case 'coregister'
hh{i} = 'Coregister';
otherwise
hh{i} = ['Prepare: ' h(i).args.task];
end
otherwise
hh{i} = h(i).fun;
end
end
|
github
|
philippboehmsturm/antx-master
|
spm_bias_estimate.m
|
.m
|
antx-master/xspm8/spm_bias_estimate.m
| 6,564 |
utf_8
|
d82c2ea740642ae1ced08ecfe885e4f2
|
function T = spm_bias_estimate(V,flags)
% Estimate image nonuniformity.
%
% FORMAT T = spm_bias_estimate(V,flags)
% V - filename or vol struct of image
% flags - a structure containing the following fields
% nbins - number of bins in histogram (1024)
% reg - amount of regularisation (1)
% cutoff - cutoff (in mm) of basis functions (35)
% T - DCT of bias field.
%
% The objective function is related to minimising the entropy of
% the image histogram, but is modified slightly.
% This fixes the problem with the SPM99 non-uniformity correction
% algorithm, which tends to try to reduce the image intensities. As
% the field was constrainded to have an average value of one, then
% this caused the field to bend upwards in regions not included in
% computations of image non-uniformity.
%
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_bias_estimate.m 1143 2008-02-07 19:33:33Z spm $
def_flags = struct('nbins',256,'reg',0.01,'cutoff',30);
if nargin < 2,
flags = def_flags;
else
fnms = fieldnames(def_flags);
for i=1:length(fnms),
if ~isfield(flags,fnms{i}),
flags.(fnms{i}) = def_flags.(fnms{i});
end;
end;
end;
reg = flags.reg; % Regularisation
co = flags.cutoff; % Highest wavelength of DCT
nh = flags.nbins;
if ischar(V), V = spm_vol(V); end;
mx = 1.1*get_max(V); % Maximum value in histogram
tmp = sqrt(sum(V(1).mat(1:3,1:3).^2));
nbas = max(round((V(1).dim(1:3).*tmp)/co),[1 1 1]);
B1 = spm_dctmtx(V(1).dim(1),nbas(1));
B2 = spm_dctmtx(V(1).dim(2),nbas(2));
B3 = spm_dctmtx(V(1).dim(3),nbas(3));
[T,IC0] = get_priors(V,nbas,reg,4);
IC0 = IC0(2:end,2:end);
%tmp = diag(IC0);
%tmp = tmp(tmp>0);
%offset = 0.5*(log(2*pi)*length(tmp) + sum(log(tmp)));
offset = 0;
fprintf('*** %s ***\nmax = %g, Bases = %dx%dx%d\n', V.fname, mx, nbas);
olpp = Inf;
x = (0:(nh-1))'*(mx/(nh-1));
plt = zeros(64,2);
for iter = 1:128,
[Alpha,Beta,ll, h, n] = spm_bias_mex(V,B1,B2,B3,T,[mx nh]);
T = T(:);
T = T(2:end);
Alpha = Alpha(2:end,2:end)/n;
Beta = Beta(2:end)/n;
ll = ll/n;
lp = offset + 0.5*(T'*IC0*T);
lpp = lp+ll;
T = (Alpha + IC0)\(Alpha*T - Beta);
T = reshape([0 ; T],nbas);
[pth,nm] = fileparts(deblank(V.fname));
S = fullfile(pth,['bias_' nm '.mat']);
%S = ['bias_' nm '.mat'];
save(S,'V','T','h');
fprintf('%g %g\n', ll, lp);
if iter==1,
fg = spm_figure('FindWin','Interactive');
if ~isempty(fg),
spm_figure('Clear',fg);
ax1 = axes('Position', [0.15 0.1 0.8 0.35],...
'Box', 'on','Parent',fg);
ax2 = axes('Position', [0.15 0.6 0.8 0.35],...
'Box', 'on','Parent',fg);
end;
h0 = h;
end;
if ~isempty(fg),
plt(iter,1) = ll;
plt(iter,2) = lpp;
plot((1:iter)',plt(1:iter,:),'Parent',ax1,'LineWidth',2);
set(get(ax1,'Xlabel'),'string','Iteration','FontSize',10);
set(get(ax1,'Ylabel'),'string','Negative Log-Likelihood','FontSize',10);
set(ax1,'Xlim',[1 iter+1]);
plot(x,h0,'r', x,h,'b', 'Parent',ax2);
set(ax2,'Xlim',[0 x(end)]);
set(get(ax2,'Xlabel'),'string','Intensity','FontSize',10);
set(get(ax2,'Ylabel'),'string','Frequency','FontSize',10);
drawnow;
end;
if olpp-lpp < 1e-5, delete([ax1 ax2]); break; end;
olpp = lpp;
end;
return;
%=======================================================================
%=======================================================================
function mx = get_max(V)
mx = 0;
for i=1:V.dim(3),
img = spm_slice_vol(V,spm_matrix([0 0 i]),V.dim(1:2),0);
mx = max([mx max(img(:))]);
end;
return;
%=======================================================================
%=======================================================================
function [T,IC0] = get_priors(VF,nbas,reg,o)
% Set up a priori covariance matrix
vx = sqrt(sum(VF(1).mat(1:3,1:3).^2));
kx = (((1:nbas(1))'-1)*pi/vx(1)/VF(1).dim(1)*10).^2;
ky = (((1:nbas(2))'-1)*pi/vx(2)/VF(1).dim(2)*10).^2;
kz = (((1:nbas(3))'-1)*pi/vx(3)/VF(1).dim(3)*10).^2;
switch o,
case 0, % Cost function based on sum of squares
IC0 = kron(kz.^0,kron(ky.^0,kx.^0))*reg;
case 1, % Cost function based on sum of squared 1st derivatives
IC0 = ( kron(kz.^1,kron(ky.^0,kx.^0)) +...
kron(kz.^0,kron(ky.^1,kx.^0)) +...
kron(kz.^0,kron(ky.^0,kx.^1)) )*reg;
case 2, % Cost function based on sum of squared 2nd derivatives
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)) )*reg;
case 3, % Cost function based on sum of squared 3rd derivatives
IC0 = (1*kron(kz.^3,kron(ky.^0,kx.^0)) +...
1*kron(kz.^0,kron(ky.^3,kx.^0)) +...
1*kron(kz.^0,kron(ky.^0,kx.^3)) +...
3*kron(kz.^2,kron(ky.^1,kx.^0)) +...
3*kron(kz.^2,kron(ky.^0,kx.^1)) +...
3*kron(kz.^1,kron(ky.^2,kx.^0)) +...
3*kron(kz.^0,kron(ky.^2,kx.^1)) +...
3*kron(kz.^1,kron(ky.^0,kx.^2)) +...
3*kron(kz.^0,kron(ky.^1,kx.^2)) +...
6*kron(kz.^1,kron(ky.^1,kx.^1)) )*reg;
case 4, % 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;
otherwise,
error('Unknown regularisation form');
end;
IC0(1) = max([max(IC0) 1e4]);
IC0 = diag(IC0);
% Initial estimate for intensity modulation field
T = zeros(nbas(1),nbas(2),nbas(3),1);
return;
%=======================================================================
|
github
|
philippboehmsturm/antx-master
|
spm_results_ui.m
|
.m
|
antx-master/xspm8/spm_results_ui.m
| 55,704 |
utf_8
|
be173ae190bcefd1a76682fea162cabb
|
function varargout = spm_results_ui(varargin)
% User interface for SPM/PPM results: Display and analysis of regional effects
% FORMAT [hReg,xSPM,SPM] = spm_results_ui('Setup',[xSPM])
%
% hReg - handle of MIP XYZ registry object
% (see spm_XYZreg.m for details)
% xSPM - structure containing specific SPM, distribution & filtering details
% (see spm_getSPM.m for contents)
% SPM - SPM structure containing generic parameters
% (see spm_spm.m for contents)
%
% NB: Results section GUI CallBacks use these data structures by name,
% which therefore *must* be assigned to the correctly named variables.
%__________________________________________________________________________
%
% The SPM results section is for the interactive exploration and
% characterisation of the results of a statistical analysis.
%
% The user is prompted to select a SPM{T} or SPM{F}, that is
% thresholded at user specified levels. The specification of the
% contrasts to use and the height and size thresholds are described in
% spm_getSPM.m. The resulting SPM is then displayed in the graphics
% window as a maximum intensity projection, alongside the design matrix
% and contrasts employed.
%
% The cursors in the MIP can be moved (dragged) to select a particular
% voxel. The three mouse buttons give different drag and drop behaviour:
% Button 1 - point & drop; Button 2 - "dynamic" drag & drop with
% co-ordinate & SPM value updating; Button 3 - "magnetic" drag & drop,
% where the cursor jumps to the nearest suprathreshold voxel in the
% MIP, and shows the value there. (See spm_mip_ui.m, the MIP GUI handling
% function for further details.)
%
% The design matrix and contrast pictures are "surfable": Click and
% drag over the images to report associated data. Clicking with
% different buttons produces different results. Double-clicking
% extracts the underlying data into the base workspace.
% See spm_DesRep.m for further details.
%
% The current voxel specifies the voxel, suprathreshold cluster, or
% orthogonal planes (planes passing through that voxel) for subsequent
% localised utilities.
%
% A control panel in the Interactive window enables interactive
% exploration of the results.
%
% p-values buttons:
% (i) volume - Tabulates p-values and statistics for entire volume.
% - see spm_list.m
% (ii) cluster - Tabulates p-values and statistics for nearest cluster
% - Note that the cursor will jump to the nearest
% suprathreshold voxel, if it is not already at a
% location with suprathreshold statistic.
% - see spm_list.m
% (iii) S.V.C - Small Volume Correction:
% Tabulates p-values corrected for a small specified
% volume of interest. (Tabulation by spm_list.m)
% - see spm_VOI.m
%
% Data extraction buttons:
% Eigenvariate/CVA
% - Extracts the principal eigenvariate for small volumes
% of interest; or CVA of data within a specified volume
% - Data can be adjusted or not for eigenvariate summaries
% - If temporal filtering was specified (fMRI), then it is
% the filtered data that is returned.
% - Choose a VOI of radius 0 to extract the (filtered &)
% adjusted data for a single voxel. Note that this vector
% will be scaled to have a 2-norm of 1. (See spm_regions.m
% for further details.)
% - The plot button also returns fitted and adjusted
% (after any filtering) data for the voxel being plotted.)
% - Note that the cursor will jump to the nearest voxel for
% which raw data was saved.
% - see spm_regions.m
%
% Visualisation buttons:
% (i) plot - Graphs of adjusted and fitted activity against
% various ordinates.
% - Note that the cursor will jump to the nearest
% suprathreshold voxel, if it is not already at a
% location with suprathreshold statistic.
% - Additionally, returns fitted and adjusted data to the
% MATLAB base workspace.
% - see spm_graph.m
% (ii) overlays - Popup menu: Overlays of filtered SPM on a structural image
% - slices - Slices of the thresholded statistic image overlaid
% on a secondary image chosen by the user. Three
% transverse slices are shown, being those at the
% level of the cursor in the z-axis and the two
% adjacent to it. - see spm_transverse.m
% - sections - Orthogonal sections of the thresholded statistic
% image overlaid on a secondary image chosen by the user.
% The sections are through the cursor position.
% - see spm_sections.m
% - render - Render blobs on previously extracted cortical surface
% - see spm_render.m
% (iii) save - Write out thresholded SPM as image
% - see spm_write_filtered.m
%
% The current cursor location can be set by editing the co-ordinate
% widgets at the bottom of the interactive window. (Note that many of the
% results section facilities are "linked" and can update co-ordinates. E.g.
% clicking on the co-ordinates in a p-value listing jumps to that location.)
%
% Graphics appear in the bottom half of the graphics window, additional
% controls and questions appearing in the interactive window.
%
% ----------------
%
% The MIP uses a template outline in MNI space. Consequently for
% the results section to display properly the input images to the
% statistics section should be in MNI space.
%
% Similarly, secondary images should be aligned with the input images
% used for the statistical analysis.
%
% ----------------
%
% In addition to setting up the results section, spm_results_ui.m sets
% up the results section GUI and services the CallBacks. FORMAT
% specifications for embedded CallBack functions are given in the main
% body of the code.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Karl Friston & Andrew Holmes
% $Id: spm_results_ui.m 4977 2012-09-27 18:38:52Z guillaume $
%==========================================================================
% - FORMAT specifications for embedded CallBack functions
%==========================================================================
%( This is a multi function function, the first argument is an action )
%( string, specifying the particular action function to take. )
%
% spm_results_ui sets up and handles the SPM results graphical user
% interface, initialising an XYZ registry (see spm_XYZreg.m) to co-ordinate
% locations between various location controls.
%
%__________________________________________________________________________
%
% FORMAT [hreg,xSPM,SPM] = spm_results_ui('Setup')
% Query SPM and setup GUI.
%
% FORMAT [hreg,xSPM,SPM] = spm_results_ui('Setup',xSPM)
% Query SPM and setup GUI using a xSPM input structure. This allows to run
% results setup without user interaction. See spm_getSPM for details of
% allowed fields.
%
% FORMAT hReg = spm_results_ui('SetupGUI',M,DIM,xSPM,Finter)
% Setup results GUI in Interactive window
% M - 4x4 transformation matrix relating voxel to "real" co-ordinates
% DIM - 3 vector of image X, Y & Z dimensions
% xSPM - structure containing xSPM. Required fields are:
% .Z - minimum of n Statistics {filtered on u and k}
% .XYZmm - location of voxels {mm}
% Finter - handle (or 'Tag') of Interactive window (default 'Interactive')
% hReg - handle of XYZ registry object
%
% FORMAT spm_results_ui('DrawButts',hReg,DIM,Finter,WS,FS)
% Draw GUI buttons
% hReg - handle of XYZ registry object
% DIM - 3 vector of image X, Y & Z dimensions
% Finter - handle of Interactive window
% WS - WinScale [Default spm('WinScale') ]
% FS - FontSizes [Default spm('FontSizes')]
%
% FORMAT hFxyz = spm_results_ui('DrawXYZgui',M,DIM,xSPM,xyz,Finter)
% Setup editable XYZ control widgets at foot of Interactive window
% M - 4x4 transformation matrix relating voxel to "real" co-ordinates
% DIM - 3 vector of image X, Y & Z dimensions
% xSPM - structure containing SPM; Required fields are:
% .Z - minimum of n Statistics {filtered on u and k}
% .XYZmm - location of voxels {mm}
% xyz - Initial xyz location {mm}
% Finter - handle of Interactive window
% hFxyz - handle of XYZ control - the frame containing the edit widgets
%
% FORMAT spm_results_ui('EdWidCB')
% Callback for editable XYZ control widgets
%
% FORMAT spm_results_ui('UpdateSPMval',hFxyz)
% FORMAT spm_results_ui('UpdateSPMval',UD)
% Updates SPM value string in Results GUI (using data from UserData of hFxyz)
% hFxyz - handle of frame enclosing widgets - the Tag object for this control
% UD - XYZ data structure (UserData of hFxyz).
%
% FORMAT xyz = spm_results_ui('GetCoords',hFxyz)
% Get current co-ordinates from editable XYZ control
% hFxyz - handle of frame enclosing widgets - the Tag object for this control
% xyz - current co-ordinates {mm}
% NB: When using the results section, should use XYZregistry to get/set location
%
% FORMAT [xyz,d] = spm_results_ui('SetCoords',xyz,hFxyz,hC)
% Set co-ordinates to XYZ widget
% xyz - (Input) desired co-ordinates {mm}
% hFxyz - handle of XYZ control - the frame containing the edit widgets
% hC - handle of calling object, if used as a callback. [Default 0]
% xyz - (Output) Desired co-ordinates are rounded to nearest voxel if hC
% is not specified, or is zero. Otherwise, caller is assumed to
% have checked verity of desired xyz co-ordinates. Output xyz returns
% co-ordinates actually set {mm}.
% d - Euclidean distance between desired and set co-ordinates.
% NB: When using the results section, should use XYZregistry to get/set location
%
% FORMAT hFxyz = spm_results_ui('FindXYZframe',h)
% Find/check XYZ edit widgets frame handle, 'Tag'ged 'hFxyz'
% h - handle of frame enclosing widgets, or containing figure [default gcf]
% If ischar(h), then uses spm_figure('FindWin',h) to locate named figures
% hFxyz - handle of confirmed XYZ editable widgets control
% Errors if hFxyz is not an XYZ widget control, or a figure containing
% a unique such control
%
% FORMAT spm_results_ui('PlotUi',hAx)
% GUI for adjusting plot attributes - Sets up controls just above results GUI
% hAx - handle of axes to work with
%
% FORMAT spm_results_ui('PlotUiCB')
% CallBack handler for Plot attribute GUI
%
% FORMAT Fgraph = spm_results_ui('Clear',F,mode)
% Clears results subpane of Graphics window, deleting all but semi-permanent
% results section stuff
% F - handle of Graphics window [Default spm_figure('FindWin','Graphics')]
% mode - 1 [default] - clear results subpane
% - 0 - clear results subpane and hide results stuff
% - 2 - clear, but respect 'NextPlot' 'add' axes
% (which is set by `hold on`)
% Fgraph - handle of Graphics window
%
% FORMAT hMP = spm_results_ui('LaunchMP',M,DIM,hReg,hBmp)
% Prototype callback handler for integrating MultiPlanar toolbox
%
% FORMAT spm_results_ui('Delete',h)
% deletes HandleGraphics objects, but only if they're valid, thus avoiding
% warning statements from MATLAB.
%__________________________________________________________________________
SVNid = '$Rev: 4977 $';
%-Condition arguments
%--------------------------------------------------------------------------
if nargin == 0, Action='SetUp'; else Action=varargin{1}; end
%==========================================================================
switch lower(Action), case 'setup' %-Set up results
%==========================================================================
%-Initialise
%----------------------------------------------------------------------
SPMid = spm('FnBanner',mfilename,SVNid);
[Finter,Fgraph,CmdLine] = spm('FnUIsetup','Stats: Results');
spm_clf('Satellite')
FS = spm('FontSizes');
%-Get thresholded xSPM data and parameters of design
%======================================================================
if nargin > 1
[SPM,xSPM] = spm_getSPM(varargin{2});
else
[SPM,xSPM] = spm_getSPM;
end
if isempty(xSPM)
varargout = {[],[],[]};
return;
end
%-Ensure pwd = swd so that relative filenames are valid
%----------------------------------------------------------------------
cd(SPM.swd)
%-Get space information
%======================================================================
M = SPM.xVol.M;
DIM = SPM.xVol.DIM;
%-Space units
%----------------------------------------------------------------------
try
try
units = SPM.xVol.units;
catch
units = xSPM.units;
end
catch
try
if strcmp(spm('CheckModality'),'EEG')
datatype = {...
'Volumetric (2D/3D)',...
'Scalp-Time',...
'Scalp-Frequency',...
'Time-Frequency',...
'Frequency-Frequency'};
selected = spm_input('Data Type: ','+1','m',datatype);
datatype = datatype{selected};
else
datatype = 'Volumetric (2D/3D)';
end
catch
datatype = 'Volumetric (2D/3D)';
end
switch datatype
case 'Volumetric (2D/3D)'
units = {'mm' 'mm' 'mm'};
case 'Scalp-Time'
units = {'mm' 'mm' 'ms'};
case 'Scalp-Frequency'
units = {'mm' 'mm' 'Hz'};
case 'Time-Frequency'
units = {'Hz' 'ms' ''};
case 'Frequency-Frequency'
units = {'Hz' 'Hz' ''};
otherwise
error('Unknown data type.');
end
end
if DIM(3) == 1, units{3} = ''; end
xSPM.units = units;
SPM.xVol.units = units;
%-Setup Results User Interface; Display MIP, design matrix & parameters
%======================================================================
%-Setup results GUI
%----------------------------------------------------------------------
spm_clf(Finter);
spm('FigName',['SPM{',xSPM.STAT,'}: Results'],Finter,CmdLine);
hReg = spm_results_ui('SetupGUI',M,DIM,xSPM,Finter);
%-Setup design interrogation menu
%----------------------------------------------------------------------
hDesRepUI = spm_DesRep('DesRepUI',SPM);
figure(Finter)
%-Setup contrast menu
%----------------------------------------------------------------------
hC = uimenu(Finter,'Label','Contrasts', 'Tag','ContrastsUI');
hC1 = uimenu(hC,'Label','New Contrast...',...
'UserData',struct('Ic',0),...
'Callback',{@mychgcon,xSPM});
hC1 = uimenu(hC,'Label','Change Contrast');
for i=1:numel(SPM.xCon)
hC2 = uimenu(hC1,'Label',[SPM.xCon(i).STAT, ': ', SPM.xCon(i).name], ...
'UserData',struct('Ic',i),...
'Callback',{@mychgcon,xSPM});
if any(xSPM.Ic == i)
set(hC2,'ForegroundColor',[0 0 1],'Checked','on');
end
end
hC1 = uimenu(hC,'Label','Previous Contrast',...
'Accelerator','P',...
'UserData',struct('Ic',xSPM.Ic-1),...
'Callback',{@mychgcon,xSPM});
if xSPM.Ic-1<1, set(hC1,'Enable','off'); end
hC1 = uimenu(hC,'Label','Next Contrast',...
'Accelerator','N',...
'UserData',struct('Ic',xSPM.Ic+1),...
'Callback',{@mychgcon,xSPM});
if xSPM.Ic+1>numel(SPM.xCon), set(hC1,'Enable','off'); end
hC1 = uimenu(hC,'Label','Significance level','Separator','on');
xSPMtmp = xSPM; xSPMtmp.thresDesc = '';
uimenu(hC1,'Label','Change...','UserData',struct('Ic',xSPM.Ic),...
'Callback',{@mychgcon,xSPMtmp});
xSPMtmp = xSPM; xSPMtmp.thresDesc = 'p<0.05 (FWE)';
uimenu(hC1,'Label','Set to 0.05 (FWE)','UserData',struct('Ic',xSPM.Ic),...
'Callback',{@mychgcon,xSPMtmp});
xSPMtmp = xSPM; xSPMtmp.thresDesc = 'p<0.001 (unc.)';
uimenu(hC1,'Label','Set to 0.001 (unc.)','UserData',struct('Ic',xSPM.Ic),...
'Callback',{@mychgcon,xSPMtmp});
uimenu(hC1,'Label',[xSPM.thresDesc ', k=' num2str(xSPM.k)],...
'Enable','off','Separator','on');
hC1 = uimenu(hC,'Label','Multiple display...',...
'Separator','on',...
'Callback',{@mycheckres,xSPM});
%-Setup Maximum intensity projection (MIP) & register
%----------------------------------------------------------------------
hMIPax = axes('Parent',Fgraph,'Position',[0.05 0.60 0.55 0.36],'Visible','off');
hMIPax = spm_mip_ui(xSPM.Z,xSPM.XYZmm,M,DIM,hMIPax,units);
spm_XYZreg('XReg',hReg,hMIPax,'spm_mip_ui');
if xSPM.STAT == 'P'
str = xSPM.STATstr;
else
str = ['SPM\{',xSPM.STATstr,'\}'];
end
text(240,260,str,...
'Interpreter','TeX',...
'FontSize',FS(14),'Fontweight','Bold',...
'Parent',hMIPax)
%-Print comparison title
%----------------------------------------------------------------------
hTitAx = axes('Parent',Fgraph,...
'Position',[0.02 0.95 0.96 0.02],...
'Visible','off');
text(0.5,0,xSPM.title,'Parent',hTitAx,...
'HorizontalAlignment','center',...
'VerticalAlignment','baseline',...
'FontWeight','Bold','FontSize',FS(14))
%-Print SPMresults: Results directory & thresholding info
%----------------------------------------------------------------------
hResAx = axes('Parent',Fgraph,...
'Position',[0.05 0.55 0.45 0.05],...
'DefaultTextVerticalAlignment','baseline',...
'DefaultTextFontSize',FS(9),...
'DefaultTextColor',[1,1,1]*.7,...
'Units','points',...
'Visible','off');
AxPos = get(hResAx,'Position'); set(hResAx,'YLim',[0,AxPos(4)])
h = text(0,24,'SPMresults:','Parent',hResAx,...
'FontWeight','Bold','FontSize',FS(14));
text(get(h,'Extent')*[0;0;1;0],24,spm_str_manip(SPM.swd,'a30'),'Parent',hResAx)
try
thresDesc = xSPM.thresDesc;
text(0,12,sprintf('Height threshold %c = %0.6f {%s}',xSPM.STAT,xSPM.u,thresDesc),'Parent',hResAx)
catch
text(0,12,sprintf('Height threshold %c = %0.6f',xSPM.STAT,xSPM.u),'Parent',hResAx)
end
text(0,00,sprintf('Extent threshold k = %0.0f voxels',xSPM.k), 'Parent',hResAx)
%-Plot design matrix
%----------------------------------------------------------------------
hDesMtx = axes('Parent',Fgraph,'Position',[0.65 0.55 0.25 0.25]);
hDesMtxIm = image((SPM.xX.nKX + 1)*32);
xlabel('Design matrix')
set(hDesMtxIm,'ButtonDownFcn','spm_DesRep(''SurfDesMtx_CB'')',...
'UserData',struct(...
'X', SPM.xX.xKXs.X,...
'fnames', {reshape({SPM.xY.VY.fname},size(SPM.xY.VY))},...
'Xnames', {SPM.xX.name}))
%-Plot contrasts
%----------------------------------------------------------------------
nPar = size(SPM.xX.X,2);
xx = [repmat([0:nPar-1],2,1);repmat([1:nPar],2,1)];
nCon = length(xSPM.Ic);
xCon = SPM.xCon;
if nCon
dy = 0.15/max(nCon,2);
hConAx = axes('Position',[0.65 (0.80 + dy*.1) 0.25 dy*(nCon-.1)],...
'Tag','ConGrphAx','Visible','off');
title('contrast(s)')
htxt = get(hConAx,'title');
set(htxt,'Visible','on','HandleVisibility','on')
end
for ii = nCon:-1:1
axes('Position',[0.65 (0.80 + dy*(nCon - ii +.1)) 0.25 dy*.9])
if xCon(xSPM.Ic(ii)).STAT == 'T' && size(xCon(xSPM.Ic(ii)).c,2) == 1
%-Single vector contrast for SPM{t} - bar
%--------------------------------------------------------------
yy = [zeros(1,nPar);repmat(xCon(xSPM.Ic(ii)).c',2,1);zeros(1,nPar)];
h = patch(xx,yy,[1,1,1]*.5);
set(gca,'Tag','ConGrphAx',...
'Box','off','TickDir','out',...
'XTick',spm_DesRep('ScanTick',nPar,10) - 0.5,'XTickLabel','',...
'XLim', [0,nPar],...
'YTick',[-1,0,+1],'YTickLabel','',...
'YLim',[min(xCon(xSPM.Ic(ii)).c),max(xCon(xSPM.Ic(ii)).c)] +...
[-1 +1] * max(abs(xCon(xSPM.Ic(ii)).c))/10 )
else
%-F-contrast - image
%--------------------------------------------------------------
h = image((xCon(xSPM.Ic(ii)).c'/max(abs(xCon(xSPM.Ic(ii)).c(:)))+1)*32);
set(gca,'Tag','ConGrphAx',...
'Box','on','TickDir','out',...
'XTick',spm_DesRep('ScanTick',nPar,10),'XTickLabel','',...
'XLim', [0,nPar]+0.5,...
'YTick',[0:size(SPM.xCon(xSPM.Ic(ii)).c,2)]+0.5,...
'YTickLabel','',...
'YLim', [0,size(xCon(xSPM.Ic(ii)).c,2)]+0.5 )
end
ylabel(num2str(xSPM.Ic(ii)))
set(h,'ButtonDownFcn','spm_DesRep(''SurfCon_CB'')',...
'UserData', struct( 'i', xSPM.Ic(ii),...
'h', htxt,...
'xCon', xCon(xSPM.Ic(ii))))
end
%-Store handles of results section Graphics window objects
%----------------------------------------------------------------------
H = get(Fgraph,'Children');
H = findobj(H,'flat','HandleVisibility','on');
H = findobj(H);
Hv = get(H,'Visible');
set(hResAx,'Tag','PermRes','UserData',struct('H',H,'Hv',{Hv}))
%-Finished results setup
%----------------------------------------------------------------------
varargout = {hReg,xSPM,SPM};
spm('Pointer','Arrow')
%======================================================================
case 'setupgui' %-Set up results section GUI
%======================================================================
% hReg = spm_results_ui('SetupGUI',M,DIM,xSPM,Finter)
if nargin < 5, Finter='Interactive'; else Finter = varargin{5}; end
if nargin < 4, error('Insufficient arguments'), end
M = varargin{2};
DIM = varargin{3};
Finter = spm_figure('GetWin',Finter);
WS = spm('WinScale');
FS = spm('FontSizes');
%-Create frame for Results GUI objects
%------------------------------------------------------------------
hReg = uicontrol(Finter,'Style','Frame','Position',[001 001 400 190].*WS,...
'BackgroundColor',spm('Colour'));
hFResUi = uicontrol(Finter,...
'Style','Pushbutton',...
'enable','off',...
'Position',[008 007 387 178].*WS);
%-Initialise registry in hReg frame object
%------------------------------------------------------------------
[hReg,xyz] = spm_XYZreg('InitReg',hReg,M,DIM,[0;0;0]);
%-Setup editable XYZ widgets & cross register with registry
%------------------------------------------------------------------
hFxyz = spm_results_ui('DrawXYZgui',M,DIM,varargin{4},xyz,Finter);
spm_XYZreg('XReg',hReg,hFxyz,'spm_results_ui');
%-Set up buttons for results functions
%------------------------------------------------------------------
spm_results_ui('DrawButts',hReg,DIM,Finter,WS,FS);
varargout = {hReg};
%======================================================================
case 'drawbutts' %-Draw results section buttons in Interactive window
%======================================================================
% spm_results_ui('DrawButts',hReg,DIM,Finter,WS,FS)
%
if nargin<3, error('Insufficient arguments'), end
hReg = varargin{2};
DIM = varargin{3};
if nargin<4, Finter = spm_figure('FindWin','Interactive');
else Finter = varargin{4}; end
if nargin < 5, WS = spm('WinScale'); else WS = varargin{5}; end
if nargin < 6, FS = spm('FontSizes'); else FS = varargin{6}; end
%-p-values
%------------------------------------------------------------------
uicontrol(Finter,'Style','Text','String','p-values',...
'Position',[020 168 080 015].*WS,...
'FontAngle','Italic',...
'FontSize',FS(10),...
'HorizontalAlignment','Left',...
'ForegroundColor','w')
uicontrol(Finter,'Style','PushButton','String','whole brain','FontSize',FS(10),...
'ToolTipString',...
'tabulate summary of local maxima, p-values & statistics',...
'Callback','TabDat = spm_list(''List'',xSPM,hReg);',...
'Interruptible','on','Enable','on',...
'Position',[015 145 100 020].*WS)
uicontrol(Finter,'Style','PushButton','String','current cluster','FontSize',FS(10),...
'ToolTipString',...
'tabulate p-values & statistics for local maxima of nearest cluster',...
'Callback','TabDat = spm_list(''ListCluster'',xSPM,hReg);',...
'Interruptible','on','Enable','on',...
'Position',[015 120 100 020].*WS)
uicontrol(Finter,'Style','PushButton','String','small volume','FontSize',FS(10),...
'ToolTipString',['Small Volume Correction - corrected p-values ',...
'for a small search region'],...
'Callback','TabDat = spm_VOI(SPM,xSPM,hReg);',...
'Interruptible','on','Enable','on',...
'Position',[015 095 100 020].*WS)
%-SPM area - used for Volume of Interest analyses
%------------------------------------------------------------------
uicontrol(Finter,'Style','Text','String','Multivariate',...
'Position',[135 168 80 015].*WS,...
'FontAngle','Italic',...
'FontSize',FS(10),...
'HorizontalAlignment','Left',...
'ForegroundColor','w')
uicontrol(Finter,'Style','PushButton','String','eigenvariate',...
'Position',[130 145 70 020].*WS,...
'ToolTipString',...
'Responses (principal eigenvariate) in volume of interest',...
'Callback','[Y,xY] = spm_regions(xSPM,SPM,hReg)',...
'Interruptible','on','Enable','on',...
'FontSize',FS(10),'ForegroundColor',[1 1 1]/3)
uicontrol(Finter,'Style','PushButton','String','CVA',...
'Position',[205 145 65 020].*WS,...
'ToolTipString',...
'Canonical variates analysis for the current contrast and VOI',...
'Callback','CVA = spm_cva(xSPM,SPM,hReg)',...
'Interruptible','on','Enable','on',...
'FontSize',FS(10),'ForegroundColor',[1 1 1]/3)
uicontrol(Finter,'Style','PushButton','String','multivariate Bayes',...
'Position',[130 120 140 020].*WS,...
'ToolTipString',...
'Multivariate Bayes',...
'Callback','[MVB] = spm_mvb_ui(xSPM,SPM,hReg)',...
'Interruptible','on','Enable','on',...
'FontSize',FS(10),'ForegroundColor',[1 1 1]/3)
uicontrol(Finter,'Style','PushButton','String','BMS',...
'Position',[130 95 68 020].*WS,...
'ToolTipString',...
'Compare or review a multivariate Bayesian model',...
'Callback','[F,P] = spm_mvb_bmc',...
'Interruptible','on','Enable','on',...
'FontSize',FS(8),'ForegroundColor',[1 1 1]/3)
uicontrol(Finter,'Style','PushButton','String','p-value',...
'Position',[202 95 68 020].*WS,...
'ToolTipString',...
'Randomisation testing of a multivariate Bayesian model',...
'Callback','spm_mvb_p',...
'Interruptible','on','Enable','on',...
'FontSize',FS(8),'ForegroundColor',[1 1 1]/3)
%-Hemodynamic modelling
%------------------------------------------------------------------
if strcmp(spm('CheckModality'),'FMRI')
uicontrol(Finter,'Style','PushButton','String','Hemodynamics',...
'FontSize',FS(10),...
'ToolTipString','Hemodynamic modelling of regional response',...
'Callback','[Ep,Cp,K1,K2] = spm_hdm_ui(xSPM,SPM,hReg);',...
'Interruptible','on','Enable','on',...
'Position',[130 055 140 020].*WS,...
'ForegroundColor',[1 1 1]/3);
end
%-Not currently used
%------------------------------------------------------------------
%uicontrol(Finter,'Style','PushButton','String','','FontSize',FS(10),...
% 'ToolTipString','',...
% 'Callback','',...
% 'Interruptible','on','Enable','on',...
% 'Position',[015 055 100 020].*WS)
%-Visualisation
%------------------------------------------------------------------
uicontrol(Finter,'Style','Text','String','Display',...
'Position',[290 168 065 015].*WS,...
'FontAngle','Italic',...
'FontSize',FS(10),...
'HorizontalAlignment','Left',...
'ForegroundColor','w')
uicontrol(Finter,'Style','PushButton','String','plot','FontSize',FS(10),...
'ToolTipString','plot data & contrasts at current voxel',...
'Callback','[Y,y,beta,Bcov] = spm_graph(xSPM,SPM,hReg);',...
'Interruptible','on','Enable','on',...
'Position',[285 145 100 020].*WS,...
'Tag','plotButton')
str = { 'overlays...','slices','sections','render','previous sections','previous render'};
tstr = { 'overlay filtered SPM on another image: ',...
'3 slices / ','ortho sections / ','render /','previous ortho sections /','previous surface rendering'};
tmp = { 'spm_transverse(''set'',xSPM,hReg)',...
'spm_sections(xSPM,hReg)',...
['spm_render( struct( ''XYZ'', xSPM.XYZ,',...
'''t'', xSPM.Z'',',...
'''mat'', xSPM.M,',...
'''dim'', xSPM.DIM))'],...
['global prevsect;','spm_sections(xSPM,hReg,prevsect)'],...
['global prevrend;','if ~isstruct(prevrend)',...
'prevrend = struct(''rendfile'','''',''brt'',[],''col'',[]); end;',...
'spm_render( struct( ''XYZ'', xSPM.XYZ,',...
'''t'', xSPM.Z'',',...
'''mat'', xSPM.M,',...
'''dim'', xSPM.DIM),prevrend.brt,prevrend.rendfile)']};
uicontrol(Finter,'Style','PopUp','String',str,'FontSize',FS(10),...
'ToolTipString',cat(2,tstr{:}),...
'Callback','spm(''PopUpCB'',gcbo)',...
'UserData',tmp,...
'Interruptible','on','Enable','on',...
'Position',[285 120 100 020].*WS)
str = {'save...',...
'thresholded SPM',...
'all clusters (binary)',...
'all clusters (n-ary)',...
'current cluster'};
tmp = {{@mysavespm, 'thresh' },...
{@mysavespm, 'binary' },...
{@mysavespm, 'n-ary' },...
{@mysavespm, 'current'}};
uicontrol(Finter,'Style','PopUp','String',str,'FontSize',FS(10),...
'ToolTipString','save as image',...
'Callback','spm(''PopUpCB'',gcbo)',...
'UserData',tmp,...
'Interruptible','on','Enable','on',...
'Position',[285 095 100 020].*WS)
%-ResultsUI controls
%------------------------------------------------------------------
hClear = uicontrol(Finter,'Style','PushButton','String','clear',...
'ToolTipString','clears results subpane',...
'FontSize',FS(9),'ForegroundColor','b',...
'Callback',['spm_results_ui(''Clear''); ',...
'spm_input(''!DeleteInputObj''),',...
'spm_clf(''Satellite'')'],...
'Interruptible','on','Enable','on',...
'DeleteFcn','spm_clf(''Graphics'')',...
'Position',[285 055 035 018].*WS);
hExit = uicontrol(Finter,'Style','PushButton','String','exit',...
'ToolTipString','exit the results section',...
'FontSize',FS(9),'ForegroundColor','r',...
'Callback','spm_results_ui(''close'')',...
'Interruptible','on','Enable','on',...
'Position',[325 055 035 018].*WS);
hHelp = uicontrol(Finter,'Style','PushButton','String','?',...
'ToolTipString','results section help',...
'FontSize',FS(9),'ForegroundColor','g',...
'Callback','spm_help(''spm_results_ui'')',...
'Interruptible','on','Enable','on',...
'Position',[365 055 020 018].*WS);
%======================================================================
case 'drawxyzgui' %-Draw XYZ GUI area
%======================================================================
% hFxyz = spm_results_ui('DrawXYZgui',M,DIM,xSPM,xyz,Finter)
if nargin<6, Finter=spm_figure('FindWin','Interactive');
else Finter=varargin{6}; end
if nargin < 5, xyz=[0;0;0]; else xyz=varargin{5}; end
if nargin < 4, error('Insufficient arguments'), end
DIM = varargin{3};
M = varargin{2};
xyz = spm_XYZreg('RoundCoords',xyz,M,DIM);
%-Font details
%------------------------------------------------------------------
WS = spm('WinScale');
FS = spm('FontSizes');
PF = spm_platform('fonts');
%-Create XYZ control objects
%------------------------------------------------------------------
hFxyz = uicontrol(Finter,'Style','Pushbutton',...
'visible','off','enable','off','Position',[010 010 265 030].*WS);
uicontrol(Finter,'Style','Text','String','co-ordinates',...
'Position',[020 035 090 016].*WS,...
'FontAngle','Italic',...
'FontSize',FS(10),...
'HorizontalAlignment','Left',...
'ForegroundColor','w')
uicontrol(Finter,'Style','Text','String','x =',...
'Position',[020 015 024 018].*WS,...
'FontName',PF.times,'FontSize',FS(10),'FontAngle','Italic',...
'HorizontalAlignment','Center');
hX = uicontrol(Finter,'Style','Edit','String',sprintf('%.2f',xyz(1)),...
'ToolTipString','enter x-coordinate',...
'Position',[044 015 056 020].*WS,...
'FontSize',FS(10),'BackGroundColor',[.8,.8,1],...
'HorizontalAlignment','Right',...
'Tag','hX',...
'Callback','spm_results_ui(''EdWidCB'')');
uicontrol(Finter,'Style','Text','String','y =',...
'Position',[105 015 024 018].*WS,...
'FontName',PF.times,'FontSize',FS(10),'FontAngle','Italic',...
'HorizontalAlignment','Center')
hY = uicontrol(Finter,'Style','Edit','String',sprintf('%.2f',xyz(2)),...
'ToolTipString','enter y-coordinate',...
'Position',[129 015 056 020].*WS,...
'FontSize',FS(10),'BackGroundColor',[.8,.8,1],...
'HorizontalAlignment','Right',...
'Tag','hY',...
'Callback','spm_results_ui(''EdWidCB'')');
if DIM(3) ~= 1
uicontrol(Finter,'Style','Text','String','z =',...
'Position',[190 015 024 018].*WS,...
'FontName',PF.times,'FontSize',FS(10),'FontAngle','Italic',...
'HorizontalAlignment','Center')
hZ = uicontrol(Finter,'Style','Edit','String',sprintf('%.2f',xyz(3)),...
'ToolTipString','enter z-coordinate',...
'Position',[214 015 056 020].*WS,...
'FontSize',FS(10),'BackGroundColor',[.8,.8,1],...
'HorizontalAlignment','Right',...
'Tag','hZ',...
'Callback','spm_results_ui(''EdWidCB'')');
else
hZ = [];
end
%-Statistic value reporting pane
%------------------------------------------------------------------
uicontrol(Finter,'Style','Text','String','statistic',...
'Position',[285 035 090 016].*WS,...
'FontAngle','Italic',...
'FontSize',FS(10),...
'HorizontalAlignment','Left',...
'ForegroundColor','w')
hSPM = uicontrol(Finter,'Style','Text','String','',...
'Position',[285 012 100 020].*WS,...
'FontSize',FS(10),...
'HorizontalAlignment','Center');
%-Store data
%------------------------------------------------------------------
set(hFxyz,'Tag','hFxyz','UserData',struct(...
'hReg', [],...
'M', M,...
'DIM', DIM,...
'XYZ', varargin{4}.XYZmm,...
'Z', varargin{4}.Z,...
'hX', hX,...
'hY', hY,...
'hZ', hZ,...
'hSPM', hSPM,...
'xyz', xyz ));
set([hX,hY,hZ],'UserData',hFxyz)
varargout = {hFxyz};
%======================================================================
case 'edwidcb' %-Callback for editable widgets
%======================================================================
% spm_results_ui('EdWidCB')
hC = gcbo;
d = find(strcmp(get(hC,'Tag'),{'hX','hY','hZ'}));
hFxyz = get(hC,'UserData');
UD = get(hFxyz,'UserData');
xyz = UD.xyz;
nxyz = xyz;
o = evalin('base',['[',get(hC,'String'),']'],'sprintf(''error'')');
if ischar(o) || length(o)>1
warning(sprintf('%s: Error evaluating ordinate:\n\t%s',...
mfilename,lasterr))
else
nxyz(d) = o;
nxyz = spm_XYZreg('RoundCoords',nxyz,UD.M,UD.DIM);
end
if abs(xyz(d)-nxyz(d))>0
UD.xyz = nxyz; set(hFxyz,'UserData',UD)
if ~isempty(UD.hReg), spm_XYZreg('SetCoords',nxyz,UD.hReg,hFxyz); end
set(hC,'String',sprintf('%.3f',nxyz(d)))
spm_results_ui('UpdateSPMval',UD)
end
%======================================================================
case 'updatespmval' %-Update SPM value in GUI
%======================================================================
% spm_results_ui('UpdateSPMval',hFxyz)
% spm_results_ui('UpdateSPMval',UD)
if nargin<2, error('insufficient arguments'), end
if isstruct(varargin{2}), UD=varargin{2}; else UD = get(varargin{2},'UserData'); end
i = spm_XYZreg('FindXYZ',UD.xyz,UD.XYZ);
if isempty(i), str = ''; else str = sprintf('%6.2f',UD.Z(i)); end
set(UD.hSPM,'String',str);
%======================================================================
case 'getcoords' % Get current co-ordinates from XYZ widget
%======================================================================
% xyz = spm_results_ui('GetCoords',hFxyz)
if nargin<2, hFxyz='Interactive'; else hFxyz=varargin{2}; end
hFxyz = spm_results_ui('FindXYZframe',hFxyz);
varargout = {getfield(get(hFxyz,'UserData'),'xyz')};
%======================================================================
case 'setcoords' % Set co-ordinates to XYZ widget
%======================================================================
% [xyz,d] = spm_results_ui('SetCoords',xyz,hFxyz,hC)
if nargin<4, hC=0; else hC=varargin{4}; end
if nargin<3, hFxyz=spm_results_ui('FindXYZframe'); else hFxyz=varargin{3}; end
if nargin<2, error('Set co-ords to what!'); else xyz=varargin{2}; end
%-If this is an internal call, then don't do anything
if hFxyz==hC, return, end
UD = get(hFxyz,'UserData');
%-Check validity of coords only when called without a caller handle
%------------------------------------------------------------------
if hC <= 0
[xyz,d] = spm_XYZreg('RoundCoords',xyz,UD.M,UD.DIM);
if d>0 && nargout<2, warning(sprintf(...
'%s: Co-ords rounded to nearest voxel centre: Discrepancy %.2f',...
mfilename,d))
end
else
d = [];
end
%-Update xyz information & widget strings
%------------------------------------------------------------------
UD.xyz = xyz; set(hFxyz,'UserData',UD)
set(UD.hX,'String',sprintf('%.2f',xyz(1)))
set(UD.hY,'String',sprintf('%.2f',xyz(2)))
set(UD.hZ,'String',sprintf('%.2f',xyz(3)))
spm_results_ui('UpdateSPMval',UD)
%-Tell the registry, if we've not been called by the registry...
%------------------------------------------------------------------
if (~isempty(UD.hReg) && UD.hReg~=hC)
spm_XYZreg('SetCoords',xyz,UD.hReg,hFxyz);
end
%-Return arguments
%------------------------------------------------------------------
varargout = {xyz,d};
%======================================================================
case 'findxyzframe' % Find hFxyz frame
%======================================================================
% hFxyz = spm_results_ui('FindXYZframe',h)
% Sorts out hFxyz handles
if nargin<2, h='Interactive'; else, h=varargin{2}; end
if ischar(h), h=spm_figure('FindWin',h); end
if ~ishandle(h), error('invalid handle'), end
if ~strcmp(get(h,'Tag'),'hFxyz'), h=findobj(h,'Tag','hFxyz'); end
if isempty(h), error('XYZ frame not found'), end
if length(h)>1, error('Multiple XYZ frames found'), end
varargout = {h};
%======================================================================
case 'plotui' %-GUI for plot manipulation
%======================================================================
% spm_results_ui('PlotUi',hAx)
if nargin<2, hAx=gca; else hAx=varargin{2}; end
WS = spm('WinScale');
FS = spm('FontSizes');
Finter=spm_figure('FindWin','Interactive');
figure(Finter)
%-Check there aren't already controls!
%------------------------------------------------------------------
hGraphUI = findobj(Finter,'Tag','hGraphUI');
if ~isempty(hGraphUI) %-Controls exist
hBs = get(hGraphUI,'UserData');
if hAx==get(hBs(1),'UserData') %-Controls linked to these axes
return
else %-Old controls remain
delete(findobj(Finter,'Tag','hGraphUIbg'))
end
end
%-Frames & text
%------------------------------------------------------------------
hGraphUIbg = uicontrol(Finter,'Style','Frame','Tag','hGraphUIbg',...
'BackgroundColor',spm('Colour'),...
'Position',[001 196 400 055].*WS);
hGraphUI = uicontrol(Finter,'Style','Frame','Tag','hGraphUI',...
'Position',[008 202 387 043].*WS);
hGraphUIButtsF = uicontrol(Finter,'Style','Frame',...
'Position',[010 205 380 030].*WS);
hText = uicontrol(Finter,'Style','Text','String','plot controls',...
'Position',[020 227 080 016].*WS,...
'FontWeight','Normal',...
'FontAngle','Italic','FontSize',FS(10),...
'HorizontalAlignment','Left',...
'ForegroundColor','w');
%-Controls
%------------------------------------------------------------------
h1 = uicontrol(Finter,'Style','CheckBox','String','hold',...
'ToolTipString','toggle hold to overlay plots',...
'FontSize',FS(10),...
'Value',strcmp(get(hAx,'NextPlot'),'add'),...
'Callback',[...
'if get(gcbo,''Value''), ',...
'set(get(gcbo,''UserData''),''NextPlot'',''add''), ',...
'else, ',...
'set(get(gcbo,''UserData''),''NextPlot'',''replace''), ',...
'end'],...
'Interruptible','on','Enable','on',...
'Tag','holdButton',...
'Position',[015 210 070 020].*WS);
set(findobj('Tag','plotButton'),'UserData',h1);
h2 = uicontrol(Finter,'Style','CheckBox','String','grid',...
'ToolTipString','toggle axes grid',...
'FontSize',FS(10),...
'Value',strcmp(get(hAx,'XGrid'),'on'),...
'Callback',[...
'if get(gcbo,''Value''), ',...
'set(get(gcbo,''UserData''),''XGrid'',''on'','...
'''YGrid'',''on'',''ZGrid'',''on''), ',...
'else, ',...
'set(get(gcbo,''UserData''),''XGrid'',''off'','...
'''YGrid'',''off'',''ZGrid'',''off''), ',...
'end'],...
'Interruptible','on','Enable','on',...
'Position',[090 210 070 020].*WS);
h3 = uicontrol(Finter,'Style','CheckBox','String','Box',...
'ToolTipString','toggle axes box',...
'FontSize',FS(10),...
'Value',strcmp(get(hAx,'Box'),'on'),...
'Callback',[...
'if get(gcbo,''Value''), ',...
'set(get(gcbo,''UserData''),''Box'',''on''), ',...
'else, ',...
'set(get(gcbo,''UserData''),''Box'',''off''), ',...
'end'],...
'Interruptible','on','Enable','on',...
'Position',[165 210 070 020].*WS);
h4 = uicontrol(Finter,'Style','PopUp',...
'ToolTipString','edit axis text annotations',...
'FontSize',FS(10),...
'String','text|Title|Xlabel|Ylabel',...
'Callback','spm_results_ui(''PlotUiCB'')',...
'Interruptible','on','Enable','on',...
'Position',[240 210 070 020].*WS);
h5 = uicontrol(Finter,'Style','PopUp',...
'ToolTipString','change various axes attributes',...
'FontSize',FS(10),...
'String','attrib|LineWidth|XLim|YLim|handle',...
'Callback','spm_results_ui(''PlotUiCB'')',...
'Interruptible','off','Enable','on',...
'Position',[315 210 070 020].*WS);
%-Handle storage for linking, and DeleteFcns for linked deletion
%------------------------------------------------------------------
set(hGraphUI,'UserData',[h1,h2,h3,h4,h5])
set([h1,h2,h3,h4,h5],'UserData',hAx)
set(hGraphUIbg,'UserData',...
[hGraphUI,hGraphUIButtsF,hText,h1,h2,h3,h4,h5],...
'DeleteFcn','spm_results_ui(''Delete'',get(gcbo,''UserData''))')
set(hAx,'UserData',hGraphUIbg,...
'DeleteFcn','spm_results_ui(''Delete'',get(gcbo,''UserData''))')
%======================================================================
case 'plotuicb'
%======================================================================
% spm_results_ui('PlotUiCB')
hPM = gcbo;
v = get(hPM,'Value');
if v==1, return, end
str = cellstr(get(hPM,'String'));
str = str{v};
hAx = get(hPM,'UserData');
switch str
case 'Title'
h = get(hAx,'Title');
set(h,'String',spm_input('Enter title:',-1,'s+',get(h,'String')))
case 'Xlabel'
h = get(hAx,'Xlabel');
set(h,'String',spm_input('Enter X axis label:',-1,'s+',get(h,'String')))
case 'Ylabel'
h = get(hAx,'Ylabel');
set(h,'String',spm_input('Enter Y axis label:',-1,'s+',get(h,'String')))
case 'LineWidth'
lw = spm_input('Enter LineWidth',-1,'e',get(hAx,'LineWidth'),1);
set(hAx,'LineWidth',lw)
case 'XLim'
XLim = spm_input('Enter XLim',-1,'e',get(hAx,'XLim'),[1,2]);
set(hAx,'XLim',XLim)
case 'YLim'
YLim = spm_input('Enter YLim',-1,'e',get(hAx,'YLim'),[1,2]);
set(hAx,'YLim',YLim)
case 'handle'
varargout={hAx};
otherwise
warning(['Unknown action: ',str])
end
set(hPM,'Value',1)
%======================================================================
case 'clear' %-Clear results subpane
%======================================================================
% Fgraph = spm_results_ui('Clear',F,mode)
% mode 1 [default] usual, mode 0 - clear & hide Res stuff, 2 - RNP
if nargin<3, mode=1; else, mode=varargin{3}; end
if nargin<2, F='Graphics'; else, F=varargin{2}; end
F = spm_figure('FindWin',F);
%-Clear input objects from 'Interactive' window
%------------------------------------------------------------------
%spm_input('!DeleteInputObj')
%-Get handles of objects in Graphics window & note permanent results objects
%------------------------------------------------------------------
H = get(F,'Children'); %-Get contents of window
H = findobj(H,'flat','HandleVisibility','on'); %-Drop GUI components
h = findobj(H,'flat','Tag','PermRes'); %-Look for 'PermRes' object
if ~isempty(h)
%-Found 'PermRes' object
% This has handles of permanent results objects in it's UserData
tmp = get(h,'UserData');
HR = tmp.H;
HRv = tmp.Hv;
else
%-No trace of permanent results objects
HR = [];
HRv = {};
end
H = setdiff(H,HR); %-Drop permanent results obj
%-Delete stuff as appropriate
%------------------------------------------------------------------
if mode==2 %-Don't delete axes with NextPlot 'add'
H = setdiff(H,findobj(H,'flat','Type','axes','NextPlot','add'));
end
delete(H)
if mode==0 %-Hide the permanent results section stuff
set(HR,'Visible','off')
else
set(HR,{'Visible'},HRv)
end
%======================================================================
case 'close' %-Close Results
%======================================================================
spm_clf('Interactive');
spm_clf('Graphics');
close(spm_figure('FindWin','Satellite'));
evalin('base','clear');
%======================================================================
case 'launchmp' %-Launch multiplanar toolbox
%======================================================================
% hMP = spm_results_ui('LaunchMP',M,DIM,hReg,hBmp)
if nargin<5, hBmp = gcbo; else hBmp = varargin{5}; end
hReg = varargin{4};
DIM = varargin{3};
M = varargin{2};
%-Check for existing MultiPlanar toolbox
hMP = get(hBmp,'UserData');
if ishandle(hMP)
figure(ancestor(hMP,'figure'));
varargout = {hMP};
return
end
%-Initialise and cross-register MultiPlanar toolbox
hMP = spm_XYZreg_Ex2('Create',M,DIM);
spm_XYZreg('Xreg',hReg,hMP,'spm_XYZreg_Ex2');
%-Setup automatic deletion of MultiPlanar on deletion of results controls
set(hBmp,'Enable','on','UserData',hMP)
set(hBmp,'DeleteFcn','spm_results_ui(''delete'',get(gcbo,''UserData''))')
varargout = {hMP};
%======================================================================
case 'delete' %-Delete HandleGraphics objects
%======================================================================
% spm_results_ui('Delete',h)
h = varargin{2};
delete(h(ishandle(h)));
%======================================================================
otherwise
%======================================================================
error('Unknown action string')
end
%==========================================================================
function mychgcon(obj,evt,xSPM)
%==========================================================================
xSPM2.swd = xSPM.swd;
try, xSPM2.units = xSPM.units; end
xSPM2.Ic = getfield(get(obj,'UserData'),'Ic');
if isempty(xSPM2.Ic) || all(xSPM2.Ic == 0), xSPM2 = rmfield(xSPM2,'Ic'); end
xSPM2.Im = xSPM.Im;
xSPM2.pm = xSPM.pm;
xSPM2.Ex = xSPM.Ex;
xSPM2.title = '';
if ~isempty(xSPM.thresDesc)
td = regexp(xSPM.thresDesc,'p\D?(?<u>[\.\d]+) \((?<thresDesc>\S+)\)','names');
if isempty(td)
td = regexp(xSPM.thresDesc,'\w=(?<u>[\.\d]+)','names');
if isempty(td)
warning('This feature is not working with PPMs.');
td = struct('u',[],'thresDesc','');
else
td.thresDesc = 'none';
end
end
if strcmp(td.thresDesc,'unc.'), td.thresDesc = 'none'; end
xSPM2.thresDesc = td.thresDesc;
xSPM2.u = str2double(td.u);
xSPM2.k = xSPM.k;
end
hReg = spm_XYZreg('FindReg',spm_figure('GetWin','Interactive'));
xyz = spm_XYZreg('GetCoords',hReg);
[hReg,xSPM,SPM] = spm_results_ui('setup',xSPM2);
spm_XYZreg('SetCoords',xyz,hReg);
assignin('base','hReg',hReg);
assignin('base','xSPM',xSPM);
assignin('base','SPM',SPM);
figure(spm_figure('GetWin','Interactive'));
%==========================================================================
function mycheckres(obj,evt,xSPM)
%==========================================================================
spm_check_results([],xSPM);
%==========================================================================
function mysavespm(action)
%==========================================================================
xSPM = evalin('base','xSPM;');
XYZ = xSPM.XYZ;
switch lower(action)
case 'thresh'
Z = xSPM.Z;
case 'binary'
Z = ones(size(xSPM.Z));
case 'n-ary'
Z = spm_clusters(XYZ);
num = max(Z);
[n, ni] = sort(histc(Z,1:num), 2, 'descend');
n = size(ni);
n(ni) = 1:num;
Z = n(Z);
case 'current'
[xyzmm,i] = spm_XYZreg('NearestXYZ',...
spm_results_ui('GetCoords'),xSPM.XYZmm);
spm_results_ui('SetCoords',xSPM.XYZmm(:,i));
A = spm_clusters(XYZ);
j = find(A == A(i));
Z = ones(1,numel(j));
XYZ = xSPM.XYZ(:,j);
otherwise
error('Unknown action.');
end
spm_write_filtered(Z, XYZ, xSPM.DIM, xSPM.M,...
sprintf('SPM{%c}-filtered: u = %5.3f, k = %d',xSPM.STAT,xSPM.u,xSPM.k));
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_downsample.m
|
.m
|
antx-master/xspm8/spm_eeg_downsample.m
| 6,776 |
utf_8
|
2acedd25acf7d367a7d5e7d1d011cba8
|
function D = spm_eeg_downsample(S)
% Downsample M/EEG data
% FORMAT D = spm_eeg_downsample(S)
%
% S - optional input struct
% (optional) fields of S:
% S.D - MEEG object or filename of M/EEG mat-file
% S.fsample_new - new sampling rate, must be lower than the original one
% S.prefix - prefix of generated file
%
% D - MEEG object (also written on disk)
%__________________________________________________________________________
%
% This function uses MATLAB Signal Processing Toolbox:
% http://www.mathworks.com/products/signal/
% (function resample.m) if present and an homebrew version otherwise
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Stefan Kiebel
% $Id: spm_eeg_downsample.m 4383 2011-07-06 15:55:39Z guillaume $
SVNrev = '$Rev: 4383 $';
%-Startup
%--------------------------------------------------------------------------
spm('FnBanner', mfilename, SVNrev);
spm('FigName','M/EEG downsampling'); spm('Pointer','Watch');
%-Test for the presence of MATLAB Signal Processing Toolbox
%--------------------------------------------------------------------------
flag_TBX = license('checkout','signal_toolbox') & ~isdeployed;
if ~flag_TBX
disp(['warning: using homemade resampling routine ' ...
'as Signal Processing Toolbox is not available.']);
end
%-Get MEEG object
%--------------------------------------------------------------------------
try
D = S.D;
catch
[D, sts] = spm_select(1, 'mat', 'Select M/EEG mat file');
if ~sts, D = []; return; end
S.D = D;
end
D = spm_eeg_load(D);
%-Get parameters
%--------------------------------------------------------------------------
try
fsample_new = S.fsample_new;
catch
str = 'New sampling rate';
YPos = -1;
while 1
if YPos == -1
YPos = '+1';
end
[fsample_new, YPos] = spm_input(str, YPos, 'r');
if fsample_new < D.fsample, break, end
str = sprintf('Sampling rate must be less than original (%d)', round(D.fsample));
end
S.fsample_new = fsample_new;
end
try
prefix = S.prefix;
catch
prefix = 'd';
end
% This is to handle non-integer sampling rates up to a reasonable precision
P = round(10*fsample_new);
Q = round(10*D.fsample);
%-First pass: Determine new D.nsamples
%==========================================================================
if flag_TBX % Signal Proc. Toolbox
nsamples_new = ceil(nsamples(D)*P/Q);
else
d = double(squeeze(D(1, :, 1)));
[d2,alpha] = spm_resample(d,P/Q);
fsample_new = D.fsample*alpha;
S.fsample_new = fsample_new;
disp(['Resampling frequency is ',num2str(fsample_new), 'Hz'])
nsamples_new = size(d2, 2);
end
%-Generate new meeg object with new filenames
%--------------------------------------------------------------------------
Dnew = clone(D, [prefix fnamedat(D)], [D.nchannels nsamples_new D.ntrials]);
t0 = clock;
%-Second pass: resample all
%==========================================================================
if strcmp(D.type, 'continuous')
%-Continuous
%----------------------------------------------------------------------
spm_progress_bar('Init', D.nchannels, 'Channels downsampled');
% work on blocks of channels
% determine block size, dependent on memory
memsz = spm('Memory');
datasz = nchannels(D)*nsamples(D)*8; % datapoints x 8 bytes per double value
blknum = ceil(datasz/memsz);
blksz = ceil(nchannels(D)/blknum);
blknum = ceil(nchannels(D)/blksz);
% now downsample blocks of channels
chncnt=1;
for blk=1:blknum
% load old meeg object blockwise into workspace
blkchan=chncnt:(min(nchannels(D), chncnt+blksz-1));
Dtemp=D(blkchan,:,1);
chncnt=chncnt+blksz;
%loop through channels
for j = 1:numel(blkchan)
d = Dtemp(j,1:D.nsamples);
Dtemp(j,:)=0; % overwrite Dtemp to save memory
if flag_TBX % Signal Proc. Toolbox
Dtemp(j,1:nsamples_new) = resample(d', P, Q)';
else
Dtemp(j,1:nsamples_new) = spm_resample(d,P/Q);
end
spm_progress_bar('Set', blkchan(j));
end
% write Dtempnew to Dnew
Dnew(blkchan,:,1)=Dtemp(:,1:nsamples_new,1);
clear Dtemp
end
else
%-Epoched
%----------------------------------------------------------------------
spm_progress_bar('Init', D.ntrials, 'Trials downsampled'); drawnow;
if D.ntrials > 100, Ibar = floor(linspace(1, D.ntrials,100));
else Ibar = [1:D.ntrials]; end
for i = 1:D.ntrials
for j = 1:D.nchannels
d = double(squeeze(D(j, :, i)));
if flag_TBX % Signal Proc. Toolbox
d2 = resample(d', P, Q)';
else
d2 = spm_resample(d,P/Q);
end
Dnew(j, 1:nsamples_new, i) = d2;
end
if ismember(i, Ibar), spm_progress_bar('Set', i); end
end
end
spm_progress_bar('Clear');
%-Display statistics
%--------------------------------------------------------------------------
fprintf('Elapsed time is %f seconds.\n',etime(clock,t0)); %-#
%-Save new downsampled M/EEG dataset
%--------------------------------------------------------------------------
Dnew = fsample(Dnew, (P/Q)*D.fsample);
D = Dnew;
D = D.history('spm_eeg_downsample', S);
save(D);
%-Cleanup
%--------------------------------------------------------------------------
spm('FigName','M/EEG downsampling: done'); spm('Pointer','Arrow');
%==========================================================================
function [Y,alpha] = spm_resample(X,alpha)
% [Jean:] Basic resample function (when no Signal Proc. Toolbox)
% FORMAT Y = spm_resample(X,alpha)
% IN:
% - X: a nXm matrix of n time series
% - alpha: the ration of input versus output sampling frequencies. If
% alpha>1, rs(X,alpha) performs upsampling of the time series.
% OUT:
% - Y: nX[alpha*m] matrix of resampled time series
% - alpha: true alpha used (due to rational rounding)
% This function operates on rows of a signal matrix. This means it can be
% used on a block of channels.
N0 = size(X,2);
N = floor(N0*alpha);
alpha = N/N0;
Y = fftshift(fft(X,[],2),2);
sy = size(Y,2);
middle = floor(sy./2)+1;
if alpha>1 % upsample
N2 = floor((N-N0)./2);
if N0/2 == floor(N0/2)
Y(:,1) = []; % throw away non symmetric DFT coef
end
Y = [zeros(size(Y,1),N2),Y,zeros(size(Y,1),N2)];
else % downsample
N2 = floor(N./2);
Y = Y(:,middle-N2:middle+N2);
end
Y = alpha*ifft(ifftshift(Y,2),[],2);
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_review.m
|
.m
|
antx-master/xspm8/spm_eeg_review.m
| 9,515 |
utf_8
|
66c2b381d0f44f9286400e307a2eddae
|
function spm_eeg_review(D,flag,inv)
% General review (display) of SPM meeg object
% FORMAT spm_eeg_review(D,flags,inv)
%
% INPUT:
% D - meeg object
% flag - switch to any of the displays (optional)
% inv - which source reconstruction to display (when called from
% spm_eeg_inv_imag_api.m)
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Jean Daunizeau
% $Id: spm_eeg_review.m 3725 2010-02-16 12:26:24Z vladimir $
if nargin == 0
[D, sts] = spm_select(1, 'mat$', 'Select M/EEG mat file');
if ~sts, return; end
D = spm_eeg_load(D);
end
D = struct(D);
%-- Initialize SPM figure
D.PSD.handles.hfig = spm_figure('GetWin','Graphics');
spm_clf(D.PSD.handles.hfig)
% Get default SPM graphics options --> revert back to defaults
D.PSD.SPMdefaults.col = get(D.PSD.handles.hfig,'colormap');
D.PSD.SPMdefaults.renderer = get(D.PSD.handles.hfig,'renderer');
%-- Create default userdata structure
try D.PSD.source.VIZU.current = inv; end
[D] = PSD_initUD(D);
if ~strcmp(D.transform.ID,'time')
D.PSD.type = 'epoched';
D.PSD.trials.current = 1;
D.PSD.VIZU.type = 2;
end
%-- Create figure uitabs
labels = {'EEG', 'MEG', 'PLANAR', 'OTHER','info','source'};
callbacks = {'spm_eeg_review_callbacks(''visu'',''main'',''eeg'')',...
'spm_eeg_review_callbacks(''visu'',''main'',''meg'')',...
'spm_eeg_review_callbacks(''visu'',''main'',''megplanar'')',...
'spm_eeg_review_callbacks(''visu'',''main'',''other'')',...
'spm_eeg_review_callbacks(''visu'',''main'',''info'')',...
'spm_eeg_review_callbacks(''visu'',''main'',''source'')'};
try
[h] = spm_uitab(D.PSD.handles.hfig,labels,callbacks,[],flag);
catch
[h] = spm_uitab(D.PSD.handles.hfig,labels,callbacks,[],5);
end
D.PSD.handles.tabs = h;
% Add prepare and SAVE buttons
object.type = 'buttons';
object.list = 1;
D = spm_eeg_review_uis(D,object);
set(D.PSD.handles.BUTTONS.pop1,...
'deletefcn',@back2defaults)
%-- Attach userdata to SPM graphics window
D.PSD.D0 = rmfield(D,'PSD');
set(D.PSD.handles.hfig,...
'units','normalized',...
'color',[1 1 1],...
'userdata',D);
try
if ismac
set(D.PSD.handles.hfig,'renderer','zbuffer');
else
set(D.PSD.handles.hfig,'renderer','OpenGL');
end
catch
set(D.PSD.handles.hfig,'renderer','OpenGL');
end
try
switch flag
case 1
spm_eeg_review_callbacks('visu','main','eeg')
case 2
spm_eeg_review_callbacks('visu','main','meg')
case 3
spm_eeg_review_callbacks('visu','main','megplanar')
case 4
spm_eeg_review_callbacks('visu','main','other')
case 5
spm_eeg_review_callbacks('visu','main','info')
case 6
spm_eeg_review_callbacks('visu','main','source')
end
catch
% Initilize display on 'info'
spm_eeg_review_callbacks('visu','main','info')
end
%% Revert graphical properties of SPM figure back to normal
function back2defaults(e1,e2)
hf = spm_figure('FindWin','Graphics');
D = get(hf,'userdata');
try
set(D.PSD.handles.hfig,'colormap',D.PSD.SPMdefaults.col);
set(D.PSD.handles.hfig,'renderer',D.PSD.SPMdefaults.renderer);
end
%% initialization of the userdata structure
function [D] = PSD_initUD(D)
% This function initializes the userdata structure.
%-- Check spm_uitable capability (JAVA compatibility) --%
D.PSD.VIZU.uitable = spm_uitable;
%-- Initialize time window basic info --%
D.PSD.VIZU.xlim = [1,min([5e2,D.Nsamples])];
D.PSD.VIZU.info = 4; % show history
D.PSD.VIZU.fromTab = [];
%-- Initialize trials info --%
switch D.type
%------ before epoching -----%
case 'continuous'
D.PSD.type = 'continuous';
if ~isempty(D.trials) && ~isempty(D.trials(1).events)
Nevents = length(D.trials.events);
for i =1:Nevents
if isempty(D.trials.events(i).duration)
D.trials.events(i).duration = 0;
end
if isempty(D.trials.events(i).value)
D.trials.events(i).value = '0';
end
if isempty(D.trials.events(i).type)
D.trials.events(i).type = '0';
end
if ~ischar(D.trials.events(i).value)
D.trials.events(i).value = num2str(D.trials.events(i).value);
end
if ~ischar(D.trials.events(i).type)
D.trials.events(i).type = num2str(D.trials.events(i).type);
end
end
end
D.PSD.VIZU.type = 1;
%------ after epoching -----%
case 'single'
D.PSD.type = 'epoched';
nTrials = length(D.trials);
D.PSD.trials.TrLabels = cell(nTrials,1);
for i = 1:nTrials
if D.trials(i).bad
str = ' (bad)';
else
str = ' (not bad)';
end
D.PSD.trials.TrLabels{i} = [...
'Trial ',num2str(i),': ',D.trials(i).label,str];
end
D.PSD.trials.current = 1;
D.PSD.VIZU.type = 1;
case {'evoked','grandmean'}
D.PSD.type = 'epoched';
nTrials = length(D.trials);
D.PSD.trials.TrLabels = cell(nTrials,1);
for i = 1:nTrials
D.PSD.trials.TrLabels{i} = [...
'Trial ',num2str(i),' (average of ',...
num2str(D.trials(i).repl),' events): ',...
D.trials(i).label];
D.trials(i).events = [];
end
D.PSD.trials.current = 1;
D.PSD.VIZU.type = 1;
end
%-- Initialize channel info --%
nc = length(D.channels);
D.PSD.EEG.I = find(strcmp('EEG',{D.channels.type}));
D.PSD.MEG.I = sort([find(strcmp('MEGMAG',{D.channels.type})),...
find(strcmp('MEGGRAD',{D.channels.type})) find(strcmp('MEG',{D.channels.type}))]);
D.PSD.MEGPLANAR.I = find(strcmp('MEGPLANAR',{D.channels.type}));
D.PSD.other.I = setdiff(1:nc,[D.PSD.EEG.I(:);D.PSD.MEG.I(:);D.PSD.MEGPLANAR.I(:)]);
%-- Get basic display variables (data range, offset,...)
if ~isempty(D.PSD.EEG.I)
set(D.PSD.handles.hfig,'userdata',D);
figure(D.PSD.handles.hfig)
[out] = spm_eeg_review_callbacks('get','VIZU',D.PSD.EEG.I);
D.PSD.EEG.VIZU = out;
else
D.PSD.EEG.VIZU = [];
end
if ~isempty(D.PSD.MEG.I)
set(D.PSD.handles.hfig,'userdata',D);
figure(D.PSD.handles.hfig)
[out] = spm_eeg_review_callbacks('get','VIZU',D.PSD.MEG.I);
D.PSD.MEG.VIZU = out;
else
D.PSD.MEG.VIZU = [];
end
if ~isempty(D.PSD.MEGPLANAR.I)
set(D.PSD.handles.hfig,'userdata',D);
figure(D.PSD.handles.hfig)
[out] = spm_eeg_review_callbacks('get','VIZU',D.PSD.MEGPLANAR.I);
D.PSD.MEGPLANAR.VIZU = out;
else
D.PSD.MEGPLANAR.VIZU = [];
end
if ~isempty(D.PSD.other.I)
set(D.PSD.handles.hfig,'userdata',D);
figure(D.PSD.handles.hfig)
[out] = spm_eeg_review_callbacks('get','VIZU',D.PSD.other.I);
D.PSD.other.VIZU = out;
else
D.PSD.other.VIZU = [];
end
%-- Initialize inverse field info --%
if isfield(D.other,'inv') && ~isempty(D.other.inv)
isInv = zeros(length(D.other.inv),1);
for i=1:length(D.other.inv)
if isfield(D.other.inv{i},'inverse') && ...
isfield(D.other.inv{i}, 'method') && ...
strcmp(D.other.inv{i}.method,'Imaging')
isInv(i) = 1;
end
end
isInv = find(isInv);
Ninv = length(isInv);
if Ninv>=1
labels = cell(Ninv,1);
callbacks = cell(Ninv,1);
F = zeros(Ninv,1);
ID = zeros(Ninv,1);
pst = [];
for i=1:Ninv
if ~isfield(D.other.inv{isInv(i)},'comment')
D.other.inv{isInv(i)}.comment{1} = num2str(i);
end
if ~isfield(D.other.inv{isInv(i)},'date')
D.other.inv{isInv(i)}.date(1,:) = '?';
D.other.inv{isInv(i)}.date(2,:) = ' ';
end
if isfield(D.other.inv{isInv(i)}.inverse,'R2') ...
&& isnan(D.other.inv{isInv(i)}.inverse.R2)
D.other.inv{isInv(i)}.inverse.R2 = [];
end
if isfield(D.other.inv{isInv(i)}.inverse, 'ID')
ID(i) = D.other.inv{isInv(i)}.inverse.ID;
else
ID(i) = nan;
end
labels{i} = [D.other.inv{isInv(i)}.comment{1}];
callbacks{i} = ['spm_eeg_review_callbacks(''visu'',''inv'',',num2str(i),')'];
try
F(i) = D.other.inv{isInv(i)}.inverse.F;
pst = [pst;D.other.inv{isInv(i)}.inverse.pst(:)];
catch
continue
end
end
if isempty(pst)
Ninv = 0;
else
pst = unique(pst);
end
end
else
Ninv = 0;
end
if Ninv >= 1
try
if D.PSD.source.VIZU.current > Ninv
D.PSD.source.VIZU.current = 1;
end
catch
D.PSD.source.VIZU.current = 1;
end
D.PSD.source.VIZU.isInv = isInv;
D.PSD.source.VIZU.pst = pst;
D.PSD.source.VIZU.F = F;
D.PSD.source.VIZU.ID = ID;
D.PSD.source.VIZU.labels = labels;
D.PSD.source.VIZU.callbacks = callbacks;
D.PSD.source.VIZU.timeCourses = 1;
else
D.PSD.source.VIZU.current = 0;
D.PSD.source.VIZU.isInv = [];
D.PSD.source.VIZU.pst = [];
D.PSD.source.VIZU.F = [];
D.PSD.source.VIZU.labels = [];
D.PSD.source.VIZU.callbacks = [];
D.PSD.source.VIZU.timeCourses = [];
end
|
github
|
philippboehmsturm/antx-master
|
spm_coreg.m
|
.m
|
antx-master/xspm8/spm_coreg.m
| 15,129 |
utf_8
|
1a1cb266498e19f17d20aef76c6358f0
|
function x = spm_coreg(varargin)
% Between modality coregistration using information theory
% FORMAT x = spm_coreg(VG,VF,flags)
% VG - handle for reference image (see spm_vol).
% VF - handle for source (moved) image.
% flags - a structure containing the following elements:
% sep - optimisation sampling steps (mm)
% default: [4 2]
% params - starting estimates (6 elements)
% default: [0 0 0 0 0 0]
% cost_fun - cost function string:
% 'mi' - Mutual Information
% 'nmi' - Normalised Mutual Information
% 'ecc' - Entropy Correlation Coefficient
% 'ncc' - Normalised Cross Correlation
% default: 'nmi'
% tol - tolerences for accuracy of each param
% default: [0.02 0.02 0.02 0.001 0.001 0.001]
% fwhm - smoothing to apply to 256x256 joint histogram
% default: [7 7]
% graphics - display coregistration outputs
% default: ~spm('CmdLine')
%
% x - the parameters describing the rigid body rotation, such that a
% mapping from voxels in G to voxels in F is attained by:
% VF.mat\spm_matrix(x(:)')*VG.mat
%
% At the end, the voxel-to-voxel affine transformation matrix is
% displayed, along with the histograms for the images in the original
% orientations, and the final orientations. The registered images are
% displayed at the bottom.
%__________________________________________________________________________
%
% The registration method used here is based on the work described in:
% A Collignon, F Maes, D Delaere, D Vandermeulen, P Suetens & G Marchal
% (1995) "Automated Multi-modality Image Registration Based On
% Information Theory". In the proceedings of Information Processing in
% Medical Imaging (1995). Y. Bizais et al. (eds.). Kluwer Academic
% Publishers.
%
% The original interpolation method described in this paper has been
% changed in order to give a smoother cost function. The images are
% also smoothed slightly, as is the histogram. This is all in order to
% make the cost function as smooth as possible, to give faster convergence
% and less chance of local minima.
%__________________________________________________________________________
% Copyright (C) 1994-2011 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_coreg.m 4156 2011-01-11 19:03:31Z guillaume $
%==========================================================================
% References
%==========================================================================
%
% Mutual Information
% -------------------------------------------------------------------------
% Collignon, Maes, Delaere, Vandermeulen, Suetens & Marchal (1995).
% "Automated multi-modality image registration based on information theory".
% In Bizais, Barillot & Di Paola, editors, Proc. Information Processing
% in Medical Imaging, pages 263--274, Dordrecht, The Netherlands, 1995.
% Kluwer Academic Publishers.
%
% Wells III, Viola, Atsumi, Nakajima & Kikinis (1996).
% "Multi-modal volume registration by maximisation of mutual information".
% Medical Image Analysis, 1(1):35-51, 1996.
%
% Entropy Correlation Coefficient
% -------------------------------------------------------------------------
% Maes, Collignon, Vandermeulen, Marchal & Suetens (1997).
% "Multimodality image registration by maximisation of mutual
% information". IEEE Transactions on Medical Imaging 16(2):187-198
%
% Normalised Mutual Information
% -------------------------------------------------------------------------
% Studholme, Hill & Hawkes (1998).
% "A normalized entropy measure of 3-D medical image alignment".
% in Proc. Medical Imaging 1998, vol. 3338, San Diego, CA, pp. 132-143.
%
% Optimisation
% -------------------------------------------------------------------------
% Press, Teukolsky, Vetterling & Flannery (1992).
% "Numerical Recipes in C (Second Edition)".
% Published by Cambridge.
%==========================================================================
if nargin >= 4
x = optfun(varargin{:});
return;
end
def_flags = spm_get_defaults('coreg.estimate');
def_flags.params = [0 0 0 0 0 0];
def_flags.graphics = ~spm('CmdLine');
if nargin < 3
flags = def_flags;
else
flags = varargin{3};
fnms = fieldnames(def_flags);
for i=1:length(fnms)
if ~isfield(flags,fnms{i})
flags.(fnms{i}) = def_flags.(fnms{i});
end
end
end
if nargin < 1
VG = spm_vol(spm_select(1,'image','Select reference image'));
else
VG = varargin{1};
if ischar(VG), VG = spm_vol(VG); end
end
if nargin < 2
VF = spm_vol(spm_select(Inf,'image','Select moved image(s)'));
else
VF = varargin{2};
if ischar(VF) || iscellstr(VF), VF = spm_vol(char(VF)); end;
end
if ~isfield(VG, 'uint8')
VG.uint8 = loaduint8(VG);
vxg = sqrt(sum(VG.mat(1:3,1:3).^2));
fwhmg = sqrt(max([1 1 1]*flags.sep(end)^2 - vxg.^2, [0 0 0]))./vxg;
VG = smooth_uint8(VG,fwhmg); % Note side effects
end
sc = flags.tol(:)'; % Required accuracy
sc = sc(1:length(flags.params));
xi = diag(sc*20);
x = zeros(numel(VF),numel(flags.params));
for k=1:numel(VF)
VFk = VF(k);
if ~isfield(VFk, 'uint8')
VFk.uint8 = loaduint8(VFk);
vxf = sqrt(sum(VFk.mat(1:3,1:3).^2));
fwhmf = sqrt(max([1 1 1]*flags.sep(end)^2 - vxf.^2, [0 0 0]))./vxf;
VFk = smooth_uint8(VFk,fwhmf); % Note side effects
end
xk = flags.params(:);
for samp=flags.sep(:)'
xk = spm_powell(xk(:), xi,sc,mfilename,VG,VFk,samp,flags.cost_fun,flags.fwhm);
x(k,:) = xk(:)';
end
if flags.graphics
display_results(VG(1),VFk(1),xk(:)',flags);
end
end
%==========================================================================
% function o = optfun(x,VG,VF,s,cf,fwhm)
%==========================================================================
function o = optfun(x,VG,VF,s,cf,fwhm)
% The function that is minimised.
if nargin<6, fwhm = [7 7]; end
if nargin<5, cf = 'mi'; end
if nargin<4, s = [1 1 1]; end
% Voxel sizes
vxg = sqrt(sum(VG.mat(1:3,1:3).^2));sg = s./vxg;
% Create the joint histogram
H = spm_hist2(VG.uint8,VF.uint8, VF.mat\spm_matrix(x(:)')*VG.mat ,sg);
% Smooth the histogram
lim = ceil(2*fwhm);
krn1 = smoothing_kernel(fwhm(1),-lim(1):lim(1)) ; krn1 = krn1/sum(krn1); H = conv2(H,krn1);
krn2 = smoothing_kernel(fwhm(2),-lim(2):lim(2))'; krn2 = krn2/sum(krn2); H = conv2(H,krn2);
% Compute cost function from histogram
H = H+eps;
sh = sum(H(:));
H = H/sh;
s1 = sum(H,1);
s2 = sum(H,2);
switch lower(cf)
case 'mi'
% Mutual Information:
H = H.*log2(H./(s2*s1));
mi = sum(H(:));
o = -mi;
case 'ecc'
% Entropy Correlation Coefficient of:
% Maes, Collignon, Vandermeulen, Marchal & Suetens (1997).
% "Multimodality image registration by maximisation of mutual
% information". IEEE Transactions on Medical Imaging 16(2):187-198
H = H.*log2(H./(s2*s1));
mi = sum(H(:));
ecc = -2*mi/(sum(s1.*log2(s1))+sum(s2.*log2(s2)));
o = -ecc;
case 'nmi'
% Normalised Mutual Information of:
% Studholme, Hill & Hawkes (1998).
% "A normalized entropy measure of 3-D medical image alignment".
% in Proc. Medical Imaging 1998, vol. 3338, San Diego, CA, pp. 132-143.
nmi = (sum(s1.*log2(s1))+sum(s2.*log2(s2)))/sum(sum(H.*log2(H)));
o = -nmi;
case 'ncc'
% Normalised Cross Correlation
i = 1:size(H,1);
j = 1:size(H,2);
m1 = sum(s2.*i');
m2 = sum(s1.*j);
sig1 = sqrt(sum(s2.*(i'-m1).^2));
sig2 = sqrt(sum(s1.*(j -m2).^2));
[i,j] = ndgrid(i-m1,j-m2);
ncc = sum(sum(H.*i.*j))/(sig1*sig2);
o = -ncc;
otherwise
error('Invalid cost function specified');
end
%==========================================================================
% function udat = loaduint8(V)
%==========================================================================
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
% Another pass to find a maximum that allows a few hot-spots in the data.
spm_progress_bar('Init',V.dim(3),...
['2nd pass max/min of ' spm_str_manip(V.fname,'t')],...
'Planes complete');
nh = 2048;
h = zeros(nh,1);
for p=1:V.dim(3)
img = spm_slice_vol(V,spm_matrix([0 0 p]),V.dim(1:2),1);
img = img(isfinite(img));
img = round((img+((mx-mn)/(nh-1)-mn))*((nh-1)/(mx-mn)));
h = h + accumarray(img,1,[nh 1]);
spm_progress_bar('Set',p);
end
tmp = [find(cumsum(h)/sum(h)>0.9999); nh];
mx = (mn*nh-mx+tmp(1)*(mx-mn))/(nh-1);
% Load data from file indicated by V into an array of unsigned bytes.
spm_progress_bar('Init',V.dim(3),...
['Loading ' spm_str_manip(V.fname,'t')],...
'Planes loaded');
udat = zeros(V.dim,'uint8');
st = rand('state'); % st = rng;
rand('state',100); % rng(100,'v5uniform'); % rng('defaults');
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(max(min(round((img-mn)*(255/(mx-mn))),255),0));
else
% Add random numbers before rounding to reduce aliasing artifact
r = rand(size(img))*acc;
udat(:,:,p) = uint8(max(min(round((img+r-mn)*(255/(mx-mn))),255),0));
end
spm_progress_bar('Set',p);
end
spm_progress_bar('Clear');
rand('state',st); % rng(st);
%==========================================================================
% function acc = paccuracy(V,p)
%==========================================================================
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
%==========================================================================
% function V = smooth_uint8(V,fwhm)
%==========================================================================
function V = smooth_uint8(V,fwhm)
% Convolve the volume in memory (fwhm in voxels).
lim = ceil(2*fwhm);
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]);
%==========================================================================
% function krn = smoothing_kernel(fwhm,x)
%==========================================================================
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;
%==========================================================================
% function display_results(VG,VF,x,flags)
%==========================================================================
function display_results(VG,VF,x,flags)
fig = spm_figure('FindWin','Graphics');
if isempty(fig), return; end;
set(0,'CurrentFigure',fig);
spm_figure('Clear','Graphics');
%txt = 'Information Theoretic Coregistration';
switch lower(flags.cost_fun)
case 'mi', txt = 'Mutual Information Coregistration';
case 'ecc', txt = 'Entropy Correlation Coefficient Registration';
case 'nmi', txt = 'Normalised Mutual Information Coregistration';
case 'ncc', txt = 'Normalised Cross Correlation';
otherwise, error('Invalid cost function specified');
end
% Display text
%--------------------------------------------------------------------------
ax = axes('Position',[0.1 0.8 0.8 0.15],'Visible','off','Parent',fig);
text(0.5,0.7, txt,'FontSize',16,...
'FontWeight','Bold','HorizontalAlignment','center','Parent',ax);
Q = inv(VF.mat\spm_matrix(x(:)')*VG.mat);
text(0,0.5, sprintf('X1 = %0.3f*X %+0.3f*Y %+0.3f*Z %+0.3f',Q(1,:)),'Parent',ax);
text(0,0.3, sprintf('Y1 = %0.3f*X %+0.3f*Y %+0.3f*Z %+0.3f',Q(2,:)),'Parent',ax);
text(0,0.1, sprintf('Z1 = %0.3f*X %+0.3f*Y %+0.3f*Z %+0.3f',Q(3,:)),'Parent',ax);
% Display joint histograms
%--------------------------------------------------------------------------
ax = axes('Position',[0.1 0.5 0.35 0.3],'Visible','off','Parent',fig);
H = spm_hist2(VG.uint8,VF.uint8,VF.mat\VG.mat,[1 1 1]);
tmp = log(H+1);
image(tmp*(64/max(tmp(:))),'Parent',ax');
set(ax,'DataAspectRatio',[1 1 1],...
'PlotBoxAspectRatioMode','auto','XDir','normal','YDir','normal',...
'XTick',[],'YTick',[]);
title('Original Joint Histogram','Parent',ax);
xlabel(spm_str_manip(VG.fname,'k22'),'Parent',ax);
ylabel(spm_str_manip(VF.fname,'k22'),'Parent',ax);
H = spm_hist2(VG.uint8,VF.uint8,VF.mat\spm_matrix(x(:)')*VG.mat,[1 1 1]);
ax = axes('Position',[0.6 0.5 0.35 0.3],'Visible','off','Parent',fig);
tmp = log(H+1);
image(tmp*(64/max(tmp(:))),'Parent',ax');
set(ax,'DataAspectRatio',[1 1 1],...
'PlotBoxAspectRatioMode','auto','XDir','normal','YDir','normal',...
'XTick',[],'YTick',[]);
title('Final Joint Histogram','Parent',ax);
xlabel(spm_str_manip(VG.fname,'k22'),'Parent',ax);
ylabel(spm_str_manip(VF.fname,'k22'),'Parent',ax);
% Display ortho-views
%--------------------------------------------------------------------------
spm_orthviews('Reset');
spm_orthviews('Image',VG,[0.01 0.01 .48 .49]);
h2 = spm_orthviews('Image',VF,[.51 0.01 .48 .49]);
global st
st.vols{h2}.premul = inv(spm_matrix(x(:)'));
spm_orthviews('Space');
spm_print;
|
github
|
philippboehmsturm/antx-master
|
spm_axis.m
|
.m
|
antx-master/xspm8/spm_axis.m
| 650 |
utf_8
|
06a3507b1acc2575b34977be7961e117
|
function varargout = spm_axis(varargin)
% AXIS Control axis scaling and appearance.
if nargout
[varargout{1:nargout}] = axis(varargin{:});
else
axis(varargin{:});
end
if nargin ==1 && strcmpi(varargin{1},'tight')
spm_axis(gca,'tight');
elseif nargin == 2 && allAxes(varargin{1}) && strcmpi(varargin{2},'tight')
for i=1:numel(varargin{1})
lm = get(varargin{1}(i),'ylim');
set(varargin{1}(i),'ylim',lm + [-1 1]*diff(lm)/16);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function result = allAxes(h)
result = all(ishghandle(h)) && ...
length(findobj(h,'type','axes','-depth',0)) == length(h);
|
github
|
philippboehmsturm/antx-master
|
spm_uw_estimate.m
|
.m
|
antx-master/xspm8/spm_uw_estimate.m
| 33,350 |
utf_8
|
640443456204e7ee34b1998cd2a57832
|
function ds = spm_uw_estimate(P,par)
% Estimation of partial derivatives of EPI deformation fields.
%
% FORMAT [ds] = spm_uw_estimate((P),(par))
%
% P - List of file names or headers.
% par - Structure containing parameters governing the specifics
% of how to estimate the fields.
% .M - When performing multi-session realignment and Unwarp we
% want to realign everything to the space of the first
% image in the first time-series. M defines the space of
% that.
% .order - Number of basis functions to use for each dimension.
% If the third dimension is left out, the order for
% that dimension is calculated to yield a roughly
% equal spatial cut-off in all directions.
% Default: [12 12 *]
% .sfP - Static field supplied by the user. It should be a
% filename or handle to a voxel-displacement map in
% the same space as the first EPI image of the time-
% series. If using the FieldMap toolbox, realignment
% should (if necessary) have been performed as part of
% the process of creating the VDM. Note also that the
% VDM mut be in undistorted space, i.e. if it is
% calculated from an EPI based field-map sequence
% it should have been inverted before passing it to
% spm_uw_estimate. Again, the FieldMap toolbox will
% do this for you.
% .regorder - Regularisation of derivative fields is based on the
% regorder'th (spatial) derivative of the field.
% Default: 1
% .lambda - Fudge factor used to decide relative weights of
% data and regularisation.
% Default: 1e5
% .jm - Jacobian Modulation. If set, intensity (Jacobian)
% deformations are included in the model. If zero,
% intensity deformations are not considered.
% .fot - List of indexes for first order terms to model
% derivatives for. Order of parameters as defined
% by spm_imatrix.
% Default: [4 5]
% .sot - List of second order terms to model second
% derivatives of. Should be an nx2 matrix where
% e.g. [4 4; 4 5; 5 5] means that second partial
% derivatives of rotation around x- and y-axis
% should be modelled.
% Default: []
% .fwhm - FWHM (mm) of smoothing filter applied to images prior
% to estimation of deformation fields.
% Default: 6
% .rem - Re-Estimation of Movement parameters. Set to unity means
% that movement-parameters should be re-estimated at each
% iteration.
% Default: 0
% .noi - Maximum number of Iterations.
% Default: 5
% .exp_round - Point in position space to do Taylor expansion around.
% 'First', 'Last' or 'Average'.
% Default: 'Average'.
% ds - The returned structure contains the following fields
% .P - Copy of P on input.
% .sfP - Copy of sfP on input (if non-empty).
% .order - Copy of order on input, or default.
% .regorder - Copy of regorder on input, or default.
% .lambda - Copy of lambda on input, or default.
% .fot - Copy of fot on input, or default.
% .sot - Copy of sot on input, or default.
% .fwhm - Copy of fwhm on input, or default.
% .rem - Copy of rem on input, or default.
% .p0 - Average position vector (three translations in mm
% and three rotations in degrees) of scans in P.
% .q - Deviations from mean position vector of modelled
% effects. Corresponds to deviations (and deviations
% squared) of a Taylor expansion of deformation fields.
% .beta - Coeffeicents of DCT basis functions for partial
% derivatives of deformation fields w.r.t. modelled
% effects. Scaled such that resulting deformation
% fields have units mm^-1 or deg^-1 (and squares
% thereof).
% .SS - Sum of squared errors for each iteration.
%
%
% This is a major rewrite which uses some new ideas to speed up
% the estimation of the field. The time consuming part is the
% evaluation of A'*A where A is a matrix with the partial
% derivatives for each scan with respect to the parameters
% describing the warp-fields. If we denote the derivative
% matrix for a single scan by Ai, then the estimation of A'*A
% is A'*A = A1'*A1 + A2'*A2 + ... +An'*An where n is the number
% of scans in the time-series. If we model the partial-derivative
% fields w.r.t. two movement parameters (e.g. pitch and roll), each
% by [8 8 8] basis-functions and the image dimensions are
% 64x64x64 then each Ai is a 262144x1024 matrix and we need to
% evaluate and add n of these 1024x1024 matrices. It takes a while.
%
% The new idea is based on the realisation that each of these
% matrices is the kroneceker-product of the relevant movement
% parameters, our basis set and a linear combination (given by
% one column of the inverse of the rotation matrix) of the image
% gradients in the x-, y- and z-directions. This means that
% they really aren't all that unique, and that the amount of
% information in these matrices doesn't really warrant all
% those calculations. After a lot of head-scratching I arrived
% at the following
%
% First some definitions
%
% n: no. of voxels
% m: no. of scans
% l: no. of effects to model
% order: [xorder yorder zorder] no. of basis functions
% q: mxl matrix of scaled realignment parameters for effects to model.
% T{i}: inv(inv(P(i).mat)*P(1).mat);
% t(i,:) = T{i}(1:3,2)';
% B: kron(Bz,By,Bx);
% Ax = repmat(dx,1,prod(order)).*B;
% Ay = repmat(dy,1,prod(order)).*B;
% Az = repmat(dz,1,prod(order)).*B;
%
% Now, my hypothesis is that A'*A is given by
%
% AtA = kron((q.*kron(ones(1,l),t(:,1)))'*(q.*kron(ones(1,l),t(:,1))),Ax'*Ax) +...
% kron((q.*kron(ones(1,l),t(:,2)))'*(q.*kron(ones(1,l),t(:,2))),Ay'*Ay) +...
% kron((q.*kron(ones(1,l),t(:,3)))'*(q.*kron(ones(1,l),t(:,3))),Az'*Az) +...
% 2*kron((q.*kron(ones(1,l),t(:,1)))'*(q.*kron(ones(1,l),t(:,2))),Ax'*Ay) +...
% 2*kron((q.*kron(ones(1,l),t(:,1)))'*(q.*kron(ones(1,l),t(:,3))),Ax'*Az) +...
% 2*kron((q.*kron(ones(1,l),t(:,2)))'*(q.*kron(ones(1,l),t(:,3))),Ay'*Az);
%
% Which turns out to be true. This means that regardless of how many
% scans we have we will always be able to create AtA as a sum of
% six individual AtAs. It has been tested against the previous
% implementation and yields exactly identical results.
%
% I know this isn't much of a derivation, but there will be a paper soon. Sorry.
%
% Other things that are new for the rewrite is
% 1. We have removed the possibility to try and estimate the "static" field.
% There simply isn't enough information about that field, and for a
% given time series the estimation is just too likely to fail.
% 2. New option to pass a static field (e.g. estimated from a dual
% echo-time measurement) as an input parameter.
% 3. Re-estimation of the movement parameters at each iteration.
% Let us say we have a nodding motion in the time series, and
% at each nod the brain appear to shrink in the phase-encode
% direction. The realignment will find the nods, but might in
% addition mistake the "shrinks" for translations, leading to
% biased estimates. We attempt to correct that by, at iteration,
% updating both parameters pertaining to distortions and to
% movement. In order to do so in an unbiased fashion we have
% also switched from sampling of images (and deformation fields)
% on a grid centered on the voxel-centers, to a grid whith a
% different sampling frequency.
% 4. Inclusion of a regularisation term. The speed-up has facilitated
% using more basis-functions, which makes it neccessary to impose
% regularisation (i.e. punisihing some order derivative of the
% deformation field).
% 5. Change of interpolation model from tri-linear/Sinc to
% tri-linear/B-spline.
% 6. Option to include the Jacobian compression/stretching effects
% in the model for the estimation of the displacement fields.
% Our tests have indicated that this is NOT a good idea though.
%
%_______________________________________________________________________
%
% Definition of some of the variables in this routine.
%
%
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Jesper Andersson
% $Id: spm_uw_estimate.m 4310 2011-04-18 16:07:35Z guillaume $
if nargin < 1 || isempty(P), P = spm_select(Inf,'image'); end
if ~isstruct(P), P = spm_vol(P); end
%
% Hardcoded default input parameters.
%
defpar = struct('sfP', [],...
'M', P(1).mat,...
'fot', [4 5],...
'sot', [],...
'hold', [1 1 1 0 1 0]);
%
% Merge hardcoded defaults and spm_defaults. Translate spm_defaults
% settings to internal defaults.
%
ud = spm_get_defaults('unwarp.estimate');
if isfield(ud,'basfcn'), defpar.order = ud.basfcn; end
if isfield(ud,'regorder'), defpar.regorder = ud.regorder; end
if isfield(ud,'regwgt'), defpar.lambda = ud.regwgt; end
if isfield(ud,'jm'), defpar.jm = ud.jm; end
if isfield(ud,'fwhm'), defpar.fwhm = ud.fwhm; end
if isfield(ud,'rem'), defpar.rem = ud.rem; end
if isfield(ud,'noi'), defpar.noi = ud.noi; end
if isfield(ud,'expround'), defpar.exp_round = ud.expround; end
defnames = fieldnames(defpar);
%
% Go through input parameters, chosing the default
% for any parameters that are missing, warning the
% user if there are "unknown" parameters (probably
% reflecting a misspelling).
%
if nargin < 2 || isempty(par)
par = defpar;
end
ds = [];
for i=1:length(defnames)
if isfield(par,defnames{i}) && ~isempty(par.(defnames{i}))
ds.(defnames{i}) = par.(defnames{i});
else
ds.(defnames{i}) = defpar.(defnames{i});
end
end
parnames = fieldnames(par);
for i=1:length(parnames)
if ~isfield(defpar,parnames{i})
warning('Unknown par field %s',parnames{i});
end
end
%
% Resolve ambiguities.
%
if length(ds.order) == 2
mm = sqrt(sum(P(1).mat(1:3,1:3).^2)).*P(1).dim(1:3);
ds.order(3) = round(ds.order(1)*mm(3)/mm(1));
end
if isfield(ds,'sfP') && ~isempty(ds.sfP)
if ~isstruct(ds.sfP)
ds.sfP = spm_vol(ds.sfP);
end
end
nscan = length(P);
nof = prod(size(ds.fot)) + size(ds.sot,1);
ds.P = P;
%
% Get matrix of 'expansion point'-corrected movement parameters
% for which we seek partial derivative fields.
%
[ds.q,ds.ep] = make_q(P,ds.fot,ds.sot,ds.exp_round);
%
% Create matrix for regularisation of warps.
%
H = make_H(P,ds.order,ds.regorder);
%
% Create a temporary smooth time series to use for
% the estimation.
%
old_P = P;
if ds.fwhm ~= 0
spm_uw_show('SmoothStart',length(P));
for i=1:length(old_P)
spm_uw_show('SmoothUpdate',i);
sfname(i,:) = [tempname '.img,1,1'];
to_smooth = sprintf('%s,%d,%d',old_P(i).fname,old_P(i).n);
spm_smooth(to_smooth,sfname(i,:),ds.fwhm);
end
P = spm_vol(sfname);
spm_uw_show('SmoothEnd');
end
% Now that we have littered the disk with smooth
% temporary files we should use a try-catch
% block for the rest of the function, to ensure files
% get deleted in the event of an error.
try % Try block starts here
%
% Initialize some stuff.
%
beta0 = zeros(nof*prod(ds.order),10);
beta = zeros(nof*prod(ds.order),1);
old_beta = zeros(nof*prod(ds.order),1);
%
% Sample images on irregular grid to avoid biasing
% re-estimated movement parameters with smoothing
% effect from voxel-interpolation (See Andersson ,
% EJNM (1998), 25:575-586.).
%
ss = [1.1 1.1 0.9];
xs = 1:ss(1):P(1).dim(1); xs = xs + (P(1).dim(1)-xs(end)) / 2;
ys = 1:ss(2):P(1).dim(2); ys = ys + (P(1).dim(2)-ys(end)) / 2;
zs = 1:ss(3):P(1).dim(3); zs = zs + (P(1).dim(3)-zs(end)) / 2;
M = spm_matrix([-xs(1)/ss(1)+1 -ys(1)/ss(2)+1 -zs(1)/ss(3)+1])*inv(diag([ss 1]))*eye(4);
nx = length(xs);
ny = length(ys);
nz = length(zs);
[x,y,z] = ndgrid(xs,ys,zs);
Bx = spm_dctmtx(P(1).dim(1),ds.order(1),x(:,1,1));
By = spm_dctmtx(P(1).dim(2),ds.order(2),y(1,:,1));
Bz = spm_dctmtx(P(1).dim(3),ds.order(3),z(1,1,:));
dBy = spm_dctmtx(P(1).dim(2),ds.order(2),y(1,:,1),'diff');
xyz = [x(:) y(:) z(:) ones(length(x(:)),1)]; clear x y z;
def = zeros(size(xyz,1),nof);
ddefa = zeros(size(xyz,1),nof);
%
% Create file struct for use with spm_orthviews to draw
% representations of the field.
%
dispP = P(1);
dispP = rmfield(dispP,{'fname','descrip','n','private'});
dispP.dim = [nx ny nz];
dispP.dt = [64 spm_platform('bigend')];
dispP.pinfo = [1 0]';
p = spm_imatrix(dispP.mat); p = p.*[zeros(1,6) ss 0 0 0];
p(1) = -mean(1:nx)*p(7);
p(2) = -mean(1:ny)*p(8);
p(3) = -mean(1:nz)*p(9);
dispP.mat = spm_matrix(p); clear p;
%
% We will need to resample the static field (if one was supplied)
% on the same grid (given by xs, ys and zs) as we are going to use
% for the time series. We will assume that the fieldmap has been
% realigned to the space of the first EPI image in the time-series.
%
if isfield(ds,'sfP') && ~isempty(ds.sfP)
T = ds.sfP.mat\ds.M;
txyz = xyz*T(1:3,:)';
c = spm_bsplinc(ds.sfP,ds.hold);
ds.sfield = spm_bsplins(c,txyz(:,1),txyz(:,2),txyz(:,3),ds.hold);
ds.sfield = ds.sfield(:);
clear c txyz;
else
ds.sfield = [];
end
msk = get_mask(P,xyz,ds,[nx ny nz]);
ssq = [];
%
% Here starts iterative search for deformation fields.
%
for iter=1:ds.noi
spm_uw_show('NewIter',iter);
[ref,dx,dy,dz,P,ds,sf,dispP] = make_ref(ds,def,ddefa,P,xyz,M,msk,beta,dispP);
AtA = build_AtA(ref,dx,dy,dz,Bx,By,Bz,dBy,ds,P);
[Aty,yty] = build_Aty(ref,dx,dy,dz,Bx,By,Bz,dBy,ds,P,xyz,beta,sf,def,ddefa,msk);
% Clean up a bit, cause inverting AtA may use a lot of memory
clear ref dx dy dz
% Check that residual error still decreases.
if iter > 1 && yty > ssq(iter-1)
%
% This means previous iteration was no good,
% and we should go back to old_beta.
%
beta = old_beta;
break;
else
ssq(iter) = yty;
spm_uw_show('StartInv',1);
% Solve for beta
Aty = Aty + AtA*beta;
AtA = AtA + ds.lambda * kron(eye(nof),diag(H)) * ssq(iter)/(nscan*sum(msk));
try % Fastest if it works
beta0(:,iter) = AtA\Aty;
catch % Sometimes necessary
beta0(:,iter) = pinv(AtA)*Aty;
end
old_beta = beta;
beta = beta0(:,iter);
for i=1:nof
def(:,i) = spm_get_def(Bx, By,Bz,beta((i-1)*prod(ds.order)+1:i*prod(ds.order)));
ddefa(:,i) = spm_get_def(Bx,dBy,Bz,beta((i-1)*prod(ds.order)+1:i*prod(ds.order)));
end
% If we are re-estimating the movement parameters, remove any DC
% components from the deformation fields, so that they end up in
% the movement-parameters instead. It shouldn't make any difference
% to the variance reduction, but might potentially lead to a better
% explanation of the variance components.
% Note that since we sub-sample the images (and the DCT basis set)
% it is NOT sufficient to reset beta(1) (and beta(prod(order)+1) etc,
% instead we explicitly subtract the DC component. Note that a DC
% component does NOT affect the Jacobian.
%
if ds.rem ~= 0
def = def - repmat(mean(def),length(def),1);
end
spm_uw_show('EndInv');
tmp = dispP.mat;
dispP.mat = P(1).mat;
spm_uw_show('FinIter',ssq,def,ds.fot,ds.sot,dispP,ds.q);
dispP.mat = tmp;
end
clear AtA
end
ds.P = old_P;
for i=1:length(ds.P)
ds.P(i).mat = P(i).mat; % Save P with new movement parameters.
end
ds.beta = reshape(refit(P,dispP,ds,def),prod(ds.order),nof);
ds.SS = ssq;
if isfield(ds,'sfield');
ds = rmfield(ds,'sfield');
end
cleanup(P,ds)
spm_uw_show('FinTot');
% Document outcome
spm_print
catch % Try block ends here
cleanup(P,ds)
spm_uw_show('FinTot');
fprintf('procedure terminated abnormally:\n%s',lasterr);
end % Catch block ends here.
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Utility functions.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [q,ep] = make_q(P,fot,sot,exp_round)
%
% P : Array of file-handles
% fot : nx1 array of indicies for first order effect.
% sot : nx2 matrix of indicies of second order effects.
% exp_round : Point in position space to perform Taylor-expansion
% around ('First','Last' or 'Average'). 'Average' should
% (in principle) give the best variance reduction. If a
% field-map acquired before the time-series is supplied
% then expansion around the 'First' MIGHT give a slightly
% better average geometric fidelity.
if strcmpi(exp_round,'average');
%
% Get geometric mean of all transformation matrices.
% This will be used as the zero-point in the space
% of object position vectors (i.e. the point at which
% the partial derivatives are estimated). This is presumably
% a little more correct than taking the average of the
% parameter estimates.
%
mT = zeros(4);
for i=1:length(P)
mT = mT+logm(inv(P(i).mat) * P(1).mat);
end
mT = real(expm(mT/length(P)));
elseif strcmpi(exp_round,'first');
mT = eye(4);
elseif strcmpi(exp_round,'last');
mT = inv(P(end).mat) * P(1).mat;
else
warning(sprintf('Unknown expansion point %s',exp_round));
end
%
% Rescaling to degrees makes translations and rotations
% roughly equally scaled. Since the scaling influences
% strongly the effects of regularisation, it would surely
% be nice with a more principled approach. Suggestions
% anyone?
%
ep = [1 1 1 180/pi 180/pi 180/pi zeros(1,6)] .* spm_imatrix(mT);
%
% Now, get a nscan-by-nof matrix containing
% mean (expansion point) corrected values for each effect we
% model.
%
q = zeros(length(P),prod(size(fot)) + size(sot,1));
for i=1:length(P)
p = [1 1 1 180/pi 180/pi 180/pi zeros(1,6)] .*...
spm_imatrix(inv(P(i).mat) * P(1).mat);
for j=1:prod(size(fot))
q(i,j) = p(fot(j)) - ep(fot(j));
end
for j=1:size(sot,1)
q(i,prod(size(fot))+j) = (p(sot(j,1)) - ep(sot(j,1))) * (p(sot(j,2)) - ep(sot(j,2)));
end
end
return
%_______________________________________________________________________
%_______________________________________________________________________
function H = make_H(P,order,regorder)
% Utility Function to create Regularisation term of AtA.
mm = sqrt(sum(P(1).mat(1:3,1:3).^2)).*P(1).dim(1:3);
kx=(pi*((1:order(1))'-1)/mm(1)).^2;
ky=(pi*((1:order(2))'-1)/mm(2)).^2;
kz=(pi*((1:order(3))'-1)/mm(3)).^2;
if regorder == 0
%
% Cost function based on sum of squares
%
H = (1*kron(kz.^0,kron(ky.^0,kx.^0)) +...
1*kron(kz.^0,kron(ky.^0,kx.^0)) +...
1*kron(kz.^0,kron(ky.^0,kx.^0)) );
elseif regorder == 1
%
% Cost function based on sum of squared 1st derivatives
%
H = (1*kron(kz.^1,kron(ky.^0,kx.^0)) +...
1*kron(kz.^0,kron(ky.^1,kx.^0)) +...
1*kron(kz.^0,kron(ky.^0,kx.^1)) );
elseif regorder == 2
%
% Cost function based on sum of squared 2nd derivatives
%
H = (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)) +...
3*kron(kz.^1,kron(ky.^1,kx.^0)) +...
3*kron(kz.^1,kron(ky.^0,kx.^1)) +...
3*kron(kz.^0,kron(ky.^1,kx.^1)) );
elseif regorder == 3
%
% Cost function based on sum of squared 3rd derivatives
%
H = (1*kron(kz.^3,kron(ky.^0,kx.^0)) +...
1*kron(kz.^0,kron(ky.^3,kx.^0)) +...
1*kron(kz.^0,kron(ky.^0,kx.^3)) +...
3*kron(kz.^2,kron(ky.^1,kx.^0)) +...
3*kron(kz.^2,kron(ky.^0,kx.^1)) +...
3*kron(kz.^1,kron(ky.^2,kx.^0)) +...
3*kron(kz.^0,kron(ky.^2,kx.^1)) +...
3*kron(kz.^1,kron(ky.^0,kx.^2)) +...
3*kron(kz.^0,kron(ky.^1,kx.^2)) +...
6*kron(kz.^1,kron(ky.^1,kx.^1)) );
else
error('Invalid order of regularisation');
end
return
%_______________________________________________________________________
%_______________________________________________________________________
function AtA = build_AtA(ref,dx,dy,dz,Bx,By,Bz,dBy,ds,P)
% Now lets build up the design matrix A, or rather A'*A since
% A itself would be forbiddingly large.
if ds.jm, spm_uw_show('StartAtA',10);
else spm_uw_show('StartAtA',6); end
nof = prod(size(ds.fot)) + size(ds.sot,1);
AxtAx = uwAtA1(dx.*dx,Bx,By,Bz); spm_uw_show('NewAtA',1);
AytAy = uwAtA1(dy.*dy,Bx,By,Bz); spm_uw_show('NewAtA',2);
AztAz = uwAtA1(dz.*dz,Bx,By,Bz); spm_uw_show('NewAtA',3);
AxtAy = uwAtA1(dx.*dy,Bx,By,Bz); spm_uw_show('NewAtA',4);
AxtAz = uwAtA1(dx.*dz,Bx,By,Bz); spm_uw_show('NewAtA',5);
AytAz = uwAtA1(dy.*dz,Bx,By,Bz); spm_uw_show('NewAtA',6);
if ds.jm
AjtAj = uwAtA1(ref.*ref,Bx,dBy,Bz); spm_uw_show('NewAtA',7);
AxtAj = uwAtA2( dx.*ref,Bx, By,Bz,Bx,dBy,Bz); spm_uw_show('NewAtA',8);
AytAj = uwAtA2( dy.*ref,Bx, By,Bz,Bx,dBy,Bz); spm_uw_show('NewAtA',9);
AztAj = uwAtA2( dz.*ref,Bx, By,Bz,Bx,dBy,Bz); spm_uw_show('NewAtA',10);
end
R = zeros(length(P),3);
for i=1:length(P)
tmp = inv(P(i).mat\P(1).mat);
R(i,:) = tmp(1:3,2)';
end
tmp = ones(1,nof);
tmp1 = ds.q.*kron(tmp,R(:,1));
tmp2 = ds.q.*kron(tmp,R(:,2));
tmp3 = ds.q.*kron(tmp,R(:,3));
AtA = kron(tmp1'*tmp1,AxtAx) + kron(tmp2'*tmp2,AytAy) + kron(tmp3'*tmp3,AztAz) +...
2*(kron(tmp1'*tmp2,AxtAy) + kron(tmp1'*tmp3,AxtAz) + kron(tmp2'*tmp3,AytAz));
if ds.jm
tmp = [ds.q.*kron(tmp,ones(length(P),1))];
AtA = AtA + kron(tmp'*tmp,AjtAj) +...
2*(kron(tmp1'*tmp,AxtAj) + kron(tmp2'*tmp,AytAj) + kron(tmp3'*tmp,AztAj));
end
spm_uw_show('EndAtA');
return;
%_______________________________________________________________________
%_______________________________________________________________________
function AtA = uwAtA1(y,Bx,By,Bz)
% Calculating off-diagonal block of AtA.
[nx,mx] = size(Bx);
[ny,my] = size(By);
[nz,mz] = size(Bz);
AtA = zeros(mx*my*mz);
for sl =1:nz
tmp = reshape(y((sl-1)*nx*ny+1:sl*nx*ny),nx,ny);
spm_krutil(Bz(sl,:)'*Bz(sl,:),spm_krutil(tmp,Bx,By,1),AtA);
% AtA = AtA + kron(Bz(sl,:)'*Bz(sl,:),spm_krutil(tmp,Bx,By,1));
end
return
%_______________________________________________________________________
%_______________________________________________________________________
function AtA = uwAtA2(y,Bx1,By1,Bz1,Bx2,By2,Bz2)
% Calculating cross-term of diagonal block of AtA
% when A is a sum of the type A1+A2 and where both
% A1 and A2 are possible to express as a kronecker
% product of lesser matrices.
[nx,mx1] = size(Bx1,1); [nx,mx2] = size(Bx2,1);
[ny,my1] = size(By1,1); [ny,my2] = size(By2,1);
[nz,mz1] = size(Bz1,1); [nz,mz2] = size(Bz2,1);
AtA = zeros(mx1*my1*mz1,mx2*my2*mz2);
for sl =1:nz
tmp = reshape(y((sl-1)*nx*ny+1:sl*nx*ny),nx,ny);
spm_krutil(Bz1(sl,:)'*Bz2(sl,:),spm_krutil(tmp,Bx1,By1,Bx2,By2),AtA);
% AtA = AtA + kron(Bz1(sl,:)'*Bz2(sl,:),spm_krutil(tmp,Bx1,By1,Bx2,By2));
end
return
%_______________________________________________________________________
%_______________________________________________________________________
function [Aty,yty] = build_Aty(ref,dx,dy,dz,Bx,By,Bz,dBy,ds,P,xyz,beta,sf,def,ddefa,msk)
% Building Aty.
nof = prod(size(ds.fot)) + size(ds.sot,1);
Aty = zeros(nof*prod(ds.order),1);
yty = 0;
spm_uw_show('StartAty',length(P));
for scan = 1:length(P)
spm_uw_show('NewAty',scan);
T = P(scan).mat\ds.M;
txyz = xyz*T(1:3,:)';
if ~(all(beta == 0) && isempty(ds.sfield))
[idef,jac] = spm_get_image_def(scan,ds,def,ddefa);
txyz(:,2) = txyz(:,2)+idef;
end;
c = spm_bsplinc(P(scan),ds.hold);
y = sf(scan) * spm_bsplins(c,txyz(:,1),txyz(:,2),txyz(:,3),ds.hold);
if ds.jm && ~(all(beta == 0) && isempty(ds.sfield))
y = y .* jac;
end;
y_diff = (ref - y).*msk;
indx = find(isnan(y));
y_diff(indx) = 0;
iTcol = inv(T(1:3,1:3));
tmpAty = spm_get_def(Bx',By',Bz',([dx dy dz]*iTcol(:,2)).*y_diff);
if ds.jm ~= 0
tmpAty = tmpAty + spm_get_def(Bx',dBy',Bz',ref.*y_diff);
end
for i=1:nof
rindx = (i-1)*prod(ds.order)+1:i*prod(ds.order);
Aty(rindx) = Aty(rindx) + ds.q(scan,i)*tmpAty;
end
yty = yty + y_diff'*y_diff;
end
spm_uw_show('EndAty');
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [ref,dx,dy,dz,P,ds,sf,dispP] = make_ref(ds,def,ddefa,P,xyz,M,msk,beta,dispP)
% First of all get the mean of all scans given their
% present deformation fields. When using this as the
% "reference" we will explicitly be minimising variance.
%
% First scan in P is still reference in terms of
% y-direction (in the scanner framework). A single set of
% image gradients is estimated from the mean of all scans,
% transformed into the space of P(1), and used for all scans.
%
spm_uw_show('StartRef',length(P));
rem = ds.rem;
if all(beta==0), rem=0; end;
if rem
[m_ref,D] = get_refD(ds,def,ddefa,P,xyz,msk);
end
ref = zeros(size(xyz,1),1);
for i=1:length(P)
spm_uw_show('NewRef',i);
T = P(i).mat\ds.M;
txyz = xyz*T(1:3,:)';
if ~(all(beta == 0) && isempty(ds.sfield))
[idef,jac] = spm_get_image_def(i,ds,def,ddefa);
txyz(:,2) = txyz(:,2)+idef;
end;
c = spm_bsplinc(P(i),ds.hold);
f = spm_bsplins(c,txyz(:,1),txyz(:,2),txyz(:,3),ds.hold);
if ds.jm ~= 0 && exist('jac')==1
f = f .* jac;
end
indx = find(~isnan(f));
sf(i) = 1 / (sum(f(indx).*msk(indx)) / sum(msk(indx)));
ref = ref + f;
if rem
indx = find(isnan(f)); f(indx) = 0;
Dty{i} = (((m_ref - sf(i)*f).*msk)'*D)';
end
end
ref = ref / length(P);
ref = reshape(ref,dispP.dim(1:3));
indx = find(~isnan(ref));
% Scale to roughly 100 mean intensity to ensure
% consistent weighting of regularisation.
gl = spm_global(ref);
sf = (100 * (sum(ref(indx).*msk(indx)) / sum(msk(indx))) / gl) * sf;
ref = (100 / gl) * ref;
dispP.dat = ref;
c = spm_bsplinc(ref,ds.hold);
txyz = xyz*M(1:3,:)';
[ref,dx,dy,dz] = spm_bsplins(c,txyz(:,1),txyz(:,2),txyz(:,3),ds.hold);
ref = ref.*msk;
dx = dx.*msk;
dy = dy.*msk;
dz = dz.*msk;
% Re-estimate (or rather nudge) movement parameters.
if rem ~= 0
iDtD = inv(D'*D);
for i=2:length(P)
P(i).mat = inv(spm_matrix((iDtD*Dty{i})'))*P(i).mat;
end
[ds.q,ds.p0] = make_q(P,ds.fot,ds.sot,ds.exp_round);
end
spm_uw_show('EndRef');
return
%_______________________________________________________________________
%_______________________________________________________________________
function [m_ref,D] = get_refD(ds,def,ddefa,P,xyz,msk)
% Get partials w.r.t. movements from first scan.
[idef,jac] = spm_get_image_def(1,ds,def,ddefa);
T = P(1).mat\ds.M;
txyz = xyz*T';
c = spm_bsplinc(P(1),ds.hold);
[m_ref,dx,dy,dz] = spm_bsplins(c,txyz(:,1),...
txyz(:,2)+idef,txyz(:,3),ds.hold);
indx = ~isnan(m_ref);
mref_sf = 1 / (sum(m_ref(indx).*msk(indx)) / sum(msk(indx)));
m_ref(indx) = m_ref(indx) .* mref_sf; m_ref(~indx) = 0;
dx(indx) = dx(indx) .* mref_sf; dx(~indx) = 0;
dy(indx) = dy(indx) .* mref_sf; dy(~indx) = 0;
dz(indx) = dz(indx) .* mref_sf; dz(~indx) = 0;
if ds.jm ~= 0
m_ref = m_ref .* jac;
dx = dx .* jac;
dy = dy .* jac;
dz = dz .* jac;
end
D = make_D(dx.*msk,dy.*msk,dz.*msk,txyz,P(1).mat);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function D = make_D(dx,dy,dz,xyz,M)
% Utility function that creates a matrix of partial
% derivatives in units of /mm and /radian.
%
% dx,dy,dz - Partial derivatives (/pixel) wrt x-, y- and z-translation.
% xyz - xyz-matrix (original positions).
% M - Current voxel->world matrix.
D = zeros(length(xyz),6);
tiny = 0.0001;
for i=1:6
p = [0 0 0 0 0 0 1 1 1 0 0 0];
p(i) = p(i)+tiny;
T = M\spm_matrix(p)*M;
dxyz = xyz*T';
dxyz = dxyz(:,1:3)-xyz(:,1:3);
D(:,i) = sum(dxyz.*[dx dy dz],2)/tiny;
end
return
%_______________________________________________________________________
%_______________________________________________________________________
function cleanup(P,ds)
% Delete temporary smooth files.
%
if ~isempty(ds.fwhm) && ds.fwhm > 0
for i=1:length(P)
spm_unlink(P(i).fname);
[fpath,fname,ext] = fileparts(P(i).fname);
spm_unlink(fullfile(fpath,[fname '.hdr']));
spm_unlink(fullfile(fpath,[fname '.mat']));
end
end
return;
%_______________________________________________________________________
%_______________________________________________________________________
function beta = refit(P,dispP,ds,def)
% We have now estimated the fields on a grid that
% does not coincide with the voxel centers. We must
% now calculate the betas that correspond to a
% a grid centered on the voxel centers.
%
spm_uw_show('StartRefit',1);
rsP = P(1);
p = spm_imatrix(rsP.mat);
p = [zeros(1,6) p(7:9) 0 0 0];
p(1) = -mean(1:rsP.dim(1))*p(7);
p(2) = -mean(1:rsP.dim(2))*p(8);
p(3) = -mean(1:rsP.dim(3))*p(9);
rsP.mat = spm_matrix(p); clear p;
[x,y,z] = ndgrid(1:rsP.dim(1),1:rsP.dim(2),1:rsP.dim(3));
xyz = [x(:) y(:) z(:) ones(numel(x),1)];
txyz = ((inv(dispP.mat)*rsP.mat)*xyz')';
Bx = spm_dctmtx(rsP.dim(1),ds.order(1));
By = spm_dctmtx(rsP.dim(2),ds.order(2));
Bz = spm_dctmtx(rsP.dim(3),ds.order(3));
nx = rsP.dim(1); mx = ds.order(1);
ny = rsP.dim(2); my = ds.order(2);
nz = rsP.dim(3); mz = ds.order(3);
nof = numel(ds.fot) + size(ds.sot,1);
for i=1:nof
dispP.dat = reshape(def(:,i),dispP.dim(1:3));
c = spm_bsplinc(dispP,ds.hold);
field = spm_bsplins(c,txyz(:,1),txyz(:,2),txyz(:,3),ds.hold);
indx = isnan(field);
wgt = ones(size(field));
wgt(indx) = 0;
field(indx) = 0;
AtA = zeros(mx*my*mz);
Aty = zeros(mx*my*mz,1);
for sl = 1:nz
indx = (sl-1)*nx*ny+1:sl*nx*ny;
tmp1 = reshape(field(indx).*wgt(indx),nx,ny);
tmp2 = reshape(wgt(indx),nx,ny);
spm_krutil(Bz(sl,:)'*Bz(sl,:),spm_krutil(tmp2,Bx,By,1),AtA);
% AtA = AtA + kron(Bz(sl,:)'*Bz(sl,:),spm_krutil(tmp2,Bx,By,1));
Aty = Aty + kron(Bz(sl,:)',spm_krutil(tmp1,Bx,By,0));
end
beta((i-1)*prod(ds.order)+1:i*prod(ds.order)) = AtA\Aty;
end
spm_uw_show('EndRefit');
return;
%_______________________________________________________________________
%_______________________________________________________________________
function msk = get_mask(P,xyz,ds,dm)
%
% Create a mask to avoid regions where data doesnt exist
% for all scans. This mask is slightly less Q&D than that
% of version 1 of Unwarp. It checks where data exist for
% all scans with present movement parameters and given
% (optionally) the static field. It creates a mask with
% non-zero values only for those voxels, and then does a
% 3D erode to preempt effects of re-estimated movement
% parameters and movement-by-susceptibility effects.
%
spm_uw_show('MaskStart',length(P));
msk = true(length(xyz),1);
for i=1:length(P)
txyz = xyz * (P(i).mat\ds.M)';
tmsk = (txyz(:,1)>=1 & txyz(:,1)<=P(1).dim(1) &...
txyz(:,2)>=1 & txyz(:,2)<=P(1).dim(2) &...
txyz(:,3)>=1 & txyz(:,3)<=P(1).dim(3));
msk = msk & tmsk;
spm_uw_show('MaskUpdate',i);
end
%
% Include static field in mask estimation
% if one has been supplied.
%
if isfield(ds,'sfP') && ~isempty(ds.sfP)
txyz = xyz * (ds.sfP.mat\ds.M)';
tmsk = (txyz(:,1)>=1 & txyz(:,1)<=ds.sfP.dim(1) &...
txyz(:,2)>=1 & txyz(:,2)<=ds.sfP.dim(2) &...
txyz(:,3)>=1 & txyz(:,3)<=ds.sfP.dim(3));
msk = msk & tmsk;
end
msk = erode_msk(msk,dm);
spm_uw_show('MaskEnd');
% maskP = P(1);
% [mypath,myname,myext] = fileparts(maskP.fname);
% maskP.fname = fullfile(mypath,['mask' myext]);
% maskP.dim = [nx ny nz];
% maskP.dt = P(1).dt;
% maskP = spm_write_vol(maskP,reshape(msk,[nx ny nz]));
return;
%_______________________________________________________________________
%_______________________________________________________________________
function omsk = erode_msk(msk,dim)
omsk = zeros(dim+[4 4 4]);
omsk(3:end-2,3:end-2,3:end-2) = reshape(msk,dim);
omsk = spm_erode(omsk(:),dim+[4 4 4]);
omsk = reshape(omsk,dim+[4 4 4]);
omsk = omsk(3:end-2,3:end-2,3:end-2);
omsk = omsk(:);
return
%_______________________________________________________________________
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_inv_vbecd_gui.m
|
.m
|
antx-master/xspm8/spm_eeg_inv_vbecd_gui.m
| 28,153 |
utf_8
|
598aea45945f5e4331f926426be3135d
|
function D = spm_eeg_inv_vbecd_gui(D,val)
% GUI function for Bayesian ECD inversion
% - load the necessary data, if not provided
% - fill in all the necessary bits for the VB-ECD inversion routine,
% - launch the B_ECD routine, aka. spm_eeg_inv_vbecd
% - displays the results.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
%
% $Id: spm_eeg_inv_vbecd_gui.m 4531 2011-10-21 11:49:08Z gareth $
%%
% Load data, if necessary
%==========
if nargin<1
D = spm_eeg_load;
end
DISTTHRESH=120; %% mm distance from centre of brain classified as inside the head
%%
% Check if the forward model was prepared & handle the other info bits
%========================================
if ~isfield(D,'inv')
error('Data must have been prepared for inversion procedure...')
end
if nargin==2
% check index provided
if val>length(D.inv)
val = length(D.inv);
D.val = val;
end
else
if isfield(D,'val')
val = D.val;
else
% use last one
val = length(D.inv);
D.val = val;
end
end
% Use val to define which is the "current" inv{} to use
% If no inverse solution already calculated (field 'inverse' doesn't exist)
% use that inv{}. Otherwise create a new one by copying the previous
% inv{} structure
if isfield(D.inv{val},'inverse')
% create an extra inv{}
Ninv = length(D.inv);
D.inv{Ninv+1} = D.inv{val};
if isfield(D.inv{Ninv+1},'contrast')
% no contrast field used here !
D.inv{Ninv+1} = rmfield(D.inv{Ninv+1},'contrast');
end
val = Ninv+1;
D.val = val;
end
if ~isfield(D.inv{val}, 'date')
% Set time , date, comments & modality
clck = fix(clock);
if clck(5) < 10
clck = [num2str(clck(4)) ':0' num2str(clck(5))];
else
clck = [num2str(clck(4)) ':' num2str(clck(5))];
end
D.inv{val}.date = strvcat(date,clck); %#ok<VCAT>
end
if ~isfield(D.inv{val}, 'comment'),
D.inv{val}.comment = {spm_input('Comment/Label for this analysis', '+1', 's')};
end
D.inv{val}.method = 'vbecd';
%% Struct that collects the inputs for vbecd code
P = [];
P.modality = spm_eeg_modality_ui(D, 1, 1);
if isfield(D.inv{val}, 'forward') && isfield(D.inv{val}, 'datareg')
for m = 1:numel(D.inv{val}.forward)
if strncmp(P.modality, D.inv{val}.forward(m).modality, 3)
P.forward.vol = D.inv{val}.forward(m).vol;
if ischar(P.forward.vol)
P.forward.vol = ft_read_vol(P.forward.vol);
end
P.forward.sens = D.inv{val}.datareg(m).sensors;
% Channels to use
P.Ic = setdiff(meegchannels(D, P.modality), badchannels(D));
M1 = D.inv{val}.datareg.toMNI;
[U, L, V] = svd(M1(1:3, 1:3));
orM1(1:3,1:3) =U*V'; %% for switching orientation between meg and mni space
% disp('Undoing transformation to Tal space !');
%disp('Fixing sphere centre !');
%P.forward.vol.o=[0 0 28]; P.forward.vol.r=100;
%mnivol = ft_transform_vol(M1, P.forward.vol); %% used for inside head calculation
end
end
end
if isempty(P.Ic)
error(['The specified modality (' P.modality ') is missing from file ' D.fname]);
else
P.channels = D.chanlabels(P.Ic);
end
[P.forward.vol, P.forward.sens] = ft_prepare_vol_sens( ...
P.forward.vol, P.forward.sens, 'channel', P.channels);
if ~isfield(P.forward.sens,'prj')
P.forward.sens.prj = D.coor2D(P.Ic);
end
%%
% Deal with data
%===============
% time bin or time window
msg_tb = ['time_bin or average_win [',num2str(round(min(D.time)*1e3)), ...
' ',num2str(round(max(D.time)*1e3)),'] ms'];
ask_tb = 1;
while ask_tb
tb = spm_input(msg_tb,1,'r'); % ! in msec
if length(tb)==1
if tb>=min(D.time([], 'ms')) && tb<=max(D.time([], 'ms'))
ask_tb = 0;
end
elseif length(tb)==2
if all(tb>=floor(min(D.time([], 'ms')))) && all(tb<=ceil(max(D.time([], 'ms')))) && tb(1)<=tb(2)
ask_tb = 0;
end
end
end
if length(tb)==1
[kk,ltb] = min(abs(D.time([], 'ms')-tb)); % round to nearest time bin
else
[kk,ltb(1)] = min(abs(D.time([], 'ms')-tb(1))); % round to nearest time bin
[kk,ltb(2)] = min(abs(D.time([], 'ms')-tb(2)));
ltb = ltb(1):ltb(2); % list of time bins 'tb' to use
end
% trial type
if D.ntrials>1
msg_tr = ['Trial type number [1 ',num2str(D.ntrials),']'];
ltr = spm_input(msg_tr,2,'i',num2str(1:D.ntrials));
tr_q = 1;
else
tr_q = 0;
ltr = 1;
end
% data, averaged over time window considered
EEGscale=1;
%% SORT OUT EEG UNITS AND CONVERT VALUES TO VOLTS
if strcmp(upper(P.modality),'EEG'),
allunits=strvcat('uV','mV','V');
allscales=[1e-6, 1e-3, 1]; %%
EEGscale=0;
eegunits = unique(D.units(D.meegchannels('EEG')));
Neegchans=numel(D.units(D.meegchannels('EEG')));
for j=1:length(allunits),
if strcmp(deblank(allunits(j,:)),deblank(eegunits));
EEGscale=allscales(j);
end; % if
end; % for j
if EEGscale==0,
warning('units unspecified');
if mean(std(D(P.Ic,ltb,ltr)))>1e-2,
guess_ind=[1 2 3];
else
guess_ind=[3 2 1];
end;
msg_str=sprintf('Units of EEG are %s ? (rms=%3.2e)',allunits(guess_ind(1),:),mean(std(D(P.Ic,ltb,ltr))));
dip_ch = sprintf('%s|%s|%s',allunits(guess_ind(1),:),allunits(guess_ind(2),:),allunits(guess_ind(3),:));
dip_val = [1,2,3];
def_opt=1;
unitind= spm_input(msg_str,2,'b',dip_ch,dip_val,def_opt);
%ans=spm_input(msg_str,1,'s','yes');
allunits(guess_ind(unitind),:)
D = units(D, 1:Neegchans, allunits(guess_ind(unitind),:));
EEGscale=allscales(guess_ind(unitind));
D.save; %% Save the new units
end; %if EEGscale==0
end; % if eeg data
dat_y = squeeze(mean(D(P.Ic,ltb,ltr)*EEGscale,2));
%%
% Other bits of the P structure, apart for priors and #dipoles
%==============================
P.ltr = ltr;
P.Nc = length(P.Ic);
% Deal with dipoles number and priors
%====================================
dip_q = 0; % number of dipole 'elements' added (single or pair)
dip_c = 0; % total number of dipoles in the model
adding_dips = 1;
clear dip_pr
priorlocvardefault=[100, 100, 100]; %% location variance default in mm
nopriorlocvardefault=[80*80, 80*80, 80*80];
nopriormomvardefault=[10, 10, 10]*100; %% moment variance in nAM
priormomvardefault=[1, 1, 1]; %%
while adding_dips
if dip_q>0,
msg_dip =['Add dipoles to ',num2str(dip_c),' or stop?'];
dip_ch = 'Single|Symmetric Pair|Stop';
dip_val = [1,2,0];
def_opt=3;
else
msg_dip =['Add dipoles to model'];
def_opt=1;
dip_ch = 'Single|Symmetric Pair';
dip_val = [1,2];
end
a_dip = spm_input(msg_dip,2+tr_q+dip_q,'b',dip_ch,dip_val,def_opt);
if a_dip == 0
adding_dips = 0;
elseif a_dip == 1
% add a single dipole to the model
dip_q = dip_q+1;
dip_pr(dip_q) = struct( 'a_dip',a_dip, ...
'mu_w0',[],'mu_s0',[],'S_s0',eye(3),'S_w0',eye(3));
%% 'ab20',[],'ab30',[]); %% ,'Tw', [],'Ts', []);
% Location prior
spr_q = spm_input('Location prior ?',1+tr_q+dip_q+1,'b', ...
'Informative|Non-info',[1,0],2);
if spr_q
% informative location prior
str = 'Location prior';
while 1
s0mni = spm_input(str, 1+tr_q+dip_q+2,'e',[0 0 0])';
%outside = ~ft_inside_vol(s0mni',mnivol);
distcentre=sqrt(dot(s0mni'-mean(D.inv{D.val}.mesh.tess_mni.vert),s0mni'-mean(D.inv{D.val}.mesh.tess_mni.vert))); %%
outside=(distcentre>DISTTHRESH);
s0=D.inv{val}.datareg.fromMNI*[s0mni' 1]';
s0=s0(1:3);
str2='Prior location variance (mm2)';
diags_s0_mni = spm_input(str2, 1+tr_q+dip_q+2,'e',priorlocvardefault)';
S_s0_ctf=orM1*diag(diags_s0_mni)*orM1'; %% transform covariance
%% need to leave diags(S0) free
if all(~outside), break, end
str = 'Prior location must be inside head';
end
dip_pr(dip_q).mu_s0 = s0;
else
% no location prior
dip_pr(dip_q).mu_s0 = zeros(3,1);
diags_s0_mni= nopriorlocvardefault';
S_s0_ctf=diag(diags_s0_mni);
end
dip_pr(dip_q).S_s0=S_s0_ctf; %
% Moment prior
wpr_q = spm_input('Moment prior ?',1+tr_q+dip_q+spr_q+2,'b', ...
'Informative|Non-info',[1,0],2);
if wpr_q
% informative moment prior
w0_mni= spm_input('Moment prior', ...
1+tr_q+dip_q+spr_q+3,'e',[0 0 0])';
str2='Prior moment variance (nAm2)';
diags_w0_mni = spm_input(str2, 1+tr_q+dip_q+2,'e',priormomvardefault)';
dip_pr(dip_q).mu_w0 =orM1*w0_mni;
S_w0_ctf=orM1*diag(diags_w0_mni)*orM1';
else
% no location prior
dip_pr(dip_q).mu_w0 = zeros(3,1);
S_w0_ctf= diag(nopriormomvardefault);
end
%% set up covariance matrix for orientation with no crosstalk terms (for single
%% dip)
dip_pr(dip_q).S_w0=S_w0_ctf;
dip_c = dip_c+1;
else
% add a pair of symmetric dipoles to the model
dip_q = dip_q+1;
dip_pr(dip_q) = struct( 'a_dip',a_dip, ...
'mu_w0',[],'mu_s0',[],'S_s0',eye(6),'S_w0',eye(6));
%%...
% 'ab20',[],'ab30',[]); %%,'Tw',eye(6),'Ts',eye(6));
% Location prior
spr_q = spm_input('Location prior ?',1+tr_q+dip_q+1,'b', ...
'Informative|Non-info',[1,0],2);
if spr_q
% informative location prior
str = 'Location prior (one side only)';
while 1
s0mni = spm_input(str, 1+tr_q+dip_q+2,'e',[0 0 0])';
syms0mni=s0mni;
syms0mni(1)=-syms0mni(1);
distcentre=sqrt(dot(s0mni'-mean(D.inv{D.val}.mesh.tess_mni.vert),s0mni'-mean(D.inv{D.val}.mesh.tess_mni.vert))); %%
outside=(distcentre>DISTTHRESH);
s0=D.inv{val}.datareg.fromMNI*[s0mni' 1]';
s0sym=D.inv{val}.datareg.fromMNI*[syms0mni' 1]';
str2='Prior location variance (mm2)';
tmp_diags_s0_mni = spm_input(str2, 1+tr_q+dip_q+2,'e',priorlocvardefault)';
tmp_diags_s0_mni= [tmp_diags_s0_mni ; tmp_diags_s0_mni ];
if all(~outside), break, end
str = 'Prior location must be inside head';
end
dip_pr(dip_q).mu_s0 = [s0(1:3);s0sym(1:3)];
else
% no location prior
dip_pr(dip_q).mu_s0 = zeros(6,1);
tmp_diags_s0 = [nopriorlocvardefault';nopriorlocvardefault'];
tmp_diags_s0_mni=[nopriorlocvardefault';nopriorlocvardefault'];
end %% end of if informative prior
%% setting up a covariance matrix where there is covariance between
%% the x parameters negatively coupled, y,z positively.
mni_dip_pr(dip_q).S_s0 = eye(length(tmp_diags_s0_mni)).*repmat(tmp_diags_s0_mni,1,length(tmp_diags_s0_mni));
mni_dip_pr(dip_q).S_s0(4,1)=-mni_dip_pr(dip_q).S_s0(4,4); % reflect in x
mni_dip_pr(dip_q).S_s0(5,2)=mni_dip_pr(dip_q).S_s0(5,5); % maintain y and z
mni_dip_pr(dip_q).S_s0(6,3)=mni_dip_pr(dip_q).S_s0(6,6);
mni_dip_pr(dip_q).S_s0(1,4)=mni_dip_pr(dip_q).S_s0(4,1);
mni_dip_pr(dip_q).S_s0(2,5)=mni_dip_pr(dip_q).S_s0(5,2);
mni_dip_pr(dip_q).S_s0(3,6)=mni_dip_pr(dip_q).S_s0(6,3);
%% transform to MEG space
%dip_pr(dip_q).S_s0(:,1:3)=orM1*mni_dip_pr(dip_q).S_s0(:,1:3)*orM1'; %% NEED TO LOOK AT THIS
%dip_pr(dip_q).S_s0(:,4:6)=orM1*mni_dip_pr(dip_q).S_s0(:,4:6)*orM1';
tmp1=orM1*mni_dip_pr(dip_q).S_s0(1:3,1:3)*orM1'; %% NEED TO LOOK AT THIS
tmp2=orM1*mni_dip_pr(dip_q).S_s0(1:3,4:6)*orM1';
tmp3=orM1*mni_dip_pr(dip_q).S_s0(4:6,4:6)*orM1';
tmp4=orM1*mni_dip_pr(dip_q).S_s0(4:6,1:3)*orM1';
dip_pr(dip_q).S_s0(1:3,1:3)=tmp1;
dip_pr(dip_q).S_s0(1:3,4:6)=tmp2;
dip_pr(dip_q).S_s0(4:6,4:6)=tmp3;
dip_pr(dip_q).S_s0(4:6,1:3)=tmp4;
% Moment prior
wpr_q = spm_input('Moment prior ?',1+tr_q+dip_q+spr_q+2,'b', ...
'Informative|Non-info',[1,0],2);
if wpr_q
% informative moment prior
tmp= spm_input('Moment prior (right only)', ...
1+tr_q+dip_q+spr_q+3,'e',[1 1 1])';
tmp = [tmp ; tmp] ; tmp(4) = tmp(4);
dip_pr(dip_q).mu_w0 = tmp;
str2='Prior moment variance (nAm2)';
diags_w0 = spm_input(str2, 1+tr_q+dip_q+spr_q+3,'e',priormomvardefault)';
tmp_diags_w0=[diags_w0; diags_w0];
else
% no moment prior
dip_pr(dip_q).mu_w0 = zeros(6,1);
tmp_diags_w0 = [nopriormomvardefault'; nopriormomvardefault'];
end
%dip_pr(dip_q).S_w0=eye(length(diags_w0)).*repmat(diags_w0,1,length(diags_w0));
%% couple all orientations, except x, positively or leave for now...
mni_dip_pr(dip_q).S_w0 = eye(length(tmp_diags_w0)).*repmat(tmp_diags_w0,1,length(tmp_diags_w0));
mni_dip_pr(dip_q).S_w0(4,1)=-mni_dip_pr(dip_q).S_w0(4,4); % reflect x orientation
mni_dip_pr(dip_q).S_w0(5,2)=mni_dip_pr(dip_q).S_w0(5,5); %
mni_dip_pr(dip_q).S_w0(6,3)=mni_dip_pr(dip_q).S_w0(6,6); %
mni_dip_pr(dip_q).S_w0(1,4)=-mni_dip_pr(dip_q).S_w0(4,1); %
mni_dip_pr(dip_q).S_w0(2,5)=mni_dip_pr(dip_q).S_w0(5,2); %
mni_dip_pr(dip_q).S_w0(3,6)=mni_dip_pr(dip_q).S_w0(6,3); %
tmp1=orM1*mni_dip_pr(dip_q).S_w0(1:3,1:3)*orM1';
tmp2=orM1*mni_dip_pr(dip_q).S_w0(1:3,4:6)*orM1';
tmp3=orM1*mni_dip_pr(dip_q).S_w0(4:6,4:6)*orM1';
tmp4=orM1*mni_dip_pr(dip_q).S_w0(4:6,1:3)*orM1';
dip_pr(dip_q).S_w0(1:3,1:3)=tmp1;
dip_pr(dip_q).S_w0(1:3,4:6)=tmp2;
dip_pr(dip_q).S_w0(4:6,4:6)=tmp3;
dip_pr(dip_q).S_w0(4:6,1:3)=tmp4;
dip_c = dip_c+2;
end
end
%str2='Data SNR (amp)';
% SNRamp = spm_input(str2, 1+tr_q+dip_q+2+1,'e',5)';
SNRamp=3;
hE=log(SNRamp^2); %% expected log precision of data
hC=1; % variability of the above precision
str2='Number of iterations';
Niter = spm_input(str2, 1+tr_q+dip_q+2+2,'e',10)';
%%
% Get all the priors together and build structure to pass to inv_becd
%============================
priors = struct('mu_w0',cat(1,dip_pr(:).mu_w0), ...
'mu_s0',cat(1,dip_pr(:).mu_s0), ...
'S_w0',blkdiag(dip_pr(:).S_w0),'S_s0',blkdiag(dip_pr(:).S_s0),'hE',hE,'hC',hC);
P.priors = priors;
%%
% Launch inversion !
%===================
% Initialise inverse field
inverse = struct( ...
'F',[], ... % free energy
'pst',D.time, ... % all time points in data epoch
'tb',tb, ... % time window/bin used
'ltb',ltb, ... % list of time points used
'ltr',ltr, ... % list of trial types used
'n_seeds',length(ltr), ... % using this field for multiple reconstruction
'n_dip',dip_c, ... % number of dipoles used
'loc',[], ... % loc of dip (3 x n_dip)
'j',[], ... % dipole(s) orient/ampl, in 1 column
'cov_loc',[], ... % cov matrix of source location
'cov_j',[], ... % cov matrix of source orient/ampl
'Mtb',1, ... % ind of max EEG power in time series, 1 as only 1 tb.
'exitflag',[], ... % Converged (1) or not (0)
'P',[]); % save all kaboodle too.
for ii=1:length(ltr)
P.y = dat_y(:,ii);
P.ii = ii;
%% set up figures
P.handles.hfig = spm_figure('GetWin','Graphics');
spm_clf(P.handles.hfig)
P.handles.SPMdefaults.col = get(P.handles.hfig,'colormap');
P.handles.SPMdefaults.renderer = get(P.handles.hfig,'renderer');
set(P.handles.hfig,'userdata',P)
dip_amp=[];
for j=1:Niter,
Pout(j) = spm_eeg_inv_vbecd(P);
close(gcf);
varresids(j)=var(Pout(j).y-Pout(j).ypost);
pov(j)=100*(1-varresids(j)/var(Pout(j).y)); %% percent variance explained
allF(j)=Pout(j).F;
dip_mom=reshape(Pout(j).post_mu_w,3,length(Pout(j).post_mu_w)/3);
dip_amp(j,:)=sqrt(dot(dip_mom,dip_mom));
% display
megloc=reshape(Pout(j).post_mu_s,3,length(Pout(j).post_mu_s)/3); % loc of dip (3 x n_dip)
mniloc=D.inv{val}.datareg.toMNI*[megloc;ones(1,size(megloc,2))]; %% actual MNI location (with scaling)
megmom=reshape(Pout(j).post_mu_w,3,length(Pout(j).post_mu_w)/3); % moments of dip (3 x n_dip)
megposvar=reshape(diag(Pout(j).post_S_s),3,length(Pout(j).post_mu_s)/3); %% estimate of positional uncertainty in three principal axes
mnimom=orM1*megmom; %% convert moments into mni coordinates through a rotation (no scaling or translation)
mniposvar=(orM1*sqrt(megposvar)).^2; %% convert pos variance into approx mni space by switching axes
displayVBupdate2(Pout(j).y,pov,allF,Niter,dip_amp,mnimom,mniloc(1:3,:),mniposvar,P,j,[],Pout(j).F,Pout(j).ypost,[]);
end; % for j
allF=[Pout.F];
[maxFvals,maxind]=max(allF);
P=Pout(maxind); %% take best F
% Get the results out.
inverse.pst = tb*1e3;
inverse.F(ii) = P.F; % free energy
megloc=reshape(P.post_mu_s,3,length(P.post_mu_s)/3); % loc of dip (3 x n_dip)
meg_w=reshape(P.post_mu_w,3,length(P.post_mu_w)/3); % moments of dip (3 x n_dip)
mni_w=orM1*meg_w; %% orientation in mni space
mniloc=D.inv{val}.datareg.toMNI*[megloc;ones(1,size(megloc,2))]; %% actual MNI location (with scaling)
inverse.mniloc{ii}=mniloc(1:3,:);
inverse.loc{ii} = megloc;
inverse.j{ii} = P.post_mu_w; % dipole(s) orient/ampl, in 1 column in meg space
inverse.jmni{ii} = reshape(mni_w,1,prod(size(mni_w)))'; % dipole(s) orient/ampl in mni space
inverse.cov_loc{ii} = P.post_S_s; % cov matrix of source location
inverse.cov_j{ii} = P.post_S_w; % cov matrix of source orient/ampl
inverse.exitflag(ii) = 1; % Converged (1) or not (0)
inverse.P{ii} = P; % save all kaboodle too.
%% show final result
pause(1);
spm_clf(P.handles.hfig)
megmom=reshape(Pout(maxind).post_mu_w,3,length(Pout(maxind).post_mu_w)/3); % moments of dip (3 x n_dip)
%megposvar=reshape(diag(Pout(maxind).post_S_s),3,length(Pout(maxind).post_mu_s)/3); %% estimate of positional uncertainty in three principal axes
mnimom=orM1*megmom; %% convert moments into mni coordinates through a rotation (no scaling or translation)
longorM1=zeros(size(Pout(maxind).post_S_s,1));
for k1=1:length(Pout(maxind).post_S_s)/3;
longorM1((k1-1)*3+1:k1*3,(k1-1)*3+1:k1*3)=orM1;
end; % for k1
S0_mni=longorM1*Pout(maxind).post_S_s*longorM1';
mniposvar=diag(S0_mni); %% convert pos variance into approx mni space by switching axes
mniposvar=reshape(mniposvar,3,length(Pout(maxind).post_S_s)/3);
displayVBupdate2(Pout(maxind).y,pov,allF,Niter,dip_amp,mnimom,mniloc(1:3,:),mniposvar,P,j,[],Pout(maxind).F,Pout(maxind).ypost,maxind);
%displayVBupdate2(Pout(maxind).y,pov,allF,Niter,dip_amp,mniloc,Pout(maxind).post_mu_s,Pout(maxind).post_S_s,P,j,[],Pout(maxind).F,Pout(maxind).ypost,maxind,D);
%
end
D.inv{val}.inverse = inverse;
%%
% Save results and display
%-------------------------
save(D)
return
function [P] = displayVBupdate2(y,pov_iter,F_iter,maxit,dipamp_iter,mu_w,mu_s,diagS_s,P,it,flag,F,yHat,maxind)
%% yHat is estimate of y based on dipole position
if ~exist('flag','var')
flag = [];
end
if ~exist('maxind','var')
maxind = [];
end
if isempty(flag) || isequal(flag,'ecd')
% plot dipoles
try
opt.ParentAxes = P.handles.axesECD;
opt.hfig = P.handles.hfig;
opt.handles.hp = P.handles.hp;
opt.handles.hq = P.handles.hq;
opt.handles.hs = P.handles.hs;
opt.handles.ht = P.handles.ht;
opt.query = 'replace';
catch
P.handles.axesECD = axes(...
'parent',P.handles.hfig,...
'Position',[0.13 0.55 0.775 0.4],...
'hittest','off',...
'visible','off',...
'deleteFcn',@back2defaults);
opt.ParentAxes = P.handles.axesECD;
opt.hfig = P.handles.hfig;
end
w = reshape(mu_w,3,[]);
s = reshape(mu_s, 3, []);
% mesh.faces=D.inv{D.val}.forward.mesh.face; %% in ctf space
% mesh.vertices=D.inv{D.val}.forward.mesh.vert; %% in ctf space
% [out] = spm_eeg_displayECD_ctf(...
% s,w,reshape(diag(S_s),3,[]),[],mesh,opt);
[out] = spm_eeg_displayECD(...
s,w,diagS_s,[],opt);
P.handles.hp = out.handles.hp;
P.handles.hq = out.handles.hq;
P.handles.hs = out.handles.hs;
P.handles.ht = out.handles.ht;
end
% plot data and predicted data
pos = P.forward.sens.prj;
ChanLabel = P.channels;
in.f = P.handles.hfig;
in.noButtons = 1;
try
P.handles.axesY;
catch
figure(P.handles.hfig)
P.handles.axesY = axes(...
'Position',[0.02 0.3 0.3 0.2],...
'hittest','off');
in.ParentAxes = P.handles.axesY;
spm_eeg_plotScalpData(y,pos,ChanLabel,in);
title(P.handles.axesY,'measured data')
end
if isempty(flag) || isequal(flag,'data') || isequal(flag,'ecd')
%yHat = P.gmn*mu_w;
miY = min([yHat;y]);
maY = max([yHat;y]);
try
P.handles.axesYhat;
d = get(P.handles.axesYhat,'userdata');
yHat = yHat(d.goodChannels);
clim = [min(yHat(:))-( max(yHat(:))-min(yHat(:)) )/63,...
max(yHat(:))];
ZI = griddata(...
d.interp.pos(1,:),d.interp.pos(2,:),full(double(yHat)),...
d.interp.XI,d.interp.YI);
set(d.hi,'Cdata',flipud(ZI));
caxis(P.handles.axesYhat,clim);
delete(d.hc)
[C,d.hc] = contour(P.handles.axesYhat,flipud(ZI),...
'linecolor',0.5.*ones(3,1));
set(P.handles.axesYhat,...
'userdata',d);
catch
figure(P.handles.hfig)
P.handles.axesYhat = axes(...
'Position',[0.37 0.3 0.3 0.2],...
'hittest','off');
in.ParentAxes = P.handles.axesYhat;
spm_eeg_plotScalpData(yHat,pos,ChanLabel,in);
title(P.handles.axesYhat,'predicted data')
end
try
P.handles.axesYhatY;
catch
figure(P.handles.hfig)
P.handles.axesYhatY = axes(...
'Position',[0.72 0.3 0.25 0.2],...
'NextPlot','replace',...
'box','on');
end
plot(P.handles.axesYhatY,y,yHat,'.')
set(P.handles.axesYhatY,...
'nextplot','add')
plot(P.handles.axesYhatY,[miY;maY],[miY;maY],'r')
set(P.handles.axesYhatY,...
'nextplot','replace')
title(P.handles.axesYhatY,'predicted vs measured data')
axis(P.handles.axesYhatY,'square','tight')
grid(P.handles.axesYhatY,'on')
end
if isempty(flag) || isequal(flag,'var')
% plot precision hyperparameters
try
P.handles.axesVar1;
catch
figure(P.handles.hfig)
P.handles.axesVar1 = axes(...
'Position',[0.05 0.05 0.25 0.2],...
'NextPlot','replace',...
'box','on');
end
plot(P.handles.axesVar1,F_iter,'o-');
if ~isempty(maxind),
hold on;
h=plot(P.handles.axesVar1,maxind,F_iter(maxind),'rd');
set(h,'linewidth',4);
end;
set(P.handles.axesVar1,'Xlimmode','manual');
set(P.handles.axesVar1,'Xlim',[1 maxit]);
set(P.handles.axesVar1,'Xtick',1:maxit);
set(P.handles.axesVar1,'Xticklabel',num2str([1:maxit]'));
set(P.handles.axesVar1,'Yticklabel','');
title(P.handles.axesVar1,'Free energy ')
axis(P.handles.axesVar1,'square');
set(P.handles.axesVar1,'Ylimmode','auto'); %,'tight')
grid(P.handles.axesVar1,'on')
try
P.handles.axesVar2;
catch
figure(P.handles.hfig)
P.handles.axesVar2 = axes(...
'Position',[0.37 0.05 0.25 0.2],...
'NextPlot','replace',...
'box','on');
end
plot(P.handles.axesVar2,pov_iter,'*-')
if ~isempty(maxind),
hold on;
h=plot(P.handles.axesVar2,maxind,pov_iter(maxind),'rd');
set(h,'linewidth',4);
end;
set(P.handles.axesVar2,'Xlimmode','manual');
set(P.handles.axesVar2,'Xlim',[1 maxit]);
set(P.handles.axesVar2,'Xtick',1:maxit);
set(P.handles.axesVar2,'Xticklabel',num2str([1:maxit]'));
set(P.handles.axesVar2,'Ylimmode','manual'); %,'tight')
set(P.handles.axesVar2,'Ylim',[0 100]);
set(P.handles.axesVar2,'Ytick',[0:20:100]);
set(P.handles.axesVar2,'Yticklabel',num2str([0:20:100]'));
%set(P.handles.axesVar2,'Yticklabel','');
title(P.handles.axesVar2,'Percent variance explained');
axis(P.handles.axesVar2,'square');
grid(P.handles.axesVar2,'on')
try
P.handles.axesVar3;
catch
figure(P.handles.hfig)
P.handles.axesVar3 = axes(...
'Position',[0.72 0.05 0.25 0.2],...
'NextPlot','replace',...
'box','on');
end
plot(P.handles.axesVar3,1:it,dipamp_iter','o-');
if ~isempty(maxind),
hold on;
h=plot(P.handles.axesVar3,maxind,dipamp_iter(maxind,:)','rd');
set(h,'linewidth',4);
end;
set(P.handles.axesVar3,'Xlimmode','manual');
set(P.handles.axesVar3,'Xlim',[1 maxit]);
set(P.handles.axesVar3,'Xtick',1:maxit);
set(P.handles.axesVar3,'Xticklabel',num2str([1:maxit]'));
set(P.handles.axesVar3,'Yticklabel','');
title(P.handles.axesVar3,'Dipole amp (nAm) ')
axis(P.handles.axesVar3,'square');
set(P.handles.axesVar3,'Ylimmode','auto'); %,'tight')
grid(P.handles.axesVar3,'on')
end
if ~isempty(flag) && (isequal(flag,'ecd') || isequal(flag,'mGN') )
try
P.handles.hte(2);
catch
figure(P.handles.hfig)
P.handles.hte(2) = uicontrol('style','text',...
'units','normalized',...
'position',[0.2,0.91,0.6,0.02],...
'backgroundcolor',[1,1,1]);
end
set(P.handles.hte(2),'string',...
['ECD locations: Modified Gauss-Newton scheme... ',num2str(floor(P.pc)),'%'])
else
try
set(P.handles.hte(2),'string','VB updates on hyperparameters')
end
end
try
P.handles.hte(1);
catch
figure(P.handles.hfig)
P.handles.hte(1) = uicontrol('style','text',...
'units','normalized',...
'position',[0.2,0.94,0.6,0.02],...
'backgroundcolor',[1,1,1]);
end
try
set(P.handles.hte(1),'string',...
['Model evidence: p(y|m) >= ',num2str(F(end),'%10.3e\n')])
end
try
P.handles.hti;
catch
figure(P.handles.hfig)
P.handles.hti = uicontrol('style','text',...
'units','normalized',...
'position',[0.3,0.97,0.4,0.02],...
'backgroundcolor',[1,1,1],...
'string',['VB ECD inversion: trial #',num2str(P.ltr(P.ii))]);
end
drawnow
function back2defaults(e1,e2)
hf = spm_figure('FindWin','Graphics');
P = get(hf,'userdata');
try
set(hf,'colormap',P.handles.SPMdefaults.col);
set(hf,'renderer',P.handles.SPMdefaults.renderer);
end
|
github
|
philippboehmsturm/antx-master
|
spm_changepath.m
|
.m
|
antx-master/xspm8/spm_changepath.m
| 3,334 |
utf_8
|
131dfc27d3dc8f5c489b56126b71ee9b
|
function varargout = spm_changepath(Sf, oldp, newp)
% Recursively replace all occurences of a text pattern in a MATLAB variable.
% FORMAT S = spm_changepath(Sf, oldp, newp)
%
% Sf - MATLAB variable to fix, or char array of MAT filenames,
% or directory name (all found MAT files will be analysed)
% oldp - old string to replace
% newp - new string replacing oldp
%
% S - updated MATLAB variable (only if Sf is one)
%
% If the pattern is found in a string, any occurence of an invalid file
% separator is replaced to match that of the current system.
%
% If MAT filenames are specified, they will be overwritten with the new
% version. A backup of the initial version is made with a ".old" suffix.
%__________________________________________________________________________
% Copyright (C) 2009 Wellcome Trust Centre for Neuroimaging
% Guillaume Flandin
% $Id: spm_changepath.m 4078 2010-10-06 17:41:26Z guillaume $
%-Input arguments
%--------------------------------------------------------------------------
if ~nargin
Sf = spm_select(Inf,'mat','Select MAT files to fix');
end
if nargin <= 1
oldp = spm_input('Old pattern','+1','s');
end
if nargin <= 2
newp = spm_input('New pattern','+1','s');
end
%-Replace pattern in given MAT-files
%--------------------------------------------------------------------------
if ischar(Sf)
if nargout
error('Output argument only valid for MATLAB variable input');
end
if exist(Sf,'dir')
Sf = spm_select('FPList',Sf,'^.*\.mat$'); % FPListRec for recursive
end
if isempty(Sf), Sf = {}; else Sf = cellstr(Sf); end
for i=1:numel(Sf)
f = Sf{i};
try
S = load(f);
catch
error(sprintf('Cannot load %s.',f));
end
tmp = changepath(S,oldp,newp);
if ~isequalwithequalnans(tmp,S)
fprintf('=> Fixing %s\n',f);
[sts, msg] = movefile(f,[f '.old']);
if ~sts, error(msg); end
save(f ,'-struct','tmp','-V6');
end
end
else
varargout = { changepath(Sf,oldp,newp) };
end
%==========================================================================
function S = changepath(S,oldp,newp)
switch class(S)
case {'double','single','logical','int8','uint8','int16','uint16',...
'int32','uint32','int64','uint64','function_handle'}
case 'cell'
for i=1:numel(S)
S{i} = changepath(S{i},oldp,newp);
end
case 'struct'
for i=1:numel(S)
fn = fieldnames(S);
for j=1:length(fn)
S(i).(fn{j}) = changepath(S(i).(fn{j}),oldp,newp);
end
end
case 'char'
f = {'\' '/'};
if ispc, f = fliplr(f); end
tmp = cellstr(S);
for i=1:numel(tmp)
t = strrep(tmp{i},oldp,newp);
if ~isequal(tmp{i},t)
t = strrep(t,f{1},f{2});
fprintf('%s\n',t);
end
tmp{i} = t;
end
S = char(tmp);
case 'nifti'
for i=1:numel(S)
S(i).dat = changepath(S(i).dat,oldp,newp);
end
case 'file_array'
S.fname = changepath(S.fname,oldp,newp);
otherwise
warning(sprintf('Unknown class %s.',class(S)));
end
|
github
|
philippboehmsturm/antx-master
|
spm_prep2sn.m
|
.m
|
antx-master/xspm8/spm_prep2sn.m
| 7,382 |
utf_8
|
296f1080e48fcd6511bd7e6ac39b97e7
|
function [po,pin] = spm_prep2sn(p)
% Convert the output from spm_preproc into an sn.mat file
% FORMAT [po,pin] = spm_prep2sn(p)
% p - the results of spm_preproc
%
% po - the output in a form that can be used by spm_write_sn
% pin - the inverse transform in a form that can be used by spm_write_sn
%
% The outputs are saved in sn.mat files only if they are not requested LHS.
%__________________________________________________________________________
% Copyright (C) 2005-2011 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_prep2sn.m 4276 2011-03-31 11:25:34Z spm $
if ischar(p), p = load(p); end
VG = p.tpm;
VF = p.image;
[Y1,Y2,Y3] = create_def(p.Twarp,VF,VG(1),p.Affine);
[Y1,Y2,Y3] = spm_invdef(Y1,Y2,Y3,VG(1).dim(1:3),eye(4),eye(4));
MT = procrustes(Y1,Y2,Y3,VG(1),VF.mat);
d = size(p.Twarp);
[Affine,Tr] = reparameterise(Y1,Y2,Y3,VG(1),VF.mat,MT,max(d(1:3)+2,[8 8 8]));
flags = struct(...
'ngaus', p.ngaus,...
'mg', p.mg,...
'mn', p.mn,...
'vr', p.vr,...
'warpreg', p.warpreg,...
'warpco', p.warpco,...
'biasreg', p.biasreg,...
'biasfwhm', p.biasfwhm,...
'regtype', p.regtype,...
'fudge', p.fudge,...
'samp', p.samp,...
'msk', p.msk,...
'Affine', p.Affine,...
'Twarp', p.Twarp,...
'Tbias', p.Tbias,...
'thresh', p.thresh);
% Parameterisation for the forward transform
po = struct(...
'VG', VG,...
'VF', VF,...
'Tr', Tr,...
'Affine', Affine,...
'flags', flags);
% Parameterisation for the inverse transform
pin = struct(...
'VG', p.image,...
'VF', p.tpm(1),...
'Tr', p.Twarp,...
'Affine', p.tpm(1).mat\p.Affine*p.image.mat,...
'flags', flags);
if ~nargout
[pth,nam] = spm_fileparts(VF.fname);
fnam_out = fullfile(pth,[nam '_seg_sn.mat']);
fnam_inv = fullfile(pth,[nam '_seg_inv_sn.mat']);
if spm_check_version('matlab','7') >= 0
save(fnam_out,'-V6','-struct','po');
save(fnam_inv,'-V6','-struct','pin');
else
save(fnam_out,'-struct','po');
save(fnam_inv,'-struct','pin');
end
end
return;
%==========================================================================
%==========================================================================
function [Affine,Tr] = reparameterise(Y1,Y2,Y3,B,M2,MT,d2)
% Take a deformation field and reparameterise in the same form
% as used by the spatial normalisation routines of SPM
d = [size(Y1) 1];
[x1,x2,o] = ndgrid(1:d(1),1:d(2),1);
x3 = 1:d(3);
Affine = M2\MT*B(1).mat;
A = inv(Affine);
B1 = spm_dctmtx(d(1),d2(1));
B2 = spm_dctmtx(d(2),d2(2));
B3 = spm_dctmtx(d(3),d2(3));
pd = prod(d2(1:3));
AA = eye(pd)*0.01;
Ab = zeros(pd,3);
spm_progress_bar('init',length(x3),'Reparameterising','Planes completed');
for z=1:length(x3)
y1 = double(Y1(:,:,z));
y2 = double(Y2(:,:,z));
y3 = double(Y3(:,:,z));
msk = isfinite(y1);
w = double(msk);
y1(~msk) = 0;
y2(~msk) = 0;
y3(~msk) = 0;
z1 = A(1,1)*y1+A(1,2)*y2+A(1,3)*y3 + w.*(A(1,4) - x1);
z2 = A(2,1)*y1+A(2,2)*y2+A(2,3)*y3 + w.*(A(2,4) - x2);
z3 = A(3,1)*y1+A(3,2)*y2+A(3,3)*y3 + w *(A(3,4) - z );
b3 = B3(z,:)';
Ab(:,1) = Ab(:,1) + kron(b3,spm_krutil(z1,B1,B2,0));
Ab(:,2) = Ab(:,2) + kron(b3,spm_krutil(z2,B1,B2,0));
Ab(:,3) = Ab(:,3) + kron(b3,spm_krutil(z3,B1,B2,0));
AA = AA + kron(b3*b3',spm_krutil(w, B1,B2,1));
spm_progress_bar('set',z);
end
spm_progress_bar('clear');
Tr = reshape(AA\Ab,[d2(1:3) 3]);
return;
%==========================================================================
%==========================================================================
function MT = procrustes(Y1,Y2,Y3,B,M2)
% Take a deformation field and determine the closest rigid-body
% transform to match it, with weighing.
%
% Example Reference:
% F. L. Bookstein (1997). "Landmark Methods for Forms Without
% Landmarks: Morphometrics of Group Differences in Outline Shape"
% Medical Image Analysis 1(3):225-243
M1 = B.mat;
d = B.dim(1:3);
[x1,x2,o] = ndgrid(1:d(1),1:d(2),1);
x3 = 1:d(3);
c1 = [0 0 0];
c2 = [0 0 0];
sw = 0;
spm_progress_bar('init',length(x3),'Procrustes (1)','Planes completed');
for z=1:length(x3)
y1 = double(Y1(:,:,z));
y2 = double(Y2(:,:,z));
y3 = double(Y3(:,:,z));
msk = find(isfinite(y1));
w = spm_sample_vol(B(1),x1(msk),x2(msk),o(msk)*z,0);
swz = sum(w(:));
sw = sw+swz;
c1 = c1 + [w'*[x1(msk) x2(msk)] swz*z ];
c2 = c2 + w'*[y1(msk) y2(msk) y3(msk)];
spm_progress_bar('set',z);
end
spm_progress_bar('clear');
c1 = c1/sw;
c2 = c2/sw;
T1 = [eye(4,3) M1*[c1 1]'];
T2 = [eye(4,3) M2*[c2 1]'];
C = zeros(3);
spm_progress_bar('init',length(x3),'Procrustes (2)','Planes completed');
for z=1:length(x3)
y1 = double(Y1(:,:,z));
y2 = double(Y2(:,:,z));
y3 = double(Y3(:,:,z));
msk = find(isfinite(y1));
w = spm_sample_vol(B(1),x1(msk),x2(msk),o(msk)*z,0);
C = C + [(x1(msk)-c1(1)).*w (x2(msk)-c1(2)).*w ( z-c1(3))*w ]' * ...
[(y1(msk)-c2(1)) (y2(msk)-c2(2)) (y3(msk)-c2(3)) ];
spm_progress_bar('set',z);
end
spm_progress_bar('clear');
[u,s,v] = svd(M1(1:3,1:3)*C*M2(1:3,1:3)');
R = eye(4);
R(1:3,1:3) = v*u';
MT = T2*R*inv(T1);
return;
%==========================================================================
%==========================================================================
function [Y1,Y2,Y3] = create_def(T,VG,VF,Affine)
% Generate a deformation field from its parameterisation.
d2 = size(T);
d = VG.dim(1:3);
M = VF.mat\Affine*VG.mat;
[x1,x2,o] = ndgrid(1:d(1),1:d(2),1);
x3 = 1:d(3);
B1 = spm_dctmtx(d(1),d2(1));
B2 = spm_dctmtx(d(2),d2(2));
B3 = spm_dctmtx(d(3),d2(3));
[pth,nam] = spm_fileparts(VG.fname);
spm_progress_bar('init',length(x3),['Creating Def: ' nam],'Planes completed');
for z=1:length(x3)
[y1,y2,y3] = defs(T,z,B1,B2,B3,x1,x2,x3,M);
Y1(:,:,z) = single(y1);
Y2(:,:,z) = single(y2);
Y3(:,:,z) = single(y3);
spm_progress_bar('set',z);
end
spm_progress_bar('clear');
return;
%==========================================================================
%==========================================================================
function [x1,y1,z1] = defs(sol,z,B1,B2,B3,x0,y0,z0,M)
if ~isempty(sol)
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));
else
x1a = x0;
y1a = y0;
z1a = z0;
end
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(T, d2(1)*d2(2),d2(3));
t1 = reshape(t1*B3', d2(1), d2(2));
t = B1*t1*B2';
return;
%==========================================================================
|
github
|
philippboehmsturm/antx-master
|
cfg_util.m
|
.m
|
antx-master/xspm8/matlabbatch/cfg_util.m
| 69,449 |
utf_8
|
77b870ddcf124262ae1a6edd3161bad5
|
function varargout = cfg_util(cmd, varargin)
% This is the command line interface to the batch system. It manages the
% following structures:
% * Generic configuration structure c0. This structure will be initialised
% to an cfg_repeat with empty .values list. Each application should
% provide an application-specific master configuration file, which
% describes the executable module(s) of an application and their inputs.
% This configuration will be rooted directly under the master
% configuration node. In this way, modules of different applications can
% be combined with each other.
% CAVE: the root nodes of each application must have an unique tag -
% cfg_util will refuse to add an application which has a root tag that is
% already used by another application.
% * Job specific configuration structure cj. This structure contains the
% modules to be executed in a job, their input arguments and
% dependencies between them. The layout of cj is not visible to the user.
% To address executable modules and their input values, cfg_util will
% return id(s) of unspecified type. If necessary, these id(s) should be
% stored in cell arrays in a calling application, since their internal
% format may change.
%
% The commands to manipulate these structures are described below in
% alphabetical order.
%
% cfg_util('addapp', cfg[, def])
%
% Add an application to cfg_util. If cfg is a cfg_item, then it is used
% as initial configuration. Alternatively, if cfg is a MATLAB function,
% this function is evaluated. The return argument of this function must be
% a single variable containing the full configuration tree of the
% application to be batched.
% Optionally, a defaults configuration struct or function can be supplied.
% This function must return a single variable containing a (pseudo) job
% struct/cell array which holds defaults values for configuration items.
% These defaults should be rooted at the application's root node, not at
% the overall root node. They will be inserted by calling initialise on the
% application specific part of the configuration tree.
%
% mod_job_id = cfg_util('addtojob', job_id, mod_cfg_id)
%
% Append module with id mod_cfg_id in the cfg tree to job with id
% job_id. Returns a mod_job_id, which can be passed on to other cfg_util
% callbacks that modify the module in the job.
%
% [mod_job_idlist, new2old_id] = cfg_util('compactjob', job_id)
%
% Modifies the internal representation of a job by removing deleted modules
% from the job configuration tree. This will invalidate all mod_job_ids and
% generate a new mod_job_idlist.
% A translation table new2old_id is provided, where
% mod_job_idlist = old_mod_job_idlist{new2old_id}
% translates between an old id list and the compact new id list.
%
% cfg_util('delfromjob', job_id, mod_job_id)
%
% Delete a module from a job.
%
% cfg_util('deljob', job_id)
%
% Delete job with job_id from the job list.
%
% sts = cfg_util('filljob', job_id, input1, ..., inputN)
% sts = cfg_util('filljobui', job_id, ui_fcn, input1, ..., inputN)
%
% Fill missing inputs in a job from a list of input items. If an can not be
% filled by the specified input, this input will be discarded. If
% cfg_util('filljobui'...) is called, [val sts] = ui_fcn(item) will be run
% and should return a value which is suitable for setval(item, val,
% false). sts should be set to true if input should continue with the
% next item. This can result in an partially filled job. If ui_fcn is
% interrupted, the job will stay unfilled.
% If cfg_util('filljob'...) is called, the current job can become partially
% filled.
% Returns the all_set status of the filled job, returns always false if
% ui_fcn is interrupted.
%
% cfg_util('gencode', fname, apptag|cfg_id[, tropts])
%
% Generate code from default configuration structure, suitable for
% recreating the tree structure. Note that function handles may not be
% saved properly. By default, the entire tree is saved into a file fname.
% If tropts is given as a traversal option specification, code generation
% will be split at the nodes matching tropts.stopspec. Each of these nodes will
% generate code in a new file with filename <fname>_<tag of node>, and the
% nodes up to tropts.stopspec will be saved into fname.
% If a file named <fname>_mlb_preamble.m exists in the folder where the
% configuration code is being written, it will be read in literally
% and its contents will be prepended to each of the created files. This
% allows to automatically include e.g. copyright or revision.
%
% cfg_util('genscript', job_id, scriptdir, filename)
%
% Generate a script which collects missing inputs of a batch job and runs
% the job using cfg_util('filljob', ...). The script will be written to
% file filename.m in scriptdir, the job will be saved to filename_job.m in
% the same folder. The script must be completed by adding code to collect
% the appropriate inputs for the job.
%
% outputs = cfg_util('getAllOutputs', job_id)
%
% outputs - cell array with module outputs. If a module has not yet been
% run, a cfg_inv_out object is returned.
%
% voutputs = cfg_util('getAllVOutputs', job_id[, mod_job_id])
%
% voutputs - cell array with virtual output descriptions (cfg_dep objects).
% These describe the structure of the job outputs. To create
% dependencies, they can be entered into matching input objects
% in subsequent modules of the same job.
% If mod_job_id is supplied, only virtual output descriptions of
% the referenced module are returned.
%
% [tag, val] = cfg_util('harvest', job_id[, mod_job_id])
%
% Harvest is a method defined for all 'cfg_item' objects. It collects the
% entered values and dependencies of the input items in the tree and
% assembles them in a struct/cell array.
% If no mod_job_id is supplied, the internal configuration tree will be
% cleaned up before harvesting. Dependencies will not be resolved in this
% case. The internal state of cfg_util is not modified in this case. The
% structure returned in val may be saved to disk as a job and can be loaded
% back into cfg_util using the 'initjob' command.
% If a mod_job_id is supplied, only the relevant part of the configuration
% tree is harvested, dependencies are resolved and the internal state of
% cfg_util is updated. In this case, the val output is only part of a job
% description and can not be loaded back into cfg_util.
%
% [tag, appdef] = cfg_util('harvestdef'[, apptag|cfg_id])
%
% Harvest the defaults branches of the current configuration tree. If
% apptag is supplied, only the subtree of that application whose root tag
% matches apptag/whose id matches cfg_id is harvested. In this case,
% appdef is a struct/cell array that can be supplied as a second argument
% in application initialisation by cfg_util('addapp', appcfg,
% appdef).
% If no application is specified, defaults of all applications will be
% returned in one struct/cell array.
%
% [tag, val] = cfg_util('harvestrun', job_id)
%
% Harvest data of a job that has been (maybe partially) run, resolving
% all dependencies that can be resolved. This can be used to document
% what has actually been done in a job and which inputs were passed to
% modules with dependencies.
% If the job has not been run yet, tag and val will be empty.
%
% cfg_util('initcfg')
%
% Initialise cfg_util configuration. All currently added applications and
% jobs will be cleared.
% Initial application data will be initialised to a combination of
% cfg_mlbatch_appcfg.m files in their order found on the MATLAB path. Each
% of these config files should be a function with calling syntax
% function [cfg, def] = cfg_mlbatch_appcfg(varargin)
% This function should do application initialisation (e.g. add
% paths). cfg and def should be configuration and defaults data
% structures or the name of m-files on the MATLAB path containing these
% structures. If no defaults are provided, the second output argument
% should be empty.
% cfg_mlbatch_appcfg files are executed in the order they are found on
% the MATLAB path with the one first found taking precedence over
% following ones.
%
% cfg_util('initdef', apptag|cfg_id[, defvar])
%
% Set default values for application specified by apptag or
% cfg_id. If defvar is supplied, it should be any representation of a
% defaults job as returned by cfg_util('harvestdef', apptag|cfg_id),
% i.e. a MATLAB variable, a function creating this variable...
% Defaults from defvar are overridden by defaults specified in .def
% fields.
% New defaults only apply to modules added to a job after the defaults
% have been loaded. Saved jobs and modules already present in the current
% job will not be changed.
%
% [job_id, mod_job_idlist] = cfg_util('initjob'[, job])
%
% Initialise a new job. If no further input arguments are provided, a new
% job without modules will be created.
% If job is given as input argument, the job tree structure will be
% loaded with data from the struct/cell array job and a cell list of job
% ids will be returned.
% The new job will be appended to an internal list of jobs. It must
% always be referenced by its job_id.
%
% sts = cfg_util('isjob_id', job_id)
% sts = cfg_util('ismod_cfg_id', mod_cfg_id)
% sts = cfg_util('ismod_job_id', job_id, mod_job_id)
% sts = cfg_util('isitem_mod_id', item_mod_id)
% Test whether the supplied id seems to be of the queried type. Returns
% true if the id matches the data format of the queried id type, false
% otherwise. For item_mod_ids, no checks are performed whether the id is
% really valid (i.e. points to an item in the configuration
% structure). This can be used to decide whether 'list*' or 'tag2*'
% callbacks returned valid ids.
%
% [mod_cfg_idlist, stop, [contents]] = cfg_util('listcfg[all]', mod_cfg_id, find_spec[, fieldnames])
%
% List modules and retrieve their contents in the cfg tree, starting at
% mod_cfg_id. If mod_cfg_id is empty, search will start at the root level
% of the tree. The returned mod_cfg_id_list is always relative to the root
% level of the tree, not to the mod_cfg_id of the start item. This search
% is designed to stop at cfg_exbranch level. Its behaviour is undefined if
% mod_cfg_id points to an item within an cfg_exbranch. See 'match' and
% 'cfg_item/find' for details how to specify find_spec. A cell list of
% matching modules is returned.
% If the 'all' version of this command is used, also matching
% non-cfg_exbranch items up to the first cfg_exbranch are returned. This
% can be used to build a menu system to manipulate configuration.
% If a cell array of fieldnames is given, contents of the specified fields
% will be returned. See 'cfg_item/list' for details. This callback is not
% very specific in its search scope. To find a cfg_item based on the
% sequence of tags of its parent items, use cfg_util('tag2mod_cfg_id',
% tagstring) instead.
%
% [item_mod_idlist, stop, [contents]] = cfg_util('listmod', job_id, mod_job_id, item_mod_id, find_spec[, tropts][, fieldnames])
% [item_mod_idlist, stop, [contents]] = cfg_util('listmod', mod_cfg_id, item_mod_id, find_spec[, tropts][, fieldnames])
%
% Find configuration items starting in module mod_job_id in the job
% referenced by job_id or in module mod_cfg_id in the defaults tree,
% starting at item item_mod_id. If item_mod_id is an empty array, start
% at the root of a module. By default, search scope are the filled items
% of a module. See 'match' and 'cfg_item/find' for details how to specify
% find_spec and tropts and how to search the default items instead of the
% filled ones. A cell list of matching items is returned.
% If a cell array of fieldnames is given, contents of the specified fields
% will be returned. See 'cfg_item/list' for details.
%
% sts = cfg_util('match', job_id, mod_job_id, item_mod_id, find_spec)
%
% Returns true if the specified item matches the given find spec and false
% otherwise. An empty item_mod_id means that the module node itself should
% be matched.
%
% new_mod_job_id = cfg_util('replicate', job_id, mod_job_id[, item_mod_id, val])
%
% If no item_mod_id is given, replicate a module by appending it to the
% end of the job with id job_id. The values of all items will be
% copied. This is in contrast to 'addtojob', where a module is added with
% default settings. Dependencies where this module is a target will be
% kept, whereas source dependencies will be dropped from the copied module.
% If item_mod_id points to a cfg_repeat object within a module, its
% setval method is called with val. To achieve replication, val(1) must
% be finite and negative, and val(2) must be the index into item.val that
% should be replicated. All values are copied to the replicated entry.
%
% cfg_util('run'[, job|job_id])
%
% Run the currently configured job. If job is supplied as argument and is
% a harvested job, then cfg_util('initjob', job) will be called first. If
% job_id is supplied and is a valid job_id, the job with this job id will
% be run.
% The job is harvested and dependencies are resolved if possible.
% If cfg_get_defaults('cfg_util.runparallel') returns true, all
% modules without unresolved dependencies will be run in arbitrary order.
% Then the remaining modules are harvested again and run, if their
% dependencies can be resolved. This process is iterated until no modules
% are left or no more dependencies can resolved. In a future release,
% independent modules may run in parallel, if there are licenses to the
% Distributed Computing Toolbox available.
% Note that this requires dependencies between modules to be described by
% cfg_dep objects. If a module e.g. relies on file output of another module
% and this output is already specified as a filename of a non-existent
% file, then the dependent module may be run before the file is created.
% Side effects (changes in global variables, working directories) are
% currently not modeled by dependencies.
% If a module fails to execute, computation will continue on modules that
% do not depend on this module. An error message will be logged and the
% module will be reported as 'failed to run' in the MATLAB command window.
%
% cfg_util('runserial'[, job|job_id])
%
% Like 'run', but force cfg_util to run the job as if each module was
% dependent on its predecessor. If cfg_get_defaults('cfg_util.runparallel')
% returns false, cfg_util('run',...) and cfg_util('runserial',...) are
% identical.
%
% cfg_util('savejob', job_id, filename)
%
% The current job will be save to the .m file specified by filename. This
% .m file contains MATLAB script code to recreate the job variable. It is
% based on gencode (part of this MATLAB batch system) for all standard
% MATLAB types. For objects to be supported, they must implement their own
% gencode method.
%
% cfg_util('savejobrun', job_id, filename)
%
% Save job after it has been run, resolving dependencies (see
% cfg_util('harvestrun',...)). If the job has not been run yet, nothing
% will be saved.
%
% sts = cfg_util('setval', job_id, mod_job_id, item_mod_id, val)
%
% Set the value of item item_mod_id in module mod_job_id to val. If item is
% a cfg_choice, cfg_repeat or cfg_menu and val is numeric, the value will
% be set to item.values{val(1)}. If item is a cfg_repeat and val is a
% 2-vector, then the min(val(2),numel(item.val)+1)-th value will be set
% (i.e. a repeat added or replaced). If val is an empty cell, the value of
% item will be cleared.
% sts returns the status of all_set_item after the value has been
% set. This can be used to check whether the item has been successfully
% set.
% Once editing of a module has finished, the module needs to be harvested
% in order to update dependencies from and to other modules.
%
% cfg_util('setdef', mod_cfg_id, item_mod_id, val)
%
% Like cfg_util('setval',...) but set items in the defaults tree. This is
% only supported for cfg_leaf items, not for cfg_choice, cfg_repeat,
% cfg_branch items.
% Defaults only apply to new jobs, not to already configured ones.
%
% doc = cfg_util('showdoc', tagstr|cfg_id|(job_id, mod_job_id[, item_mod_id]))
%
% Return help text for specified item. Item can be either a tag string or
% a cfg_id in the default configuration tree, or a combination of job_id,
% mod_job_id and item_mod_id from the current job.
% The text returned will be a cell array of strings, each string
% containing one paragraph of the help text. In addition to the help
% text, hints about valid values, defaults etc. are displayed.
%
% doc = cfg_util('showdocwidth', handle|width, tagstr|cfg_id|(job_id, mod_job_id[, item_mod_id]))
%
% Same as cfg_util('showdoc', but use handle or width to determine the
% width of the returned strings.
%
% [mod_job_idlist, str, sts, dep sout] = cfg_util('showjob', job_id[, mod_job_idlist])
%
% Return information about the current job (or the part referenced by the
% input cell array mod_job_idlist). Output arguments
% * mod_job_idlist - cell list of module ids (same as input, if provided)
% * str - cell string of names of modules
% * sts - array of all set status of modules
% * dep - array of dependency status of modules
% * sout - array of output description structures
% Each module configuration may provide a callback function 'vout' that
% returns a struct describing module output variables. See 'cfg_exbranch'
% for details about this callback, output description and output structure.
% The module needs to be harvested before to make output_struct available.
% This information can be used by the calling application to construct a
% dependency object which can be passed as input to other modules. See
% 'cfg_dep' for details about dependency objects.
%
% [mod_cfg_id, item_mod_id] = cfg_util('tag2cfg_id', tagstr)
%
% Return a mod_cfg_id for the cfg_exbranch item that is the parent to the
% item in the configuration tree whose parents have tag names as in the
% dot-delimited tag string. item_mod_id is relative to the cfg_exbranch
% parent. If tag string matches a node above cfg_exbranch level, then
% item_mod_id will be invalid and mod_cfg_id will point to the specified
% node.
% Use cfg_util('ismod_cfg_id') and cfg_util('isitem_mod_id') to determine
% whether returned ids are valid or not.
% Tag strings should begin at the root level of an application configuration,
% not at the matlabbatch root level.
%
% mod_cfg_id = cfg_util('tag2mod_cfg_id', tagstr)
%
% Same as cfg_util('tag2cfg_id', tagstr), but it only returns a proper
% mod_cfg_id. If none of the tags in tagstr point to a cfg_exbranch, then
% mod_cfg_id will be invalid.
%
% The layout of the configuration tree and the types of configuration items
% have been kept compatible to a configuration system and job manager
% implementation in SPM5 (Statistical Parametric Mapping, Copyright (C)
% 2005 Wellcome Department of Imaging Neuroscience). This code has been
% completely rewritten based on an object oriented model of the
% configuration tree.
%
% 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_util.m 4252 2011-03-15 17:49:51Z volkmar $
rev = '$Rev: 4252 $';
%% Initialisation of cfg variables
% load persistent configuration data, initialise if necessary
% generic configuration structure
persistent c0;
% job specific configuration structure
% This will be initialised to a struct (array) with fields cj and
% id2subs. When initialising a new job, it will be appended to this
% array. Jobs in this array may be cleared by setting cj and id2subs to
% [].
% field cj:
% configuration tree of this job.
% field cjid2subs:
% cell array that maps ids to substructs into the configuration tree -
% ids do not change for a cfg_util life time, while the actual position
% of a module in cj may change due to adding/removing modules. This would
% also allow to reorder modules in cj without changing their id.
persistent jobs;
if isempty(c0) && ~strcmp(cmd,'initcfg')
% init, if not yet done
cfg_util('initcfg');
end
%% Callback switches
% evaluate commands
switch lower(cmd),
case 'addapp',
[c0 jobs] = local_addapp(c0, jobs, varargin{:});
case 'addtojob',
cjob = varargin{1};
mod_cfg_id = varargin{2};
if cfg_util('isjob_id', cjob) && cfg_util('ismod_cfg_id', mod_cfg_id)
[jobs(cjob), mod_job_id] = local_addtojob(jobs(cjob), mod_cfg_id);
varargout{1} = mod_job_id;
end
case 'compactjob',
cjob = varargin{1};
if cfg_util('isjob_id', cjob)
[jobs(cjob), n2oid] = local_compactjob(jobs(cjob));
varargout{1} = num2cell(1:numel(jobs(cjob).cjid2subs));
varargout{2} = n2oid;
end
case 'delfromjob',
cjob = varargin{1};
mod_job_id = varargin{2};
if cfg_util('ismod_job_id', cjob, mod_job_id)
jobs(cjob) = local_delfromjob(jobs(cjob), mod_job_id);
end
case 'deljob',
if cfg_util('isjob_id', varargin{1})
if varargin{1} == numel(jobs) && varargin{1} > 1
jobs = jobs(1:end-1);
else
jobs(varargin{1}).cj = c0;
jobs(varargin{1}).cjid2subs = {};
jobs(varargin{1}).cjrun = [];
jobs(varargin{1}).cjid2subsrun = {};
end
end
case 'dumpcfg'
%-Locate batch configs and copy them
apps = which('cfg_mlbatch_appcfg','-all');
appcfgs = cell(size(apps));
p = fileparts(mfilename('fullpath'));
for k = 1:numel(apps)
appcfgs{k} = fullfile(p,'private',sprintf('cfg_mlbatch_appcfg_%d.m',k));
copyfile(apps{k}, appcfgs{k});
end
cmaster = fullfile(p, 'private', 'cfg_mlbatch_appcfg_master.m');
fid = fopen(cmaster,'w');
fprintf(fid,'function cfg_mlbatch_appcfg_master\n');
for k = 1:numel(apps)
fprintf(fid,'[cfg, def] = cfg_mlbatch_appcfg_%d;\n', k);
fprintf(fid,'cfg_util(''addapp'', cfg, def);\n');
end
fclose(fid);
case 'filljob',
cjob = varargin{1};
if cfg_util('isjob_id', cjob)
try
jobs(cjob).cj = fillvals(jobs(cjob).cj, varargin(2:end), []);
sts = all_set(jobs(cjob).cj);
catch
sts = false;
end
else
sts = false;
end
varargout{1} = sts;
case 'filljobui',
cjob = varargin{1};
if cfg_util('isjob_id', cjob)
try
jobs(cjob).cj = fillvals(jobs(cjob).cj, varargin(3:end), varargin{2});
sts = all_set(jobs(cjob).cj);
catch
sts = false;
end
else
sts = false;
end
varargout{1} = sts;
case 'gencode',
fname = varargin{1};
cm = local_getcm(c0, varargin{2});
if nargin > 3
tropts = varargin{3};
else
% default for SPM5 menu structure
tropts = cfg_tropts(cfg_findspec, 1, 2, 0, Inf, true);
end
local_gencode(cm, fname, tropts);
case 'genscript',
cjob = varargin{1};
if cfg_util('isjob_id', cjob)
% Get information about job
[mod_job_idlist, str, sts, dep sout] = cfg_util('showjob', cjob);
opensel = find(~sts);
fspec = cfg_findspec({{'hidden',false}});
tropts = cfg_tropts({{'hidden','true'}},1,inf,1,inf,false);
oclass = cell(1,numel(opensel));
onames = cell(1,numel(opensel));
% List modules with open inputs
for cmind = 1:numel(opensel)
[item_mod_idlist, stop, contents] = cfg_util('listmod', cjob, mod_job_idlist{opensel(cmind)}, [], fspec, tropts, {'class','name','all_set_item'});
% module name is 1st in list
% collect classes and names of open inputs
oclass{cmind} = contents{1}(~[contents{3}{:}]);
onames{cmind} = cellfun(@(iname)sprintf([contents{2}{1} ': %s'],iname),contents{2}(~[contents{3}{:}]),'UniformOutput',false);
end
% Generate filenames, save job
scriptdir = char(varargin{2});
[un filename] = fileparts(varargin{3});
scriptfile = fullfile(scriptdir, [filename '.m']);
jobfile = {fullfile(scriptdir, [filename '_job.m'])};
cfg_util('savejob', cjob, char(jobfile));
% Prepare script code
oclass = [oclass{:}];
onames = [onames{:}];
% Document open inputs
script = {'% List of open inputs'};
for cmind = 1:numel(oclass)
script{end+1} = sprintf('%% %s - %s', onames{cmind}, oclass{cmind});
end
% Create script stub code
script{end+1} = 'nrun = X; % enter the number of runs here';
script = [script{:} gencode(jobfile)];
script{end+1} = 'jobs = repmat(jobfile, 1, nrun);';
script{end+1} = sprintf('inputs = cell(%d, nrun);', numel(oclass));
script{end+1} = 'for crun = 1:nrun';
for cmind = 1:numel(oclass)
script{end+1} = sprintf(' inputs{%d, crun} = MATLAB_CODE_TO_FILL_INPUT; %% %s - %s', cmind, onames{cmind}, oclass{cmind});
end
script{end+1} = 'end';
genscript_run = cfg_get_defaults('cfg_util.genscript_run');
if ~isempty(genscript_run) && subsasgn_check_funhandle(genscript_run)
[s1 cont] = feval(genscript_run);
script = [script(:); s1(:)];
else
cont = true;
end
if cont
script{end+1} = 'job_id = cfg_util(''initjob'', jobs);';
script{end+1} = 'sts = cfg_util(''filljob'', job_id, inputs{:});';
script{end+1} = 'if sts';
script{end+1} = ' cfg_util(''run'', job_id);';
script{end+1} = 'end';
script{end+1} = 'cfg_util(''deljob'', job_id);';
end
fid = fopen(scriptfile, 'wt');
fprintf(fid, '%s\n', script{:});
fclose(fid);
end
case 'getalloutputs',
cjob = varargin{1};
if cfg_util('isjob_id', cjob) && ~isempty(jobs(cjob).cjrun)
varargout{1} = cellfun(@(cid)subsref(jobs(cjob).cjrun, [cid substruct('.','jout')]), jobs(cjob).cjid2subsrun, 'UniformOutput',false);
else
varargout{1} = {};
end
case 'getallvoutputs',
if nargin == 2 && cfg_util('isjob_id', varargin{1})
cjob = varargin{1};
vmods = ~cellfun('isempty',jobs(cjob).cjid2subs); % Ignore deleted modules
varargout{1} = cellfun(@(cid)subsref(jobs(cjob).cj, [cid substruct('.','sout')]), jobs(cjob).cjid2subs(vmods), 'UniformOutput',false);
elseif nargin > 2 && cfg_util('ismod_job_id',varargin{1},varargin{2})
cjob = varargin{1};
cmod = varargin{2};
varargout{1} = {subsref(jobs(cjob).cj, [jobs(cjob).cjid2subs{cmod} substruct('.','sout')])};
else
varargout{1} = {};
end
case 'harvest',
tag = '';
val = [];
cjob = varargin{1};
if nargin == 2
if cfg_util('isjob_id', cjob)
% harvest entire job
% do not resolve dependencies
cj1 = local_compactjob(jobs(cjob));
[tag val] = harvest(cj1.cj, cj1.cj, false, false);
end
else
mod_job_id = varargin{2};
if cfg_util('ismod_job_id', cjob, mod_job_id)
[tag val u3 u4 u5 jobs(cjob).cj] = harvest(subsref(jobs(cjob).cj, ...
jobs(cjob).cjid2subs{mod_job_id}), ...
jobs(cjob).cj, ...
false, true);
end
end
varargout{1} = tag;
varargout{2} = val;
case 'harvestdef',
if nargin == 1
% harvest all applications
cm = c0;
else
cm = local_getcm(c0, varargin{1});
end
[tag defval] = harvest(cm, cm, true, false);
varargout{1} = tag;
varargout{2} = defval;
case 'harvestrun',
tag = '';
val = [];
cjob = varargin{1};
if cfg_util('isjob_id', cjob) && ~isempty(jobs(cjob).cjrun)
[tag val] = harvest(jobs(cjob).cjrun, jobs(cjob).cjrun, false, ...
true);
end
varargout{1} = tag;
varargout{2} = val;
case 'initcfg',
[c0 jobs cjob] = local_initcfg;
local_initapps;
case 'initdef',
[cm id] = local_getcm(c0, varargin{1});
cm = local_initdef(cm, varargin{2});
c0 = subsasgn(c0, id{1}, cm);
case 'initjob'
if isempty(jobs(end).cjid2subs)
cjob = numel(jobs);
else
cjob = numel(jobs)+1;
end
if nargin == 1
jobs(cjob).c0 = c0;
jobs(cjob).cj = jobs(cjob).c0;
jobs(cjob).cjid2subs = {};
jobs(cjob).cjrun = [];
jobs(cjob).cjid2subsrun = {};
varargout{1} = cjob;
varargout{2} = {};
return;
elseif ischar(varargin{1}) || iscellstr(varargin{1})
[job jobdedup] = cfg_load_jobs(varargin{1});
elseif iscell(varargin{1}) && iscell(varargin{1}{1})
% try to initialise cell array of jobs
job = varargin{1};
jobdedup = NaN; % Postpone duplicate detection
else
% try to initialise single job
job{1} = varargin{1};
jobdedup = 1;
end
% job should be a cell array of job structures
isjob = true(size(job));
for k = 1:numel(job)
isjob(k) = iscell(job{k}) && all(cellfun('isclass', job{k}, 'struct'));
end
job = job(isjob);
if isempty(job)
cfg_message('matlabbatch:initialise:invalid','No valid job.');
else
if any(isnan(jobdedup))
% build up list of unique jobs
jobdedup = NaN*ones(size(job));
cu = 0;
for k = 1:numel(job)
if isnan(jobdedup(k))
% found new candidate
cu = cu+1;
jobdedup(k) = cu;
% look for similar jobs under remaining candidates
csel = find(isnan(jobdedup));
eqind = cellfun(@(cjob)isequalwithequalnans(cjob,job{k}),job(csel));
jobdedup(csel(eqind)) = cu;
end
end
else
jobdedup = jobdedup(isjob);
end
jobs(cjob).c0 = c0;
[jobs(cjob) mod_job_idlist] = local_initjob(jobs(cjob), job, jobdedup);
varargout{1} = cjob;
varargout{2} = mod_job_idlist;
end
case 'isitem_mod_id'
varargout{1} = isempty(varargin{1}) || ...
(isstruct(varargin{1}) && ...
all(isfield(varargin{1}, {'type','subs'})));
case 'isjob_id'
varargout{1} = ~isempty(varargin{1}) && ...
isnumeric(varargin{1}) && ...
varargin{1} <= numel(jobs) ...
&& (~isempty(jobs(varargin{1}).cjid2subs) ...
|| varargin{1} == numel(jobs));
case 'ismod_cfg_id'
varargout{1} = isstruct(varargin{1}) && ...
all(isfield(varargin{1}, {'type','subs'}));
case 'ismod_job_id'
varargout{1} = cfg_util('isjob_id', varargin{1}) && ...
isnumeric(varargin{2}) && ...
varargin{2} <= numel(jobs(varargin{1}).cjid2subs) ...
&& ~isempty(jobs(varargin{1}).cjid2subs{varargin{2}});
case {'listcfg','listcfgall'}
% could deal with hidden/modality fields here
if strcmpi(cmd(end-2:end), 'all')
exspec = cfg_findspec({});
else
exspec = cfg_findspec({{'class','cfg_exbranch'}});
end
% Stop traversal at hidden flag
% If user input find_spec contains {'hidden',false}, then a hidden
% node will not match and will not be listed. If a hidden node
% matches, it will return with a stop-flag set.
tropts = cfg_tropts({{'class','cfg_exbranch','hidden',true}}, 1, Inf, 0, Inf, true);
% Find start node
if isempty(varargin{1})
cs = c0;
sid = [];
else
cs = subsref(c0, varargin{1});
sid = varargin{1};
end
if nargin < 4
[id stop] = list(cs, [varargin{2} exspec], tropts);
for k=1:numel(id)
id{k} = [sid id{k}];
end
varargout{1} = id;
varargout{2} = stop;
else
[id stop val] = list(cs, [varargin{2} exspec], tropts, varargin{3});
for k=1:numel(id)
id{k} = [sid id{k}];
end
varargout{1} = id;
varargout{2} = stop;
varargout{3} = val;
end
case 'listmod'
if cfg_util('ismod_job_id', varargin{1}, varargin{2}) && ...
cfg_util('isitem_mod_id', varargin{3})
cjob = varargin{1};
mod_job_id = varargin{2};
item_mod_id = varargin{3};
nids = 3;
if isempty(item_mod_id)
cm = subsref(jobs(cjob).cj, jobs(cjob).cjid2subs{mod_job_id});
else
cm = subsref(jobs(cjob).cj, [jobs(cjob).cjid2subs{mod_job_id} item_mod_id]);
end
elseif cfg_util('ismod_cfg_id', varargin{1}) && ...
cfg_util('isitem_mod_id', varargin{2})
mod_cfg_id = varargin{1};
item_mod_id = varargin{2};
nids = 2;
if isempty(varargin{2})
cm = subsref(c0, mod_cfg_id);
else
cm = subsref(c0, [mod_cfg_id item_mod_id]);
end
end
findspec = varargin{nids+1};
if (nargin > nids+2 && isstruct(varargin{nids+2})) || nargin > nids+3
tropts = varargin{nids+2};
else
tropts = cfg_tropts({{'hidden',true}}, 1, Inf, 0, Inf, false);
end
if (nargin > nids+2 && iscellstr(varargin{nids+2}))
fn = varargin{nids+2};
elseif nargin > nids+3
fn = varargin{nids+3};
else
fn = {};
end
if isempty(fn)
[id stop] = list(cm, findspec, tropts);
varargout{1} = id;
varargout{2} = stop;
else
[id stop val] = list(cm, findspec, tropts, fn);
varargout{1} = id;
varargout{2} = stop;
varargout{3} = val;
end
case 'match'
res = {};
cjob = varargin{1};
mod_job_id = varargin{2};
item_mod_id = varargin{3};
if cfg_util('ismod_job_id', cjob, mod_job_id) && ...
cfg_util('isitem_mod_id', item_mod_id)
if isempty(item_mod_id)
cm = subsref(jobs(cjob).cj, jobs(cjob).cjid2subs{mod_job_id});
else
cm = subsref(jobs(cjob).cj, [jobs(cjob).cjid2subs{mod_job_id} item_mod_id]);
end
res = match(cm, varargin{4});
end
varargout{1} = res;
case 'replicate'
cjob = varargin{1};
mod_job_id = varargin{2};
if cfg_util('ismod_job_id', cjob, mod_job_id)
if nargin == 3
% replicate module
[jobs(cjob) id] = local_replmod(jobs(cjob), mod_job_id);
elseif nargin == 5 && ~isempty(varargin{3}) && ...
cfg_util('isitem_mod_id', varargin{3})
% replicate val entry of cfg_repeat, use setval with sanity
% check
cm = subsref(jobs(cjob).cj, [jobs(cjob).cjid2subs{mod_job_id}, varargin{3}]);
if isa(cm, 'cfg_repeat')
cm = setval(cm, varargin{4}, false);
jobs(cjob).cj = subsasgn(jobs(cjob).cj, ...
[jobs(cjob).cjid2subs{mod_job_id}, ...
varargin{3}], cm);
end
end
% clear run configuration
jobs(cjob).cjrun = [];
jobs(cjob).cjid2subsrun = {};
end
case {'run','runserial','cont','contserial'}
if cfg_util('isjob_id',varargin{1})
cjob = varargin{1};
dflag = false;
else
cjob = cfg_util('initjob',varargin{1});
dflag = true;
end
pflag = any(strcmpi(cmd, {'run','cont'})) && cfg_get_defaults([mfilename '.runparallel']);
cflag = any(strcmpi(cmd, {'cont','contserial'}));
[jobs(cjob) err] = local_runcj(jobs(cjob), cjob, pflag, cflag);
if dflag
cfg_util('deljob', cjob);
end
if ~isempty(err)
cfg_message(err);
end
case {'savejob','savejobrun'}
cjob = varargin{1};
if strcmpi(cmd,'savejob')
[tag matlabbatch] = cfg_util('harvest', cjob);
else
[tag matlabbatch] = cfg_util('harvestrun', cjob);
end
if isempty(tag)
cfg_message('matlabbatch:cfg_util:savejob:nojob', ...
'Nothing to save for job #%d', cjob);
else
[p n e] = fileparts(varargin{2});
switch lower(e)
case '.mat',
save(varargin{2},'matlabbatch','-v6');
case '.m'
jobstr = gencode(matlabbatch, tag);
fid = fopen(fullfile(p, [n '.m']), 'wt');
fprintf(fid, '%%-----------------------------------------------------------------------\n');
fprintf(fid, '%% Job configuration created by %s (rev %s)\n', mfilename, rev);
fprintf(fid, '%%-----------------------------------------------------------------------\n');
fprintf(fid, '%s\n', jobstr{:});
fclose(fid);
otherwise
cfg_message('matlabbatch:cfg_util:savejob:unknown', 'Unknown file format for %s.', varargin{2});
end
end
case 'setdef',
% Set defaults for new jobs only
cm = subsref(c0, [varargin{1}, varargin{2}]);
cm = setval(cm, varargin{3}, true);
c0 = subsasgn(c0, [varargin{1}, varargin{2}], cm);
case 'setval',
cjob = varargin{1};
mod_job_id = varargin{2};
item_mod_id = varargin{3};
if cfg_util('ismod_job_id', cjob, mod_job_id) && ...
cfg_util('isitem_mod_id', item_mod_id)
cm = subsref(jobs(cjob).cj, [jobs(cjob).cjid2subs{mod_job_id}, item_mod_id]);
cm = setval(cm, varargin{4}, false);
jobs(cjob).cj = subsasgn(jobs(cjob).cj, [jobs(cjob).cjid2subs{mod_job_id}, item_mod_id], cm);
varargout{1} = all_set_item(cm);
% clear run configuration
jobs(cjob).cjrun = [];
jobs(cjob).cjid2subsrun = {};
end
case 'showdoc',
if nargin == 2
% get item from defaults tree
cm = local_getcm(c0, varargin{1});
elseif nargin >= 3
% get item from job
cm = local_getcmjob(jobs, varargin{:});
end
varargout{1} = showdoc(cm,'');
case 'showdocwidth',
if nargin == 3
% get item from defaults tree
cm = local_getcm(c0, varargin{2});
elseif nargin >= 4
% get item from job
cm = local_getcmjob(jobs, varargin{2:end});
end
varargout{1} = cfg_justify(varargin{1}, showdoc(cm,''));
case 'showjob',
cjob = varargin{1};
if cfg_util('isjob_id', cjob)
if nargin > 2
mod_job_ids = varargin{2};
[unused str sts dep sout] = local_showjob(jobs(cjob).cj, ...
subsref(jobs(cjob).cjid2subs, ...
substruct('{}', mod_job_ids)));
else
[id str sts dep sout] = local_showjob(jobs(cjob).cj, jobs(cjob).cjid2subs);
end
varargout{1} = id;
varargout{2} = str;
varargout{3} = sts;
varargout{4} = dep;
varargout{5} = sout;
else
varargout = {{}, {}, [], [], {}};
end
case 'tag2cfg_id',
[mod_cfg_id item_mod_id] = local_tag2cfg_id(c0, varargin{1}, ...
true);
if iscell(mod_cfg_id)
% don't force mod_cfg_id to point to cfg_exbranch
mod_cfg_id = local_tag2cfg_id(c0, varargin{1}, false);
end
varargout{1} = mod_cfg_id;
varargout{2} = item_mod_id;
case 'tag2mod_cfg_id',
varargout{1} = local_tag2cfg_id(c0, varargin{1}, true);
otherwise
cfg_message('matlabbatch:usage', '%s: Unknown command ''%s''.', mfilename, cmd);
end
return;
%% Local functions
% These are the internal implementations of commands.
%-----------------------------------------------------------------------
%-----------------------------------------------------------------------
function [c0, jobs] = local_addapp(c0, jobs, cfg, varargin)
% Add configuration data to c0 and all jobs
% Input
% * cfg - Function name, function handle or cfg_item tree. If a
% function is passed, this will be evaluated with no arguments and
% must return a single configuration tree.
% * def - Optional. Function name, function handle or defaults struct/cell.
% This function should return a job struct suitable to initialise
% the defaults branches of the cfg tree.
% If def is empty or does not exist, no defaults will be added.
if isempty(cfg)
% Gracefully return if there is nothing to do
return;
end
if subsasgn_check_funhandle(cfg)
cvstate = cfg_get_defaults('cfg_item.checkval');
cfg_get_defaults('cfg_item.checkval',true);
c1 = feval(cfg);
cfg_get_defaults('cfg_item.checkval',cvstate);
elseif isa(cfg, 'cfg_item')
c1 = cfg;
end
if ~isa(c1, 'cfg_item')
cfg_message('matlabbatch:cfg_util:addapp:inv',...
'Invalid configuration');
return;
end
dpind = cellfun(@(c0item)strcmp(c1.tag, c0item.tag), c0.values);
if any(dpind)
dpind = find(dpind);
cfg_message('matlabbatch:cfg_util:addapp:dup',...
'Duplicate application tag in applications ''%s'' and ''%s''.', ...
c1.name, c0.values{dpind(1)}.name);
return;
end
if nargin > 3 && ~isempty(varargin{1})
c1 = local_initdef(c1, varargin{1});
end
c0.values{end+1} = c1;
for k = 1:numel(jobs)
jobs(k).cj.values{end+1} = c1;
jobs(k).c0.values{end+1} = c1;
% clear run configuration
jobs(k).cjrun = [];
jobs(k).cjid2subsrun = {};
end
cfg_message('matlabbatch:cfg_util:addapp:done', 'Added application ''%s''\n', c1.name);
%-----------------------------------------------------------------------
%-----------------------------------------------------------------------
function [job, id] = local_addtojob(job, c0subs)
% Add module subsref(c0, c0subs) to job.cj, append its subscript to
% job.cjid2subs and return the index into job.cjid2subs to the caller.
% The module will be added in a 'degenerated' branch of a cfg tree, where
% it is the only exbranch that can be reached on the 'val' path.
id = numel(job.cj.val)+1;
cjsubs = c0subs;
for k = 1:2:numel(cjsubs)
% assume subs is [.val(ues){X}]+ and there are only choice/repeats
% above exbranches
% replace values{X} with val{1} in '.' references
if strcmp(cjsubs(k).subs, 'values')
cjsubs(k).subs = 'val';
if k == 1
% set id in cjsubs(2)
cjsubs(k+1).subs = {id};
else
cjsubs(k+1).subs = {1};
end
end
cm = subsref(job.c0, c0subs(1:(k+1)));
if k == numel(cjsubs)-1
% initialise dynamic defaults - not only in defaults tree, but
% also in pre-configured .val items.
cm = initialise(cm, '<DEFAULTS>', false);
end
% add path to module to cj
job.cj = subsasgn(job.cj, cjsubs(1:(k+1)), cm);
end
% set id in module
job.cj = subsasgn(job.cj, [cjsubs substruct('.', 'id')], cjsubs);
job.cjid2subs{id} = cjsubs;
% clear run configuration
job.cjrun = [];
job.cjid2subsrun = {};
%-----------------------------------------------------------------------
%-----------------------------------------------------------------------
function varargout = local_cd(pth)
% Try to work around some unexpected behaviour of MATLAB's cd command
if ~isempty(pth)
if ischar(pth)
wd = pwd;
cd(pth);
else
cfg_message('matlabbatch:usage','CD: path must be a string.');
end
else
% Do not cd if pth is empty.
wd = pwd;
end
if nargout > 0
varargout{1} = wd;
end
%-----------------------------------------------------------------------
%-----------------------------------------------------------------------
function [job, n2oid] = local_compactjob(ojob)
% Remove placeholders from cj and recursively update dependencies to fit
% new ids. Warning: this will invalidate mod_job_ids!
job = ojob;
job.cj.val = {};
job.cjid2subs = {};
oid = cell(size(ojob.cjid2subs));
n2oid = NaN*ones(size(ojob.cjid2subs));
nid = 1;
for k = 1:numel(ojob.cjid2subs)
if ~isempty(ojob.cjid2subs{k})
cjsubs = ojob.cjid2subs{k};
oid{nid} = ojob.cjid2subs{k};
cjsubs(2).subs = {nid};
job.cjid2subs{nid} = cjsubs;
for l = 1:2:numel(cjsubs)
% subs is [.val(ues){X}]+
% add path to module to cj
job.cj = subsasgn(job.cj, job.cjid2subs{nid}(1:(l+1)), ...
subsref(ojob.cj, ojob.cjid2subs{k}(1:(l+1))));
end
n2oid(nid) = k;
nid = nid + 1;
end
end
oid = oid(1:(nid-1));
n2oid = n2oid(1:(nid-1));
% update changed ids in job (where n2oid ~= 1:numel(n2oid))
cid = n2oid ~= 1:numel(n2oid);
if any(cid)
job.cj = update_deps(job.cj, oid(cid), job.cjid2subs(cid));
end
% clear run configuration
job.cjrun = [];
job.cjid2subsrun = {};
%-----------------------------------------------------------------------
%-----------------------------------------------------------------------
function job = local_delfromjob(job, id)
% Remove module subsref(job.cj, job.cjid2subs{id}) from job.cj. All
% target and source dependencies between the module and other modules in
% job.cj are removed. Corresponding entries in job.cj and job.cjid2subs
% are set to {} in order to keep relationships within the tree consistent
% and in order to keep other ids valid. A rebuild of job.cj and an update
% of changed subsrefs would be possible (and needs to be done before
% e.g. saving the job).
if isempty(job.cjid2subs) || isempty(job.cjid2subs{id}) || numel(job.cjid2subs) < id
cfg_message('matlabbatch:cfg_util:invid', ...
'Invalid id %d.', id);
return;
end
cm = subsref(job.cj, job.cjid2subs{id});
if ~isempty(cm.tdeps)
job.cj = del_in_source(cm.tdeps, job.cj);
end
if ~isempty(cm.sdeps)
job.cj = del_in_target(cm.sdeps, job.cj);
end
% replace module with placeholder
cp = cfg_const;
cp.tag = 'deleted_item';
cp.val = {''};
cp.hidden = true;
% replace deleted module at top level, not at branch level
job.cj = subsasgn(job.cj, job.cjid2subs{id}(1:2), cp);
job.cjid2subs{id} = struct([]);
% clear run configuration
job.cjrun = [];
job.cjid2subsrun = {};
%-----------------------------------------------------------------------
%-----------------------------------------------------------------------
function local_gencode(c0, fname, tropts, preamble)
% Generate code, split at nodes matching stopspec (if stopspec is not
% empty). fname will be overwritten if tropts is empty (i.e. for single
% file output or subtrees). Note that some manual fixes may be required
% (function handles, variable/function names).
% If a preamble is passed as cellstr, it will be prepended to each
% generated file after the function... line. If no preamble is specified and
% a file <fname>_mlb_preamble.m exists in the folder where the
% configuration is being written, this file will be read and included
% literally.
if isempty(tropts)||isequal(tropts,cfg_tropts({{}},1,Inf,1,Inf,true)) || ...
isequal(tropts, cfg_tropts({{}},1,Inf,1,Inf,false))
tropts(1).clvl = 1;
tropts(1).mlvl = Inf;
tropts(1).cnt = 1;
[p funcname e] = fileparts(fname);
[cstr tag] = gencode_item(c0, '', {}, [funcname '_'], tropts);
funcname = [funcname '_' tag];
fname = fullfile(p, [funcname '.m']);
unpostfix = '';
while exist(fname, 'file')
cfg_message('matlabbatch:cfg_util:gencode:fileexist', ...
['While generating code for cfg_item: ''%s'', %s. File ' ...
'''%s'' already exists. Trying new filename - you will ' ...
'need to adjust generated code.'], ...
c0.name, tag, fname);
unpostfix = [unpostfix '1'];
fname = fullfile(p, [funcname unpostfix '.m']);
end
fid = fopen(fname, 'wt');
fprintf(fid, 'function %s = %s\n', tag, funcname);
fprintf(fid, '%s\n', preamble{:});
fprintf(fid, '%s\n', cstr{:});
fclose(fid);
else
% generate root level code
[p funcname e] = fileparts(fname);
[cstr tag] = gencode_item(c0, 'jobs', {}, [funcname '_'], tropts);
fname = fullfile(p, [funcname '.m']);
if nargin < 4 || isempty(preamble) || ~iscellstr(preamble)
try
fid = fopen(fullfile(p, [funcname '_mlb_preamble.m']),'r');
ptmp = textscan(fid,'%s','Delimiter',sprintf('\n'));
fclose(fid);
preamble = ptmp{1};
catch
preamble = {};
end
end
fid = fopen(fname, 'wt');
fprintf(fid, 'function %s = %s\n', tag, funcname);
fprintf(fid, '%s\n', preamble{:});
fprintf(fid, '%s\n', cstr{:});
fclose(fid);
% generate subtree code - find nodes one level below stop spec
tropts.mlvl = tropts.mlvl+1;
[ids stop] = list(c0, tropts.stopspec, tropts);
ids = ids(stop); % generate code for stop items only
ctropts = cfg_tropts({{}},1,Inf,1,Inf,tropts.dflag);
for k = 1:numel(ids)
if ~isempty(ids{k}) % don't generate root level code again
local_gencode(subsref(c0, ids{k}), fname, ctropts, preamble);
end
end
end
%-----------------------------------------------------------------------
%-----------------------------------------------------------------------
function [cj, cjid2subs] = local_getcjid2subs(cjin)
% Find ids of exbranches.
% find ids
exspec = cfg_findspec({{'class', 'cfg_exbranch'}});
tropts = cfg_tropts({{'class', 'cfg_exbranch'}}, 1, Inf, 0, Inf, false);
cjid2subsin = list(cjin, exspec, tropts);
cjid2subs = cjid2subsin;
cj = cjin;
cancjid2subs = false(size(cjid2subsin));
for k = 1:numel(cjid2subs)
% assume 1-D subscripts into val, and there should be at least one
tmpsubs = [cjid2subs{k}(2:2:end).subs];
cancjid2subs(k) = all(cellfun(@(cs)isequal(cs,1), tmpsubs(2:end)));
end
if all(cancjid2subs)
idsubs = substruct('.', 'id');
for k = 1:numel(cjid2subs)
cj = subsasgn(cj, [cjid2subs{k} idsubs], ...
cjid2subs{k});
end
else
cj.val = cell(size(cjid2subs));
idsubs = substruct('.', 'id');
for k = 1:numel(cjid2subs)
if cancjid2subs(k)
% add path to module to cj
cpath = subsref(cjin, cjid2subs{k}(1:2));
cpath = subsasgn(cpath, [cjid2subs{k}(3:end) ...
idsubs], cjid2subs{k});
cj = subsasgn(cj, cjid2subs{k}(1:2), cpath);
else
% canonicalise SPM5 batches to cj.val{X}.val{1}....val{1}
% This would break dependencies, but in SPM5 batches there should not be any
% assume subs is [.val{X}]+ and there are only choice/repeats
% above exbranches
for l = 2:2:numel(cjid2subs{k})
if l == 2
cjid2subs{k}(l).subs = {k};
else
cjid2subs{k}(l).subs = {1};
end
% add path to module to cj
cpath = subsref(cjin, cjid2subsin{k}(1:l));
% clear val field for nodes below exbranch
if l < numel(cjid2subs{k})
cpath.val = {};
else
cpath.id = cjid2subs{k};
end
cj = subsasgn(cj, cjid2subs{k}(1:l), cpath);
end
end
end
end
%-----------------------------------------------------------------------
%-----------------------------------------------------------------------
function [cm, cfg_id] = local_getcm(c0, cfg_id)
if cfg_util('ismod_cfg_id', cfg_id)
% This should better test something like 'iscfg_id'
% do nothing
else
[mod_cfg_id, item_mod_id] = cfg_util('tag2cfg_id', cfg_id);
if isempty(mod_cfg_id)
cfg_message('matlabbatch:cfg_util:invid', ...
'Item with tag ''%s'' not found.', cfg_id);
else
cfg_id = [mod_cfg_id, item_mod_id];
cm = subsref(c0, cfg_id);
end
end
%-----------------------------------------------------------------------
%-----------------------------------------------------------------------
function cm = local_getcmjob(jobs, job_id, mod_job_id, item_mod_id)
if nargin < 4
item_mod_id = struct('subs',{},'type',{});
end
if cfg_util('isjob_id', job_id) && cfg_util('ismod_job_id', mod_job_id) ...
&& cfg_util('isitem_mod_id', item_mod_id)
cm = subsref(jobs(job_id).cj, ...
[jobs(job_id).cjid2subs{mod_job_id} item_mod_id]);
else
cfg_message('matlabbatch:cfg_util:invid', ...
'Item not found.');
end
%-----------------------------------------------------------------------
%-----------------------------------------------------------------------
function local_initapps
% add application data
if isdeployed
cfg_mlbatch_appcfg_master;
else
appcfgs = which('cfg_mlbatch_appcfg','-all');
cwd = pwd;
dirs = cell(size(appcfgs));
for k = 1:numel(appcfgs)
% cd into directory containing config file
[p n e] = fileparts(appcfgs{k});
local_cd(p);
% try to work around MATLAB bug in symlink handling
% only add application if this directory has not been visited yet
dirs{k} = pwd;
if ~any(strcmp(dirs{k}, dirs(1:k-1)))
try
[cfg def] = feval('cfg_mlbatch_appcfg');
ests = true;
catch
ests = false;
estr = cfg_disp_error(lasterror);
cfg_message('matlabbatch:cfg_util:eval_appcfg', ...
'Failed to load %s', which('cfg_mlbatch_appcfg'));
cfg_message('matlabbatch:cfg_util:eval_appcfg', '%s\n', estr{:});
end
if ests
cfg_util('addapp', cfg, def);
end
end
end
local_cd(cwd);
end
%-----------------------------------------------------------------------
%-----------------------------------------------------------------------
function [c0, jobs, cjob] = local_initcfg
% initial config
c0 = cfg_mlbatch_root;
cjob = 1;
jobs(cjob).cj = c0;
jobs(cjob).c0 = c0;
jobs(cjob).cjid2subs = {};
jobs(cjob).cjrun = [];
jobs(cjob).cjid2subsrun = {};
%-----------------------------------------------------------------------
%-----------------------------------------------------------------------
function c1 = local_initdef(c1, varargin)
if nargin > 1
defspec = varargin{1};
if subsasgn_check_funhandle(defspec)
opwd = pwd;
if ischar(defspec)
[p fn e] = fileparts(defspec);
local_cd(p);
defspec = fn;
end
def = feval(defspec);
local_cd(opwd);
elseif isa(defspec, 'cell') || isa(defspec, 'struct')
def = defspec;
else
def = [];
end
if ~isempty(def)
c1 = initialise(c1, def, true);
end
end
%-----------------------------------------------------------------------
%-----------------------------------------------------------------------
function [cjob, mod_job_idlist] = local_initjob(cjob, job, jobdedup)
% Initialise a cell array of jobs
idsubs = substruct('.','id');
sdsubs = substruct('.','sdeps');
tdsubs = substruct('.','tdeps');
v1subs = substruct('.','val','{}',{1});
% Update application defaults - not only in .values, but also in
% pre-configured .val items. Use this as template for all jobs.
cjd = initialise(cjob.c0, '<DEFAULTS>', false);
% Prepare all jobs - initialise similar jobs only once.
[ujobdedup ui uj] = unique(jobdedup);
% Initialise jobs
ucj = cellfun(@(ucjob)initialise(cjd,ucjob,false), job(ui), 'UniformOutput', false);
% Canonicalise (this may break dependencies, see comment in
% local_getcjid2subs)
[ucj ucjid2subs] = cellfun(@local_getcjid2subs, ucj, 'UniformOutput', false);
% Harvest, keeping dependencies
[u1 u2 u3 u4 u5 ucj] = cellfun(@(cucj)harvest(cucj, cucj, false, false), ucj, 'UniformOutput', false);
% Deduplicate, concatenate
cjob.cj = ucj{uj(1)};
cjob.cjid2subs = ucjid2subs{uj(1)};
for n = 2:numel(uj)
cjidoffset = numel(cjob.cjid2subs);
cj1 = ucj{uj(n)};
cjid2subs1 = ucjid2subs{uj(n)};
cjid2subs2 = ucjid2subs{uj(n)};
for k = 1:numel(cjid2subs2)
% update id subscripts
cjid2subs2{k}(2).subs{1} = cjid2subs2{k}(2).subs{1} + cjidoffset;
cj1 = subsasgn(cj1, [cjid2subs1{k}, idsubs], ...
cjid2subs2{k});
% update src_exbranch in dependent cfg_items
sdeps = subsref(cj1, [cjid2subs1{k}, sdsubs]);
for l = 1:numel(sdeps)
csdep = sdeps(l);
tgt_exbranch = csdep.tgt_exbranch;
tgt_input = [csdep.tgt_input v1subs];
% dependencies in dependent item
ideps = subsref(cj1, [tgt_exbranch tgt_input]);
isel = cellfun(@(iid)isequal(iid,cjid2subs1{k}),{ideps.src_exbranch});
ideps(isel).src_exbranch = cjid2subs2{k};
% save updated item & module
cj1 = subsasgn(cj1, [tgt_exbranch tgt_input], ...
ideps);
% delete old tdeps - needs to be updated by harvest
cj1 = subsasgn(cj1, [tgt_exbranch tdsubs], []);
end
% done with sdeps - clear
cj1 = subsasgn(cj1, [cjid2subs1{k}, sdsubs], []);
end
% concatenate configs
cjob.cjid2subs = [cjob.cjid2subs cjid2subs2];
cjob.cj.val = [cjob.cj.val cj1.val];
end
% harvest, update dependencies
[u1 u2 u3 u4 u5 cjob.cj] = harvest(cjob.cj, cjob.cj, false, false);
mod_job_idlist = num2cell(1:numel(cjob.cjid2subs));
% add field to keep run results from job
cjob.cjrun = [];
cjob.cjid2subsrun = {};
%-----------------------------------------------------------------------
%-----------------------------------------------------------------------
function [job, id] = local_replmod(job, oid)
% Replicate module subsref(job.cj,job.cjid2subs{oid}) by adding it to the end of
% the job list. Update id in module and delete links to dependent modules,
% these dependencies are the ones of the original module, not of the
% replica.
id = numel(job.cj.val)+1;
% subsref of original module
ocjsubs = job.cjid2subs{oid};
% subsref of replica module
rcjsubs = ocjsubs;
rcjsubs(2).subs = {id};
for k = 1:2:numel(ocjsubs)
% Add path to replica module, copying items from original path
job.cj = subsasgn(job.cj, rcjsubs(1:(k+1)), subsref(job.cj, ocjsubs(1:(k+1))));
end
% set id in module, delete copied sdeps and tdeps
job.cj = subsasgn(job.cj, [rcjsubs substruct('.', 'id')], rcjsubs);
job.cj = subsasgn(job.cj, [rcjsubs substruct('.', 'sdeps')], []);
job.cj = subsasgn(job.cj, [rcjsubs substruct('.', 'tdeps')], []);
% re-harvest to update tdeps and outputs
[u1 u2 u3 u4 u5 job.cj] = harvest(subsref(job.cj, rcjsubs), job.cj, false, false);
job.cjid2subs{id} = rcjsubs;
% clear run configuration
job.cjrun = [];
job.cjid2subsrun = {};
%-----------------------------------------------------------------------
%-----------------------------------------------------------------------
function [job err] = local_runcj(job, cjob, pflag, cflag)
% Matlab uses a copy-on-write policy with very high granularity - if
% modified, only parts of a struct or cell array are copied.
% However, forward resolution may lead to high memory consumption if
% variables are passed, but avoids extra housekeeping for outputs and
% resolved dependencies.
% Here, backward resolution is used. This may be time consuming for large
% jobs with many dependencies, because dependencies of any cfg_item are
% resolved only if all of them are resolvable (i.e. there can't be a mix of
% values and dependencies in a .val field).
% If pflag is true, then modules will be executed in parallel if they are
% independent. Setting pflag to false forces serial execution of modules
% even if they seem to be independent.
% If cflag is true, and a job with pre-set module outputs .jout is passed
% in job.cjrun, the corresponding modules will not be run again.
cfg_message('matlabbatch:run:jobstart', ...
['\n\n------------------------------------------------------------------------\n',...
'Running job #%d\n', ...
'------------------------------------------------------------------------'], cjob);
if cflag && ~isempty(job.cjrun)
[u1 mlbch] = harvest(job.cjrun, job.cjrun, false, true);
else
job1 = local_compactjob(job);
job.cjid2subsrun = job1.cjid2subs;
[u1 mlbch u3 u4 u5 job.cjrun] = harvest(job1.cj, job1.cj, false, true);
end
% copy cjid2subs, it will be modified for each module that is run
cjid2subs = job.cjid2subsrun;
cjid2subsfailed = {};
cjid2subsskipped = {};
tdsubs = substruct('.','tdeps');
chsubs = substruct('.','chk');
while ~isempty(cjid2subs)
% find mlbch that can run
cand = false(size(cjid2subs));
if pflag
% Check dependencies of all remaining mlbch
maxcand = numel(cjid2subs);
else
% Check dependencies of first remaining job only
maxcand = min(1, numel(cjid2subs));
end
for k = 1:maxcand
cand(k) = isempty(subsref(job.cjrun, [cjid2subs{k} tdsubs])) ...
&& subsref(job.cjrun, [cjid2subs{k} chsubs]) ...
&& all_set(subsref(job.cjrun, cjid2subs{k}));
end
if ~any(cand)
cfg_message('matlabbatch:run:nomods', ...
'No executable modules, but still unresolved dependencies or incomplete module inputs.');
cjid2subsskipped = cjid2subs;
break;
end
% split job list
cjid2subsrun = cjid2subs(cand);
cjid2subs = cjid2subs(~cand);
% collect sdeps of really running modules
csdeps = cell(size(cjid2subsrun));
% run modules that have all dependencies resolved
for k = 1:numel(cjid2subsrun)
cm = subsref(job.cjrun, cjid2subsrun{k});
if isa(cm.jout,'cfg_inv_out')
% no cached outputs (module did not run or it does not return
% outputs) - run job
cfg_message('matlabbatch:run:modstart', 'Running ''%s''', cm.name);
try
cm = cfg_run_cm(cm, subsref(mlbch, cfg2jobsubs(job.cjrun, cjid2subsrun{k})));
csdeps{k} = cm.sdeps;
cfg_message('matlabbatch:run:moddone', 'Done ''%s''', cm.name);
catch
cjid2subsfailed = [cjid2subsfailed cjid2subsrun(k)];
le = lasterror;
% try to filter out stack trace into matlabbatch
try
runind = find(strcmp('cfg_run_cm', {le.stack.name}));
le.stack = le.stack(1:runind-1);
end
str = cfg_disp_error(le);
cfg_message('matlabbatch:run:modfailed', 'Failed ''%s''', cm.name);
cfg_message('matlabbatch:run:modfailed', '%s\n', str{:});
end
% save results (if any) into job tree
job.cjrun = subsasgn(job.cjrun, cjid2subsrun{k}, cm);
else
% Use cached outputs
cfg_message('matlabbatch:run:cached', 'Using cached outputs for ''%s''', cm.name);
end
end
% update dependencies, re-harvest mlbch
tmp = [csdeps{:}];
if ~isempty(tmp)
ctgt_exbranch = {tmp.tgt_exbranch};
% assume job.cjrun.val{k}.val{1}... structure
ctgt_exbranch_id = zeros(size(ctgt_exbranch));
for k = 1:numel(ctgt_exbranch)
ctgt_exbranch_id(k) = ctgt_exbranch{k}(2).subs{1};
end
% harvest only targets and only once
[un ind] = unique(ctgt_exbranch_id);
for k = 1:numel(ind)
cm = subsref(job.cjrun, ctgt_exbranch{ind(k)});
[u1 cmlbch u3 u4 u5 job.cjrun] = harvest(cm, job.cjrun, false, ...
true);
mlbch = subsasgn(mlbch, cfg2jobsubs(job.cjrun, ctgt_exbranch{ind(k)}), ...
cmlbch);
end
end
end
if isempty(cjid2subsfailed) && isempty(cjid2subsskipped)
cfg_message('matlabbatch:run:jobdone', 'Done\n');
err = [];
else
str = cell(numel(cjid2subsfailed)+numel(cjid2subsskipped)+1,1);
str{1} = 'The following modules did not run:';
for k = 1:numel(cjid2subsfailed)
str{k+1} = sprintf('Failed: %s', subsref(job.cjrun, [cjid2subsfailed{k} substruct('.','name')]));
end
for k = 1:numel(cjid2subsskipped)
str{numel(cjid2subsfailed)+k+1} = sprintf('Skipped: %s', ...
subsref(job.cjrun, [cjid2subsskipped{k} substruct('.','name')]));
end
% Commented out for SPM public release
% str{end+1} = sprintf(['If the problem can be fixed without modifying ' ...
% 'the job, the computation can be resumed by ' ...
% 'running\n cfg_util(''cont'',%d)\nfrom the ' ...
% 'MATLAB command line.'],cjob);
cfg_message('matlabbatch:run:jobfailed', '%s\n', str{:});
err.identifier = 'matlabbatch:run:jobfailederr';
err.message = sprintf(['Job execution failed. The full log of this run can ' ...
'be found in MATLAB command window, starting with ' ...
'the lines (look for the line showing the exact ' ...
'#job as displayed in this error message)\n' ...
'------------------ \nRunning job #%d' ...
'\n------------------\n'], cjob);
err.stack = struct('file','','name','MATLABbatch system','line',0);
end
%-----------------------------------------------------------------------
%-----------------------------------------------------------------------
function [id, str, sts, dep, sout] = local_showjob(cj, cjid2subs)
% Return name, all_set status and id of internal job representation
id = cell(size(cjid2subs));
str = cell(size(cjid2subs));
sts = false(size(cjid2subs));
dep = false(size(cjid2subs));
sout = cell(size(cjid2subs));
cmod = 1; % current module count
for k = 1:numel(cjid2subs)
if ~isempty(cjid2subs{k})
cm = subsref(cj, cjid2subs{k});
id{cmod} = k;
str{cmod} = cm.name;
sts(cmod) = all_set(cm);
dep(cmod) = ~isempty(cm.tdeps);
sout{cmod} = cm.sout;
cmod = cmod + 1;
end
end
id = id(1:(cmod-1));
str = str(1:(cmod-1));
sts = sts(1:(cmod-1));
dep = dep(1:(cmod-1));
sout = sout(1:(cmod-1));
%-----------------------------------------------------------------------
%-----------------------------------------------------------------------
function [mod_cfg_id, item_mod_id] = local_tag2cfg_id(c0, tagstr, splitspec)
tags = textscan(tagstr, '%s', 'delimiter', '.');
taglist = tags{1};
if ~strcmp(taglist{1}, c0.tag)
% assume tag list starting at application level
taglist = [c0.tag taglist(:)'];
end
if splitspec
% split ids at cfg_exbranch level
finalspec = cfg_findspec({{'class','cfg_exbranch'}});
else
finalspec = {};
end
tropts=cfg_tropts({{'class','cfg_exbranch'}},0, inf, 0, inf, true);
[mod_cfg_id stop rtaglist] = tag2cfgsubs(c0, taglist, finalspec, tropts);
if iscell(mod_cfg_id)
item_mod_id = {};
return;
end
if isempty(rtaglist)
item_mod_id = struct('type',{}, 'subs',{});
else
% re-add tag of stopped node
taglist = [gettag(subsref(c0, mod_cfg_id)) rtaglist(:)'];
tropts.stopspec = {};
[item_mod_id stop rtaglist] = tag2cfgsubs(subsref(c0, mod_cfg_id), ...
taglist, {}, tropts);
end
|
github
|
philippboehmsturm/antx-master
|
cfg_load_jobs.m
|
.m
|
antx-master/xspm8/matlabbatch/cfg_load_jobs.m
| 1,970 |
utf_8
|
9737297b9817628afdf1fe120831a43c
|
function [newjobs uind] = cfg_load_jobs(job)
% function newjobs = cfg_load_jobs(job)
%
% Load a list of possible job files, return a cell list of jobs.
%
% 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_jobs.m 4073 2010-09-24 12:07:57Z volkmar $
rev = '$Rev: 4073 $'; %#ok
if ischar(job)
filenames = cellstr(job);
else
filenames = job;
end;
[ufilenames unused uind] = unique(filenames);
ujobs = cell(size(ufilenames));
usts = false(size(ufilenames));
for cf = 1:numel(ufilenames)
[ujobs{cf} usts(cf)] = load_single_job(ufilenames{cf});
end
sts = usts(uind);
uind = uind(sts);
newjobs = ujobs(uind);
function [matlabbatch sts] = load_single_job(filename)
[p,nam,ext] = fileparts(filename);
switch ext
case '.xml',
try
loadxml(filename,'matlabbatch');
catch
cfg_message('matlabbatch:initialise:xml','LoadXML failed: ''%s''',filename);
end;
case '.mat'
try
S=load(filename);
matlabbatch = S.matlabbatch;
catch
cfg_message('matlabbatch:initialise:mat','Load failed: ''%s''',filename);
end;
case '.m'
try
fid = fopen(filename,'rt');
str = fread(fid,'*char');
fclose(fid);
eval(str);
catch
cfg_message('matlabbatch:initialise:m','Eval failed: ''%s''',filename);
end;
if ~exist('matlabbatch','var')
cfg_message('matlabbatch:initialise:m','No matlabbatch job found in ''%s''', filename);
end;
otherwise
cfg_message('matlabbatch:initialise:unknown','Unknown extension: ''%s''', filename);
end;
if exist('matlabbatch','var')
sts = true;
else
sts = false;
matlabbatch = [];
end;
|
github
|
philippboehmsturm/antx-master
|
cfg_ui.m
|
.m
|
antx-master/xspm8/matlabbatch/cfg_ui.m
| 67,352 |
utf_8
|
ea452d4894336f912277165f1aa4e3a3
|
function varargout = cfg_ui(varargin)
% CFG_UI M-File for cfg_ui.fig
% CFG_UI, by itself, creates a new CFG_UI or raises the existing
% singleton*.
%
% H = CFG_UI returns the handle to a new CFG_UI or the handle to
% the existing singleton*.
%
% CFG_UI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in CFG_UI.M with the given input arguments.
%
% CFG_UI('Property','Value',...) creates a new CFG_UI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before cfg_ui_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to cfg_ui_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
%
% 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_ui.m 6128 2014-08-01 16:09:57Z guillaume $
rev = '$Rev: 6128 $'; %#ok
% edit the above text to modify the response to help cfg_ui
% Last Modified by GUIDE v2.5 04-Mar-2010 16:09:52
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @cfg_ui_OpeningFcn, ...
'gui_OutputFcn', @cfg_ui_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
%% Local functions
% Most callbacks just refer to one of these local_ functions.
% --------------------------------------------------------------------
function local_DelMod(hObject)
handles = guidata(hObject);
udmodlist = get(handles.modlist,'userdata');
val = get(handles.modlist,'value');
if ~isempty(udmodlist.cmod)
cfg_util('delfromjob',udmodlist.cjob, udmodlist.id{val});
udmodlist.modified = true;
set(handles.modlist,'userdata',udmodlist);
local_showjob(hObject);
end;
% --------------------------------------------------------------------
function local_ReplMod(hObject)
handles = guidata(hObject);
udmodlist = get(handles.modlist,'userdata');
val = get(handles.modlist,'value');
if ~isempty(udmodlist.cmod)
cfg_util('replicate',udmodlist.cjob, udmodlist.id{val});
udmodlist.modified = true;
set(handles.modlist,'userdata',udmodlist);
local_showjob(hObject);
end;
%% Dynamic Menu Creation
% --------------------------------------------------------------------
function local_setmenu(parent, id, cb, dflag)
% parent: menu parent
% id: id to start listcfgall
% cb: callback to add/run new nodes
% dflag: add defaults edit (true/false)
% delete previous added menu, if any
prevmenu = findobj(parent, 'Tag', 'AddedAppMenu');
if ~isempty(prevmenu)
delete(prevmenu);
end;
% get strings and ids
[id,stop,val]=cfg_util('listcfgall',id,cfg_findspec({{'hidden',false}}),{'name','level'});
str = val{1};
lvl = cat(1,val{2}{:});
% strings and ids are in preorder - if stop is true, then we are at leaf
% level, if lvl(k) <= lvl(k-1) we are at siblings/parent level
% remember last menu at lvl for parents, start at lvl > 1 (top parent is
% figure menu)
lastmenulvl = zeros(1, max(lvl));
lastmenulvl(1) = parent;
toplevelmenus = [];
toplevelids = {};
% 1st entry is top of matlabbatch config tree, applications start at 2nd entry
for k = 2:numel(lvl)
label = str{k};
if stop(k)
udata = id{k};
cback = cb;
else
udata = [];
cback = '';
end;
cm = uimenu('parent',lastmenulvl(lvl(k)-1), 'Label',label, 'Userdata',udata, ...
'Callback',cback, 'tag','AddedAppMenu');
lastmenulvl(lvl(k)) = cm;
if lvl(k) == 2
toplevelmenus(end+1) = cm;
toplevelids{end+1} = id{k};
end;
end;
hkeys = cell(1,numel(toplevelmenus)+2);
hkeys{1} = 'f';
hkeys{2} = 'e';
for k =1:numel(toplevelmenus)
% add hot keys
clabel = get(toplevelmenus(k),'Label');
for l = 1:numel(clabel)
if ~isspace(clabel(l)) && ~any(strcmpi(clabel(l),hkeys))
hkeys{k+2} = lower(clabel(l));
clabel = [clabel(1:l-1) '&' clabel(l:end)];
break;
end;
end;
set(toplevelmenus(k),'Label',clabel);
if dflag
% add defaults manipulation entries
% disable Load/Save
%cm = uimenu('Parent',toplevelmenus(k), 'Label','Load Defaults', ...
% 'Callback',@local_loaddefs, 'Userdata',toplevelids{k}, ...
% 'tag','AddedAppMenu', 'Separator','on');
%cm = uimenu('Parent',toplevelmenus(k), 'Label','Save Defaults', ...
% 'Callback',@local_savedefs, 'Userdata',toplevelids{k}, ...
% 'tag','AddedAppMenu');
cm = uimenu('parent',toplevelmenus(k), 'Label','Edit Defaults', ...
'Callback',@local_editdefs, 'Userdata',toplevelids{k}, ...
'tag','AddedAppMenu', 'Separator','on');
end;
end;
% --------------------------------------------------------------------
function local_addtojob(varargin)
id = get(gcbo, 'userdata');
handles = guidata(gcbo);
udmodlist = get(handles.modlist, 'userdata');
% add module to job, harvest to initialise its virtual outputs
mod_job_id = cfg_util('addtojob', udmodlist.cjob, id);
cfg_util('harvest', udmodlist.cjob, mod_job_id);
udmodlist.modified = true;
set(handles.modlist,'userdata',udmodlist);
local_showjob(gcbo);
% --------------------------------------------------------------------
function local_loaddefs(varargin)
appid = get(gcbo, 'Userdata');
[file sts] = cfg_getfile(1, '.*\.m$','Load Defaults from');
if sts
cfg_util('initdef', appid, file{1});
end;
% --------------------------------------------------------------------
function local_savedefs(varargin)
appid = get(gcbo, 'Userdata');
[tag, def] = cfg_util('harvestdef', appid);
[file path] = uiputfile({'*.m','MATLAB .m file'}, 'Save Defaults as', ...
sprintf('%s_defaults.m', tag));
if ~ischar(file)
return;
end;
fid = fopen(fullfile(path, file), 'wt');
if fid < 1
cfg_message('matlabbatch:savefailed', ...
'Save failed: no defaults written to %s.', ...
fullfile(path, file));
return;
end;
[defstr tagstr] = gencode(def, tag);
[u1 funcname] = fileparts(file);
fprintf(fid, 'function %s = %s\n', tagstr, funcname);
for k = 1:numel(defstr)
fprintf(fid, '%s\n', defstr{k});
end;
fclose(fid);
% --------------------------------------------------------------------
function local_editdefs(varargin)
% Defaults edit mode bypasses local_showjob, but uses all other GUI
% callbacks. Where behaviour/GUI visibility is different for
% normal/defaults mode, a check for the presence of udmodlist(1).defid is
% performed.
handles = guidata(gcbo);
% Disable application menus & file, edit menus
set(findobj(handles.cfg_ui, 'Tag', 'AddedAppMenu'), 'Enable','off');
set(findobj(handles.cfg_ui, 'Tag', 'MenuFile'), 'Enable', 'off');
set(findobj(handles.cfg_ui,'-regexp', 'Tag','.*(Del)|(Repl)Mod$'),'Enable','off');
set(findobj(handles.cfg_ui,'-regexp','Tag','^MenuEditVal.*'), 'Enable', 'off');
% Change current menu to 'Quit'
set(gcbo, 'Enable','on', 'Callback',@local_editdefsquit, ...
'Label','Quit Defaults');
set(get(gcbo, 'Parent'), 'Enable','on');
% Get module list for application
appid = get(gcbo, 'Userdata');
[id,stop,val]=cfg_util('listcfg', appid, cfg_findspec({{'hidden',false}}), ...
{'name'});
udmodlist = get(handles.modlist, 'userdata');
udmodlist(1).defid = id;
udmodlist(1).cmod = 1;
set(handles.modlist, 'Value',1, 'ListboxTop',1, 'Userdata',udmodlist, 'String',val{1});
local_showmod(gcbo);
% --------------------------------------------------------------------
function local_editdefsquit(varargin)
handles = guidata(gcbo);
set(findobj(handles.cfg_ui, 'Tag', 'AddedAppMenu'), 'Enable','on');
set(findobj(handles.cfg_ui, 'Tag', 'MenuFile'), 'Enable', 'on');
set(gcbo, 'Enable','on', 'Callback',@local_editdefs, ...
'Label','Edit Defaults');
% remove defs field from udmodlist
udmodlist = rmfield(get(handles.modlist, 'userdata'), 'defid');
if numel(fieldnames(udmodlist)) == 0
udmodlist = local_init_udmodlist;
end;
set(handles.modlist, 'userdata',udmodlist);
local_showjob(gcbo);
%% Show job contents
% --------------------------------------------------------------------
function local_showjob(obj,cjob)
handles = guidata(obj);
if nargin == 1
% udmodlist should be initialised here
udmodlist = get(handles.modlist,'userdata');
cjob = udmodlist.cjob;
else
% set cjob, if supplied
udmodlist = local_init_udmodlist;
udmodlist(1).cjob = cjob;
% move figure onscreen
cfg_onscreen(obj);
set(obj,'Visible','on');
end;
[id str sts dep sout] = cfg_util('showjob',cjob);
if isempty(str)
str = {'No Modules in Batch'};
cmod = 1;
udmodlist.cmod = [];
set(findobj(handles.cfg_ui,'-regexp', 'Tag','.*(Del)|(Repl)Mod$'),'Enable','off');
else
if isempty(udmodlist.cmod)
cmod = 1;
else
cmod = min(get(handles.modlist,'value'), numel(str));
if udmodlist.cmod ~= cmod
set(handles.module, 'Userdata',[]);
end;
end
udmodlist.id = id;
udmodlist.sout = sout;
udmodlist.cmod = cmod;
set(findobj(handles.cfg_ui,'-regexp', 'Tag','.*(Del)|(Repl)Mod$'),'Enable','on');
mrk = cell(size(sts));
[mrk{dep}] = deal('DEP');
[mrk{~sts}] = deal('<-X');
[mrk{~dep & sts}] = deal('');
str = cfg_textfill(handles.modlist, str, mrk, false);
end;
ltop = local_getListboxTop(handles.modlist, cmod, numel(str));
set(handles.modlist, 'userdata',udmodlist, 'value', cmod, 'ListboxTop', ltop, 'string', str);
if ~isempty(sts) && all(sts)
set(findobj(handles.cfg_ui,'-regexp', 'Tag','.*File(Run)|(RunSerial)$'),'Enable','on');
else
set(findobj(handles.cfg_ui,'-regexp', 'Tag','.*File(Run)|(RunSerial)$'),'Enable','off');
end
local_showmod(obj);
%% Show Module Contents
% --------------------------------------------------------------------
function local_showmod(obj)
handles = guidata(obj);
udmodlist = get(handles.modlist, 'userdata');
if ~isempty(udmodlist.cmod)
cmod = get(handles.modlist, 'value');
% fill module box with module contents
if isfield(udmodlist, 'defid')
% list defaults
dflag = true;
cid = {udmodlist.defid{cmod} ,[]};
else
dflag = false;
cid = {udmodlist.cjob, udmodlist.id{cmod}, []};
end;
[id stop contents] = ...
cfg_util('listmod', cid{:}, ...
cfg_findspec({{'hidden',false}}), ...
cfg_tropts({{'hidden', true}},1,Inf,1,Inf,dflag), ...
{'name','val','labels','values','class','level', ...
'all_set','all_set_item','num'});
if isempty(id) || ~cfg_util('isitem_mod_id', id{1})
% Module not found without hidden flag
% Try to list top level entry of module anyway, but not module items.
[id stop contents] = ...
cfg_util('listmod', cid{:}, ...
cfg_findspec({}), ...
cfg_tropts({{'hidden', true}},1,1,1,1,dflag), ...
{'name','val','labels','values','class','level', ...
'all_set','all_set_item'});
end;
set(handles.moduleHead,'String',sprintf('Current Module: %s', contents{1}{1}));
namestr = cell(1,numel(contents{1}));
datastr = cell(1,numel(contents{1}));
namestr{1} = sprintf('Help on: %s',contents{1}{1});
datastr{1} = '';
for k = 2:numel(contents{1})
if contents{6}{k}-2 > 0
indent = [' ' repmat('. ', 1, contents{6}{k}-2)];
else
indent = '';
end
if contents{8}{k} || (isfield(udmodlist,'defid') && ~isempty(contents{2}{k}))
if any(strcmp(contents{5}{k}, {'cfg_menu','cfg_files','cfg_entry'})) && ...
isa(contents{2}{k}{1}, 'cfg_dep')
if numel(contents{2}{k}{1}) == 1
datastr{k} = sprintf('DEP %s', contents{2}{k}{1}.sname);
else
datastr{k} = sprintf('DEP (%d outputs)', numel(contents{2}{k}{1}));
end;
else
switch contents{5}{k}
case 'cfg_menu',
datastr{k} = 'Unknown selection';
for l = 1:numel(contents{4}{k})
if isequalwithequalnans(contents{2}{k}{1}, contents{4}{k}{l})
datastr{k} = contents{3}{k}{l};
break;
end;
end;
case 'cfg_files',
if numel(contents{2}{k}{1}) == 1
if isempty(contents{2}{k}{1}{1})
datastr{k} = ' ';
else
datastr{k} = contents{2}{k}{1}{1};
end;
else
datastr{k} = sprintf('%d files', numel(contents{2}{k}{1}));
end;
case 'cfg_entry'
csz = size(contents{2}{k}{1});
% TODO use gencode like string formatting
if ischar(contents{2}{k}{1}) && ...
numel(csz) == 2 && any(csz(1:2) == 1)
datastr{k} = contents{2}{k}{1};
elseif (isnumeric(contents{2}{k}{1}) || ...
islogical(contents{2}{k}{1})) && ...
numel(csz) == 2 && any(csz(1:2) == 1) &&...
numel(contents{2}{k}{1}) <= 4
% always display line vector as summary
datastr{k} = mat2str(contents{2}{k}{1}(:)');
elseif any(csz == 0)
switch class(contents{2}{k}{1})
case 'char',
datastr{k} = '''''';
case 'double',
datastr{k} = '[]';
otherwise
datastr{k} = sprintf('%s([])', ...
class(contents{2}{k}{1}));
end;
else
szstr = sprintf('%dx', csz);
datastr{k} = sprintf('%s %s', ...
szstr(1:end-1), class(contents{2}{k}{1}));
end;
otherwise
datastr{k} = ' ';
end;
end;
else
datastr{k} = '<-X';
end;
namestr{k} = sprintf('%s%s ', indent, contents{1}{k});
end;
str = cfg_textfill(handles.module,namestr,datastr,true);
udmodule = get(handles.module, 'userdata');
if isempty(udmodule)
citem = min(2,numel(id));
else
% try to find old item in new module struct - this may change due
% to repeat/choice changes
% Try to make first input item active, not module head
oldid = udmodule.id{udmodule.oldvalue};
citem = find(cellfun(@(cid)isequal(cid, oldid),id));
if isempty(citem)
citem = min(2,numel(id));
end
end;
udmodule.contents = contents;
udmodule.id = id;
udmodule.oldvalue = citem;
ltop = local_getListboxTop(handles.module, citem, numel(str));
set(handles.module, 'Value', citem, 'ListboxTop', ltop, 'userdata', udmodule, 'String', str);
udmodlist(1).cmod = cmod;
set(handles.modlist, 'userdata', udmodlist);
local_showvaledit(obj);
uicontrol(handles.module);
else
set(handles.module, 'Value',1,'ListboxTop',1,'Userdata',[], 'String',{'No Module selected'});
set(handles.moduleHead,'String','No Current Module');
set(findobj(handles.cfg_ui,'-regexp','Tag','^Btn.*'), 'Visible', 'off');
set(findobj(handles.cfg_ui,'-regexp','Tag','^MenuEditVal.*'), 'Enable', 'off');
set(handles.valshow, 'String','', 'Visible','off');
set(handles.valshowLabel, 'Visible','off');
% set help box to matlabbatch top node help
[id stop help] = cfg_util('listcfgall', [], cfg_findspec({{'tag','matlabbatch'}}), {'showdoc'});
set(handles.helpbox, 'Value',1, 'ListboxTop',1, 'String',cfg_justify(handles.helpbox, help{1}{1}));
end;
%% Show Item
% --------------------------------------------------------------------
function local_showvaledit(obj)
handles = guidata(obj);
udmodlist = get(handles.modlist, 'userdata');
cmod = get(handles.modlist, 'value');
udmodule = get(handles.module, 'userdata');
citem = get(handles.module, 'value');
set(findobj(handles.cfg_ui,'-regexp', 'Tag','^BtnVal.*'), 'Visible','off');
set(findobj(handles.cfg_ui,'-regexp', 'Tag','^MenuEditVal.*'), 'Enable','off');
set(findobj(handles.cfg_ui,'-regexp', 'Tag','^CmVal.*'), 'Visible','off');
delete(findobj(handles.cfg_ui,'-regexp', 'Tag','^MenuEditVal.*Dyn$'))
set(findobj(handles.cfg_ui,'-regexp', 'Tag','^valshow.*'), 'Visible','off');
set(handles.valshow,'String', '','Min',0,'Max',0,'Callback',[]);
set(handles.valshowLabel, 'String',sprintf('Current Item: %s',udmodule.contents{1}{citem}));
switch(udmodule.contents{5}{citem})
case {'cfg_entry','cfg_files'}
if ~isempty(udmodule.contents{2}{citem}) && isa(udmodule.contents{2}{citem}{1}, 'cfg_dep')
str = {'Reference from'};
for k = 1:numel(udmodule.contents{2}{citem}{1}) % we may have multiple dependencies
str{k+1} = udmodule.contents{2}{citem}{1}(k).sname; % return something to be printed
end;
elseif ~isempty(udmodule.contents{2}{citem})
if ndims(udmodule.contents{2}{citem}{1}) <= 2
if ischar(udmodule.contents{2}{citem}{1})
str = cellstr(udmodule.contents{2}{citem}{1});
elseif iscellstr(udmodule.contents{2}{citem}{1})
str = udmodule.contents{2}{citem}{1};
elseif isnumeric(udmodule.contents{2}{citem}{1}) || ...
islogical(udmodule.contents{2}{citem}{1})
str = cellstr(num2str(udmodule.contents{2}{citem}{1}));
else
str = gencode(udmodule.contents{2}{citem}{1},'val');
end;
else
str = gencode(udmodule.contents{2}{citem}{1},'val');
end;
else
str = '';
end;
set(handles.valshow, 'Visible','on', 'Value',1, 'ListboxTop',1,'String', str);
set(handles.valshowLabel, 'Visible','on');
if ~isfield(udmodlist, 'defid')
sout = local_showvaledit_deps(obj);
if ~isempty(sout)
set(findobj(handles.cfg_ui,'-regexp','Tag','.*AddDep$'), ...
'Visible','on', 'Enable','on');
end;
end;
if strcmp(udmodule.contents{5}{citem},'cfg_files')
set(findobj(handles.cfg_ui,'-regexp','Tag','.*SelectFiles$'), ...
'Visible','on', 'Enable','on');
else
set(findobj(handles.cfg_ui,'-regexp','Tag','.*EditVal$'), ...
'Visible','on', 'Enable','on');
end
set(findobj(handles.cfg_ui,'-regexp','Tag','.*ClearVal$'), ...
'Visible','on', 'Enable','on');
case {'cfg_menu','cfg_choice'}
if strcmp(udmodule.contents{5}{citem},'cfg_menu') || ~isfield(udmodlist, 'defid')
cval = -1;
if strcmp(udmodule.contents{5}{citem},'cfg_choice')
% compare tag, not filled entries
cmpsubs = substruct('.','tag');
else
cmpsubs = struct('type',{},'subs',{});
end;
valsubs = substruct('{}',{1});
nitem = numel(udmodule.contents{4}{citem});
mrk = cell(1,nitem);
for l = 1:nitem
valuesubs = substruct('{}',{l});
if ~isempty(udmodule.contents{2}{citem}) && isequal(subsref(udmodule.contents{2}{citem},[valsubs cmpsubs]), subsref(udmodule.contents{4}{citem},[valuesubs cmpsubs]))
mrk{l} = '*';
cval = l;
else
mrk{l} = ' ';
end;
end;
if strcmp(udmodule.contents{5}{citem},'cfg_choice')
str = cell(1,nitem);
for k = 1:nitem
str{k} = udmodule.contents{4}{citem}{k}.name;
end;
else
str = udmodule.contents{3}{citem};
end;
str = strcat(mrk(:), str(:));
udvalshow = local_init_udvalshow;
udvalshow.cval = cval;
if cval == -1
cval = 1;
end;
ltop = local_getListboxTop(handles.valshow, cval, numel(str));
set(handles.valshow, 'Visible','on', 'Value',cval, 'ListboxTop',ltop, 'String',str, ...
'Callback',@local_valedit_list, ...
'Keypressfcn',@local_valedit_key, ...
'Userdata',udvalshow);
set(handles.valshowLabel, 'Visible','on');
set(findobj(handles.cfg_ui,'-regexp','Tag','.*EditVal$'), ...
'Visible','on', 'Enable','on');
set(findobj(handles.cfg_ui,'-regexp','Tag','.*ClearVal$'), ...
'Visible','on', 'Enable','on');
end;
case {'cfg_repeat'}
if ~isfield(udmodlist, 'defid')
udvalshow = local_init_udvalshow;
udvalshow.cval = 1;
% Already selected items
ncitems = numel(udmodule.contents{2}{citem});
str3 = cell(ncitems,1);
cmd3 = cell(ncitems,1);
for k = 1:ncitems
str3{k} = sprintf('Delete: %s (%d)',...
udmodule.contents{2}{citem}{k}.name, k);
cmd3{k} = [Inf k];
uimenu(handles.MenuEditValDelItem, ...
'Label',sprintf('%s (%d)', ...
udmodule.contents{2}{citem}{k}.name, k), ...
'Callback',@(ob,ev)local_setvaledit(ob,cmd3{k},ev), ...
'Tag','MenuEditValDelItemDyn');
uimenu(handles.CmValDelItem, ...
'Label',sprintf('%s (%d)', ...
udmodule.contents{2}{citem}{k}.name, k), ...
'Callback',@(ob,ev)local_setvaledit(ob,cmd3{k},ev), ...
'Tag','CmValDelItemDyn');
end
% Add/Replicate callbacks will be shown only if max number of
% items not yet reached
if ncitems < udmodule.contents{9}{citem}(2)
% Available items
naitems = numel(udmodule.contents{4}{citem});
str1 = cell(naitems,1);
cmd1 = cell(naitems,1);
for k = 1:naitems
str1{k} = sprintf('New: %s', udmodule.contents{4}{citem}{k}.name);
cmd1{k} = [k Inf];
uimenu(handles.MenuEditValAddItem, ...
'Label',udmodule.contents{4}{citem}{k}.name, ...
'Callback',@(ob,ev)local_setvaledit(ob,cmd1{k},ev), ...
'Tag','MenuEditValAddItemDyn');
uimenu(handles.CmValAddItem, ...
'Label',udmodule.contents{4}{citem}{k}.name, ...
'Callback',@(ob,ev)local_setvaledit(ob,cmd1{k},ev), ...
'Tag','CmValAddItemDyn');
end;
str2 = cell(ncitems,1);
cmd2 = cell(ncitems,1);
for k = 1:ncitems
str2{k} = sprintf('Replicate: %s (%d)',...
udmodule.contents{2}{citem}{k}.name, k);
cmd2{k} = [-1 k];
uimenu(handles.MenuEditValReplItem, ...
'Label',sprintf('%s (%d)', ...
udmodule.contents{2}{citem}{k}.name, k), ...
'Callback',@(ob,ev)local_setvaledit(ob,cmd2{k},ev), ...
'Tag','MenuEditValReplItemDyn');
uimenu(handles.CmValReplItem, ...
'Label',sprintf('%s (%d)', ...
udmodule.contents{2}{citem}{k}.name, k), ...
'Callback',@(ob,ev)local_setvaledit(ob,cmd2{k},ev), ...
'Tag','CmValReplItemDyn');
end
set(findobj(handles.cfg_ui,'-regexp','Tag','.*AddItem$'), ...
'Visible','on', 'Enable','on');
if ncitems > 0
set(findobj(handles.cfg_ui,'-regexp','Tag','.*ReplItem$'), ...
'Visible','on', 'Enable','on');
set(findobj(handles.cfg_ui,'-regexp','Tag','.*ReplItem$'), ...
'Visible','on', 'Enable','on');
end
else
str1 = {};
str2 = {};
cmd1 = {};
cmd2 = {};
end
str = [str1(:); str2(:); str3(:)];
udvalshow.cmd = [cmd1(:); cmd2(:); cmd3(:)];
set(handles.valshow, 'Visible','on', 'Value',1, 'ListboxTop',1, 'String', str, ...
'Callback',@local_valedit_repeat, ...
'KeyPressFcn', @local_valedit_key, ...
'Userdata',udvalshow);
set(handles.valshowLabel, 'Visible','on');
set(findobj(handles.cfg_ui,'-regexp','Tag','^Btn.*EditVal$'), ...
'Visible','on', 'Enable','on');
if ncitems > 0
set(findobj(handles.cfg_ui,'-regexp','Tag','.*DelItem$'), ...
'Visible','on', 'Enable','on');
end;
set(findobj(handles.cfg_ui,'-regexp','Tag','.*ClearVal$'), ...
'Visible','on', 'Enable','on');
end;
end;
if isfield(udmodlist, 'defid')
cmid = udmodlist.defid(cmod);
else
cmid = {udmodlist.cjob udmodlist.id{cmod}};
end;
[id stop help] = cfg_util('listmod', cmid{:}, udmodule.id{citem}, cfg_findspec, ...
cfg_tropts(cfg_findspec,1,1,1,1,false), {'showdoc'});
set(handles.helpbox, 'Value',1, 'ListboxTop',1, 'string',cfg_justify(handles.helpbox, help{1}{1}));
drawnow;
%% List matching dependencies
% --------------------------------------------------------------------
function sout = local_showvaledit_deps(obj)
handles = guidata(obj);
udmodlist = get(handles.modlist, 'userdata');
cmod = get(handles.modlist, 'value');
udmodule = get(handles.module, 'userdata');
citem = get(handles.module, 'value');
sout = cat(2,udmodlist(1).sout{1:cmod-1});
smatch = false(size(sout));
% loop over sout to find whether there are dependencies that match the current item
for k = 1:numel(sout)
smatch(k) = cfg_util('match', udmodlist.cjob, udmodlist.id{cmod}, udmodule.id{citem}, sout(k).tgt_spec);
end;
sout = sout(smatch);
%% Value edit dialogue
% --------------------------------------------------------------------
function local_valedit_edit(hObject)
% Normal mode. Depending on strtype, put '' or [] around entered
% input. If input has ndims > 2, isn't numeric or char, proceed with
% expert dialogue.
handles = guidata(hObject);
value = get(handles.module, 'Value');
udmodule = get(handles.module, 'Userdata');
cmod = get(handles.modlist, 'Value');
udmodlist = get(handles.modlist, 'Userdata');
val = udmodule.contents{2}{value};
if isfield(udmodlist, 'defid')
cmid = udmodlist.defid(cmod);
else
cmid = {udmodlist.cjob, udmodlist.id{cmod}};
end;
[id stop strtype] = cfg_util('listmod', cmid{:}, udmodule.id{value}, cfg_findspec, ...
cfg_tropts(cfg_findspec,1,1,1,1,false), {'strtype'});
if isempty(val) || isa(val{1}, 'cfg_dep')
% silently clear cfg_deps
if strtype{1}{1} == 's'
val = {''};
else
val = {[]};
end;
end;
% If requested or we can't handle this, use expert mode
expmode = strcmp(cfg_get_defaults([mfilename '.ExpertEdit']), 'on') ||...
ndims(val{1}) > 2 || ~(ischar(val{1}) || isnumeric(val{1}) || islogical(val{1}));
% Generate code for current value, if not empty
% Set dialog texts
if expmode
if ~isequal(val, {''})
instr = gencode(val{1},'val');
% remove comments and put in 1-cell multiline char array
nc = cellfun(@isempty,regexp(instr,'^\s*%'));
instr = {char(instr(nc))};
else
instr = {''};
end
hlptxt = char({'Enter a valid MATLAB expression.', ...
' ', ...
['Strings must be enclosed in single quotes ' ...
'(''A''), multiline arrays in brackets ([ ]).'], ...
' ', ...
'To clear a value, enter an empty cell ''{}''.', ...
' ', ...
'Leave input box with CTRL-TAB to access buttons.'});
failtxt = {'Input could not be evaluated. Possible reasons are:',...
'1) Input should be a vector or matrix, but is not enclosed in ''['' and '']'' brackets.',...
'2) Input should be a character or string, but is not enclosed in '' single quotes.',...
'3) Input should be a MATLAB variable, but is misspelled.',...
'4) Input should be a MATLAB expression, but has syntax errors.'};
else
if strtype{1}{1} == 's'
instr = val;
encl = {'''' ''''};
else
try
instr = {num2str(val{1})};
catch
instr = {''};
end;
encl = {'[' ']'};
end;
hlptxt = char({'Enter a value.', ...
' ', ...
'To clear a value, clear the input field and accept.', ...
' ', ...
'Leave input box with CTRL-TAB to access buttons.'});
failtxt = {'Input could not be evaluated.'};
end
sts = false;
while ~sts
% estimate size of input field based on instr
% Maximum widthxheight 140x20, minimum 60x2
szi = size(instr{1});
mxwidth = 140;
rdup = ceil(szi(2)/mxwidth)+3;
szi = max(min([szi(1)*rdup szi(2)],[20 140]),[2,60]);
str = inputdlg(hlptxt, ...
udmodule.contents{1}{value}, ...
szi,instr);
if iscell(str) && isempty(str)
% User has hit cancel button
return;
end;
% save instr in case of evaluation error
instr = str;
% str{1} is a multiline char array
% 1) cellify it
% 2) add newline to each string
% 3) concatenate into one string
cstr = cellstr(str{1});
str = strcat(cstr, {char(10)});
str = cat(2, str{:});
% Evaluation is encapsulated to avoid users compromising this function
% context - graphics handles are made invisible to avoid accidental
% damage
hv = local_disable(handles.cfg_ui,'HandleVisibility');
[val sts] = cfg_eval_valedit(str);
local_enable(handles.cfg_ui,'HandleVisibility',hv);
% for strtype 's', val must be a string
sts = sts && (~strcmp(strtype{1}{1},'s') || ischar(val));
if ~sts
if ~expmode
% try with matching value enclosure
if strtype{1}{1} == 's'
if ishandle(val) % delete accidentally created objects
delete(val);
end
% escape single quotes and place the whole string in single quotes
str = strcat(encl(1), strrep(cstr,'''',''''''), encl(2), {char(10)});
else
cestr = [encl(1); cstr(:); encl(2)]';
str = strcat(cestr, {char(10)});
end;
str = cat(2, str{:});
% Evaluation is encapsulated to avoid users compromising this function
% context - graphics handles are made invisible to avoid accidental
% damage
hv = local_disable(handles.cfg_ui,'HandleVisibility');
[val sts] = cfg_eval_valedit(str);
local_enable(handles.cfg_ui,'HandleVisibility',hv);
end;
if ~sts % (Still) no valid input
uiwait(msgbox(failtxt,'Evaluation error','modal'));
end;
end;
end
% This code will only be reached if a new value has been set
local_setvaledit(hObject, val);
% --------------------------------------------------------------------
function en = local_disable(hObject, property)
% disable property in all ui objects, returning their previous state in
% cell list en
handles = guidata(hObject);
c = findall(handles.cfg_ui);
en = cell(size(c));
sel = isprop(c,property);
en(sel) = get(c(sel),property);
set(c(sel),property,'off');
% --------------------------------------------------------------------
function local_enable(hObject, property, en)
% reset original property status. if en is empty, return without changing
% anything.
if ~isempty(en)
handles = guidata(hObject);
c = findall(handles.cfg_ui);
sel = isprop(c,property);
set(c(sel),{property},en(sel));
end
%% Value choice dialogue
% --------------------------------------------------------------------
function local_valedit_accept(hObject,val)
handles = guidata(hObject);
udvalshow = get(handles.valshow, 'Userdata');
local_enable(hObject, 'Enable', udvalshow.en);
uiresume(handles.cfg_ui);
set(findobj(handles.cfg_ui, '-regexp', 'Tag','^valshowBtn.*'), ...
'Visible','off', 'Callback',[]);
if nargin == 1
val = get(handles.valshow, 'Value');
end
local_setvaledit(hObject,val);
% --------------------------------------------------------------------
function local_valedit_cancel(hObject)
handles = guidata(hObject);
udvalshow = get(handles.valshow, 'Userdata');
local_enable(hObject, 'Enable', udvalshow.en);
uiresume(handles.cfg_ui);
set(findobj(handles.cfg_ui, '-regexp', 'Tag','^valshowBtn.*'), ...
'Visible','off', 'Callback',[]);
uicontrol(handles.module);
% --------------------------------------------------------------------
function local_valedit_key(hObject, data, varargin)
if strcmpi(data.Key,'escape')
% ESC must be checked here
local_valedit_cancel(hObject);
else
% collect key info for evaluation in local_valedit_list
handles = guidata(hObject);
udvalshow = get(handles.valshow, 'Userdata');
udvalshow.key = data;
set(handles.valshow, 'Userdata',udvalshow);
end
% --------------------------------------------------------------------
function local_valedit_list(hObject,varargin)
handles = guidata(hObject);
udvalshow = get(handles.valshow, 'Userdata');
val = get(handles.valshow, 'Value');
if ((isempty(udvalshow.key) || ...
strcmpi(udvalshow.key.Key,'return')) && ...
isequal(hObject, handles.valshow)) || ...
isequal(hObject, handles.valshowBtnAccept)
% callback called from handles.valshow, finish editing and set value
if val ~= udvalshow.cval
local_valedit_accept(hObject);
else
local_valedit_cancel(hObject);
end;
elseif (~isempty(udvalshow.key) && strcmpi(udvalshow.key.Key,'escape') && ...
isequal(hObject, handles.valshow)) || ...
isequal(hObject, handles.valshowBtnCancel)
local_valedit_cancel(hObject);
elseif ~isequal(hObject, handles.valshow)
% callback called from elsewhere (module, menu, button) - init editing
udvalshow.en = local_disable(hObject,'Enable');
udvalshow.key = [];
figure(handles.cfg_ui);
set(handles.valshow,'enable','on','Userdata',udvalshow, 'Min',0, ...
'Max',1);
set(findobj(handles.cfg_ui, '-regexp', 'Tag','^valshowBtn.*'), ...
'Enable','on', 'Visible','on', 'Callback',@local_valedit_list);
uicontrol(handles.valshow);
uiwait(handles.cfg_ui);
else
udvalshow.key = [];
set(handles.valshow, 'Userdata',udvalshow);
end;
%% Repeat edit dialogue
% --------------------------------------------------------------------
function local_valedit_repeat(hObject,varargin)
handles = guidata(hObject);
udvalshow = get(handles.valshow, 'Userdata');
if ((isempty(udvalshow.key) || ...
strcmpi(udvalshow.key.Key,'return')) && ...
isequal(hObject, handles.valshow)) || ...
isequal(hObject, handles.valshowBtnAccept)
% Mouse selection - no key
% Keyboard selection - return key
ccmd = get(hObject,'Value');
local_valedit_accept(hObject,udvalshow.cmd{ccmd});
elseif (~isempty(udvalshow.key) && strcmpi(udvalshow.key.Key,'escape') && ...
isequal(hObject, handles.valshow)) || ...
isequal(hObject, handles.valshowBtnCancel)
% callback called from handles.valshow, finish editing
local_valedit_cancel(hObject);
elseif ~isequal(hObject, handles.valshow)
% callback called from elsewhere (module, menu, button)
% if there is just one action, do it, else init editing
if numel(udvalshow.cmd) == 1
local_valedit_accept(hObject,udvalshow.cmd{1});
else
udvalshow.en = local_disable(hObject,'Enable');
udvalshow.key = [];
figure(handles.cfg_ui);
set(handles.valshow,'enable','on','Userdata',udvalshow, 'Min',0, ...
'Max',1);
set(findobj(handles.cfg_ui, '-regexp', 'Tag','^valshowBtn.*'), ...
'Enable','on', 'Visible','on', 'Callback',@local_valedit_repeat);
uicontrol(handles.valshow);
uiwait(handles.cfg_ui);
end
else
udvalshow.key = [];
set(handles.valshow, 'Userdata',udvalshow);
end;
%% Set changed values
% --------------------------------------------------------------------
function local_setvaledit(obj, val,varargin)
handles = guidata(obj);
udmodlist = get(handles.modlist, 'Userdata');
cmod = get(handles.modlist, 'Value');
udmodule = get(handles.module, 'Userdata');
citem = get(handles.module, 'Value');
if isfield(udmodlist, 'defid')
cfg_util('setdef', udmodlist(1).defid{cmod}, udmodule.id{citem}, val);
local_showmod(obj);
else
cfg_util('setval', udmodlist.cjob, udmodlist.id{cmod}, udmodule.id{citem}, val);
cfg_util('harvest', udmodlist.cjob, udmodlist.id{cmod});
udmodlist.modified = true;
set(handles.modlist,'userdata',udmodlist);
local_showjob(obj);
end;
%% Button/Menu callbacks
% These callbacks are called from both the Edit menu and the GUI buttons
% --------------------------------------------------------------------
function local_valedit_SelectFiles(hObject)
handles = guidata(hObject);
udmodlist = get(handles.modlist, 'Userdata');
cmod = get(handles.modlist, 'Value');
udmodule = get(handles.module, 'Userdata');
citem = get(handles.module, 'Value');
if isfield(udmodlist,'defid')
cmid = udmodlist.defid(cmod);
else
cmid = {udmodlist.cjob, udmodlist.id{cmod}};
end;
[unused1 unused2 contents] = cfg_util('listmod', cmid{:}, udmodule.id{citem},{},cfg_tropts({},1,1,1,1,false),{'val','num','filter','name','dir','ufilter'});
if isempty(contents{1}{1}) || isa(contents{1}{1}{1}, 'cfg_dep')
inifile = '';
else
inifile = contents{1}{1}{1};
end;
[val sts] = cfg_getfile(contents{2}{1}, contents{3}{1}, contents{4}{1}, inifile, contents{5}{1}, contents{6}{1});
if sts
local_setvaledit(hObject, val);
end;
% --------------------------------------------------------------------
function local_valedit_EditValue(hObject)
handles = guidata(hObject);
value = get(handles.module, 'Value');
udmodule = get(handles.module, 'Userdata');
switch udmodule.contents{5}{value}
case {'cfg_choice','cfg_menu'}
local_valedit_list(hObject);
case 'cfg_repeat'
local_valedit_repeat(hObject);
otherwise
local_valedit_edit(hObject);
end;
% --------------------------------------------------------------------
function local_valedit_ClearVal(hObject)
local_setvaledit(hObject, {});
% --------------------------------------------------------------------
function local_valedit_AddDep(hObject)
handles = guidata(hObject);
udmodule = get(handles.module, 'Userdata');
citem = get(handles.module, 'Value');
sout = local_showvaledit_deps(hObject);
str = {sout.sname};
[val sts] = listdlg('Name',udmodule.contents{1}{citem}, 'ListString',str);
if sts
local_setvaledit(hObject, sout(val));
end;
%% Automatic Callbacks
% --- Executes just before cfg_ui is made visible.
function cfg_ui_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 cfg_ui (see VARARGIN)
% move figure onscreen
cfg_onscreen(hObject);
% Add configuration specific menu items
local_setmenu(handles.cfg_ui, [], @local_addtojob, true);
% Check udmodlist
udmodlist = get(handles.modlist, 'userdata');
if isempty(udmodlist) || ~(~isempty(udmodlist.cjob) && cfg_util('isjob_id', udmodlist.cjob))
udmodlist = local_init_udmodlist;
udmodlist.cjob = cfg_util('initjob');
set(handles.modlist, 'userdata', udmodlist);
end;
% set initial font
fs = cfg_get_defaults([mfilename '.lfont']);
local_setfont(hObject, fs);
% set ExpertEdit checkbox
set(handles.MenuViewExpertEdit, ...
'checked',cfg_get_defaults([mfilename '.ExpertEdit']));
% show job
local_showjob(hObject);
% Choose default command line output for cfg_ui
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes cfg_ui wait for user response (see UIRESUME)
% uiwait(handles.cfg_ui);
% --- Outputs from this function are returned to the command line.
function varargout = cfg_ui_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;
%% File Menu Callbacks
% --------------------------------------------------------------------
function MenuFile_Callback(hObject, eventdata, handles)
% hObject handle to MenuFile (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function MenuFileNew_Callback(hObject, eventdata, handles)
% hObject handle to MenuFileNew (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
udmodlist = get(handles.modlist, 'userdata');
if isfield(udmodlist, 'modified') && udmodlist.modified
cmd = questdlg(['The current batch contains unsaved changes. '...
'Do you want to replace it with another batch?'], ...
'Unsaved Changes', 'Continue','Cancel', 'Continue');
else
cmd = 'Continue';
end;
if strcmpi(cmd,'continue')
udmodlist = get(handles.modlist, 'userdata');
if ~isempty(udmodlist.cmod)
cfg_util('deljob',udmodlist(1).cjob);
end;
udmodlist = local_init_udmodlist;
udmodlist.cjob = cfg_util('initjob');
set(handles.modlist, 'userdata', udmodlist);
local_showjob(hObject);
end;
% --------------------------------------------------------------------
function MenuFileLoad_Callback(hObject, eventdata, handles)
% hObject handle to MenuFileLoad (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
udmodlist = get(handles.modlist, 'userdata');
if udmodlist.modified
cmd = questdlg(['The current batch contains unsaved changes. '...
'Do you want to replace it with another batch?'], ...
'Unsaved Changes', 'Continue','Cancel', 'Continue');
else
cmd = 'Continue';
end;
if strcmpi(cmd,'continue')
[files sts] = cfg_getfile([1 Inf], 'batch', 'Load Job File(s)', {}, udmodlist.wd);
if sts
local_pointer('watch');
cfg_util('deljob',udmodlist(1).cjob);
udmodlist = local_init_udmodlist;
try
udmodlist.wd = fileparts(files{1});
udmodlist.cjob = cfg_util('initjob', files);
catch
l = lasterror;
errordlg(l.message,'Error loading job', 'modal');
end
set(handles.modlist, 'userdata', udmodlist);
set(handles.module, 'userdata', []);
local_showjob(hObject);
local_pointer('arrow');
end;
end;
% --------------------------------------------------------------------
function MenuFileSave_Callback(hObject, eventdata, handles)
% hObject handle to MenuFileSave (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
udmodlist = get(handles.modlist, 'userdata');
opwd = pwd;
if ~isempty(udmodlist.wd)
cd(udmodlist.wd);
end;
[file pth idx] = uiputfile({'*.mat','Matlab .mat File';...
'*.m','Matlab .m Script File'}, 'Save Job');
cd(opwd);
if isnumeric(file) && file == 0
return;
end;
local_pointer('watch');
[p n e] = fileparts(file);
if isempty(e) || ~any(strcmp(e,{'.mat','.m'}))
e1 = {'.mat','.m'};
e2 = e1{idx};
file = sprintf('%s%s', n, e);
else
file = n;
e2 = e;
end
try
cfg_util('savejob', udmodlist.cjob, fullfile(pth, [file e2]));
udmodlist.modified = false;
udmodlist.wd = pth;
set(handles.modlist,'userdata',udmodlist);
catch
l = lasterror;
errordlg(l.message,'Error saving job', 'modal');
end
local_pointer('arrow');
% --------------------------------------------------------------------
function MenuFileScript_Callback(hObject, eventdata, handles)
% hObject handle to MenuFileScript (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
udmodlist = get(handles.modlist, 'userdata');
opwd = pwd;
if ~isempty(udmodlist.wd)
cd(udmodlist.wd);
end;
[file pth idx] = uiputfile({'*.m','Matlab .m Script File'},...
'Script File name');
cd(opwd);
if isnumeric(file) && file == 0
return;
end;
local_pointer('watch');
[p n e] = fileparts(file);
try
cfg_util('genscript', udmodlist.cjob, pth, [n '.m']);
udmodlist.modified = false;
udmodlist.wd = pth;
set(handles.modlist,'userdata',udmodlist);
if ~isdeployed
edit(fullfile(pth, [n '.m']));
end
catch
l = lasterror;
errordlg(l.message,'Error generating job script', 'modal');
end
local_pointer('arrow');
function MenuFileRun_Callback(hObject, eventdata, handles)
% hObject handle to MenuFileRun (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
local_pointer('watch');
udmodlist = get(handles.modlist, 'userdata');
try
cfg_util('run',udmodlist(1).cjob);
catch
l = lasterror;
errordlg(l.message,'Error in job execution', 'modal');
end;
local_pointer('arrow');
% --------------------------------------------------------------------
function MenuFileRunSerial_Callback(hObject, eventdata, handles)
% hObject handle to MenuFileRunSerial (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
local_pointer('watch');
udmodlist = get(handles.modlist, 'userdata');
cfg_util('runserial',udmodlist(1).cjob);
local_pointer('arrow');
% --------------------------------------------------------------------
function MenuFileAddApp_Callback(hObject, eventdata, handles)
% hObject handle to MenuFileAddApp (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
udmodlist = get(handles.modlist, 'userdata');
if udmodlist.modified
cmd = questdlg(['The current batch contains unsaved changes. '...
'Adding a new application will discard this batch.'], ...
'Unsaved Changes', 'Continue','Cancel', 'Continue');
else
cmd = 'Continue';
end;
if strcmpi(cmd,'continue')
[file sts] = cfg_getfile([1 1], '.*\.m$', 'Load Application Configuration');
if sts
udmodlist = get(handles.modlist, 'userdata');
if ~isempty(udmodlist.cmod)
cfg_util('deljob',udmodlist(1).cjob);
end;
[p fun e] = fileparts(file{1});
addpath(p);
cfg_util('addapp', fun);
local_setmenu(handles.cfg_ui, [], @local_addtojob, true);
udmodlist = local_init_udmodlist;
udmodlist.cjob = cfg_util('initjob');
set(handles.modlist, 'userdata', udmodlist);
local_showjob(hObject);
end;
end;
% --------------------------------------------------------------------
function MenuFileClose_Callback(hObject, eventdata, handles)
% hObject handle to MenuFileClose (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
close(handles.cfg_ui);
%% Edit Menu Callbacks
% --------------------------------------------------------------------
function MenuEdit_Callback(hObject, eventdata, handles)
% hObject handle to MenuEdit (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function MenuViewUpdateView_Callback(hObject, eventdata, handles)
% hObject handle to MenuViewUpdateView (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% This function seems to be called on startup without guidata - do nothing
% there
if ~isempty(handles)
local_setmenu(handles.cfg_ui, [], @local_addtojob, true);
udmodlist = get(handles.modlist,'Userdata');
if isstruct(udmodlist)
if isfield(udmodlist,'defid')
local_showmod(hObject);
else
local_showjob(hObject);
end;
end
end;
% --------------------------------------------------------------------
function MenuEditReplMod_Callback(hObject, eventdata, handles)
% hObject handle to MenuEditReplMod (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
local_ReplMod(hObject);
% --------------------------------------------------------------------
function MenuEditDelMod_Callback(hObject, eventdata, handles)
% hObject handle to MenuEditDelMod (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
local_DelMod(hObject);
% --------------------------------------------------------------------
function MenuEditValEditVal_Callback(hObject, eventdata, handles)
% hObject handle to MenuEditValEditVal (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
local_valedit_EditValue(hObject);
% --------------------------------------------------------------------
function MenuEditValClearVal_Callback(hObject, eventdata, handles)
% hObject handle to MenuEditValClearVal (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
local_valedit_ClearVal(hObject);
% --------------------------------------------------------------------
function MenuEditValSelectFiles_Callback(hObject, eventdata, handles)
% hObject handle to MenuEditValSelectFiles (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
local_valedit_SelectFiles(hObject);
% --------------------------------------------------------------------
function MenuEditValAddDep_Callback(hObject, eventdata, handles)
% hObject handle to MenuEditValAddDep (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
local_valedit_AddDep(hObject);
% --------------------------------------------------------------------
function MenuViewExpertEdit_Callback(hObject, eventdata, handles)
% hObject handle to MenuViewExpertEdit (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if strcmp(get(gcbo,'checked'),'on')
newstate = 'off';
else
newstate = 'on';
end;
set(gcbo, 'checked', newstate);
cfg_get_defaults([mfilename '.ExpertEdit'], newstate);
%% Module List Callbacks
% --- Executes on selection change in modlist.
function modlist_Callback(hObject, eventdata, handles)
% hObject handle to modlist (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = get(hObject,'String') returns modlist contents as cell array
% contents{get(hObject,'Value')} returns selected item from modlist
udmodlist = get(handles.modlist, 'userdata');
if ~isempty(udmodlist.cmod)
if ~isfield(udmodlist, 'defid')
local_showjob(hObject);
else
local_showmod(hObject);
end;
end;
% Return focus to modlist - otherwise it would be on current module
uicontrol(handles.modlist);
% --- Executes during object creation, after setting all properties.
function modlist_CreateFcn(hObject, eventdata, handles)
% hObject handle to modlist (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
%% Module List Context Menu Callbacks
% --------------------------------------------------------------------
function CmModlistReplMod_Callback(hObject, eventdata, handles)
% hObject handle to CmModlistReplMod (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
local_ReplMod(hObject);
% --------------------------------------------------------------------
function CmModlistDelMod_Callback(hObject, eventdata, handles)
% hObject handle to CmModlistDelMod (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
local_DelMod(hObject);
% --------------------------------------------------------------------
function CmModlist_Callback(hObject, eventdata, handles)
% hObject handle to CmModlist (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%% Module Callbacks
% --- Executes on selection change in module.
function module_Callback(hObject, eventdata, handles)
% hObject handle to module (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = get(hObject,'String') returns module contents as cell array
% contents{get(hObject,'Value')} returns selected item from module
% Selection change is called both when there is a real selection change,
% but also if return is hit or there is a double click
value = get(hObject,'Value');
udmodule = get(hObject,'Userdata');
if isempty(udmodule)
return;
end;
if udmodule.oldvalue ~= value
udmodule.oldvalue = value;
set(hObject, 'Userdata', udmodule);
local_showvaledit(hObject);
end;
if strcmp(get(handles.cfg_ui,'SelectionType'),'open')
% open modal MenuEdit window, do editing
% Unfortunately, MATLAB focus behaviour makes it impossible to do this
% in the existing valshow object - if this object looses focus, it will
% call its callback without checking why it lost focus.
% Call appropriate input handler for editable and selection types
switch udmodule.contents{5}{value}
case {'cfg_entry'},
local_valedit_edit(hObject);
case { 'cfg_files'},
local_valedit_SelectFiles(hObject);
case {'cfg_choice', 'cfg_menu'},
local_valedit_list(hObject);
case {'cfg_repeat'},
local_valedit_repeat(hObject);
end;
end;
% --- Executes during object creation, after setting all properties.
function module_CreateFcn(hObject, eventdata, handles)
% hObject handle to module (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
%% Value Display Callbacks
% --- Executes during object creation, after setting all properties.
function valshow_CreateFcn(hObject, eventdata, handles)
% hObject handle to valshow (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: MenuEdit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --------------------------------------------------------------------
function valshow_Callback(hObject, eventdata, handles)
% hObject handle to valshow (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of valshow as text
% str2double(get(hObject,'String')) returns contents of valshow as a double
%% GUI Buttons
% --- Executes on button press in BtnValSelectFiles.
function BtnValSelectFiles_Callback(hObject, eventdata, handles)
% hObject handle to BtnValSelectFiles (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
local_valedit_SelectFiles(hObject);
% --- Executes on button press in BtnValEditVal.
function BtnValEditVal_Callback(hObject, eventdata, handles)
% hObject handle to BtnValEditVal (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
local_valedit_EditValue(hObject);
% --- Executes on button press in BtnValAddDep.
function BtnValAddDep_Callback(hObject, eventdata, handles)
% hObject handle to BtnValAddDep (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
local_valedit_AddDep(hObject);
% --------------------------------------------------------------------
function udmodlist = local_init_udmodlist
% Initialise udmodlist to empty struct
% Don't initialise defid field - this will be added by defaults editor
udmodlist = struct('cjob',[],'cmod',[],'id',[],'sout',[],'modified',false,'wd','');
% --------------------------------------------------------------------
function udvalshow = local_init_udvalshow
% Initialise udvalshow to empty struct
udvalshow = struct('cval',[],'en',[],'key',[]);
% --------------------------------------------------------------------
function ltop = local_getListboxTop(obj, val, maxval)
% Get a safe value for ListboxTop property while keeping previous settings
% if possible.
% obj handle of Listbox object
% val new Value property
% maxval new number of lines in obj
oltop = get(obj, 'ListboxTop');
ltop = min([max(oltop,1), max(val-1,1), maxval]);
% --- Executes when user attempts to close cfg_ui.
function cfg_ui_CloseRequestFcn(hObject, eventdata, handles)
% hObject handle to cfg_ui (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: delete(hObject) closes the figure
udmodlist = get(handles.modlist,'userdata');
if udmodlist.modified
cmd = questdlg(['The current batch contains unsaved changes. Do you want to quit ' ...
'anyway or do you want to hide the batch window ' ...
'instead?'], 'Unsaved Changes', 'Quit','Cancel','Hide', ...
'Quit');
else
cmd = 'Quit';
end;
switch lower(cmd)
case 'quit'
if ~isempty(udmodlist.cjob)
cfg_util('deljob', udmodlist.cjob);
end;
set(hObject,'Visible','off');
udmodlist = local_init_udmodlist;
udmodlist.cjob = cfg_util('initjob');
set(handles.modlist,'userdata',udmodlist);
case 'hide'
set(hObject,'Visible','off');
end;
% --- Executes on button press in valshowBtnAccept.
function valshowBtnAccept_Callback(hObject, eventdata, handles)
% hObject handle to valshowBtnAccept (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 valshowBtnCancel.
function valshowBtnCancel_Callback(hObject, eventdata, handles)
% hObject handle to valshowBtnCancel (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function MenuViewFontSize_Callback(hObject, eventdata, handles)
% hObject handle to MenuViewFontSize (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
fs = uisetfont(cfg_get_defaults([mfilename '.lfont']));
if isstruct(fs)
local_setfont(hObject,fs);
MenuViewUpdateView_Callback(hObject, eventdata, handles);
end;
% --- Executes when cfg_ui is resized.
function cfg_ui_ResizeFcn(hObject, eventdata, handles)
% hObject handle to cfg_ui (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% this is just "Update View"
MenuViewUpdateView_Callback(hObject, eventdata, handles);
% --------------------------------------------------------------------
function local_setfont(obj,fs)
handles = guidata(obj);
cfg_get_defaults([mfilename '.lfont'], fs);
% construct argument list for set
fn = fieldnames(fs);
fs = struct2cell(fs);
fnfs = [fn'; fs'];
set(handles.modlist, fnfs{:});
set(handles.module, fnfs{:});
set(handles.valshow, fnfs{:});
set(handles.helpbox, fnfs{:});
% --------------------------------------------------------------------
function local_pointer(ptr)
shh = get(0,'showhiddenhandles');
set(0,'showhiddenhandles','on');
set(get(0,'Children'),'Pointer',ptr);
drawnow;
set(0,'showhiddenhandles',shh);
% --------------------------------------------------------------------
function CmValEditVal_Callback(hObject, eventdata, handles)
% hObject handle to CmValEditVal (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
local_valedit_EditValue(hObject);
% --------------------------------------------------------------------
function CmValSelectFiles_Callback(hObject, eventdata, handles)
% hObject handle to CmValSelectFiles (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
local_valedit_SelectFiles(hObject);
% --------------------------------------------------------------------
function CmValAddDep_Callback(hObject, eventdata, handles)
% hObject handle to CmValAddDep (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
local_valedit_AddDep(hObject);
% --------------------------------------------------------------------
function CmValClearVal_Callback(hObject, eventdata, handles)
% hObject handle to CmValClearVal (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
local_valedit_ClearVal(hObject);
% --------------------------------------------------------------------
function MenuView_Callback(hObject, eventdata, handles)
% hObject handle to MenuView (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function MenuViewShowCode_Callback(hObject, eventdata, handles)
% hObject handle to MenuViewShowCode (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
udmodlist = get(handles.modlist, 'userdata');
[un matlabbatch] = cfg_util('harvest', udmodlist.cjob);
str = gencode(matlabbatch);
fg = findobj(0,'Type','figure','Tag',[mfilename 'ShowCode']);
if isempty(fg)
fg = figure('Menubar','none', 'Toolbar','none', 'Tag',[mfilename 'ShowCode'], 'Units','normalized', 'Name','Batch Code Browser', 'NumberTitle','off');
ctxt = uicontrol('Parent',fg, 'Style','listbox', 'Units','normalized', 'Position',[0 0 1 1], 'FontName','FixedWidth','Tag',[mfilename 'ShowCodeList']);
else
figure(fg);
ctxt = findobj(fg,'Tag',[mfilename 'ShowCodeList']);
end
um = uicontextmenu;
um1 = uimenu('Label','Copy', 'Callback',@(ob,ev)ShowCode_Copy(ob,ev,ctxt), 'Parent',um);
um1 = uimenu('Label','Select all', 'Callback',@(ob,ev)ShowCode_SelAll(ob,ev,ctxt), 'Parent',um);
um1 = uimenu('Label','Unselect all', 'Callback',@(ob,ev)ShowCode_UnSelAll(ob,ev,ctxt), 'Parent',um);
set(ctxt, 'Max',numel(str), 'UIContextMenu',um, 'Value',[], 'ListboxTop',1);
set(ctxt, 'String',str);
function ShowCode_Copy(ob, ev, ctxt)
str = get(ctxt,'String');
sel = get(ctxt,'Value');
str = str(sel);
clipboard('copy',sprintf('%s\n',str{:}));
function ShowCode_SelAll(ob, ev, ctxt)
set(ctxt,'Value', 1:numel(get(ctxt, 'String')));
function ShowCode_UnSelAll(ob, ev, ctxt)
set(ctxt,'Value', []);
|
github
|
philippboehmsturm/antx-master
|
gencode_rvalue.m
|
.m
|
antx-master/xspm8/matlabbatch/gencode_rvalue.m
| 4,767 |
utf_8
|
324bb965793e9d6d29c11737869ea998
|
function [str, sts] = gencode_rvalue(item)
% GENCODE_RVALUE Code for right hand side of MATLAB assignment
% Generate the right hand side for a valid MATLAB variable
% assignment. This function is a helper to GENCODE, but can be used on
% its own to generate code for the following types of variables:
% * scalar, 1D or 2D numeric, logical or char arrays
% * scalar or 1D cell arrays, where each item can be one of the supported
% array types (i.e. nested cells are allowed)
%
% function [str, sts] = gencode_rvalue(item)
% Input argument:
% item - value to generate code for
% Output arguments:
% str - cellstr with generated code, line per line
% sts - true, if successful, false if code could not be generated
%
% See also GENCODE, 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_rvalue.m 6128 2014-08-01 16:09:57Z guillaume $
rev = '$Rev: 6128 $'; %#ok
str = {};
sts = true;
switch class(item)
case 'char'
if ndims(item) == 2 %#ok<ISMAT>
cstr = {''};
% Create cell string, keep white space padding
for k = 1:size(item,1)
cstr{k} = item(k,:);
end
str1 = genstrarray(cstr);
if numel(str1) == 1
% One string, do not print brackets
str = str1;
else
% String array, print brackets and concatenate str1
str = [ {'['} str1(:)' {']'} ];
end
else
% not an rvalue
sts = false;
end
case 'cell'
if isempty(item)
str = {'{}'};
elseif ndims(item) == 2 && any(size(item) == 1) %#ok<ISMAT>
str1 = {};
for k = 1:numel(item)
[str2 sts] = gencode_rvalue(item{k});
if ~sts
break;
end
str1 = [str1(:)' str2(:)'];
end
if sts
if numel(str1) == 1
% One item, print as one line
str{1} = sprintf('{%s}', str1{1});
else
% Cell vector, print braces and concatenate str1
if size(item,1) == 1
endstr = {'}'''};
else
endstr = {'}'};
end
str = [{'{'} str1(:)' endstr];
end
end
else
sts = false;
end
case 'function_handle'
fstr = func2str(item);
% sometimes (e.g. for anonymous functions) '@' is already included
% in func2str output
if fstr(1) == '@'
str{1} = fstr;
else
str{1} = sprintf('@%s', fstr);
end
otherwise
if isobject(item) || ~(isnumeric(item) || islogical(item)) || issparse(item) || ndims(item) > 2 %#ok<ISMAT>
sts = false;
else
% treat item as numeric or logical, don't create 'class'(...)
% classifier code for double
clsitem = class(item);
if isempty(item)
if strcmp(clsitem, 'double') %#ok<STISA>
str{1} = '[]';
else
str{1} = sprintf('%s([])', clsitem);
end
else
% Use mat2str with standard precision 15
if any(strcmp(clsitem, {'double', 'logical'}))
sitem = mat2str(item);
else
sitem = mat2str(item,'class');
end
try
if ~verLessThan('matlab', '8.4')
bszopt = {};
else
error('Need bufsize option');
end
catch
bsz = max(numel(sitem)+2,100); % bsz needs to be > 100 and larger than string length
bszopt = {'bufsize', bsz};
end
str1 = textscan(sitem, '%s', 'delimiter',';', bszopt{:});
if numel(str1{1}) > 1
str = str1{1};
else
str{1} = str1{1}{1};
end
end
end
end
function str = genstrarray(stritem)
% generate a cell string of properly quoted strings suitable for code
% generation.
str = strrep(stritem, '''', '''''');
for k = 1:numel(str)
str{k} = sprintf('''%s''', str{k});
end
|
github
|
philippboehmsturm/antx-master
|
cfg_getfile.m
|
.m
|
antx-master/xspm8/matlabbatch/cfg_getfile.m
| 46,070 |
utf_8
|
3e6a6877315f1b08af13c88de5044295
|
function [t,sts] = cfg_getfile(varargin)
% File selector
% FORMAT [t,sts] = cfg_getfile(n,typ,mesg,sel,wd,filt,frames)
% n - Number of files
% A single value or a range. e.g.
% 1 - Select one file
% Inf - Select any number of files
% [1 Inf] - Select 1 to Inf files
% [0 1] - select 0 or 1 files
% [10 12] - select from 10 to 12 files
% typ - file type
% 'any' - all files
% 'batch' - SPM batch files (.m, .mat and XML)
% 'dir' - select a directory
% 'image' - Image files (".img" and ".nii")
% Note that it gives the option to select
% individual volumes of the images.
% 'mat' - Matlab .mat files or .txt files (assumed to contain
% ASCII representation of a 2D-numeric array)
% 'mesh' - Mesh files (".gii" and ".mat")
% 'nifti' - NIfTI files without the option to select frames
% 'xml' - XML files
% Other strings act as a filter to regexp. This means
% that e.g. DCM*.mat files should have a typ of '^DCM.*\.mat$'
% mesg - a prompt (default 'Select files...')
% sel - list of already selected files
% wd - Directory to start off in
% filt - value for user-editable filter (default '.*')
% frames - Image frame numbers to include (default '1')
%
% t - selected files
% sts - status (1 means OK, 0 means window quit)
%
% FORMAT [t,ind] = cfg_getfile('Filter',files,typ,filt,frames)
% filter the list of files (cell array) in the same way as the
% GUI would do. There is an additional typ 'extimage' which will match
% images with frame specifications, too. The 'frames' argument
% is currently ignored, i.e. image files will not be filtered out if
% their frame numbers do not match.
% When filtering directory names, the filt argument will be applied to the
% last directory in a path only.
% t returns the filtered list (cell array), ind an index array, such that
% t = files(ind).
%
% FORMAT cpath = cfg_getfile('CPath',path,cwd)
% function to canonicalise paths: Prepends cwd to relative paths, processes
% '..' & '.' directories embedded in path.
% path - string matrix containing path name
% cwd - current working directory [default '.']
% cpath - conditioned paths, in same format as input path argument
%
% FORMAT [files,dirs]=cfg_getfile('List',direc,filt)
% Returns files matching the filter (filt) and directories within dire
% direc - directory to search
% filt - filter to select files with (see regexp) e.g. '^w.*\.img$'
% files - files matching 'filt' in directory 'direc'
% dirs - subdirectories of 'direc'
% FORMAT [files,dirs]=cfg_getfile('ExtList',direc,filt,frames)
% As above, but for selecting frames of 4D NIfTI files
% frames - vector of frames to select (defaults to 1, if not
% specified). If the frame number is Inf, all frames for the
% matching images are listed.
% FORMAT [files,dirs]=cfg_getfile('FPList',direc,filt)
% FORMAT [files,dirs]=cfg_getfile('ExtFPList',direc,filt,frames)
% As above, but returns files with full paths (i.e. prefixes direc to each)
% FORMAT [files,dirs]=cfg_getfile('FPListRec',direc,filt)
% FORMAT [files,dirs]=cfg_getfile('ExtFPListRec',direc,filt,frames)
% As above, but returns files with full paths (i.e. prefixes direc to
% each) and searches through sub directories recursively.
%
% FORMAT cfg_getfile('prevdirs',dir)
% Add directory dir to list of previous directories.
% FORMAT dirs=cfg_getfile('prevdirs')
% Retrieve list of previous directories.
%
% This code is based on the file selection dialog in SPM5, with virtual
% file handling turned off.
%____________________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
%
% 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
% John Ashburner and Volkmar Glauche
% $Id: cfg_getfile.m 6251 2014-10-30 13:58:44Z volkmar $
t = {};
sts = false;
if nargin > 0 && ischar(varargin{1})
switch lower(varargin{1})
case {'addvfiles', 'clearvfiles', 'vfiles'}
cfg_message('matlabbatch:deprecated:vfiles', ...
'Trying to use deprecated ''%s'' call.', ...
lower(varargin{1}));
case 'cpath'
cfg_message(nargchk(2,Inf,nargin,'struct'));
t = cpath(varargin{2:end});
sts = true;
case 'filter'
filt = mk_filter(varargin{3:end});
t = varargin{2};
if numel(t) == 1 && isempty(t{1})
sts = 1;
return;
end;
t1 = cell(size(t));
if any(strcmpi(varargin{3},{'dir','extdir'}))
% only filter last directory in path
for k = 1:numel(t)
t{k} = cpath(t{k});
if t{k}(end) == filesep
[p n] = fileparts(t{k}(1:end-1));
else
[p n] = fileparts(t{k});
end
if strcmpi(varargin{3},'extdir')
t1{k} = [n filesep];
else
t1{k} = n;
end
end
else
% only filter filenames, not paths
for k = 1:numel(t)
[p n e] = fileparts(t{k});
t1{k} = [n e];
end
end
[t1,sts1] = do_filter(t1,filt.ext);
[t1,sts2] = do_filter(t1,filt.filt);
sts = sts1(sts2);
t = t(sts);
case {'list', 'fplist', 'extlist', 'extfplist'}
if nargin > 3
frames = varargin{4};
else
frames = 1; % (ignored in listfiles if typ==any)
end;
if regexpi(varargin{1}, 'ext') % use frames descriptor
typ = 'extimage';
else
typ = 'any';
end
filt = mk_filter(typ, varargin{3}, frames);
[t sts] = listfiles(varargin{2}, filt); % (sts is subdirs here)
sts = sts(~(strcmp(sts,'.')|strcmp(sts,'..'))); % remove '.' and '..' entries
if regexpi(varargin{1}, 'fplist') % return full pathnames
direc = cfg_getfile('cpath', varargin{2});
% remove trailing path separator if present
direc = regexprep(direc, [filesep '$'], '');
if ~isempty(t)
t = strcat(direc, filesep, t);
end
if nargout > 1
% subdirs too
sts = cellfun(@(sts1)cpath(sts1, direc), sts, 'UniformOutput',false);
end
end
case {'fplistrec', 'extfplistrec'}
% list directory
[f1 d1] = cfg_getfile(varargin{1}(1:end-3),varargin{2:end});
f2 = cell(size(d1));
d2 = cell(size(d1));
for k = 1:numel(d1)
% recurse into sub directories
[f2{k} d2{k}] = cfg_getfile(varargin{1}, d1{k}, ...
varargin{3:end});
end
t = vertcat(f1, f2{:});
if nargout > 1
sts = vertcat(d1, d2{:});
end
case 'prevdirs',
if nargin > 1
prevdirs(varargin{2});
end;
if nargout > 0 || nargin == 1
t = prevdirs;
sts = true;
end;
otherwise
cfg_message('matlabbatch:usage','Inappropriate usage.');
end
else
[t,sts] = selector(varargin{:});
end
%=======================================================================
%=======================================================================
function [t,ok] = selector(n,typ,mesg,already,wd,filt,frames,varargin)
if nargin<1 || ~isnumeric(n) || numel(n) > 2
n = [0 Inf];
else
if numel(n)==1, n = [n n]; end;
if n(1)>n(2), n = n([2 1]); end;
if ~isfinite(n(1)), n(1) = 0; end;
end
if nargin<2 || ~ischar(typ), typ = 'any'; end;
if nargin<3 || ~(ischar(mesg) || iscellstr(mesg))
mesg = 'Select files...';
elseif iscellstr(mesg)
mesg = char(mesg);
end
if nargin<4 || isempty(already) || (iscell(already) && isempty(already{1}))
already = {};
else
% Add folders of already selected files to prevdirs list
pd1 = cellfun(@(a1)strcat(fileparts(a1),filesep), already, ...
'UniformOutput',false);
prevdirs(pd1);
end
if nargin<5 || isempty(wd) || ~ischar(wd)
if isempty(already)
wd = pwd;
else
wd = fileparts(already{1});
if isempty(wd)
wd = pwd;
end
end;
end
if nargin<6 || ~ischar(filt), filt = '.*'; end;
if nargin<7 || ~(isnumeric(frames) || ischar(frames))
frames = '1';
elseif isnumeric(frames)
frames = char(gencode_rvalue(frames(:)'));
elseif ischar(frames)
try
ev = eval(frames);
if ~isnumeric(ev)
frames = '1';
end
catch
frames = '1';
end
end
ok = 0;
t = '';
sfilt = mk_filter(typ,filt,eval(frames));
[col1,col2,col3,lf,bf] = colours;
% delete old selector, if any
fg = findobj(0,'Tag',mfilename);
if ~isempty(fg)
delete(fg);
end
% create figure
fg = figure('IntegerHandle','off',...
'Tag',mfilename,...
'Name',mesg,...
'NumberTitle','off',...
'Units','Pixels',...
'MenuBar','none',...
'DefaultTextInterpreter','none',...
'DefaultUicontrolInterruptible','on',...
'Visible','off');
cfg_onscreen(fg);
set(fg,'Visible','on');
sellines = min([max([n(2) numel(already)]), 4]);
[pselp pcntp pfdp pdirp] = panelpositions(fg, sellines+1);
uicontrol(fg,...
'style','text',...
'units','normalized',...
'position',posinpanel([0 sellines/(sellines+1) 1 1/(sellines+1)],pselp),...
lf,...
'BackgroundColor',get(fg,'Color'),...
'ForegroundColor',col3,...
'HorizontalAlignment','left',...
'string',mesg,...
'tag','msg');
% Selected Files
sel = uicontrol(fg,...
'style','listbox',...
'units','normalized',...
'Position',posinpanel([0 0 1 sellines/(sellines+1)],pselp),...
lf,...
'Callback',@unselect,...
'tag','selected',...
'BackgroundColor',col1,...
'ForegroundColor',col3,...
'Max',10000,...
'Min',0,...
'String',already,...
'Value',1);
c0 = uicontextmenu('Parent',fg);
set(sel,'uicontextmenu',c0);
uimenu('Label','Unselect All', 'Parent',c0,'Callback',@unselect_all);
% get cwidth for buttons
tmp=uicontrol('style','text','string',repmat('X',[1,50]),bf,...
'units','normalized','visible','off');
fnp = get(tmp,'extent');
delete(tmp);
cw = 3*fnp(3)/50;
if strcmpi(typ,'image'),
uicontrol(fg,...
'style','edit',...
'units','normalized',...
'Position',posinpanel([0.61 0 0.37 .45],pcntp),...
'Callback',@update_frames,...
'tag','frame',...
lf,...
'BackgroundColor',col1,...
'String',frames,'UserData',eval(frames));
% 'ForegroundGolor',col3,...
end;
% Help
uicontrol(fg,...
'Style','pushbutton',...
'units','normalized',...
'Position',posinpanel([0.02 .5 cw .45],pcntp),...
bf,...
'Callback',@heelp,...
'tag','?',...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'String','?',...
'ToolTipString','Show Help');
uicontrol(fg,...
'Style','pushbutton',...
'units','normalized',...
'Position',posinpanel([0.03+cw .5 cw .45],pcntp),...
bf,...
'Callback',@editwin,...
'tag','Ed',...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'String','Ed',...
'ToolTipString','Edit Selected Files');
uicontrol(fg,...
'Style','pushbutton',...
'units','normalized',...
'Position',posinpanel([0.04+2*cw .5 cw .45],pcntp),...
bf,...
'Callback',@select_rec,...
'tag','Rec',...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'String','Rec',...
'ToolTipString','Recursively Select Files with Current Filter');
% Done
dne = uicontrol(fg,...
'Style','pushbutton',...
'units','normalized',...
'Position',posinpanel([0.05+3*cw .5 0.45-3*cw .45],pcntp),...
bf,...
'Callback',@(h,e)delete(h),...
'tag','D',...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'String','Done',...
'Enable','off',...
'DeleteFcn',@null);
if numel(already)>=n(1) && numel(already)<=n(2),
set(dne,'Enable','on');
end;
% Filter Button
uicontrol(fg,...
'Style','pushbutton',...
'units','normalized',...
'Position',posinpanel([0.51 .5 0.1 .45],pcntp),...
bf,...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'Callback',@clearfilt,...
'String','Filt');
% Filter
uicontrol(fg,...
'style','edit',...
'units','normalized',...
'Position',posinpanel([0.61 .5 0.37 .45],pcntp),...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
lf,...
'Callback',@(ob,ev)update(ob),...
'tag','regexp',...
'String',filt,...
'UserData',sfilt);
% Directories
db = uicontrol(fg,...
'style','listbox',...
'units','normalized',...
'Position',posinpanel([0.02 0 0.47 1],pfdp),...
lf,...
'Callback',@click_dir_box,...
'tag','dirs',...
'BackgroundColor',col1,...
'ForegroundColor',col3,...
'Max',1,...
'Min',0,...
'String','',...
'UserData',wd,...
'Value',1);
% Files
tmp = uicontrol(fg,...
'style','listbox',...
'units','normalized',...
'Position',posinpanel([0.51 0 0.47 1],pfdp),...
lf,...
'Callback',@click_file_box,...
'tag','files',...
'BackgroundColor',col1,...
'ForegroundColor',col3,...
'UserData',n,...
'Max',10240,...
'Min',0,...
'String','',...
'Value',1);
c0 = uicontextmenu('Parent',fg);
set(tmp,'uicontextmenu',c0);
uimenu('Label','Select All', 'Parent',c0,'Callback',@select_all);
% Drives
if strcmpi(computer,'PCWIN') || strcmpi(computer,'PCWIN64'),
% get fh for lists
tmp=uicontrol('style','text','string','X',lf,...
'units','normalized','visible','off');
fnp = get(tmp,'extent');
delete(tmp);
fh = 2*fnp(4); % Heuristics: why do we need 2*
sz = get(db,'Position');
sz(4) = sz(4)-fh-2*0.01;
set(db,'Position',sz);
uicontrol(fg,...
'style','text',...
'units','normalized',...
'Position',posinpanel([0.02 1-fh-0.01 0.10 fh],pfdp),...
'HorizontalAlignment','left',...
lf,...
'BackgroundColor',get(fg,'Color'),...
'ForegroundColor',col3,...
'String','Drive');
uicontrol(fg,...
'style','popupmenu',...
'units','normalized',...
'Position',posinpanel([0.12 1-fh-0.01 0.37 fh],pfdp),...
lf,...
'Callback',@setdrive,...
'tag','drive',...
'BackgroundColor',col1,...
'ForegroundColor',col3,...
'String',listdrives(false),...
'Value',1);
end;
[pd,vl] = prevdirs([wd filesep]);
% Previous dirs
uicontrol(fg,...
'style','popupmenu',...
'units','normalized',...
'Position',posinpanel([0.12 .05 0.86 .95*1/3],pdirp),...
lf,...
'Callback',@click_dir_list,...
'tag','previous',...
'BackgroundColor',col1,...
'ForegroundColor',col3,...
'String',pd,...
'Value',vl);
uicontrol(fg,...
'style','text',...
'units','normalized',...
'Position',posinpanel([0.02 0 0.10 .95*1/3],pdirp),...
'HorizontalAlignment','left',...
lf,...
'BackgroundColor',get(fg,'Color'),...
'ForegroundColor',col3,...
'String','Prev');
% Parent dirs
uicontrol(fg,...
'style','popupmenu',...
'units','normalized',...
'Position',posinpanel([0.12 1/3+.05 0.86 .95*1/3],pdirp),...
lf,...
'Callback',@click_dir_list,...
'tag','pardirs',...
'BackgroundColor',col1,...
'ForegroundColor',col3,...
'String',pardirs(wd));
uicontrol(fg,...
'style','text',...
'units','normalized',...
'Position',posinpanel([0.02 1/3 0.10 .95*1/3],pdirp),...
'HorizontalAlignment','left',...
lf,...
'BackgroundColor',get(fg,'Color'),...
'ForegroundColor',col3,...
'String','Up');
% Directory
uicontrol(fg,...
'style','edit',...
'units','normalized',...
'Position',posinpanel([0.12 2/3 0.86 .95*1/3],pdirp),...
lf,...
'Callback',@edit_dir,...
'tag','edit',...
'BackgroundColor',col1,...
'ForegroundColor',col3,...
'String','');
uicontrol(fg,...
'style','text',...
'units','normalized',...
'Position',posinpanel([0.02 2/3 0.10 .95*1/3],pdirp),...
'HorizontalAlignment','left',...
lf,...
'BackgroundColor',get(fg,'Color'),...
'ForegroundColor',col3,...
'String','Dir');
resize_fun(fg);
set(fg, 'ResizeFcn',@resize_fun);
update(sel,wd)
set(fg,'windowstyle', 'modal');
waitfor(dne);
drawnow;
if ishandle(sel),
t = get(sel,'String');
if isempty(t)
t = {''};
elseif sfilt.code == -1
% canonicalise non-empty folder selection
t = cellfun(@(t1)cpath(t1, pwd), t, 'UniformOutput',false);
end;
ok = 1;
end;
if ishandle(fg), delete(fg); end;
drawnow;
return;
%=======================================================================
%=======================================================================
function apos = posinpanel(rpos,ppos)
% Compute absolute positions based on panel position and relative
% position
apos = [ppos(1:2)+ppos(3:4).*rpos(1:2) ppos(3:4).*rpos(3:4)];
%=======================================================================
%=======================================================================
function [pselp, pcntp, pfdp, pdirp] = panelpositions(fg, sellines)
if nargin == 1
na = numel(get(findobj(fg,'Tag','selected'),'String'));
n = get(findobj(fg,'Tag','files'),'Userdata');
sellines = min([max([n(2) na]), 4]);
end
lf = cfg_get_defaults('cfg_ui.lfont');
bf = cfg_get_defaults('cfg_ui.bfont');
% Create dummy text to estimate character height
t=uicontrol('style','text','string','Xg','units','normalized','visible','off',lf);
lfh = 1.05*get(t,'extent');
delete(t)
t=uicontrol('style','text','string','Xg','units','normalized','visible','off',bf);
bfh = 1.05*get(t,'extent');
delete(t)
% panel heights
% 3 lines for directory, parent and prev directory list
% variable height for dir/file navigation
% 2 lines for buttons, filter etc
% sellines plus scrollbar for selected files
pselh = sellines*lfh(4) + 1.2*lfh(4);
pselp = [0 0 1 pselh];
pcnth = 2*bfh(4);
pcntp = [0 pselh 1 pcnth];
pdirh = 3*lfh(4);
pdirp = [0 1-pdirh 1 pdirh];
pfdh = 1-(pselh+pcnth+pdirh);
pfdp = [0 pselh+pcnth 1 pfdh];
%=======================================================================
%=======================================================================
function null(varargin)
%=======================================================================
%=======================================================================
function omsg = msg(ob,str)
ob = sib(ob,'msg');
omsg = get(ob,'String');
set(ob,'String',str);
if nargin>=3,
set(ob,'ForegroundColor',[1 0 0],'FontWeight','bold');
else
set(ob,'ForegroundColor',[0 0 0],'FontWeight','normal');
end;
drawnow;
return;
%=======================================================================
%=======================================================================
function setdrive(ob,varargin)
st = get(ob,'String');
vl = get(ob,'Value');
update(ob,st{vl});
return;
%=======================================================================
%=======================================================================
function resize_fun(fg,varargin)
% do nothing
return;
[pselp pcntp pfdp pdirp] = panelpositions(fg);
set(findobj(fg,'Tag','msg'), 'Position',pselp);
set(findobj(fg,'Tag','pcnt'), 'Position',pcntp);
set(findobj(fg,'Tag','pfd'), 'Position',pfdp);
set(findobj(fg,'Tag','pdir'), 'Position',pdirp);
return;
%=======================================================================
%=======================================================================
function [d,mch] = prevdirs(d)
persistent pd
if ~iscell(pd), pd = {}; end;
if nargin == 0
d = pd;
else
if ~iscell(d)
d = cellstr(d);
end
d = unique(d(:));
mch = cellfun(@(d1)find(strcmp(d1,pd)), d, 'UniformOutput',false);
sel = cellfun(@isempty, mch);
npd = numel(pd);
pd = [pd(:);d(sel)];
mch = [mch{~sel} npd+(1:nnz(sel))];
d = pd;
end
return;
%=======================================================================
%=======================================================================
function pd = pardirs(wd)
if ispc
fs = '\\';
else
fs = filesep;
end
pd1 = textscan(wd,'%s','delimiter',fs,'MultipleDelimsAsOne',1);
if ispc
pd = cell(size(pd1{1}));
pd{end} = pd1{1}{1};
for k = 2:numel(pd1{1})
pd{end-k+1} = fullfile(pd1{1}{1:k},filesep);
end
else
pd = cell(numel(pd1{1})+1,1);
pd{end} = filesep;
for k = 1:numel(pd1{1})
pd{end-k} = fullfile(filesep,pd1{1}{1:k},filesep);
end
end
%=======================================================================
%=======================================================================
function clearfilt(ob,varargin)
set(sib(ob,'regexp'),'String','.*');
update(ob);
return;
%=======================================================================
%=======================================================================
function click_dir_list(ob,varargin)
vl = get(ob,'Value');
ls = get(ob,'String');
update(ob,deblank(ls{vl}));
return;
%=======================================================================
%=======================================================================
function edit_dir(ob,varargin)
update(ob,get(ob,'String'));
return;
%=======================================================================
%=======================================================================
function c = get_current_char(lb)
fg = sib(lb, mfilename);
c = get(fg, 'CurrentCharacter');
if ~isempty(c)
% reset CurrentCharacter
set(fg, 'CurrentCharacter', char(13));
end
%=======================================================================
%=======================================================================
function click_dir_box(lb,varargin)
c = get_current_char(lb);
if isempty(c) || isequal(c,char(13))
vl = get(lb,'Value');
str = get(lb,'String');
pd = get(sib(lb,'edit'),'String');
while ~isempty(pd) && strcmp(pd(end),filesep)
pd=pd(1:end-1); % Remove any trailing fileseps
end
sel = str{vl};
if strcmp(sel,'..'), % Parent directory
[dr odr] = fileparts(pd);
elseif strcmp(sel,'.'), % Current directory
dr = pd;
odr = '';
else
dr = fullfile(pd,sel);
odr = '';
end;
update(lb,dr);
if ~isempty(odr)
% If moving up one level, try to set focus on previously visited
% directory
cdrs = get(lb, 'String');
dind = find(strcmp(odr, cdrs));
if ~isempty(dind)
set(lb, 'Value',dind(1));
end
end
end
return;
%=======================================================================
%=======================================================================
function re = getfilt(ob)
ob = sib(ob,'regexp');
ud = get(ob,'UserData');
re = struct('code',ud.code,...
'frames',get(sib(ob,'frame'),'UserData'),...
'ext',{ud.ext},...
'filt',{{get(sib(ob,'regexp'),'String')}});
return;
%=======================================================================
%=======================================================================
function update(lb,dr)
lb = sib(lb,'dirs');
if nargin<2 || isempty(dr) || ~ischar(dr)
dr = get(lb,'UserData');
end;
if ~(strcmpi(computer,'PCWIN') || strcmpi(computer,'PCWIN64'))
dr = [filesep dr filesep];
else
dr = [dr filesep];
end;
dr(strfind(dr,[filesep filesep])) = [];
[f,d] = listfiles(dr,getfilt(lb));
if isempty(d),
dr = get(lb,'UserData');
[f,d] = listfiles(dr,getfilt(lb));
else
set(lb,'UserData',dr);
end;
set(lb,'Value',1,'String',d);
set(sib(lb,'files'),'Value',1,'String',f);
set(sib(lb,'pardirs'),'String',pardirs(dr),'Value',1);
[ls,mch] = prevdirs(dr);
set(sib(lb,'previous'),'String',ls,'Value',mch);
set(sib(lb,'edit'),'String',dr);
if numel(dr)>1 && dr(2)==':',
str = char(get(sib(lb,'drive'),'String'));
mch = find(lower(str(:,1))==lower(dr(1)));
if ~isempty(mch),
set(sib(lb,'drive'),'Value',mch);
end;
end;
return;
%=======================================================================
%=======================================================================
function update_frames(lb,varargin)
str = get(lb,'String');
%r = get(lb,'UserData');
try
r = eval(['[',str,']']);
catch
msg(lb,['Failed to evaluate "' str '".'],'r');
beep;
return;
end;
if ~isnumeric(r),
msg(lb,['Expression non-numeric "' str '".'],'r');
beep;
else
set(lb,'UserData',r);
msg(lb,'');
update(lb);
end;
%=======================================================================
%=======================================================================
function select_all(ob,varargin)
lb = sib(ob,'files');
set(lb,'Value',1:numel(get(lb,'String')));
drawnow;
click_file_box(lb);
return;
%=======================================================================
%=======================================================================
function click_file_box(lb,varargin)
c = get_current_char(lb);
if isempty(c) || isequal(c, char(13))
vlo = get(lb,'Value');
if isempty(vlo),
msg(lb,'Nothing selected');
return;
end;
lim = get(lb,'UserData');
ob = sib(lb,'selected');
str3 = get(ob,'String');
str = get(lb,'String');
lim1 = min([max([lim(2)-numel(str3),0]),numel(vlo)]);
if lim1==0,
msg(lb,['Selected ' num2str(size(str3,1)) '/' num2str(lim(2)) ' already.']);
beep;
set(sib(lb,'D'),'Enable','on');
return;
end;
vl = vlo(1:lim1);
msk = false(size(str,1),1);
if vl>0, msk(vl) = true; else msk = []; end;
str1 = str( msk);
str2 = str(~msk);
dr = get(sib(lb,'edit'), 'String');
str1 = strcat(dr, str1);
set(lb,'Value',min([vl(1),numel(str2)]),'String',str2);
r = (1:numel(str1))+numel(str3);
str3 = [str3(:);str1(:)];
set(ob,'String',str3,'Value',r);
if numel(vlo)>lim1,
msg(lb,['Retained ' num2str(lim1) '/' num2str(numel(vlo))...
' of selection.']);
beep;
elseif isfinite(lim(2))
if lim(1)==lim(2),
msg(lb,['Selected ' num2str(numel(str3)) '/' num2str(lim(2)) ' files.']);
else
msg(lb,['Selected ' num2str(numel(str3)) '/' num2str(lim(1)) '-' num2str(lim(2)) ' files.']);
end;
else
if size(str3,1) == 1, ss = ''; else ss = 's'; end;
msg(lb,['Selected ' num2str(numel(str3)) ' file' ss '.']);
end;
if ~isfinite(lim(1)) || numel(str3)>=lim(1),
set(sib(lb,'D'),'Enable','on');
end;
end
return;
%=======================================================================
%=======================================================================
function obj = sib(ob,tag)
persistent fg;
if isempty(fg) || ~ishandle(fg)
fg = findobj(0,'Tag',mfilename);
end
obj = findobj(fg,'Tag',tag);
return;
%if isempty(obj),
% cfg_message('matlabbatch:usage',['Can''t find object with tag "' tag '".']);
%elseif length(obj)>1,
% cfg_message('matlabbatch:usage',['Found ' num2str(length(obj)) ' objects with tag "' tag '".']);
%end;
%return;
%=======================================================================
%=======================================================================
function unselect(lb,varargin)
vl = get(lb,'Value');
if isempty(vl), return; end;
str = get(lb,'String');
msk = true(numel(str),1);
if vl~=0, msk(vl) = false; end;
str2 = str(msk);
set(lb,'Value',min(vl(1),numel(str2)),'String',str2);
lim = get(sib(lb,'files'),'UserData');
if numel(str2)>= lim(1) && numel(str2)<= lim(2),
set(sib(lb,'D'),'Enable','on');
else
set(sib(lb,'D'),'Enable','off');
end;
if numel(str2) == 1, ss1 = ''; else ss1 = 's'; end;
%msg(lb,[num2str(size(str2,1)) ' file' ss ' remaining.']);
if numel(vl) == 1, ss = ''; else ss = 's'; end;
msg(lb,['Unselected ' num2str(numel(vl)) ' file' ss '. ' ...
num2str(numel(str2)) ' file' ss1 ' remaining.']);
return;
%=======================================================================
%=======================================================================
function unselect_all(ob,varargin)
lb = sib(ob,'selected');
set(lb,'Value',[],'String',{},'ListBoxTop',1);
msg(lb,'Unselected all files.');
lim = get(sib(lb,'files'),'UserData');
if lim(1)>0, set(sib(lb,'D'),'Enable','off'); end;
return;
%=======================================================================
%=======================================================================
function [f,d] = listfiles(dr,filt)
try
ob = sib(gco,'msg');
domsg = ~isempty(ob);
catch
domsg = false;
end
if domsg
omsg = msg(ob,'Listing directory...');
end
if nargin<2, filt = ''; end;
if nargin<1, dr = '.'; end;
de = dir(dr);
if ~isempty(de),
d = {de([de.isdir]).name};
if ~any(strcmp(d, '.'))
d = [{'.'}, d(:)'];
end;
if filt.code~=-1,
f = {de(~[de.isdir]).name};
else
% f = d(3:end);
f = d;
end;
else
d = {'.','..'};
f = {};
end;
if domsg
msg(ob,['Filtering ' num2str(numel(f)) ' files...']);
end
f = do_filter(f,filt.ext);
f = do_filter(f,filt.filt);
ii = cell(1,numel(f));
if filt.code==1 && (numel(filt.frames)~=1 || filt.frames(1)~=1),
if domsg
msg(ob,['Reading headers of ' num2str(numel(f)) ' images...']);
end
for i=1:numel(f),
try
ni = nifti(fullfile(dr,f{i}));
dm = [ni.dat.dim 1 1 1 1 1];
d4 = (1:dm(4))';
catch
d4 = 1;
end;
if all(isfinite(filt.frames))
msk = false(size(filt.frames));
for j=1:numel(msk), msk(j) = any(d4==filt.frames(j)); end;
ii{i} = filt.frames(msk);
else
ii{i} = d4;
end;
end
elseif filt.code==1 && (numel(filt.frames)==1 && filt.frames(1)==1),
for i=1:numel(f),
ii{i} = 1;
end;
end;
if domsg
msg(ob,['Listing ' num2str(numel(f)) ' files...']);
end
[f,ind] = sortrows(f(:));
ii = ii(ind);
msk = true(1,numel(f));
for i=2:numel(f),
if strcmp(f{i-1},f{i}),
if filt.code==1,
tmp = sort([ii{i}(:) ; ii{i-1}(:)]);
tmp(~diff(tmp,1)) = [];
ii{i} = tmp;
end;
msk(i-1) = false;
end;
end;
f = f(msk);
if filt.code==1,
% Combine filename and frame number(s)
ii = ii(msk);
nii = cellfun(@numel, ii);
c = cell(sum(nii),1);
fi = cell(numel(f),1);
for k = 1:numel(fi)
fi{k} = k*ones(1,nii(k));
end
ii = [ii{:}];
fi = [fi{:}];
for i=1:numel(c),
c{i} = sprintf('%s,%d', f{fi(i)}, ii(i));
end;
f = c;
elseif filt.code==-1,
fs = filesep;
for i=1:numel(f),
f{i} = [f{i} fs];
end;
end;
f = f(:);
d = unique(d(:));
if domsg
msg(ob,omsg);
end
return;
%=======================================================================
%=======================================================================
function [f,ind] = do_filter(f,filt)
t2 = false(numel(f),1);
filt_or = sprintf('(%s)|',filt{:});
t1 = regexp(f,filt_or(1:end-1));
if numel(f)==1 && ~iscell(t1), t1 = {t1}; end;
for i=1:numel(t1),
t2(i) = ~isempty(t1{i});
end;
ind = find(t2);
f = f(t2);
return;
%=======================================================================
%=======================================================================
function heelp(ob,varargin)
[col1,col2,col3,fn] = colours;
fg = sib(ob,mfilename);
t = uicontrol(fg,...
'style','listbox',...
'units','normalized',...
'Position',[0.01 0.01 0.98 0.98],...
fn,...
'BackgroundColor',col2,...
'ForegroundColor',col3,...
'Max',0,...
'Min',0,...
'tag','HelpWin',...
'String',' ');
c0 = uicontextmenu('Parent',fg);
set(t,'uicontextmenu',c0);
uimenu('Label','Done', 'Parent',c0,'Callback',@helpclear);
str = cfg_justify(t, {[...
'File Selection help. You can return to selecting files via the right mouse button (the "Done" option). '],...
'',[...
'The panel at the bottom shows files that are already selected. ',...
'Clicking a selected file will un-select it. To un-select several, you can ',...
'drag the cursor over the files, and they will be gone on release. ',...
'You can use the right mouse button to un-select everything.'],...
'',[...
'Directories are navigated by editing the name of the current directory (where it says "Dir"), ',...
'by going to one of the previously entered directories ("Prev"), ',...
'by going to one of the parent directories ("Up") or by navigating around ',...
'the parent or subdirectories listed in the left side panel.'],...
'',[...
'Files matching the filter ("Filt") are shown in the panel on the right. ',...
'These can be selected by clicking or dragging. Use the right mouse button if ',...
'you would like to select all files. Note that when selected, the files disappear ',...
'from this panel. They can be made to reappear by re-specifying the directory ',...
'or the filter. '],...
'',[...
'Both directory and file lists can also be browsed by typing the leading ',...
'character(s) of a directory or file name.'],...
'',[...
'Note that the syntax of the filter differs from that used by most other file selectors. ',...
'The filter works using so called ''regular expressions''. Details can be found in the ',...
'MATLAB help text on ''regexp''. ',...
'The following is a list of symbols with special meaning for filtering the filenames:'],...
' ^ start of string',...
' $ end of string',...
' . any character',...
' \ quote next character',...
' * match zero or more',...
' + match one or more',...
' ? match zero or one, or match minimally',...
' {} match a range of occurrances',...
' [] set of characters',...
' [^] exclude a set of characters',...
' () group subexpression',...
' \w match word [a-z_A-Z0-9]',...
' \W not a word [^a-z_A-Z0-9]',...
' \d match digit [0-9]',...
' \D not a digit [^0-9]',...
' \s match white space [ \t\r\n\f]',...
' \S not a white space [^ \t\r\n\f]',...
' \<WORD\> exact word match',...
'',[...
'Individual time frames of image files can also be selected. The frame filter ',...
'allows specified frames to be shown, which is useful for image files that ',...
'contain multiple time points. If your images are only single time point, then ',...
'reading all the image headers can be avoided by specifying a frame filter of "1". ',...
'The filter should contain a list of integers indicating the frames to be used. ',...
'This can be generated by e.g. "1:100", or "1:2:100".'],...
'',[...
'The recursive selection button (Rec) allows files matching the regular expression to ',...
'be recursively selected. If there are many directories to search, then this can take ',...
'a while to run.'],...
'',[...
'There is also an edit button (Ed), which allows you to edit your selection of files. ',...
'When you are done, then use the menu-button of your mouse to either cancel or accept your changes.'],''});
set(t,'String',str);
return;
%=======================================================================
%=======================================================================
function helpclear(ob,varargin)
ob = get(ob,'Parent');
ob = get(ob,'Parent');
ob = findobj(ob,'Tag','HelpWin');
delete(ob);
%=======================================================================
%=======================================================================
function t = cpath(t,d)
switch filesep,
case '/',
mch = '^/';
fs = '/';
fs1 = '/';
case '\',
mch = '^.:\\';
fs = '\';
fs1 = '\\';
otherwise;
cfg_message('matlabbatch:usage','What is this filesystem?');
end
if isempty(regexp(t,mch,'once')),
if (nargin<2)||isempty(d), d = pwd; end;
t = [d fs t];
end;
% Replace occurences of '/./' by '/' (problems with e.g. /././././././')
re = [fs1 '\.' fs1];
while ~isempty(regexp(t,re, 'once' )),
t = regexprep(t,re,fs);
end;
t = regexprep(t,[fs1 '\.' '$'], fs);
% Replace occurences of '/abc/../' by '/'
re = [fs1 '[^' fs1 ']+' fs1 '\.\.' fs1];
while ~isempty(regexp(t,re, 'once' )),
t = regexprep(t,re,fs,'once');
end;
t = regexprep(t,[fs1 '[^' fs1 ']+' fs1 '\.\.' '$'],fs,'once');
% Replace '//'
t = regexprep(t,[fs1 '+'], fs);
%=======================================================================
%=======================================================================
function editwin(ob,varargin)
[col1,col2,col3,lf,bf] = colours;
fg = gcbf;
lb = sib(ob,'selected');
str = get(lb,'String');
ac = allchild(fg);
acv = get(ac,'Visible');
h = uicontrol(fg,...
'Style','Edit',...
'units','normalized',...
'String',str,...
lf,...
'Max',2,...
'Tag','EditWindow',...
'HorizontalAlignment','Left',...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'Position',[0.01 0.08 0.98 0.9],...
'Userdata',struct('ac',{ac},'acv',{acv}));
ea = uicontrol(fg,...
'Style','pushbutton',...
'units','normalized',...
'Position',[.01 .01,.32,.07],...
bf,...
'Callback',@editdone,...
'tag','EditWindowAccept',...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'String','Accept');
ee = uicontrol(fg,...
'Style','pushbutton',...
'units','normalized',...
'Position',[.34 .01,.32,.07],...
bf,...
'Callback',@editeval,...
'tag','EditWindowEval',...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'String','Eval');
ec = uicontrol(fg,...
'Style','pushbutton',...
'units','normalized',...
'Position',[.67 .01,.32,.07],...
bf,...
'Callback',@editclear,...
'tag','EditWindowCancel',...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'String','Cancel');
set(ac,'visible','off');
%=======================================================================
%=======================================================================
function editeval(ob,varargin)
ob = get(ob, 'Parent');
ob = sib(ob, 'EditWindow');
str = get(ob, 'String');
if ~isempty(str)
[out,sts] = cfg_eval_valedit(char(str));
if sts && (iscellstr(out) || ischar(out))
set(ob, 'String', cellstr(out));
else
fgc = get(ob, 'ForegroundColor');
set(ob, 'ForegroundColor', 'red');
pause(1);
set(ob, 'ForegroundColor', fgc);
end
end
%=======================================================================
%=======================================================================
function editdone(ob,varargin)
ob = get(ob,'Parent');
ob = sib(ob,'EditWindow');
str = cellstr(get(ob,'String'));
if isempty(str) || isempty(str{1})
str = {};
else
dstr = deblank(str);
if ~isequal(str, dstr)
c = questdlg(['Some of the filenames contain trailing blanks. This may ' ...
'be due to copy/paste of strings between MATLAB and the ' ...
'edit window. Do you want to remove any trailing blanks?'], ...
'Trailing Blanks in Filenames', ...
'Remove', 'Keep', 'Remove');
switch lower(c)
case 'remove'
str = dstr;
end
end
filt = getfilt(ob);
if filt.code >= 0 % filter files, but not dirs
[p,n,e] = cellfun(@fileparts, str, 'uniformoutput',false);
fstr = strcat(n, e);
[fstr1,fsel] = do_filter(fstr, filt.ext);
str = str(fsel);
end
end
lim = get(sib(ob,'files'),'UserData');
if numel(str)>lim(2),
msg(ob,['Retained ' num2str(lim(2)) ' of the ' num2str(numel(str)) ' files.']);
beep;
str = str(1:lim(2));
elseif isfinite(lim(2)),
if lim(1)==lim(2),
msg(ob,['Selected ' num2str(numel(str)) '/' num2str(lim(2)) ' files.']);
else
msg(ob,['Selected ' num2str(numel(str)) '/' num2str(lim(1)) '-' num2str(lim(2)) ' files.']);
end;
else
if numel(str) == 1, ss = ''; else ss = 's'; end;
msg(ob,['Specified ' num2str(numel(str)) ' file' ss '.']);
end;
if ~isfinite(lim(1)) || numel(str)>=lim(1),
set(sib(ob,'D'),'Enable','on');
else
set(sib(ob,'D'),'Enable','off');
end;
set(sib(ob,'selected'),'String',str,'Value',[]);
acs = get(ob,'Userdata');
fg = gcbf;
delete(findobj(fg,'-regexp','Tag','^EditWindow.*'));
set(acs.ac,{'Visible'},acs.acv);
%=======================================================================
%=======================================================================
function editclear(ob,varargin)
fg = gcbf;
acs = get(findobj(fg,'Tag','EditWindow'),'Userdata');
delete(findobj(fg,'-regexp','Tag','^EditWindow.*'));
set(acs.ac,{'Visible'},acs.acv);
%=======================================================================
%=======================================================================
function [c1,c2,c3,lf,bf] = colours
c1 = [1 1 1];
c2 = [1 1 1];
c3 = [0 0 0];
lf = cfg_get_defaults('cfg_ui.lfont');
bf = cfg_get_defaults('cfg_ui.bfont');
if isempty(lf)
lf = struct('FontName',get(0,'FixedWidthFontName'), ...
'FontWeight','normal', ...
'FontAngle','normal', ...
'FontSize',14, ...
'FontUnits','points');
end
if isempty(bf)
bf = struct('FontName',get(0,'FixedWidthFontName'), ...
'FontWeight','normal', ...
'FontAngle','normal', ...
'FontSize',14, ...
'FontUnits','points');
end
%=======================================================================
%=======================================================================
function select_rec(ob, varargin)
start = get(sib(ob,'edit'),'String');
filt = get(sib(ob,'regexp'),'Userdata');
filt.filt = {get(sib(ob,'regexp'), 'String')};
fob = sib(ob,'frame');
if ~isempty(fob)
filt.frames = get(fob,'Userdata');
else
filt.frames = [];
end;
ptr = get(gcbf,'Pointer');
try
set(gcbf,'Pointer','watch');
sel = select_rec1(start,filt);
catch
set(gcbf,'Pointer',ptr);
sel = {};
end;
set(gcbf,'Pointer',ptr);
already= get(sib(ob,'selected'),'String');
fb = sib(ob,'files');
lim = get(fb,'Userdata');
limsel = min(lim(2)-size(already,1),size(sel,1));
set(sib(ob,'selected'),'String',[already(:);sel(1:limsel)],'Value',[]);
msg(ob,sprintf('Added %d/%d matching files to selection.', limsel, size(sel,1)));
if ~isfinite(lim(1)) || size(sel,1)>=lim(1),
set(sib(ob,'D'),'Enable','on');
else
set(sib(ob,'D'),'Enable','off');
end;
%=======================================================================
%=======================================================================
function sel=select_rec1(cdir,filt)
sel={};
[t,d] = listfiles(cdir,filt);
if ~isempty(t)
sel = strcat([cdir,filesep],t);
end;
for k = 1:numel(d)
if ~any(strcmp(d{k},{'.','..'}))
sel1 = select_rec1(fullfile(cdir,d{k}),filt);
sel = [sel(:); sel1(:)];
end;
end;
%=======================================================================
%=======================================================================
function sfilt=mk_filter(typ,filt,frames)
if nargin<3, frames = 1; end;
if nargin<2, filt = '.*'; end;
if nargin<1, typ = 'any'; end;
switch lower(typ),
case {'any','*'}, code = 0; ext = {'.*'};
case {'image'}, code = 1; ext = {'.*\.nii(,\d+){0,2}$','.*\.img(,\d+){0,2}$','.*\.NII(,\d+){0,2}$','.*\.IMG(,\d+){0,2}$'};
case {'mesh'}, code = 0; ext = {'.*\.gii$','.*\.GII$','.*\.mat$','.*\.MAT$'};
case {'nifti'}, code = 0; ext = {'.*\.nii$','.*\.img$','.*\.NII$','.*\.IMG$'};
case {'gifti'}, code = 0; ext = {'.*\.gii$','.*\.GII$'};
case {'extimage'}, code = 1; ext = {'.*\.nii(,[0-9]*){0,2}$',...
'.*\.img(,[0-9]*){0,2}$',...
'.*\.NII(,[0-9]*){0,2}$',...
'.*\.IMG(,[0-9]*){0,2}$'};
case {'xml'}, code = 0; ext = {'.*\.xml$','.*\.XML$'};
case {'mat'}, code = 0; ext = {'.*\.mat$','.*\.MAT$','.*\.txt','.*\.TXT'};
case {'batch'}, code = 0; ext = {'.*\.mat$','.*\.MAT$','.*\.m$','.*\.M$','.*\.xml$','.*\.XML$'};
case {'dir'}, code =-1; ext = {'.*'};
case {'extdir'}, code =-1; ext = {['.*' filesep '$']};
otherwise, code = 0; ext = {typ};
end;
sfilt = struct('code',code,'frames',frames,'ext',{ext},...
'filt',{{filt}});
%=======================================================================
%=======================================================================
function drivestr = listdrives(reread)
persistent mydrivestr;
if isempty(mydrivestr) || reread
driveLett = strcat(cellstr(char(('C':'Z')')), ':');
dsel = false(size(driveLett));
for i=1:numel(driveLett)
dsel(i) = exist([driveLett{i} '\'],'dir')~=0;
end
mydrivestr = driveLett(dsel);
end;
drivestr = mydrivestr;
%=======================================================================
%=======================================================================
|
github
|
philippboehmsturm/antx-master
|
cfg_struct2cfg.m
|
.m
|
antx-master/xspm8/matlabbatch/cfg_struct2cfg.m
| 4,221 |
utf_8
|
528320103babd350c9b0d18dcd1ac728
|
function cc = cfg_struct2cfg(co, indent)
% Import a config structure into a matlabbatch class tree. Input structures
% are those generated from the configuration editor, cfg2struct methods or
% spm_jobman config structures.
%
% The layout of the configuration tree and the types of configuration items
% have been kept compatible to a configuration system and job manager
% implementation in SPM5 (Statistical Parametric Mapping, Copyright (C)
% 2005 Wellcome Department of Imaging Neuroscience). This code has been
% completely rewritten based on an object oriented model of the
% configuration tree.
%
% 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_struct2cfg.m 1862 2008-06-30 14:12:49Z volkmar $
rev = '$Rev: 1862 $'; %#ok
if nargin < 2
indent = '';
end;
%% Class of node
% Usually, the class is determined by the node type. Only for branches
% there is a distinction necessary between executable and non-executable
% branches in spm_jobman config files.
if strcmp(co.type, 'branch') && isfield(co, 'prog')
typ = 'cfg_exbranch';
else
if numel(co.type > 4) && strcmp(co.type(1:4), 'cfg_')
typ = co.type;
else
typ = sprintf('cfg_%s', co.type);
end;
end;
try
cfg_message('matlabbatch:cfg_struct2cfg:info', ...
'%sNode %s (%s): %s > %s', indent, co.tag, co.name, co.type, typ);
catch
cfg_message('matlabbatch:cfg_struct2cfg:info', ...
'%sNode UNKNOWN: %s > %s', indent, co.type, typ);
end;
eval(sprintf('cc = %s;', typ));
%% Import children
% for branches, repeats, choices children are collected first, before the
% object is created.
switch typ
case {'cfg_branch','cfg_exbranch'}
val = cell(size(co.val));
for k = 1:numel(co.val)
val{k} = cfg_struct2cfg(co.val{k}, [indent ' ']);
end;
co.val = val;
case {'cfg_repeat', 'cfg_choice'}
if isfield(co, 'val')
val = cell(size(co.val));
for k = 1:numel(co.val)
val{k} = cfg_struct2cfg(co.val{k}, [indent ' ']);
end;
co.val = val;
end;
values = cell(size(co.values));
for k = 1:numel(co.values)
values{k} = cfg_struct2cfg(co.values{k}, [indent ' ']);
end;
co.values = values;
end;
%% Assign fields
% try to assign fields, give warnings if something goes wrong
co = rmfield(co, 'type');
fn = fieldnames(co);
% omit id field, it has a different meaning in cfg_items than in spm_jobman
% and it does not contain necessary information.
idind = strcmp('id',fn);
fn = fn(~idind);
% treat name and tag fields first
try
cc.name = co.name;
fn = fn(~strcmp('name', fn));
end;
try
cc.tag = co.tag;
fn = fn(~strcmp('tag', fn));
end;
% if present, treat num field before value assignments
nind = strcmp('num',fn);
if any(nind)
if numel(co.num) == 1
onum = co.num;
if isfinite(co.num) && co.num > 0
co.num = [co.num co.num];
else
co.num = [0 Inf];
end;
cfg_message('matlabbatch:cfg_struct2cfg:num', ...
' Node %s / ''%s'' field num [%d] padded to %s', ...
cc.tag, cc.name, onum, mat2str(co.num));
end;
cc = try_assign(cc,co,'num');
% remove num field from list
fn = fn(~nind);
end;
% if present, convert .def field
nind = strcmp('def',fn);
if any(nind)
if ~isempty(co.def) && ischar(co.def)
% assume SPM5 style defaults
co.def = @(val)spm_get_defaults(co.def, val{:});
end;
cc = try_assign(cc,co,'def');
% remove def field from list
fn = fn(~nind);
end;
for k = 1:numel(fn)
cc = try_assign(cc,co,fn{k});
end;
function cc = try_assign(cc, co, fn)
try
cc.(fn) = co.(fn);
catch
le = lasterror;
le1.identifier = 'matlabbatch:cfg_struct2cfg:failed';
le1.message = sprintf(' Node %s / ''%s'' field %s: import failed.\n%s', cc.tag, ...
cc.name, fn, le.message);
cfg_message(le1);
end;
|
github
|
philippboehmsturm/antx-master
|
cfg_serial.m
|
.m
|
antx-master/xspm8/matlabbatch/cfg_serial.m
| 10,089 |
utf_8
|
bcf267514c3f2975d12bf5ba10940323
|
function cfg_serial(guifcn, job, varargin)
% This function is deprecated.
% The functionality should replaced by the following sequence of calls:
%
% Instead of
% cfg_serial(guifcn, job, varargin)
% use
% cjob = cfg_util('initjob', job);
% sts = cfg_util('filljobui', cjob, guifcn, varargin);
% if sts
% cfg_util('run', cjob);
% end;
% cfg_util('deljob', cjob);
%
% Instead of
% cfg_serial(guifcn, tagstr, varargin)
% use
% cjob = cfg_util('initjob');
% mod_cfg_id = cfg_util('tag2cfg_id', tagstr);
% cfg_util('addtojob', cjob, mod_cfg_id);
% sts = cfg_util('filljobui', cjob, guifcn, varargin);
% if sts
% cfg_util('run', cjob);
% end;
% cfg_util('deljob', cjob);
%
% Instead of
% cfg_serial(guifcn, mod_cfg_id, varargin)
% use
% cjob = cfg_util('initjob');
% cfg_util('addtojob', cjob, mod_cfg_id);
% sts = cfg_util('filljobui', cjob, guifcn, varargin);
% if sts
% cfg_util('run', cjob);
% end;
% cfg_util('deljob', cjob);
%
% If no guifcn is specified, use cfg_util('filljob',... instead.
%
% GuiFcn semantics
% [val sts] = guifcn(item)
% val should be suitable to set item.val{1} using setval(item, val,
% false) for all cfg_leaf items. For cfg_repeat/cfg_choice items, val
% should be a cell array of indices into item.values. For each element of
% val, setval(item, [val{k} Inf], false)
% will be called and thus item.values{k} will be appended to item.val.
% sts should be set to true, if guifcn returns with success (i.e. a
% valid value is returned or input should continue for the next item,
% regardless of value validity).
% Old help
% function cfg_serial(guifcn, job|tagstr|mod_cfg_id, varargin)
% A matlabbatch user interface which completes a matlabbatch job with
% incomplete inputs one at a time and runs the job.
% This interface may be called with or without user interaction. If
% guifcn is a function handle, then this function will be called to enter
% unspecified inputs. Otherwise, the first argument will be ignored and
% inputs will be assigned from the argument list only.
% During job completion and execution, this interface may interfere with
% cfg_ui. However, after the job is executed, it will be removed from the
% job list.
%
% cfg_serial(guifcn, job|tagstr|mod_cfg_id[, input1, input2, ...inputN])
% Ask for missing inputs in a job. Job should be a matlabbatch job as
% returned by cfg_util('harvest'). Modifications to the job structure are
% limited:
% - no new modules can be added
% - no dependencies can be created
% - unset cfg_choice items can be selected, but not altered
% - unset cfg_repeat items can be completed, but no repeats can be added
% to or removed from already set items
% Data to complete a job can specified as additional arguments. This
% allows to script filling of a predefined job with missing inputs.
% For cfg_entry and cfg_file items, this can be any data that meets the
% consistency (type, filter, size) constraints of the item.
% For cfg_menu and cfg_choice items, it can be the number of a menu
% option, counting from 1.
% For cfg_repeat items, it is a cell list of numbers of menu options. The
% corresponding option will be added at the end of the repeat list.
% Any input data that can not be assigned to the current input item will
% be discarded.
%
% cfg_serial(guifcn, tagstr)
% Start input at the node addressed by tagstr in the configuration
% tree. If tagstr points to an cfg_exbranch, then only this cfg_exbranch
% will be filled and run. If tagstr points to a node above cfg_exbranch
% level, then multiple cfg_exbranches below this node may be added and
% filled.
%
% guifcn Interface
% The guifcn will be called to enter inputs to cfg_choice, cfg_repeat,
% cfg_entry, cfg_files, cfg_menu items. The general call syntax is
% val = feval(guifcn, class, name, item_specific_data);
% Input arguments
% class - string: one of cfg_choice, cfg_repeat,
% cfg_entry, cfg_files, cfg_menu
% name - string: Item display name
% Item specific data
% * cfg_choice, cfg_menu
% labels - cell array of strings, menu labels
% values - cell array of values corresponding to labels
% * cfg_repeat
% labels and values as above
% num - 2-vector of min/max number of required elements in val
% * cfg_entry
% strtype - input type
% extras - extra data to evaluate input
% num - required size of data
% * cfg_files
% filter, ufilter - file filter specifications (see cfg_select)
% dir - initial directory
% num - 2-vector of min/max number of required files
%
% 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_serial.m 1862 2008-06-30 14:12:49Z volkmar $
rev = '$Rev: 1862 $'; %#ok
cfg_message('matlabbatch:deprecated:cfg_serial', '''cfg_serial'' is deprecated. Please use cfg_util(''filljob[ui]'',...) to fill a job in serial mode.');
if ischar(job)
% Assume dot delimited sequence of tags
mod_cfg_id = cfg_util('tag2mod_cfg_id', job);
if cfg_util('ismod_cfg_id', mod_cfg_id)
% tag string points to somewhere in an cfg_exbranch
% initialise new job
cjob = cfg_util('initjob');
% add mod_cfg_id
cfg_util('addtojob', cjob, mod_cfg_id);
else
% tag string points to somewhere above cfg_branch
cjob = local_addtojob(job);
end;
elseif cfg_util('ismod_cfg_id', job)
% initialise new job
cjob = cfg_util('initjob');
% add mod_cfg_id
cfg_util('addtojob', cjob, job);
else
% assume job to be a saved job structure
cjob = cfg_util('initjob', job);
end;
% varargin{:} is a list of input items
in = varargin;
% get job information
[mod_job_idlist str sts dep sout] = cfg_util('showjob', cjob);
for cm = 1:numel(mod_job_idlist)
% loop over modules, enter missing inputs
if ~sts(cm)
in = local_fillmod(guifcn, cjob, mod_job_idlist{cm}, in);
end;
end;
cfg_util('run',cjob);
cfg_util('deljob',cjob);
%% local functions
function cjob = local_addtojob(job)
% traverse tree down to cfg_exbranch level, add selected modules to job
cfg_message('matlabbatch:cfg_serial:notimplemented', ...
'Menu traversal not yet implemented.');
function inputs = local_fillmod(guifcn, cjob, cm, inputs)
[item_mod_idlist stop contents] = ...
cfg_util('listmod', cjob, cm, [], cfg_findspec({{'hidden',false}}), ...
cfg_tropts({{'hidden', true}},1,Inf,1,Inf,false), ...
{'class', 'all_set_item'});
for ci = 1:numel(item_mod_idlist)
% loop over items, enter missing inputs
if ~contents{2}{ci}
if ~isempty(inputs)
sts = local_setval(cjob, cm, item_mod_idlist, contents, ci, inputs{1});
% discard input{1}, even if setval failed
inputs = inputs(2:end);
else
sts = false;
end;
if ~sts && ~isa(guifcn, 'function_handle')
% no input given, or input did not match required criteria
cfg_message('matlabbatch:cfg_serial:notimplemented', ...
'User prompted input not yet implemented.');
end;
while ~sts
% call guifcn until a valid input is returned
val = local_call_guifcn(guifcn, cjob, cm, item_mod_idlist{ci}, ...
contents{1}{ci});
sts = local_setval(cjob, cm, item_mod_idlist, contents, ci, val);
end;
if strcmp(contents{1}{ci}, 'cfg_choice')||...
strcmp(contents{1}{ci}, 'cfg_repeat')
% restart filling current module, break out of for loop
% afterwards
inputs = local_fillmod(guifcn, cjob, cm, inputs);
return;
end;
end;
end;
function sts = local_setval(cjob, cm, item_mod_idlist, contents, ci, val)
if strcmp(contents{1}{ci}, 'cfg_repeat')
% assume val to be a cell array of indices into
% .values
% note that sts may return true even if some of the
% indices failed. sts only indicates that the cfg_repeat
% all_set_item status is met (i.e. the min/max number of
% repeated items are present).
sts = false;
for cv = 1:numel(val)
% do not use fast track || here, otherwise
% cfg_util('setval') must be called in any case to
% append val{cv} to cfg_repeat list.
sts = sts | cfg_util('setval', cjob, cm, item_mod_idlist{ci}, ...
[val{cv} Inf]);
end;
else
% try to set val
sts = cfg_util('setval', cjob, cm, item_mod_idlist{ci}, ...
val);
end;
function val = local_call_guifcn(guifcn, cjob, cm, citem, cmclass)
% fieldnames depend on class of item
switch cmclass
case {'cfg_choice', 'cfg_repeat'},
fnames = {'name', 'values', 'num'};
case 'cfg_entry',
fnames = {'name', 'strtype', 'num', 'extras'};
case 'cfg_files',
fnames = {'name', 'num', 'filter', 'dir', 'ufilter'};
case 'cfg_menu',
fnames = {'name', 'labels', 'values'};
end;
% only search current module/item
fspec = cfg_findspec({{'hidden',false}});
tropts = cfg_tropts({{'hidden', true}},1,1,1,1,false);
if isempty(citem)
% we are not in a module
[u1 u2 contents] = cfg_util('listcfgall', cm, fspec, tropts, fnames);
else
[u1 u2 contents] = cfg_util('listmod', cjob, cm, citem, fspec, tropts, fnames);
end;
cmname = contents{1}{1};
switch cmclass
case {'cfg_choice', 'cfg_repeat'}
% construct labels and values from 'values' field
for k = 1:numel(contents{2}{1})
labels{k} = contents{2}{1}{k}.name;
end;
values = num2cell(1:numel(contents{2}{1}));
args = {labels, values};
if strcmp(cmclass, 'cfg_repeat')
args{3} = contents{3}{1};
end;
case {'cfg_entry', 'cfg_files', 'cfg_menu'}
for k = 2:numel(contents)
args{k-1} = contents{k}{1};
end;
end;
val = feval(guifcn, cmclass, cmname, args{:});
|
github
|
philippboehmsturm/antx-master
|
gencode.m
|
.m
|
antx-master/xspm8/matlabbatch/gencode.m
| 8,370 |
utf_8
|
622b87c73ebd907748793445b6274507
|
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 3355 2009-09-04 09:37:35Z volkmar $
rev = '$Rev: 3355 $'; %#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/xspm8/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/xspm8/matlabbatch/@cfg_branch/initialise.m
| 1,882 |
utf_8
|
e6462e87b54b082c3e9a47f4ab86806b
|
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 2101 2008-09-16 13:56:26Z volkmar $
rev = '$Rev: 2101 $'; %#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/xspm8/matlabbatch/cfg_basicio/cfg_run_subsrefvar.m
| 6,686 |
utf_8
|
daad846e0faec15f03788c48065c474d
|
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 3948 2010-06-25 09:48:03Z volkmar $
rev = '$Rev: 3948 $'; %#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/xspm8/matlabbatch/cfg_basicio/cfg_run_call_matlab.m
| 5,995 |
utf_8
|
afc10d877d7bb3f52c6f308ede6c4707
|
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 3810 2010-04-07 12:42:32Z volkmar $
rev = '$Rev: 3810 $'; %#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/xspm8/matlabbatch/cfg_basicio/cfg_load_vars.m
| 5,292 |
utf_8
|
f097076d4059331911b30b3a67a48c3d
|
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 3944 2010-06-23 08:53:40Z volkmar $
rev = '$Rev: 3944 $'; %#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/xspm8/matlabbatch/@cfg_choice/initialise.m
| 2,953 |
utf_8
|
cb956cc1e0b8157ff8899fc1720189cb
|
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 2427 2008-11-03 08:46:17Z volkmar $
rev = '$Rev: 2427 $'; %#ok
if ~(isempty(val) || strcmp(val,'<UNDEFINED>'))
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;
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 val 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
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;
|
github
|
philippboehmsturm/antx-master
|
subsasgn.m
|
.m
|
antx-master/xspm8/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/xspm8/matlabbatch/examples/cfg_example_cumsum1.m
| 2,891 |
utf_8
|
23f6fba4270a8acd77c9324318e47a05
|
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 1716 2008-05-23 08:18:45Z volkmar $
rev = '$Rev: 1716 $'; %#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/xspm8/matlabbatch/examples/cfg_example_div.m
| 3,312 |
utf_8
|
0b78f049e9e37d5746c7afc33384510b
|
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 1716 2008-05-23 08:18:45Z volkmar $
rev = '$Rev: 1716 $'; %#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/xspm8/matlabbatch/examples/cfg_example_add2.m
| 2,622 |
utf_8
|
1f1af41a7da0e1e6bd9839d66705b0ed
|
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 1716 2008-05-23 08:18:45Z volkmar $
rev = '$Rev: 1716 $'; %#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/xspm8/matlabbatch/examples/cfg_example_add1.m
| 3,291 |
utf_8
|
ea93e248b0ce90d87b6616e927d55829
|
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 1716 2008-05-23 08:18:45Z volkmar $
rev = '$Rev: 1716 $'; %#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/xspm8/matlabbatch/examples/cfg_example_cumsum2.m
| 3,392 |
utf_8
|
db5b5ac94fe794d4450fecbf07fe0c63
|
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 1716 2008-05-23 08:18:45Z volkmar $
rev = '$Rev: 1716 $'; %#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/xspm8/matlabbatch/examples/cfg_example_sum.m
| 2,706 |
utf_8
|
2dcd9f8e452fa818b4d3aaee964921d5
|
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 1716 2008-05-23 08:18:45Z volkmar $
rev = '$Rev: 1716 $'; %#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
|
cfg_load_jobs.m
|
.m
|
antx-master/xspm8/matlabbatch/private/cfg_load_jobs.m
| 1,970 |
utf_8
|
058edb216e5c1523eb5fcd533ce9cfa6
|
function [newjobs uind] = cfg_load_jobs(job)
% function newjobs = cfg_load_jobs(job)
%
% Load a list of possible job files, return a cell list of jobs.
%
% 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_jobs.m 4150 2011-01-07 14:41:56Z volkmar $
rev = '$Rev: 4150 $'; %#ok
if ischar(job)
filenames = cellstr(job);
else
filenames = job;
end;
[ufilenames unused uind] = unique(filenames);
ujobs = cell(size(ufilenames));
usts = false(size(ufilenames));
for cf = 1:numel(ufilenames)
[ujobs{cf} usts(cf)] = load_single_job(ufilenames{cf});
end
sts = usts(uind);
uind = uind(sts);
newjobs = ujobs(uind);
function [matlabbatch sts] = load_single_job(filename)
[p,nam,ext] = fileparts(filename);
switch ext
case '.xml',
try
loadxml(filename,'matlabbatch');
catch
cfg_message('matlabbatch:initialise:xml','LoadXML failed: ''%s''',filename);
end;
case '.mat'
try
S=load(filename);
matlabbatch = S.matlabbatch;
catch
cfg_message('matlabbatch:initialise:mat','Load failed: ''%s''',filename);
end;
case '.m'
try
fid = fopen(filename,'rt');
str = fread(fid,'*char');
fclose(fid);
eval(str);
catch
cfg_message('matlabbatch:initialise:m','Eval failed: ''%s''',filename);
end;
if ~exist('matlabbatch','var')
cfg_message('matlabbatch:initialise:m','No matlabbatch job found in ''%s''', filename);
end;
otherwise
cfg_message('matlabbatch:initialise:unknown','Unknown extension: ''%s''', filename);
end;
if exist('matlabbatch','var')
sts = true;
else
sts = false;
matlabbatch = [];
end;
|
github
|
philippboehmsturm/antx-master
|
num2str.m
|
.m
|
antx-master/xspm8/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/xspm8/matlabbatch/private/inputdlg.m
| 12,681 |
utf_8
|
b307689fbe51aff80422b745d656b0b5
|
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: 1896 $
%%%%%%%%%%%%%%%%%%%%
%%% 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/xspm8/matlabbatch/private/cfg_justify.m
| 4,781 |
utf_8
|
f35de815dab47aff40ab2987909d5f26
|
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 3944 2010-06-23 08:53:40Z volkmar $
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/xspm8/matlabbatch/private/listdlg.m
| 8,511 |
utf_8
|
87109bfdddbe0b70e9a3aa7346fbd072
|
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: 2131 $ $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
|
cfg_confgui.m
|
.m
|
antx-master/xspm8/matlabbatch/cfg_confgui/cfg_confgui.m
| 31,065 |
utf_8
|
7e950964f42b1fa1eb1485784aab5d6c
|
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 3944 2010-06-23 08:53:40Z volkmar $
rev = '$Rev: 3944 $'; %#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/xspm8/matlabbatch/cfg_confgui/cfg_run_template.m
| 4,822 |
utf_8
|
183bd6f71f7414a9f76b339601c1087d
|
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 3785 2010-03-17 15:53:42Z volkmar $
rev = '$Rev: 3785 $'; %#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/xspm8/matlabbatch/@cfg_entry/subsasgn_check.m
| 8,354 |
utf_8
|
258ddede644584f90f8655abda9a8f1f
|
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 4864 2012-08-27 13:57:31Z volkmar $
rev = '$Rev: 4864 $'; %#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/xspm8/matlabbatch/@cfg_entry/showdoc.m
| 1,963 |
utf_8
|
9667d455526f2337667bf1ad4424dbfc
|
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 1716 2008-05-23 08:18:45Z volkmar $
rev = '$Rev: 1716 $'; %#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/xspm8/matlabbatch/@cfg_item/resolve_deps.m
| 3,622 |
utf_8
|
fdaa013305212ae2a83040c5ee7f41ad
|
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 3944 2010-06-23 08:53:40Z volkmar $
rev = '$Rev: 3944 $'; %#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/xspm8/matlabbatch/@cfg_repeat/initialise.m
| 4,835 |
utf_8
|
777a87451848155c3879b72196664aa9
|
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 4073 2010-09-24 12:07:57Z volkmar $
rev = '$Rev: 4073 $'; %#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_ovhelper_3Dreg.m
|
.m
|
antx-master/xspm8/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_roi.m
|
.m
|
antx-master/xspm8/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/xspm8/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
|
coor2D.m
|
.m
|
antx-master/xspm8/@meeg/coor2D.m
| 4,007 |
utf_8
|
f94070275bb14e35788e110abf929115
|
function [res, plotind] = coor2D(this, ind, val, mindist)
% returns x and y coordinates of channels in 2D plane
% FORMAT coor2D(this)
% _______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Vladimir Litvak, Laurence Hunt
% $Id: coor2D.m 4372 2011-06-21 21:26:46Z vladimir $
megind = strmatch('MEG', chantype(this));
eegind = strmatch('EEG', chantype(this), 'exact');
otherind = setdiff(1:nchannels(this), [megind; eegind]);
if nargin==1 || isempty(ind)
if nargin<3 || (size(val, 2)<nchannels(this))
if ~isempty(megind)
ind = megind;
elseif ~isempty(eegind)
ind = eegind;
else
ind = 1:nchannels(this);
end
else
ind = 1:nchannels(this);
end
elseif ischar(ind)
switch upper(ind)
case 'MEG'
ind = megind;
case 'EEG'
ind = eegind;
otherwise
ind = otherind;
end
end
if nargin < 3 || isempty(val)
if ~isempty(intersect(ind, megind))
if ~any(cellfun('isempty', {this.channels(megind).X_plot2D}))
meg_xy = [this.channels(megind).X_plot2D; this.channels(megind).Y_plot2D];
elseif all(cellfun('isempty', {this.channels(megind).X_plot2D}))
meg_xy = grid(length(megind));
else
error('Either all or none of MEG channels should have 2D coordinates defined.');
end
end
if ~isempty(intersect(ind, eegind))
if ~any(cellfun('isempty', {this.channels(eegind).X_plot2D}))
eeg_xy = [this.channels(eegind).X_plot2D; this.channels(eegind).Y_plot2D];
elseif all(cellfun('isempty', {this.channels(eegind).X_plot2D}))
eeg_xy = grid(length(eegind));
else
error('Either all or none of EEG channels should have 2D coordinates defined.');
end
end
if ~isempty(intersect(ind, otherind))
other_xy = grid(length(otherind));
end
xy = zeros(2, length(ind));
plotind = zeros(1, length(ind));
for i = 1:length(ind)
[found, loc] = ismember(ind(i), megind);
if found
xy(:, i) = meg_xy(:, loc);
plotind(i) = 1;
else
[found, loc] = ismember(ind(i), eegind);
if found
xy(:, i) = eeg_xy(:, loc);
plotind(i) = 2;
else
[found, loc] = ismember(ind(i), otherind);
if found
xy(:, i) = other_xy(:, loc);
plotind(i) = 3;
end
end
end
end
if nargin > 3 && ~isempty(mindist)
xy = shiftxy(xy,mindist);
end
res = xy;
else
this = getset(this, 'channels', 'X_plot2D', ind, val(1, :));
this = getset(this, 'channels', 'Y_plot2D', ind, val(2, :));
res = this;
end
function xy = grid(n)
ncol = ceil(sqrt(n));
x = 0:(1/(ncol+1)):1;
x = 0.9*x+0.05;
x = x(2:(end-1));
y = fliplr(x);
[X, Y] = meshgrid(x, y);
xy = [X(1:n); Y(1:n)];
function xy = shiftxy(xy,mindist)
x = xy(1,:);
y = xy(2,:);
l=1;
i=1; %filler
mindist = mindist/0.999; % limits the number of loops
while (~isempty(i) && l<50)
xdiff = repmat(x,length(x),1) - repmat(x',1,length(x));
ydiff = repmat(y,length(y),1) - repmat(y',1,length(y));
xydist= sqrt(xdiff.^2 + ydiff.^2); %euclidean distance between all sensor pairs
[i,j] = find(xydist<mindist*0.999);
rm=(i<=j); i(rm)=[]; j(rm)=[]; %only look at i>j
for m = 1:length(i);
if (xydist(i(m),j(m)) == 0)
diffvec = [mindist./sqrt(2) mindist./sqrt(2)];
else
xydiff = [xdiff(i(m),j(m)) ydiff(i(m),j(m))];
diffvec = xydiff.*mindist./xydist(i(m),j(m)) - xydiff;
end
x(i(m)) = x(i(m)) - diffvec(1)/2;
y(i(m)) = y(i(m)) - diffvec(2)/2;
x(j(m)) = x(j(m)) + diffvec(1)/2;
y(j(m)) = y(j(m)) + diffvec(2)/2;
end
l = l+1;
end
xy = [x; y];
|
github
|
philippboehmsturm/antx-master
|
cache.m
|
.m
|
antx-master/xspm8/@meeg/cache.m
| 754 |
utf_8
|
327310c88f9e84a225af302977c46fe6
|
function res = cache(this, stuff)
% Method for retrieving/putting stuff from/into the temporary cache
% FORMAT res = cache(obj, name)
% _______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Stefan Kiebel
% $Id: cache.m 1373 2008-04-11 14:24:03Z spm $
if ischar(stuff)
% assume this is a retrieval
res = getcache(this, stuff);
else
% assume this is a put
name = inputname(2);
res = setcache(this, name, stuff);
end
function res = getcache(this, stuff)
if isfield(this.cache, stuff)
eval(['res = this.cache.' stuff ';']);
else
res = [];
end
function this = setcache(this, name, stuff)
eval(['this.cache(1).' name ' = stuff;']);
|
github
|
philippboehmsturm/antx-master
|
path.m
|
.m
|
antx-master/xspm8/@meeg/path.m
| 558 |
utf_8
|
7149045fd0a2ac178f0e2dcaf166b5e0
|
function res = path(this, name)
% Method for getting/setting path
% FORMAT res = path(this, name)
% _______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Stefan Kiebel
% $Id: path.m 1373 2008-04-11 14:24:03Z spm $
switch nargin
case 1
res = getpath(this);
case 2
res = setpath(this, name);
otherwise
end
function res = getpath(this)
try
res = this.path;
catch
res = '';
end
function this = setpath(this, name)
this.path = name;
|
github
|
philippboehmsturm/antx-master
|
fname.m
|
.m
|
antx-master/xspm8/@meeg/fname.m
| 538 |
utf_8
|
00404808a43026efada0ed0cb853d259
|
function res = fname(this, name)
% Method for getting/setting file name
% FORMAT res = fname(this, name)
% _______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Stefan Kiebel
% $Id: fname.m 1373 2008-04-11 14:24:03Z spm $
switch nargin
case 1
res = getfname(this);
case 2
res = setfname(this, name);
otherwise
end
function res = getfname(this)
res = this.fname;
function this = setfname(this, name)
this.fname = name;
|
github
|
philippboehmsturm/antx-master
|
fnamedat.m
|
.m
|
antx-master/xspm8/@meeg/fnamedat.m
| 589 |
utf_8
|
39857f5d9ecf819f3bc1581bde7009cf
|
function res = fnamedat(this, name)
% Method for getting/setting file name of data file
% FORMAT res = fnamedat(this, name)
% _______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Stefan Kiebel
% $Id: fnamedat.m 1373 2008-04-11 14:24:03Z spm $
switch nargin
case 1
res = getfnamedat(this);
case 2
res = setfnamedat(this, name);
otherwise
end
function res = getfnamedat(this)
res = this.data.fnamedat;
function this = setfnamedat(this, name)
this.data.fnamedat = name;
|
github
|
philippboehmsturm/antx-master
|
subsasgn.m
|
.m
|
antx-master/xspm8/@file_array/subsasgn.m
| 4,602 |
utf_8
|
0b4cd116c71239ee913cdf7c826c838a
|
function obj = subsasgn(obj,subs,dat)
% Overloaded subsasgn function for file_array objects.
% _______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
%
% $Id: subsasgn.m 4136 2010-12-09 22:22:28Z guillaume $
if isempty(subs)
return;
end;
if ~strcmp(subs(1).type,'()'),
if strcmp(subs(1).type,'.'),
%error('Attempt to reference field of non-structure array.');
if numel(struct(obj))~=1,
error('Can only change the fields of simple file_array objects.');
end;
switch(subs(1).subs)
case 'fname', obj = asgn(obj,@fname, subs(2:end),dat); %fname(obj,dat);
case 'dtype', obj = asgn(obj,@dtype, subs(2:end),dat); %dtype(obj,dat);
case 'offset', obj = asgn(obj,@offset, subs(2:end),dat); %offset(obj,dat);
case 'dim', obj = asgn(obj,@dim, subs(2:end),dat); %obj = dim(obj,dat);
case 'scl_slope', obj = asgn(obj,@scl_slope, subs(2:end),dat); %scl_slope(obj,dat);
case 'scl_inter', obj = asgn(obj,@scl_inter, subs(2:end),dat); %scl_inter(obj,dat);
case 'permission', obj = asgn(obj,@permission,subs(2:end),dat); %permission(obj,dat);
otherwise, error(['Reference to non-existent field "' subs.subs '".']);
end;
return;
end;
if strcmp(subs(1).type,'{}'), error('Cell contents reference from a non-cell array object.'); end;
end;
if numel(subs)~=1, error('Expression too complicated');end;
dm = size(obj);
sobj = struct(obj);
if length(subs.subs) < length(dm),
l = length(subs.subs);
dm = [dm(1:(l-1)) prod(dm(l:end))];
if numel(sobj) ~= 1,
error('Can only reshape simple file_array objects.');
end;
if numel(sobj.scl_slope)>1 || numel(sobj.scl_inter)>1,
error('Can not reshape file_array objects with multiple slopes and intercepts.');
end;
end;
dm = [dm ones(1,16)];
di = ones(1,16);
args = {};
for i=1:length(subs.subs),
if ischar(subs.subs{i}),
if ~strcmp(subs.subs{i},':'), error('This shouldn''t happen....'); end;
args{i} = int32(1:dm(i));
else
args{i} = int32(subs.subs{i});
end;
di(i) = length(args{i});
end;
for j=1:length(sobj),
if strcmp(sobj(j).permission,'ro'),
error('Array is read-only.');
end
end
if length(sobj)==1
sobj.dim = dm;
if numel(dat)~=1,
subfun(sobj,double(dat),args{:});
else
dat1 = double(dat) + zeros(di);
subfun(sobj,dat1,args{:});
end;
else
for j=1:length(sobj),
ps = [sobj(j).pos ones(1,length(args))];
dm = [sobj(j).dim ones(1,length(args))];
siz = ones(1,16);
for i=1:length(args),
msk = args{i}>=ps(i) & args{i}<(ps(i)+dm(i));
args2{i} = find(msk);
args3{i} = int32(double(args{i}(msk))-ps(i)+1);
siz(i) = numel(args2{i});
end;
if numel(dat)~=1,
dat1 = double(subsref(dat,struct('type','()','subs',{args2})));
else
dat1 = double(dat) + zeros(siz);
end;
subfun(sobj(j),dat1,args3{:});
end
end
return
function sobj = subfun(sobj,dat,varargin)
va = varargin;
dt = datatypes;
ind = find(cat(1,dt.code)==sobj.dtype);
if isempty(ind), error('Unknown datatype'); end;
if dt(ind).isint, dat(~isfinite(dat)) = 0; end;
if ~isempty(sobj.scl_inter),
inter = sobj.scl_inter;
if numel(inter)>1,
inter = resize_scales(inter,sobj.dim,varargin);
end;
dat = double(dat) - inter;
end;
if ~isempty(sobj.scl_slope),
slope = sobj.scl_slope;
if numel(slope)>1,
slope = resize_scales(slope,sobj.dim,varargin);
dat = double(dat)./slope;
else
dat = double(dat)/slope;
end;
end;
if dt(ind).isint, dat = round(dat); end;
% Avoid warning messages in R14 SP3
wrn = warning;
warning('off');
dat = feval(dt(ind).conv,dat);
warning(wrn);
nelem = dt(ind).nelem;
if nelem==1,
mat2file(sobj,dat,va{:});
elseif nelem==2,
sobj1 = sobj;
sobj1.dim = [2 sobj.dim];
sobj1.dtype = dt(find(strcmp(dt(ind).prec,{dt.prec}) & (cat(2,dt.nelem)==1))).code;
dat = reshape(dat,[1 size(dat)]);
dat = [real(dat) ; imag(dat)];
mat2file(sobj1,dat,int32([1 2]),va{:});
else
error('Inappropriate number of elements per voxel.');
end;
return
function obj = asgn(obj,fun,subs,dat)
if ~isempty(subs),
tmp = feval(fun,obj);
tmp = subsasgn(tmp,subs,dat);
obj = feval(fun,obj,tmp);
else
obj = feval(fun,obj,dat);
end;
|
github
|
philippboehmsturm/antx-master
|
subsref.m
|
.m
|
antx-master/xspm8/@file_array/subsref.m
| 5,317 |
utf_8
|
64728e33af32c06b26b99b74b700f1f5
|
function varargout=subsref(obj,subs)
% SUBSREF Subscripted reference
% An overloaded function...
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
%
% $Id: subsref.m 4136 2010-12-09 22:22:28Z guillaume $
if isempty(subs), return; end
switch subs(1).type
case '{}'
error('Cell contents reference from a non-cell array object.');
case '.'
varargout = access_fields(obj,subs);
return;
end
if numel(subs)~=1, error('Expression too complicated'); end;
dim = [size(obj) ones(1,16)];
nd = find(dim>1,1,'last')-1;
sobj = struct(obj);
if ~numel(subs.subs)
[subs.subs{1:nd+1}] = deal(':');
elseif length(subs.subs) < nd
l = length(subs.subs);
dim = [dim(1:(l-1)) prod(dim(l:end))];
if numel(sobj) ~= 1
error('Can only reshape simple file_array objects.');
else
if numel(sobj.scl_slope)>1 || numel(sobj.scl_inter)>1
error('Can not reshape file_array objects with multiple slopes and intercepts.');
end
sobj.dim = dim;
end
end
di = ones(16,1);
args = cell(1,length(subs.subs));
for i=1:length(subs.subs)
if ischar(subs.subs{i})
if ~strcmp(subs.subs{i},':'), error('This shouldn''t happen....'); end
if length(subs.subs) == 1
args{i} = 1:prod(dim); % possible overflow when int32()
k = 0;
for j=1:length(sobj)
sobj(j).dim = [prod(sobj(j).dim) 1];
sobj(j).pos = [k+1 1];
k = k + sobj(j).dim(1);
end
else
args{i} = 1:dim(i);
end
else
args{i} = subs.subs{i};
end
di(i) = length(args{i});
end
if length(sobj)==1
t = subfun(sobj,args{:});
else
dt = datatypes;
dt = dt([dt.code]==sobj(1).dtype); % assuming identical datatypes
t = zeros(di',func2str(dt.conv));
for j=1:length(sobj)
ps = [sobj(j).pos ones(1,length(args))];
dm = [sobj(j).dim ones(1,length(args))];
for i=1:length(args)
msk = find(args{i}>=ps(i) & args{i}<(ps(i)+dm(i)));
args2{i} = msk;
args3{i} = double(args{i}(msk))-ps(i)+1;
end
t = subsasgn(t,struct('type','()','subs',{args2}),subfun(sobj(j),args3{:}));
end
end
varargout = {t};
%==========================================================================
% function t = subfun(sobj,varargin)
%==========================================================================
function t = subfun(sobj,varargin)
%sobj.dim = [sobj.dim ones(1,16)];
try
args = cell(size(varargin));
for i=1:length(varargin)
args{i} = int32(varargin{i});
end
t = file2mat(sobj,args{:});
catch
t = multifile2mat(sobj,varargin{:});
end
if ~isempty(sobj.scl_slope) || ~isempty(sobj.scl_inter)
slope = 1;
inter = 0;
if ~isempty(sobj.scl_slope), slope = sobj.scl_slope; end
if ~isempty(sobj.scl_inter), inter = sobj.scl_inter; end
if numel(slope)>1
slope = resize_scales(slope,sobj.dim,varargin);
t = double(t).*slope;
else
t = double(t)*slope;
end
if numel(inter)>1
inter = resize_scales(inter,sobj.dim,varargin);
end;
t = t + inter;
end
%==========================================================================
% function c = access_fields(obj,subs)
%==========================================================================
function c = access_fields(obj,subs)
sobj = struct(obj);
c = cell(1,numel(sobj));
for i=1:numel(sobj)
%obj = class(sobj(i),'file_array');
obj = sobj(i);
switch(subs(1).subs)
case 'fname', t = fname(obj);
case 'dtype', t = dtype(obj);
case 'offset', t = offset(obj);
case 'dim', t = dim(obj);
case 'scl_slope', t = scl_slope(obj);
case 'scl_inter', t = scl_inter(obj);
case 'permission', t = permission(obj);
otherwise
error(['Reference to non-existent field "' subs(1).subs '".']);
end
if numel(subs)>1
t = subsref(t,subs(2:end));
end
c{i} = t;
end
%==========================================================================
% function val = multifile2mat(sobj,varargin)
%==========================================================================
function val = multifile2mat(sobj,varargin)
% Convert subscripts into linear index
[indx2{1:length(varargin)}] = ndgrid(varargin{:},1);
ind = sub2ind(sobj.dim,indx2{:});
% Work out the partition
dt = datatypes;
dt = dt([dt.code]==sobj.dtype);
sz = dt.size;
try
mem = spm('Memory'); % in bytes, has to be a multiple of 16 (max([dt.size]))
catch
mem = 200 * 1024 * 1024;
end
s = ceil(prod(sobj.dim) * sz / mem);
% Assign indices to partitions
[x,y] = ind2sub([mem/sz s],ind(:));
c = histc(y,1:s);
cc = [0 reshape(cumsum(c),1,[])];
% Read data in relevant partitions
obj = sobj;
val = zeros(length(x),1,func2str(dt.conv));
for i=reshape(find(c),1,[])
obj.offset = sobj.offset + mem*(i-1);
obj.dim = [1 min(mem/sz, prod(sobj.dim)-(i-1)*mem/sz)];
val(cc(i)+1:cc(i+1)) = file2mat(obj,int32(1),int32(x(y==i)));
end
r = cellfun('length',varargin);
if numel(r) == 1, r = [r 1]; end
val = reshape(val,r);
|
github
|
philippboehmsturm/antx-master
|
disp.m
|
.m
|
antx-master/xspm8/@file_array/disp.m
| 929 |
utf_8
|
d0546a638c254605a9122a095e4a06ff
|
function disp(obj)
% Display a file_array object
% _______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
%
% $Id: disp.m 4136 2010-12-09 22:22:28Z guillaume $
if numel(struct(obj))>1,
fprintf(' %s object: ', class(obj));
sz = size(obj);
if length(sz)>4,
fprintf('%d-D\n',length(sz));
else
for i=1:(length(sz)-1),
fprintf('%d-by-',sz(i));
end;
fprintf('%d\n',sz(end));
end;
else
disp(mystruct(obj))
end;
return;
%=======================================================================
%=======================================================================
function t = mystruct(obj)
fn = fieldnames(obj);
for i=1:length(fn)
t.(fn{i}) = subsref(obj,struct('type','.','subs',fn{i}));
end;
return;
%=======================================================================
|
github
|
philippboehmsturm/antx-master
|
offset.m
|
.m
|
antx-master/xspm8/@file_array/private/offset.m
| 738 |
utf_8
|
366c2df9f0b718e446521ec24447d7a8
|
function varargout = offset(varargin)
% Format
% For getting the value
% dat = offset(obj)
%
% For setting the value
% obj = offset(obj,dat)
% _______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
%
% $Id: offset.m 1143 2008-02-07 19:33:33Z spm $
if nargin==2,
varargout{1} = asgn(varargin{:});
elseif nargin==1,
varargout{1} = ref(varargin{:});
else
error('Wrong number of arguments.');
end;
return;
function dat = ref(obj)
dat = obj.offset;
return;
function obj = asgn(obj,dat)
if isnumeric(dat) && numel(dat)==1 && dat>=0 && rem(dat,1)==0,
obj.offset = double(dat);
else
error('"offset" must be a positive integer.');
end;
return;
|
github
|
philippboehmsturm/antx-master
|
scl_slope.m
|
.m
|
antx-master/xspm8/@file_array/private/scl_slope.m
| 724 |
utf_8
|
3da54efdb2422c907f41b13b577c1e11
|
function varargout = scl_slope(varargin)
% Format
% For getting the value
% dat = scl_slope(obj)
%
% For setting the value
% obj = scl_slope(obj,dat)
% _______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
%
% $Id: scl_slope.m 1143 2008-02-07 19:33:33Z spm $
if nargin==2,
varargout{1} = asgn(varargin{:});
elseif nargin==1,
varargout{1} = ref(varargin{:});
else
error('Wrong number of arguments.');
end;
return;
function dat = ref(obj)
dat = obj.scl_slope;
return;
function obj = asgn(obj,dat)
if isnumeric(dat), % && numel(dat)<=1,
obj.scl_slope = double(dat);
else
error('"scl_slope" must be numeric.');
end;
return;
|
github
|
philippboehmsturm/antx-master
|
scl_inter.m
|
.m
|
antx-master/xspm8/@file_array/private/scl_inter.m
| 725 |
utf_8
|
8beb5c3767db12faab13c212db9a22ee
|
function varargout = scl_inter(varargin)
% Format
% For getting the value
% dat = scl_inter(obj)
%
% For setting the value
% obj = scl_inter(obj,dat)
% _______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
%
% $Id: scl_inter.m 1143 2008-02-07 19:33:33Z spm $
if nargin==2,
varargout{1} = asgn(varargin{:});
elseif nargin==1,
varargout{1} = ref(varargin{:});
else
error('Wrong number of arguments.');
end;
return;
function dat = ref(obj)
dat = obj.scl_inter;
return;
function obj = asgn(obj,dat)
if isnumeric(dat), % && numel(dat)<=1,
obj.scl_inter = double(dat);
else
error('"scl_inter" must be numeric.');
end;
return;
|
github
|
philippboehmsturm/antx-master
|
fname.m
|
.m
|
antx-master/xspm8/@file_array/private/fname.m
| 688 |
utf_8
|
a873d5e909b320be0af566b05e301636
|
function varargout = fname(varargin)
% Format
% For getting the value
% dat = fname(obj)
%
% For setting the value
% obj = fname(obj,dat)
% _______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
%
% $Id: fname.m 1143 2008-02-07 19:33:33Z spm $
if nargin==2,
varargout{1} = asgn(varargin{:});
elseif nargin==1,
varargout{1} = ref(varargin{:});
else
error('Wrong number of arguments.');
end;
return;
function dat = ref(obj)
dat = obj.fname;
return;
function obj = asgn(obj,dat)
if ischar(dat)
obj.fname = deblank(dat(:)');
else
error('"fname" must be a character string.');
end;
return;
|
github
|
philippboehmsturm/antx-master
|
dim.m
|
.m
|
antx-master/xspm8/@file_array/private/dim.m
| 800 |
utf_8
|
ee81353b13c1dd2f6e5a186f9db0f205
|
function varargout = dim(varargin)
% Format
% For getting the value
% dat = dim(obj)
%
% For setting the value
% obj = dim(obj,dat)
% _______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
%
% $Id: dim.m 1143 2008-02-07 19:33:33Z spm $
if nargin==2,
varargout{1} = asgn(varargin{:});
elseif nargin==1,
varargout{1} = ref(varargin{:});
else
error('Wrong number of arguments.');
end;
return;
function dat = ref(obj)
dat = obj.dim;
return;
function obj = asgn(obj,dat)
if isnumeric(dat) && all(dat>=0) && all(rem(dat,1)==0),
dat = [double(dat(:)') 1 1];
lim = max([2 find(dat~=1)]);
dat = dat(1:lim);
obj.dim = dat;
else
error('"dim" must be a vector of positive integers.');
end;
return;
|
github
|
philippboehmsturm/antx-master
|
permission.m
|
.m
|
antx-master/xspm8/@file_array/private/permission.m
| 873 |
utf_8
|
c058329145646bbcd34aaeffb7184ea9
|
function varargout = permission(varargin)
% Format
% For getting the value
% dat = permission(obj)
%
% For setting the value
% obj = permission(obj,dat)
% _______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
%
% $Id: permission.m 1340 2008-04-09 17:11:23Z john $
if nargin==2,
varargout{1} = asgn(varargin{:});
elseif nargin==1,
varargout{1} = ref(varargin{:});
else
error('Wrong number of arguments.');
end;
return;
function dat = ref(obj)
dat = obj.permission;
return;
function obj = asgn(obj,dat)
if ischar(dat)
tmp = lower(deblank(dat(:)'));
switch tmp,
case 'ro',
case 'rw',
otherwise,
error('Permission must be either "ro" or "rw"');
end
obj.permission = tmp;
else
error('"permission" must be a character string.');
end;
return;
|
github
|
philippboehmsturm/antx-master
|
dtype.m
|
.m
|
antx-master/xspm8/@file_array/private/dtype.m
| 2,265 |
utf_8
|
0298fb2f4de45f2f789a8a855bf62a2c
|
function varargout = dtype(varargin)
% Format
% For getting the value
% dat = dtype(obj)
%
% For setting the value
% obj = dtype(obj,dat)
% _______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
%
% $Id: dtype.m 1143 2008-02-07 19:33:33Z spm $
if nargin==2,
varargout{1} = asgn(varargin{:});
elseif nargin==1,
varargout{1} = ref(varargin{:});
else
error('Wring number of arguments.');
end;
return;
function t = ref(obj)
d = datatypes;
mch = find(cat(1,d.code)==obj.dtype);
if isempty(mch), t = 'UNKNOWN'; else t = d(mch).label; end;
if obj.be, t = [t '-BE']; else t = [t '-LE']; end;
return;
function obj = asgn(obj,dat)
d = datatypes;
if isnumeric(dat)
if numel(dat)>=1,
mch = find(cat(1,d.code)==dat(1));
if isempty(mch) || mch==0,
fprintf('Invalid datatype (%d).', dat(1));
disp('First part of datatype should be of one of the following');
disp(sortrows([num2str(cat(1,d.code)) ...
repmat(' ',numel(d),2) strvcat(d.label)]));
%error(['Invalid datatype (' num2str(dat(1)) ').']);
return;
end;
obj.dtype = double(dat(1));
end;
if numel(dat)>=2,
obj.be = double(dat(2)~=0);
end;
if numel(dat)>2,
error('Too many elements in numeric datatype.');
end;
elseif ischar(dat),
dat1 = lower(dat);
sep = find(dat1=='-' | dat1=='/');
sep = sep(sep~=1);
if ~isempty(sep),
c1 = dat1(1:(sep(1)-1));
c2 = dat1((sep(1)+1):end);
else
c1 = dat1;
c2 = '';
end;
mch = find(strcmpi(c1,lower({d.label})));
if isempty(mch),
disp('First part of datatype should be of one of the following');
disp(sortrows([num2str(cat(1,d.code)) ...
repmat(' ',numel(d),2) strvcat(d.label)]));
%error(['Invalid datatype (' c1 ').']);
return;
else
obj.dtype = double(d(mch(1)).code);
end;
if any(c2=='b'),
if any(c2=='l'),
error('Cannot be both big and little endian.');
end;
obj.be = 1;
elseif any(c2=='l'),
obj.be = 0;
end;
else
error('Invalid datatype.');
end;
return;
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_ppi.m
|
.m
|
antx-master/xspm8/config/spm_cfg_ppi.m
| 5,867 |
utf_8
|
895e4dae672dbaf9f85422e01a2647f2
|
function ppis = spm_cfg_ppi
% SPM Configuration file for PPIs
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Guillaume Flandin
% $Id: spm_cfg_ppi.m 4136 2010-12-09 22:22:28Z guillaume $
% ---------------------------------------------------------------------
% spmmat Select SPM.mat
% ---------------------------------------------------------------------
spmmat = cfg_files;
spmmat.tag = 'spmmat';
spmmat.name = 'Select SPM.mat';
spmmat.help = {'Select SPM.mat file'};
spmmat.filter = 'mat';
spmmat.ufilter = '^SPM\.mat$';
spmmat.num = [1 1];
% ---------------------------------------------------------------------
% voi1 Select VOI.mat
% ---------------------------------------------------------------------
voi1 = cfg_files;
voi1.tag = 'voi';
voi1.name = 'Select VOI';
voi1.help = {'physiological variable'};
voi1.filter = 'mat';
voi1.ufilter = '^VOI.*\.mat$';
voi1.num = [1 1];
% ---------------------------------------------------------------------
% voi2 Select VOI.mat
% ---------------------------------------------------------------------
voi2 = cfg_files;
voi2.tag = 'voi';
voi2.name = 'Select VOI';
voi2.help = {'physiological variables'};
voi2.filter = 'mat';
voi2.ufilter = '^VOI.*\.mat$';
voi2.num = [2 2];
% ---------------------------------------------------------------------
% con Matrix of input variables and contrast weights
% ---------------------------------------------------------------------
con = cfg_entry;
con.tag = 'u';
con.name = ' Input variables and contrast weights';
con.help = {['Matrix of input variables and contrast weights.',...
'This is an [n x 3] matrix. The first column indexes SPM.Sess.U(i). ',...
'The second column indexes the name of the input or cause, see ',...
'SPM.Sess.U(i).name{j}. The third column is the contrast weight. ',...
' Unless there are parametric effects the second column will generally ',...
'be a 1.']};
con.strtype = 'e';
con.num = [Inf 3];
% ---------------------------------------------------------------------
% sd Simple deconvolution
% ---------------------------------------------------------------------
sd = cfg_branch;
sd.tag = 'sd';
sd.name = 'Simple deconvolution';
sd.val = {voi1};
sd.help = {'Simple deconvolution'};
% ---------------------------------------------------------------------
% phipi Physio-Physiologic Interaction
% ---------------------------------------------------------------------
phipi = cfg_branch;
phipi.tag = 'phipi';
phipi.name = 'Physio-Physiologic Interaction';
phipi.val = {voi2};
phipi.help = {'Physio-Physiologic Interaction'};
% ---------------------------------------------------------------------
% ppi Psycho-Physiologic Interaction
% ---------------------------------------------------------------------
ppi = cfg_branch;
ppi.tag = 'ppi';
ppi.name = 'Psycho-Physiologic Interaction';
ppi.val = {voi1 con};
ppi.help = {'Psycho-Physiologic Interaction'};
% ---------------------------------------------------------------------
% ppiflag Type of analysis
% ---------------------------------------------------------------------
ppiflag = cfg_choice;
ppiflag.tag = 'type';
ppiflag.name = 'Type of analysis';
ppiflag.help = {'Type of analysis'};
ppiflag.values = {sd ppi phipi};
% ---------------------------------------------------------------------
% name Name of PPI
% ---------------------------------------------------------------------
name = cfg_entry;
name.tag = 'name';
name.name = 'Name of PPI';
name.help = {['Name of the PPI mat file that will be saved in the ',...
'same directory than the SPM.mat file. A ''PPI_'' prefix will be added.']};
name.strtype = 's';
name.num = [1 Inf];
% ---------------------------------------------------------------------
% showGraphics Display results
% ---------------------------------------------------------------------
showGraphics = cfg_menu;
showGraphics.tag = 'disp';
showGraphics.name = 'Display results';
showGraphics.help = {'Display results'};
showGraphics.labels = {'Yes' 'No'};
showGraphics.values = { 1 0 };
showGraphics.val = { 0 };
% ---------------------------------------------------------------------
% ppis PPI
% ---------------------------------------------------------------------
ppis = cfg_exbranch;
ppis.tag = 'ppi';
ppis.name = 'Physio/Psycho-Physiologic Interaction';
ppis.val = {spmmat ppiflag name showGraphics};
ppis.help = {['Bold deconvolution to create physio- or '...
'psycho-physiologic interactions.']};
ppis.prog = @run_ppi;
ppis.vout = @vout_ppi;
%-------------------------------------------------------------------------
%-------------------------------------------------------------------------
function out = run_ppi(job)
switch char(fieldnames(job.type))
case 'sd'
PPI = spm_peb_ppi(job.spmmat{1}, 'sd', char(job.type.sd.voi),...
[], job.name, job.disp);
case 'ppi'
PPI = spm_peb_ppi(job.spmmat{1}, 'ppi', char(job.type.ppi.voi),...
job.type.ppi.u, job.name, job.disp);
case 'phipi'
PPI = spm_peb_ppi(job.spmmat{1}, 'phipi', char(job.type.phipi.voi),...
[], job.name, job.disp);
otherwise
error('Unknown type of analysis.');
end
[p n] = fileparts(job.name);
out.ppimat = cellstr(fullfile(fileparts(job.spmmat{1}),['PPI_' n '.mat']));
%-------------------------------------------------------------------------
function dep = vout_ppi(varargin)
dep(1) = cfg_dep;
dep(1).sname = ' PPI mat File';
dep(1).src_output = substruct('.','ppimat');
dep(1).tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}});
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_preproc.m
|
.m
|
antx-master/xspm8/config/spm_cfg_preproc.m
| 30,016 |
utf_8
|
b471e8090bf6ae6a44134c195fcdaefb
|
function preproc = spm_cfg_preproc
% SPM Configuration file
% automatically generated by the MATLABBATCH utility function GENCODE
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% $Id: spm_cfg_preproc.m 3124 2009-05-18 08:13:52Z volkmar $
rev = '$Rev: 3124 $';
% ---------------------------------------------------------------------
% data Data
% ---------------------------------------------------------------------
data = cfg_files;
data.tag = 'data';
data.name = 'Data';
data.help = {'Select scans for processing. This assumes that there is one scan for each subject. Note that multi-spectral (when there are two or more registered images of different contrasts) processing is not yet implemented for this method.'};
data.filter = 'image';
data.ufilter = '.*';
data.num = [1 Inf];
% ---------------------------------------------------------------------
% GM Grey Matter
% ---------------------------------------------------------------------
GM = cfg_menu;
GM.tag = 'GM';
GM.name = 'Grey Matter';
GM.help = {'Options to produce grey matter images: c1*.img, wc1*.img and mwc1*.img.'};
GM.labels = {
'None'
'Native Space'
'Unmodulated Normalised'
'Modulated Normalised'
'Native + Unmodulated Normalised'
'Native + Modulated Normalised'
'Native + Modulated + Unmodulated'
'Modulated + Unmodulated Normalised'
}';
GM.values = {[0 0 0] [0 0 1] [0 1 0] [1 0 0] [0 1 1] [1 0 1] [1 1 1]...
[1 1 0]};
GM.def = @(val)spm_get_defaults('preproc.output.GM', val{:});
% ---------------------------------------------------------------------
% WM White Matter
% ---------------------------------------------------------------------
WM = cfg_menu;
WM.tag = 'WM';
WM.name = 'White Matter';
WM.help = {'Options to produce white matter images: c2*.img, wc2*.img and mwc2*.img.'};
WM.labels = {
'None'
'Native Space'
'Unmodulated Normalised'
'Modulated Normalised'
'Native + Unmodulated Normalised'
'Native + Modulated Normalised'
'Native + Modulated + Unmodulated'
'Modulated + Unmodulated Normalised'
}';
WM.values = {[0 0 0] [0 0 1] [0 1 0] [1 0 0] [0 1 1] [1 0 1] [1 1 1]...
[1 1 0]};
WM.def = @(val)spm_get_defaults('preproc.output.WM', val{:});
% ---------------------------------------------------------------------
% CSF Cerebro-Spinal Fluid
% ---------------------------------------------------------------------
CSF = cfg_menu;
CSF.tag = 'CSF';
CSF.name = 'Cerebro-Spinal Fluid';
CSF.help = {'Options to produce CSF images: c3*.img, wc3*.img and mwc3*.img.'};
CSF.labels = {
'None'
'Native Space'
'Unmodulated Normalised'
'Modulated Normalised'
'Native + Unmodulated Normalised'
'Native + Modulated Normalised'
'Native + Modulated + Unmodulated'
'Modulated + Unmodulated Normalised'
}';
CSF.values = {[0 0 0] [0 0 1] [0 1 0] [1 0 0] [0 1 1] [1 0 1] [1 1 1]...
[1 1 0]};
CSF.def = @(val)spm_get_defaults('preproc.output.CSF', val{:});
% ---------------------------------------------------------------------
% biascor Bias Corrected
% ---------------------------------------------------------------------
biascor = cfg_menu;
biascor.tag = 'biascor';
biascor.name = 'Bias Corrected';
biascor.help = {'This is the option to produce a bias corrected version of your image. 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. The bias corrected version should have more uniform intensities within the different types of tissues.'};
biascor.labels = {
'Save Bias Corrected'
'Don''t Save Corrected'
}';
biascor.values = {1 0};
biascor.def = @(val)spm_get_defaults('preproc.output.biascor', val{:});
% ---------------------------------------------------------------------
% cleanup Clean up any partitions
% ---------------------------------------------------------------------
cleanup = cfg_menu;
cleanup.tag = 'cleanup';
cleanup.name = 'Clean up any partitions';
cleanup.help = {
'This uses a crude routine for extracting the brain from segmentedimages. It begins by taking the white matter, and eroding it acouple of times to get rid of any odd voxels. The algorithmcontinues on to do conditional dilations for several iterations,where the condition is based upon gray or white matter being present.This identified region is then used to clean up the grey and whitematter partitions, and has a slight influences on the CSF partition.'
''
'If you find pieces of brain being chopped out in your data, then you may wish to disable or tone down the cleanup procedure.'
}';
cleanup.labels = {
'Dont do cleanup'
'Light Clean'
'Thorough Clean'
}';
cleanup.values = {0 1 2};
cleanup.def = @(val)spm_get_defaults('preproc.output.cleanup', val{:});
% ---------------------------------------------------------------------
% output Output Files
% ---------------------------------------------------------------------
output = cfg_branch;
output.tag = 'output';
output.name = 'Output Files';
output.val = {GM WM CSF biascor cleanup };
output.help = {
'This routine produces spatial normalisation parameters (*_seg_sn.mat files) by default. These can be used for writing spatially normalised versions of your data, via the "Normalise: Write" option. This mechanism may produce superior results than the "Normalise: Estimate" option (but probably not as good as those produced using DARTEL).'
''
'In addition, it also produces files that can be used for doing inverse normalisation. If you have an image of regions defined in the standard space, then the inverse deformations can be used to warp these regions so that it approximately overlay your image. To use this facility, the bounding-box and voxel sizes should be set to non-finite values (e.g. [NaN NaN NaN] for the voxel sizes, and ones(2,3)*NaN for the bounding box. This would be done by the spatial normalisation module, which allows you to select a set of parameters that describe the nonlinear warps, and the images that they should be applied to.'
''
'There are a number of options about what data you would like the routine to produce. The routine can be used for producing images of tissue classes, as well as bias corrected images. The native space option will produce a tissue class image (c*) that is in alignment with the original/* (see Figure \ref{seg1})*/. You can also produce spatially normalised versions - both with (mwc*) and without (wc*) modulation/* (see Figure \ref{seg2})*/. The bounding box and voxel sizes of the spatially normalised versions are the same as that of the tissue probability maps with which they are registered. These can be used for doing voxel-based morphometry with (also see the ``Using DARTEL'' chapter of the manual). All you need to do is smooth them and do the stats (which means no more questions on the mailing list about how to do "optimized VBM").'
''
'Modulation is to compensate for the effect of spatial normalisation. When warping a series of images to match a template, it is inevitable that volumetric differences will be introduced into the warped images. For example, if one subject''s temporal lobe has half the volume of that of the template, then its volume will be doubled during spatial normalisation. This will also result in a doubling of the voxels labelled grey matter. In order to remove this confound, the spatially normalised grey matter (or other tissue class) is adjusted by multiplying by its relative volume before and after warping. If warping results in a region doubling its volume, then the correction will halve the intensity of the tissue label. This whole procedure has the effect of preserving the total amount of grey matter signal in the normalised partitions.'
'/*\begin{figure} \begin{center} \includegraphics[width=140mm]{images/seg1} \end{center} \caption{Segmentation results. These are the results that can be obtained in the original space of the image (i.e. the results that are not spatially normalised). Top left: original image (X.img). Top right: bias corrected image (mX.img). Middle and bottom rows: segmented grey matter (c1X.img), white matter (c2X.img) and CSF (c3X.img). \label{seg1}} \end{figure} */'
'/*\begin{figure} \begin{center} \includegraphics[width=140mm]{images/seg2} \end{center} \caption{Segmentation results. These are the spatially normalised results that can be obtained (note that CSF data is not shown). Top row: The tissue probability maps used to guide the segmentation. Middle row: Spatially normalised tissue maps of grey and white matter (wc1X.img and wc2X.img). Bottom row: Modulated spatially normalised tissue maps of grey and white matter (mwc1X.img and mwc2X.img). \label{seg2}} \end{figure} */'
'A deformation field is a vector field, where three values are associated with each location in the field. The field maps from co-ordinates in the normalised image back to co-ordinates in the original image. The value of the field at co-ordinate [x y z] in the normalised space will be the co-ordinate [x'' y'' z''] in the original volume. The gradient of the deformation field at a co-ordinate is its Jacobian matrix, and it consists of a 3x3 matrix:'
''
'% / \'
'% | dx''/dx dx''/dy dx''/dz |'
'% | |'
'% | dy''/dx dy''/dy dy''/dz |'
'% | |'
'% | dz''/dx dz''/dy dz''/dz |'
'% \ /'
'/* \begin{eqnarray*}\begin{pmatrix}\frac{dx''}{dx} & \frac{dx''}{dy} & \frac{dx''}{dz}\cr\frac{dy''}{dx} & \frac{dy''}{dy} & \frac{dy''}{dz}\cr\frac{dz''}{dx} & \frac{dz''}{dy} & \frac{dz''}{dz}\cr\end{pmatrix}\end{eqnarray*}*/'
'The value of dx''/dy is a measure of how much x'' changes if y is changed by a tiny amount. The determinant of the Jacobian is the measure of relative volumes of warped and unwarped structures. The modulation step simply involves multiplying by the relative volumes /*(see Figure \ref{seg2})*/.'
}';
% ---------------------------------------------------------------------
% tpm Tissue probability maps
% ---------------------------------------------------------------------
tpm = cfg_files;
tpm.tag = 'tpm';
tpm.name = 'Tissue probability maps';
tpm.help = {
'Select the tissue probability images. These should be maps of grey matter, white matter and cerebro-spinal fluid probability. A nonlinear deformation field is estimated that best overlays the tissue probability maps on the individual subjects'' image. The default tissue probability maps are modified versions of the ICBM Tissue Probabilistic Atlases.These tissue probability maps are kindly provided by the International Consortium for Brain Mapping, John C. Mazziotta and Arthur W. Toga. http://www.loni.ucla.edu/ICBM/ICBM_TissueProb.html. The original data are derived from 452 T1-weighted scans, which were aligned with an atlas space, corrected for scan inhomogeneities, and classified into grey matter, white matter and cerebrospinal fluid. These data were then affine registered to the MNI space and downsampled to 2mm resolution.'
''
'Rather than assuming stationary prior probabilities based upon mixing proportions, additional information is used, based on other subjects'' brain images. Priors are usually generated by registering a large number of subjects together, assigning voxels to different tissue types and averaging tissue classes over subjects. Three tissue classes are used: grey matter, white matter and cerebro-spinal fluid. A fourth class is also used, which is simply one minus the sum of the first three. These maps give the prior probability of any voxel in a registered image being of any of the tissue classes - irrespective of its intensity.'
''
'The model is refined further by allowing the tissue probability maps to be deformed according to a set of estimated parameters. This allows spatial normalisation and segmentation to be combined into the same model. This implementation uses a low-dimensional approach, which parameterises the deformations by a linear combination of about a thousand cosine transform bases. This is not an especially precise way of encoding deformations, but it can model the variability of overall brain shape. Evaluations by Hellier et al have shown that this simple model can achieve a registration accuracy comparable to other fully automated methods with many more parameters.'
}';
tpm.filter = 'image';
tpm.dir = fullfile(spm('dir'),'tpm');
tpm.ufilter = '.*';
tpm.num = [3 3];
tpm.def = @(val)spm_get_defaults('preproc.tpm', val{:});
% ---------------------------------------------------------------------
% ngaus Gaussians per class
% ---------------------------------------------------------------------
ngaus = cfg_entry;
ngaus.tag = 'ngaus';
ngaus.name = 'Gaussians per class';
ngaus.help = {'The number of Gaussians used to represent the intensity distribution for each tissue class can be greater than one. In other words, a tissue probability map may be shared by several clusters. The assumption of a single Gaussian distribution for each class does not hold for a number of reasons. In particular, a voxel may not be purely of one tissue type, and instead contain signal from a number of different tissues (partial volume effects). Some partial volume voxels could fall at the interface between different classes, or they may fall in the middle of structures such as the thalamus, which may be considered as being either grey or white matter. Various other image segmentation approaches use additional clusters to model such partial volume effects. These generally assume that a pure tissue class has a Gaussian intensity distribution, whereas intensity distributions for partial volume voxels are broader, falling between the intensities of the pure classes. Unlike these partial volume segmentation approaches, the model adopted here simply assumes that the intensity distribution of each class may not be Gaussian, and assigns belonging probabilities according to these non-Gaussian distributions. Typical numbers of Gaussians could be two for grey matter, two for white matter, two for CSF, and four for everything else.'};
ngaus.strtype = 'n';
ngaus.num = [4 1];
ngaus.def = @(val)spm_get_defaults('preproc.ngaus', val{:});
% ---------------------------------------------------------------------
% regtype Affine Regularisation
% ---------------------------------------------------------------------
regtype = cfg_menu;
regtype.tag = 'regtype';
regtype.name = 'Affine Regularisation';
regtype.help = {
'The procedure is a local optimisation, so it needs reasonable initial starting estimates. Images should be placed in approximate alignment using the Display function of SPM before beginning. A Mutual Information affine registration with the tissue probability maps (D''Agostino et al, 2004) is used to achieve approximate alignment. Note that this step does not include any model for intensity non-uniformity. This means that if the procedure is to be initialised with the affine registration, then the data should not be too corrupted with this artifact.If there is a lot of intensity non-uniformity, then manually position your image in order to achieve closer starting estimates, and turn off the affine registration.'
''
'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). For example, if registering to an image in ICBM/MNI space, then choose this option. If registering to a template that is close in size, then select the appropriate option for this.'
}';
regtype.labels = {
'No Affine Registration'
'ICBM space template - European brains'
'ICBM space template - East Asian brains'
'Average sized template'
'No regularisation'
}';
regtype.values = {
''
'mni'
'eastern'
'subj'
'none'
}';
regtype.def = @(val)spm_get_defaults('preproc.regtype', val{:});
% ---------------------------------------------------------------------
% warpreg Warping Regularisation
% ---------------------------------------------------------------------
warpreg = cfg_entry;
warpreg.tag = 'warpreg';
warpreg.name = 'Warping Regularisation';
warpreg.help = {'The objective function for registering the tissue probability maps to the image to process, involves minimising the sum of two terms. One term gives a function of how probable the data is given the warping parameters. The other is a function of how probable the parameters are, and provides a penalty for unlikely deformations. Smoother deformations are deemed to be more probable. The amount of regularisation determines the tradeoff between the terms. Pick a value around one. However, if your normalised images appear distorted, then it may be an idea to increase the amount of regularisation (by an order of magnitude). More regularisation gives smoother deformations, where the smoothness measure is determined by the bending energy of the deformations. '};
warpreg.strtype = 'e';
warpreg.num = [1 1];
warpreg.def = @(val)spm_get_defaults('preproc.warpreg', val{:});
% ---------------------------------------------------------------------
% warpco Warp Frequency Cutoff
% ---------------------------------------------------------------------
warpco = cfg_entry;
warpco.tag = 'warpco';
warpco.name = 'Warp Frequency Cutoff';
warpco.help = {'Cutoff of DCT bases. Only DCT bases of periods longer than the cutoff are used to describe the warps. The number actually used will depend on the cutoff and the field of view of your image. A smaller cutoff frequency will allow more detailed deformations to be modelled, but unfortunately comes at a cost of greatly increasing the amount of memory needed, and the time taken.'};
warpco.strtype = 'e';
warpco.num = [1 1];
warpco.def = @(val)spm_get_defaults('preproc.warpco', val{:});
% ---------------------------------------------------------------------
% biasreg Bias regularisation
% ---------------------------------------------------------------------
biasreg = cfg_menu;
biasreg.tag = 'biasreg';
biasreg.name = 'Bias regularisation';
biasreg.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.'
''
'An important issue relates to the distinction between intensity variations that arise because of bias artifact due to the physics of MR scanning, and those that arise due to different tissue properties. The objective is to model the latter by different tissue classes, while modelling the former with a bias field. 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 non-uniformity 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 non-uniformity.'
}';
biasreg.labels = {
'no regularisation (0)'
'extremely light regularisation (0.00001)'
'very light regularisation (0.0001)'
'light regularisation (0.001)'
'medium regularisation (0.01)'
'heavy regularisation (0.1)'
'very heavy regularisation (1)'
'extremely heavy regularisation (10)'
}';
biasreg.values = {0 1e-5 .0001 .001 .01 .1 1 10};
biasreg.def = @(val)spm_get_defaults('preproc.biasreg', val{:});
% ---------------------------------------------------------------------
% biasfwhm Bias FWHM
% ---------------------------------------------------------------------
biasfwhm = cfg_menu;
biasfwhm.tag = 'biasfwhm';
biasfwhm.name = 'Bias FWHM';
biasfwhm.help = {'FWHM of Gaussian smoothness of bias. If your intensity non-uniformity 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 non-uniformity 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 non-uniformities.'};
biasfwhm.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'
}';
biasfwhm.values = {30 40 50 60 70 80 90 100 110 120 130 140 150 Inf};
biasfwhm.def = @(val)spm_get_defaults('preproc.biasfwhm', val{:});
% ---------------------------------------------------------------------
% samp Sampling distance
% ---------------------------------------------------------------------
samp = cfg_entry;
samp.tag = 'samp';
samp.name = 'Sampling distance';
samp.help = {'The approximate distance between sampled points when estimating the model parameters. Smaller values use more of the data, but the procedure is slower.'};
samp.strtype = 'e';
samp.num = [1 1];
samp.def = @(val)spm_get_defaults('preproc.samp', val{:});
% ---------------------------------------------------------------------
% msk Masking image
% ---------------------------------------------------------------------
msk = cfg_files;
msk.tag = 'msk';
msk.name = 'Masking image';
msk.val{1} = {''};
msk.help = {'The segmentation can be masked by an image that conforms to the same space as the images to be segmented. If an image is selected, then it must match the image(s) voxel-for voxel, and have the same voxel-to-world mapping. Regions containing a value of zero in this image do not contribute when estimating the various parameters. '};
msk.filter = 'image';
msk.ufilter = '.*';
msk.num = [0 1];
% ---------------------------------------------------------------------
% opts Custom
% ---------------------------------------------------------------------
opts = cfg_branch;
opts.tag = 'opts';
opts.name = 'Custom';
opts.val = {tpm ngaus regtype warpreg warpco biasreg biasfwhm samp msk };
opts.help = {'Various options can be adjusted in order to improve the performance of the algorithm with your data. Knowing what works best should be a matter of empirical exploration. For example, if your data has very little intensity non-uniformity artifact, then the bias regularisation should be increased. This effectively tells the algorithm that there is very little bias in your data, so it does not try to model it.'};
% ---------------------------------------------------------------------
% preproc Segment
% ---------------------------------------------------------------------
preproc = cfg_exbranch;
preproc.tag = 'preproc';
preproc.name = 'Segment';
preproc.val = {data output opts };
preproc.help = {
'Segment, bias correct and spatially normalise - all in the same model/* \cite{ashburner05}*/. This function can be used for bias correcting, spatially normalising or segmenting your data. Note that this module needs the images to be roughly aligned with the tissue probability maps before you begin. If strange results are obtained, then this is usually because the images were poorly aligned beforehand. The Display option can be used to manually reposition the images so that the AC is close to coordinate 0,0,0 (within a couple of cm) and the orientation is within a few degrees of the tissue probability map data.'
''
'Many investigators use tools within older versions of SPM for a technique that has become known as "optimised" voxel-based morphometry (VBM). VBM performs region-wise volumetric comparisons among populations of subjects. It requires the images to be spatially normalised, segmented into different tissue classes, and smoothed, prior to performing statistical tests/* \cite{wright_vbm,am_vbmreview,ashburner00b,john_should}*/. The "optimised" pre-processing strategy involved spatially normalising subjects'' brain images to a standard space, by matching grey matter in these images, to a grey matter reference. The historical motivation behind this approach was to reduce the confounding effects of non-brain (e.g. scalp) structural variability on the registration. Tissue classification in older versions of SPM required the images to be registered with tissue probability maps. After registration, these maps represented the prior probability of different tissue classes being found at each location in an image. Bayes rule can then be used to combine these priors with tissue type probabilities derived from voxel intensities, to provide the posterior probability.'
''
'This procedure was inherently circular, because the registration required an initial tissue classification, and the tissue classification requires an initial registration. This circularity is resolved here by combining both components into a single generative model. This model also includes parameters that account for image intensity non-uniformity. Estimating the model parameters (for a maximum a posteriori solution) involves alternating among classification, bias correction and registration steps. This approach provides better results than simple serial applications of each component.'
''
'Note that multi-spectral segmentation (e.g. from a registered T1 and T2 image) is not yet implemented, but is planned for a future SPM version.'
}';
preproc.prog = @spm_run_preproc;
preproc.vout = @vout;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function dep = vout(job)
opts = job.output;
cdep(1) = cfg_dep;
cdep(1).sname = 'Norm Params Subj->MNI';
cdep(1).src_output = substruct('()',{1}, '.','snfile','()',{':'});
cdep(1).tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}});
cdep(2) = cfg_dep;
cdep(2).sname = 'Norm Params MNI->Subj';
cdep(2).src_output = substruct('()',{1}, '.','isnfile','()',{':'});
cdep(2).tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}});
if opts.biascor,
cdep(end+1) = cfg_dep;
cdep(end).sname = 'Bias Corr Images';
cdep(end).src_output = substruct('()',{1}, '.','biascorr','()',{':'});
cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
end;
sonames = {'GM','WM','CSF'};
for k1=1:3,
if ~strcmp(opts.(sonames{k1}),'<UNDEFINED>')
if opts.(sonames{k1})(3),
cdep(end+1) = cfg_dep;
cdep(end).sname = sprintf('c%d Images',k1);
cdep(end).src_output = substruct('()',{1}, '.',sprintf('c%d',k1),'()',{':'});
cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
end;
if opts.(sonames{k1})(2),
cdep(end+1) = cfg_dep;
cdep(end).sname = sprintf('wc%d Images',k1);
cdep(end).src_output = substruct('()',{1}, '.',sprintf('wc%d',k1),'()',{':'});
cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
end;
if opts.(sonames{k1})(1),
cdep(end+1) = cfg_dep;
cdep(end).sname = sprintf('mwc%d Images',k1);
cdep(end).src_output = substruct('()',{1}, '.',sprintf('mwc%d',k1),'()',{':'});
cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
end;
end
end;
dep = cdep;
|
github
|
philippboehmsturm/antx-master
|
spm_run_fmri_design.m
|
.m
|
antx-master/xspm8/config/spm_run_fmri_design.m
| 11,410 |
utf_8
|
966cf5ef726bcdbf52473fdcdd3d3525
|
function out = spm_run_fmri_design(job)
% Set up the design matrix and run a design.
% 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.
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% $Id: spm_run_fmri_design.m 4185 2011-02-01 18:46:18Z guillaume $
original_dir = pwd;
my_cd(job.dir);
%-Ask about overwriting files from previous analyses...
%-------------------------------------------------------------------
if exist(fullfile(job.dir{1},'SPM.mat'),'file')
str = { 'Current directory contains existing SPM file:',...
'Continuing will overwrite existing file!'};
if spm_input(str,1,'bd','stop|continue',[1,0],1,mfilename);
fprintf('%-40s: %30s\n\n',...
'Abort... (existing SPM file)',spm('time'));
return
end
end
% If we've gotten to this point we're committed to overwriting files.
% Delete them so we don't get stuck in spm_spm
%------------------------------------------------------------------------
files = {'^mask\..{3}$','^ResMS\..{3}$','^RPV\..{3}$',...
'^beta_.{4}\..{3}$','^con_.{4}\..{3}$','^ResI_.{4}\..{3}$',...
'^ess_.{4}\..{3}$', '^spm\w{1}_.{4}\..{3}$'};
for i=1:length(files)
j = spm_select('List',pwd,files{i});
for k=1:size(j,1)
spm_unlink(deblank(j(k,:)));
end
end
% Variables
%-------------------------------------------------------------
SPM.xY.RT = job.timing.RT;
% Slice timing
%-------------------------------------------------------------
% The following lines have the side effect of modifying the global
% defaults variable. This is necessary to pass job.timing.fmri_t to
% spm_hrf.m. The original values are saved here and restored at the end
% of this function, after the design has been specified. The original
% values may not be restored if this function crashes.
olddefs.stats.fmri.fmri_t = spm_get_defaults('stats.fmri.fmri_t');
olddefs.stats.fmri.fmri_t0 = spm_get_defaults('stats.fmri.fmri_t0');
spm_get_defaults('stats.fmri.t', job.timing.fmri_t);
spm_get_defaults('stats.fmri.t0', job.timing.fmri_t0);
% Basis function variables
%-------------------------------------------------------------
SPM.xBF.UNITS = job.timing.units;
SPM.xBF.dt = job.timing.RT/job.timing.fmri_t;
SPM.xBF.T = job.timing.fmri_t;
SPM.xBF.T0 = job.timing.fmri_t0;
% Basis functions
%-------------------------------------------------------------
if strcmp(fieldnames(job.bases),'hrf')
if all(job.bases.hrf.derivs == [0 0])
SPM.xBF.name = 'hrf';
elseif all(job.bases.hrf.derivs == [1 0])
SPM.xBF.name = 'hrf (with time derivative)';
elseif all(job.bases.hrf.derivs == [1 1])
SPM.xBF.name = 'hrf (with time and dispersion derivatives)';
else
error('Unrecognized hrf derivative choices.')
end
else
nambase = fieldnames(job.bases);
if ischar(nambase)
nam=nambase;
else
nam=nambase{1};
end
switch nam,
case 'fourier',
SPM.xBF.name = 'Fourier set';
case 'fourier_han',
SPM.xBF.name = 'Fourier set (Hanning)';
case 'gamma',
SPM.xBF.name = 'Gamma functions';
case 'fir',
SPM.xBF.name = 'Finite Impulse Response';
otherwise
error('Unrecognized hrf derivative choices.')
end
SPM.xBF.length = job.bases.(nam).length;
SPM.xBF.order = job.bases.(nam).order;
end
SPM.xBF = spm_get_bf(SPM.xBF);
if isempty(job.sess),
SPM.xBF.Volterra = false;
else
SPM.xBF.Volterra = job.volt;
end;
for i = 1:numel(job.sess),
sess = job.sess(i);
% Image filenames
%-------------------------------------------------------------
SPM.nscan(i) = sess.nscan;
U = [];
% Augment the singly-specified conditions with the multiple conditions
% specified in a .mat file provided by the user
%------------------------------------------------------------
if ~isempty(sess.multi{1})
try
multicond = load(sess.multi{1});
catch
error('Cannot load %s',sess.multi{1});
end
if ~(isfield(multicond,'names')&&isfield(multicond,'onsets')&&...
isfield(multicond,'durations')) || ...
~all([numel(multicond.names),numel(multicond.onsets), ...
numel(multicond.durations)]==numel(multicond.names))
error(['Multiple conditions MAT-file ''%s'' is invalid.\n',...
'File must contain names, onsets, and durations '...
'cell arrays of equal length.\n'],sess.multi{1});
end
%-contains three cell arrays: names, onsets and durations
for j=1:length(multicond.onsets)
cond.name = multicond.names{j};
cond.onset = multicond.onsets{j};
cond.duration = multicond.durations{j};
% ADDED BY DGITELMAN
% Mutiple Conditions Time Modulation
%------------------------------------------------------
% initialize the variable.
cond.tmod = 0;
if isfield(multicond,'tmod');
try
cond.tmod = multicond.tmod{j};
catch
error('Error specifying time modulation.');
end
end
% Mutiple Conditions Parametric Modulation
%------------------------------------------------------
% initialize the parametric modulation variable.
cond.pmod = [];
if isfield(multicond,'pmod')
% only access existing modulators
try
% check if there is a parametric modulator. this allows
% pmod structures with fewer entries than conditions.
% then check whether any cells are filled in.
if (j <= numel(multicond.pmod)) && ...
~isempty(multicond.pmod(j).name)
% we assume that the number of cells in each
% field of pmod is the same (or should be).
for ii = 1:numel(multicond.pmod(j).name)
cond.pmod(ii).name = multicond.pmod(j).name{ii};
cond.pmod(ii).param = multicond.pmod(j).param{ii};
cond.pmod(ii).poly = multicond.pmod(j).poly{ii};
end
end;
catch
error('Error specifying parametric modulation.');
end
end
sess.cond(end+1) = cond;
end
end
% Configure the input structure array
%-------------------------------------------------------------
for j = 1:length(sess.cond),
cond = sess.cond(j);
U(j).name = {cond.name};
U(j).ons = cond.onset(:);
U(j).dur = cond.duration(:);
if length(U(j).dur) == 1
U(j).dur = U(j).dur*ones(size(U(j).ons));
elseif length(U(j).dur) ~= length(U(j).ons)
error('Mismatch between number of onset and number of durations.')
end
P = [];
q1 = 0;
if cond.tmod>0,
% time effects
P(1).name = 'time';
P(1).P = U(j).ons*job.timing.RT/60;
P(1).h = cond.tmod;
q1 = 1;
end;
if ~isempty(cond.pmod)
for q = 1:numel(cond.pmod),
% Parametric effects
q1 = q1 + 1;
P(q1).name = cond.pmod(q).name;
P(q1).P = cond.pmod(q).param(:);
P(q1).h = cond.pmod(q).poly;
end;
end
if isempty(P)
P.name = 'none';
P.h = 0;
end
U(j).P = P;
end
SPM.Sess(i).U = U;
% User specified regressors
%-------------------------------------------------------------
C = [];
Cname = cell(1,numel(sess.regress));
for q = 1:numel(sess.regress),
Cname{q} = sess.regress(q).name;
C = [C, sess.regress(q).val(:)];
end
% Augment the singly-specified regressors with the multiple regressors
% specified in the regressors.mat file
%------------------------------------------------------------
if ~strcmp(sess.multi_reg,'')
tmp=load(char(sess.multi_reg{:}));
if isstruct(tmp) && isfield(tmp,'R')
R = tmp.R;
elseif isnumeric(tmp)
% load from e.g. text file
R = tmp;
else
warning('Can''t load user specified regressors in %s', ...
char(sess.multi_reg{:}));
R = [];
end
C=[C, R];
nr=size(R,2);
nq=length(Cname);
for inr=1:nr,
Cname{inr+nq}=['R',int2str(inr)];
end
end
SPM.Sess(i).C.C = C;
SPM.Sess(i).C.name = Cname;
end
% Factorial design
%-------------------------------------------------------------
if isfield(job,'fact')
if ~isempty(job.fact)
NC=length(SPM.Sess(1).U); % Number of conditions
CheckNC=1;
for i=1:length(job.fact)
SPM.factor(i).name=job.fact(i).name;
SPM.factor(i).levels=job.fact(i).levels;
CheckNC=CheckNC*SPM.factor(i).levels;
end
if ~(CheckNC==NC)
disp('Error in fmri_spec job: factors do not match conditions');
return
end
end
else
SPM.factor=[];
end
% Globals
%-------------------------------------------------------------
SPM.xGX.iGXcalc = job.global;
SPM.xGX.sGXcalc = 'mean voxel value';
SPM.xGX.sGMsca = 'session specific';
% High Pass filter
%-------------------------------------------------------------
for i = 1:numel(job.sess),
SPM.xX.K(i).HParam = job.sess(i).hpf;
end
% Autocorrelation
%-------------------------------------------------------------
SPM.xVi.form = job.cvi;
% Let SPM configure the design
%-------------------------------------------------------------
SPM = spm_fMRI_design(SPM);
%-Save SPM.mat
%-------------------------------------------------------------------------
fprintf('%-40s: ','Saving SPM configuration') %-#
if spm_check_version('matlab','7') >= 0
save('SPM.mat','-V6','SPM');
else
save('SPM.mat','SPM');
end
fprintf('%30s\n','...SPM.mat saved') %-#
out.spmmat{1} = fullfile(pwd, 'SPM.mat');
my_cd(original_dir); % Change back dir
spm_get_defaults('stats.fmri.fmri_t',olddefs.stats.fmri.fmri_t); % Restore old timing
spm_get_defaults('stats.fmri.fmri_t0',olddefs.stats.fmri.fmri_t0); % parameters
fprintf('Done\n')
return
%-------------------------------------------------------------------------
%-------------------------------------------------------------------------
function my_cd(varargin)
% jobDir must be the actual directory to change to, NOT the job structure.
jobDir = varargin{1};
if ~isempty(jobDir)
try
cd(char(jobDir));
fprintf('Changing directory to: %s\n',char(jobDir));
catch
error('Failed to change directory. Aborting run.')
end
end
return;
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_eeg_grandmean.m
|
.m
|
antx-master/xspm8/config/spm_cfg_eeg_grandmean.m
| 2,570 |
utf_8
|
41cefba7c2387be2142bfcd23931e054
|
function S = spm_cfg_eeg_grandmean
% configuration file for averaging evoked responses
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Stefan Kiebel
% $Id: spm_cfg_eeg_grandmean.m 3881 2010-05-07 21:02:57Z vladimir $
% -------------------------------------------------------------------------
% weighted Weighted average
% -------------------------------------------------------------------------
weighted = cfg_menu;
weighted.tag = 'weighted';
weighted.name = 'Weighted average?';
weighted.help = {'Average weighted by number of replications in input.'};
weighted.labels = {'Yes' 'No'};
weighted.values = {1 0};
%--------------------------------------------------------------------------
% D File Names
%--------------------------------------------------------------------------
D = cfg_files;
D.tag = 'D';
D.name = 'File Names';
D.filter = 'mat';
D.num = [1 inf];
D.help = {'Select the M/EEG mat file.'};
%--------------------------------------------------------------------------
% Dout Output filename
%--------------------------------------------------------------------------
Dout = cfg_entry;
Dout.tag = 'Dout';
Dout.name = 'Output filename';
Dout.strtype = 's';
Dout.num = [1 inf];
Dout.help = {'Choose filename'};
%--------------------------------------------------------------------------
% S Grandmean
%--------------------------------------------------------------------------
S = cfg_exbranch;
S.tag = 'grandmean';
S.name = 'M/EEG Grandmean';
S.val = {D Dout weighted};
S.help = {'Average multiple evoked responses'};
S.prog = @eeg_grandmean;
S.vout = @vout_eeg_grandmean;
S.modality = {'EEG'};
%==========================================================================
function out = eeg_grandmean(job)
% construct the S struct
S.D = strvcat(job.D);
S.Dout = job.Dout;
S.weighted = job.weighted;
out.D = spm_eeg_grandmean(S);
out.Dfname = {fullfile(out.D.path, out.D.fname)};
%==========================================================================
function dep = vout_eeg_grandmean(job)
dep(1) = cfg_dep;
dep(1).sname = 'Grandmean Data';
dep(1).src_output = substruct('.','D');
dep(1).tgt_spec = cfg_findspec({{'strtype','e'}});
dep(2) = cfg_dep;
dep(2).sname = 'Grandmean Datafile';
dep(2).src_output = substruct('.','Dfname');
dep(2).tgt_spec = cfg_findspec({{'filter','mat'}});
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_dicom.m
|
.m
|
antx-master/xspm8/config/spm_cfg_dicom.m
| 5,587 |
utf_8
|
bf4d49bb102e084fbe7722b3589b8ea9
|
function dicom = spm_cfg_dicom
% SPM Configuration file for DICOM Import
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% $Id: spm_cfg_dicom.m 4012 2010-07-22 12:45:53Z volkmar $
% ---------------------------------------------------------------------
% data DICOM files
% ---------------------------------------------------------------------
data = cfg_files;
data.tag = 'data';
data.name = 'DICOM files';
data.help = {'Select the DICOM files to convert.'};
data.filter = 'any';
data.ufilter = '.*';
data.num = [1 Inf];
% ---------------------------------------------------------------------
% 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:'
''
'* 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.'};
outdir.filter = 'dir';
outdir.ufilter = '.*';
outdir.num = [1 1];
% ---------------------------------------------------------------------
% 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 = {0 1};
icedims.val = {0};
% ---------------------------------------------------------------------
% 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 = 'dicom';
dicom.name = 'DICOM Import';
dicom.val = {data root outdir 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 = @spm_run_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'}});
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_mfx.m
|
.m
|
antx-master/xspm8/config/spm_cfg_mfx.m
| 7,440 |
utf_8
|
a686fb62a68adf0ecfec1bc72c9e10de
|
function mfx = spm_cfg_mfx
% SPM Configuration file for MFX
%______________________________________________________________________
% Copyright (C) 2010 Wellcome Trust Centre for Neuroimaging
% Guillaume Flandin
% $Id: spm_cfg_mfx.m 4023 2010-07-28 18:41:36Z guillaume $
% ---------------------------------------------------------------------
% dir Directory
% ---------------------------------------------------------------------
dir = cfg_files;
dir.tag = 'dir';
dir.name = 'Directory';
dir.help = {'Select a directory where the SPM.mat file containing the specified design matrix will be written.'};
dir.filter = 'dir';
dir.ufilter = '.*';
dir.num = [1 1];
% ---------------------------------------------------------------------
% spmmat Select SPM.mat
% ---------------------------------------------------------------------
spmmat = cfg_files;
spmmat.tag = 'spmmat';
spmmat.name = 'Select SPM.mat files';
spmmat.help = {...
'Select the SPM.mat files that contains first-level designs.'
'They must have the same number of parameters for each session.'
['These are assumed to represent session-specific realisations of ' ...
'2nd-level effects.']};
spmmat.filter = 'mat';
spmmat.ufilter = '^SPM\.mat$';
spmmat.num = [1 Inf];
% ---------------------------------------------------------------------
% ffx Create first-level design
% ---------------------------------------------------------------------
ffx = cfg_exbranch;
ffx.tag = 'ffx';
ffx.name = 'Create repeated-measure design';
ffx.val = {dir spmmat};
ffx.help = {'Create repeated-measure multi-session first-level design'};
ffx.prog = @spm_local_ffx;
ffx.vout = @vout_ffx;
% ---------------------------------------------------------------------
% spmmat Select SPM.mat
% ---------------------------------------------------------------------
spmmat = cfg_files;
spmmat.tag = 'spmmat';
spmmat.name = 'Select SPM.mat';
spmmat.help = {...
'Design and estimation structure after a 1st-level analysis'};
spmmat.filter = 'mat';
spmmat.ufilter = '^SPM\.mat$';
spmmat.num = [1 1];
% ---------------------------------------------------------------------
% spec MFX Specification
% ---------------------------------------------------------------------
spec = cfg_exbranch;
spec.tag = 'spec';
spec.name = 'MFX Specification';
spec.val = {spmmat};
spec.help = {'MFX Specification'};
spec.prog = @spm_local_mfx;
spec.vout = @vout_mfx;
% ---------------------------------------------------------------------
% mfx Mixed-effects (MFX) analysis
% ---------------------------------------------------------------------
mfx = cfg_choice;
mfx.tag = 'mfx';
mfx.name = 'Mixed-effects (MFX) analysis';
mfx.help = {'Mixed-effects (MFX) analysis'};
mfx.values = {ffx spec};
% =====================================================================
function out = spm_local_ffx(job)
spmmat = job.spmmat;
SPMS = cell(size(spmmat));
for i=1:numel(spmmat)
load(spmmat{i},'SPM');
SPMS{i} = SPM;
end
matlabbatch{1}.spm.stats.fmri_spec.dir = cellstr(job.dir);
matlabbatch{1}.spm.stats.fmri_spec.timing.units = SPMS{1}.xBF.UNITS;
matlabbatch{1}.spm.stats.fmri_spec.timing.RT = SPMS{1}.xY.RT;
matlabbatch{1}.spm.stats.fmri_spec.timing.fmri_t = SPMS{1}.xBF.T;
matlabbatch{1}.spm.stats.fmri_spec.timing.fmri_t0 = SPMS{1}.xBF.T0;
switch SPMS{1}.xBF.name
case 'hrf'
matlabbatch{1}.spm.stats.fmri_spec.hrf.derivs = [0 0];
case 'hrf (with time derivative)'
matlabbatch{1}.spm.stats.fmri_spec.hrf.derivs = [1 0];
case 'hrf (with time and dispersion derivatives)'
matlabbatch{1}.spm.stats.fmri_spec.hrf.derivs = [1 1];
case 'Fourier set'
matlabbatch{1}.spm.stats.fmri_spec.bases.fourier.length = SPMS{1}.xBF.length;
matlabbatch{1}.spm.stats.fmri_spec.bases.fourier.order = SPMS{1}.xBF.order;
case 'Fourier set (Hanning)'
matlabbatch{1}.spm.stats.fmri_spec.bases.fourier_han.length = SPMS{1}.xBF.length;
matlabbatch{1}.spm.stats.fmri_spec.bases.fourier_han.order = SPMS{1}.xBF.order;
case 'Gamma functions'
matlabbatch{1}.spm.stats.fmri_spec.bases.gamma.length = SPMS{1}.xBF.length;
matlabbatch{1}.spm.stats.fmri_spec.bases.gamma.order = SPMS{1}.xBF.order;
case 'Finite Impulse Response'
matlabbatch{1}.spm.stats.fmri_spec.bases.fir.length = SPMS{1}.xBF.length;
matlabbatch{1}.spm.stats.fmri_spec.bases.fir.order = SPMS{1}.xBF.order;
end
matlabbatch{1}.spm.stats.fmri_spec.volt = SPMS{1}.xBF.Volterra;
matlabbatch{1}.spm.stats.fmri_spec.global = SPMS{1}.xGX.iGXcalc;
if ~isempty(SPMS{1}.xM.VM)
matlabbatch{1}.spm.stats.fmri_spec.mask = cellstr(SPMS{1}.xM.VM.fname); % can be intersection
end
if strncmp('AR',SPMS{1}.xVi.form,2)
matlabbatch{1}.spm.stats.fmri_spec.cvi = 'AR(1)';
else
matlabbatch{1}.spm.stats.fmri_spec.cvi = 'none';
end
k = 1;
for i=1:numel(SPMS)
n = cumsum([1 SPMS{i}.nscan]);
for j=1:numel(SPMS{i}.Sess)
matlabbatch{1}.spm.stats.fmri_spec.sess(k).scans = cellstr(SPMS{i}.xY.P(n(j):n(j+1)-1,:));
for l=1:numel(SPMS{i}.Sess(j).U)
matlabbatch{1}.spm.stats.fmri_spec.sess(k).cond(l).name = SPMS{i}.Sess(j).U(l).name{1};
matlabbatch{1}.spm.stats.fmri_spec.sess(k).cond(l).onset = SPMS{i}.Sess(j).U(l).ons;
matlabbatch{1}.spm.stats.fmri_spec.sess(k).cond(l).duration = SPMS{i}.Sess(j).U(l).dur;
o = 1;
for m=1:numel(SPMS{i}.Sess(j).U(l).P)
switch SPMS{i}.Sess(j).U(l).P(m).name
case 'time'
matlabbatch{1}.spm.stats.fmri_spec.sess(k).cond(l).tmod = SPMS{i}.Sess(j).U(l).P(m).h;
case 'none'
otherwise
matlabbatch{1}.spm.stats.fmri_spec.sess(k).cond(l).pmod(o).name = SPMS{i}.Sess(j).U(l).P(m).name;
matlabbatch{1}.spm.stats.fmri_spec.sess(k).cond(l).pmod(o).param = SPMS{i}.Sess(j).U(l).P(m).P;
matlabbatch{1}.spm.stats.fmri_spec.sess(k).cond(l).pmod(o).poly = SPMS{i}.Sess(j).U(l).P(m).h;
o = o + 1;
end
end
end
for l=1:numel(SPMS{i}.Sess(j).C.name)
matlabbatch{1}.spm.stats.fmri_spec.sess(k).regress(l).name = SPMS{i}.Sess(j).C.name{l};
matlabbatch{1}.spm.stats.fmri_spec.sess(k).regress(l).val = SPMS{i}.Sess(j).C.C(:,l);
end
matlabbatch{1}.spm.stats.fmri_spec.sess(k).hpf = SPMS{i}.xX.K(j).HParam;
k = k + 1;
end
end
spm_jobman('run',matlabbatch);
out.spmmat{1} = fullfile(job.dir{1},'SPM.mat');
% =====================================================================
function dep = vout_ffx(job)
dep = cfg_dep;
dep.sname = 'SPM.mat File';
dep.src_output = substruct('.','spmmat');
dep.tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}});
% =====================================================================
function out = spm_local_mfx(job)
load(job.spmmat{1},'SPM');
spm_mfx(SPM);
out.spmmat{1} = fullfile(fileparts(job.spmmat{1}),'mfx','SPM.mat');
% =====================================================================
function dep = vout_mfx(job)
dep = cfg_dep;
dep.sname = 'SPM.mat File';
dep.src_output = substruct('.','spmmat');
dep.tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}});
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_factorial_design.m
|
.m
|
antx-master/xspm8/config/spm_cfg_factorial_design.m
| 50,375 |
utf_8
|
ecbb87ccd5528ba75b6b9a85758a9c3b
|
function factorial_design = spm_cfg_factorial_design
% SPM Configuration file for 2nd-level models
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Will Penny
% $Id: spm_cfg_factorial_design.m 3900 2010-05-25 16:17:13Z guillaume $
% ---------------------------------------------------------------------
% dir Directory
% ---------------------------------------------------------------------
dir = cfg_files;
dir.tag = 'dir';
dir.name = 'Directory';
dir.help = {'Select a directory where the SPM.mat file containing the specified design matrix will be written.'};
dir.filter = 'dir';
dir.ufilter = '.*';
dir.num = [1 1];
% ---------------------------------------------------------------------
% scans Scans
% ---------------------------------------------------------------------
scans = cfg_files;
scans.tag = 'scans';
scans.name = 'Scans';
scans.help = {'Select the images. They must all have the same image dimensions, orientation, voxel size etc.'};
scans.filter = 'image';
scans.ufilter = '.*';
scans.num = [1 Inf];
% ---------------------------------------------------------------------
% t1 One-sample t-test
% ---------------------------------------------------------------------
t1 = cfg_branch;
t1.tag = 't1';
t1.name = 'One-sample t-test';
t1.val = {scans };
t1.help = {''};
% ---------------------------------------------------------------------
% scans1 Group 1 scans
% ---------------------------------------------------------------------
scans1 = cfg_files;
scans1.tag = 'scans1';
scans1.name = 'Group 1 scans';
scans1.help = {'Select the images from sample 1. They must all have the same image dimensions, orientation, voxel size etc.'};
scans1.filter = 'image';
scans1.ufilter = '.*';
scans1.num = [1 Inf];
% ---------------------------------------------------------------------
% scans2 Group 2 scans
% ---------------------------------------------------------------------
scans2 = cfg_files;
scans2.tag = 'scans2';
scans2.name = 'Group 2 scans';
scans2.help = {'Select the images from sample 2. They must all have the same image dimensions, orientation, voxel size etc.'};
scans2.filter = 'image';
scans2.ufilter = '.*';
scans2.num = [1 Inf];
% ---------------------------------------------------------------------
% dept Independence
% ---------------------------------------------------------------------
dept = cfg_menu;
dept.tag = 'dept';
dept.name = 'Independence';
dept.help = {
'By default, the measurements are assumed to be independent between levels. '
''
'If you change this option to allow for dependencies, this will violate the assumption of sphericity. It would therefore be an example of non-sphericity. One such example would be where you had repeated measurements from the same subjects - it may then be the case that, over subjects, measure 1 is correlated to measure 2. '
''
'Restricted Maximum Likelihood (REML): The ensuing covariance components will be estimated using ReML in spm_spm (assuming the same for all responsive voxels) and used to adjust the statistics and degrees of freedom during inference. By default spm_spm will use weighted least squares to produce Gauss-Markov or Maximum likelihood estimators using the non-sphericity structure specified at this stage. The components will be found in SPM.xVi and enter the estimation procedure exactly as the serial correlations in fMRI models.'
''
}';
dept.labels = {
'Yes'
'No'
}';
dept.values = {0 1};
dept.val = {0};
% ---------------------------------------------------------------------
% deptn Independence (default is 'No')
% ---------------------------------------------------------------------
deptn = cfg_menu;
deptn.tag = 'dept';
deptn.name = 'Independence';
deptn.help = {
'By default, the measurements are assumed to be dependent between levels. '
''
'If you change this option to allow for dependencies, this will violate the assumption of sphericity. It would therefore be an example of non-sphericity. One such example would be where you had repeated measurements from the same subjects - it may then be the case that, over subjects, measure 1 is correlated to measure 2. '
''
'Restricted Maximum Likelihood (REML): The ensuing covariance components will be estimated using ReML in spm_spm (assuming the same for all responsive voxels) and used to adjust the statistics and degrees of freedom during inference. By default spm_spm will use weighted least squares to produce Gauss-Markov or Maximum likelihood estimators using the non-sphericity structure specified at this stage. The components will be found in SPM.xVi and enter the estimation procedure exactly as the serial correlations in fMRI models.'
''
}';
deptn.labels = {
'Yes'
'No'
}';
deptn.values = {0 1};
deptn.val = {1};
% ---------------------------------------------------------------------
% variance Variance
% ---------------------------------------------------------------------
variance = cfg_menu;
variance.tag = 'variance';
variance.name = 'Variance';
variance.help = {
'By default, the measurements in each level are assumed to have unequal variance. '
''
'This violates the assumption of ''sphericity'' and is therefore an example of ''non-sphericity''.'
''
'This can occur, for example, in a 2nd-level analysis of variance, one contrast may be scaled differently from another. Another example would be the comparison of qualitatively different dependent variables (e.g. normals vs. patients). Different variances (heteroscedasticy) induce different error covariance components that are estimated using restricted maximum likelihood (see below).'
''
'Restricted Maximum Likelihood (REML): The ensuing covariance components will be estimated using ReML in spm_spm (assuming the same for all responsive voxels) and used to adjust the statistics and degrees of freedom during inference. By default spm_spm will use weighted least squares to produce Gauss-Markov or Maximum likelihood estimators using the non-sphericity structure specified at this stage. The components will be found in SPM.xVi and enter the estimation procedure exactly as the serial correlations in fMRI models.'
''
}';
variance.labels = {
'Equal'
'Unequal'
}';
variance.values = {0 1};
variance.val = {1};
% ---------------------------------------------------------------------
% gmsca Grand mean scaling
% ---------------------------------------------------------------------
gmsca = cfg_menu;
gmsca.tag = 'gmsca';
gmsca.name = 'Grand mean scaling';
gmsca.help = {
'This option is only used for PET data.'
''
'Selecting YES will specify ''grand mean scaling by factor'' which could be eg. ''grand mean scaling by subject'' if the factor is ''subject''. '
''
'Since differences between subjects may be due to gain and sensitivity effects, AnCova by subject could be combined with "grand mean scaling by subject" to obtain a combination of between subject proportional scaling and within subject AnCova. '
''
}';
gmsca.labels = {
'No'
'Yes'
}';
gmsca.values = {0 1};
gmsca.val = {0};
% ---------------------------------------------------------------------
% ancova ANCOVA
% ---------------------------------------------------------------------
ancova = cfg_menu;
ancova.tag = 'ancova';
ancova.name = 'ANCOVA';
ancova.help = {
'This option is only used for PET data.'
''
'Selecting YES will specify ''ANCOVA-by-factor'' regressors. This includes eg. ''Ancova by subject'' or ''Ancova by effect''. These options allow eg. different subjects to have different relationships between local and global measurements. '
''
}';
ancova.labels = {
'No'
'Yes'
}';
ancova.values = {0 1};
ancova.val = {0};
% ---------------------------------------------------------------------
% t2 Two-sample t-test
% ---------------------------------------------------------------------
t2 = cfg_branch;
t2.tag = 't2';
t2.name = 'Two-sample t-test';
t2.val = {scans1 scans2 dept variance gmsca ancova };
t2.help = {''};
% ---------------------------------------------------------------------
% scans Scans [1,2]
% ---------------------------------------------------------------------
scans = cfg_files;
scans.tag = 'scans';
scans.name = 'Scans [1,2]';
scans.help = {'Select the pair of images. '};
scans.filter = 'image';
scans.ufilter = '.*';
scans.num = [2 2];
% ---------------------------------------------------------------------
% pair Pair
% ---------------------------------------------------------------------
pair = cfg_branch;
pair.tag = 'pair';
pair.name = 'Pair';
pair.val = {scans };
pair.help = {'Add a new pair of scans to your experimental design'};
% ---------------------------------------------------------------------
% generic Pairs
% ---------------------------------------------------------------------
generic = cfg_repeat;
generic.tag = 'generic';
generic.name = 'Pairs';
generic.help = {''};
generic.values = {pair};
generic.num = [1 Inf];
% ---------------------------------------------------------------------
% pt Paired t-test
% ---------------------------------------------------------------------
pt = cfg_branch;
pt.tag = 'pt';
pt.name = 'Paired t-test';
pt.val = {generic gmsca ancova};
pt.help = {''};
% ---------------------------------------------------------------------
% scans Scans
% ---------------------------------------------------------------------
scans = cfg_files;
scans.tag = 'scans';
scans.name = 'Scans';
scans.help = {'Select the images. They must all have the same image dimensions, orientation, voxel size etc.'};
scans.filter = 'image';
scans.ufilter = '.*';
scans.num = [1 Inf];
% ---------------------------------------------------------------------
% c Vector
% ---------------------------------------------------------------------
c = cfg_entry;
c.tag = 'c';
c.name = 'Vector';
c.help = {'Vector of covariate values'};
c.strtype = 'e';
c.num = [Inf 1];
% ---------------------------------------------------------------------
% cname Name
% ---------------------------------------------------------------------
cname = cfg_entry;
cname.tag = 'cname';
cname.name = 'Name';
cname.help = {'Name of covariate'};
cname.strtype = 's';
cname.num = [1 Inf];
% ---------------------------------------------------------------------
% iCC Centering
% ---------------------------------------------------------------------
iCC = cfg_menu;
iCC.tag = 'iCC';
iCC.name = 'Centering';
iCC.help = {''};
iCC.labels = {
'Overall mean'
'No centering'
}';
iCC.values = {1 5};
iCC.val = {1};
% ---------------------------------------------------------------------
% mcov Covariate
% ---------------------------------------------------------------------
mcov = cfg_branch;
mcov.tag = 'mcov';
mcov.name = 'Covariate';
mcov.val = {c cname iCC };
mcov.help = {'Add a new covariate to your experimental design'};
% ---------------------------------------------------------------------
% generic Covariates
% ---------------------------------------------------------------------
generic = cfg_repeat;
generic.tag = 'generic';
generic.name = 'Covariates';
generic.help = {'Covariates'};
generic.values = {mcov };
generic.num = [0 Inf];
% ---------------------------------------------------------------------
% incint Intercept
% ---------------------------------------------------------------------
incint = cfg_menu;
incint.tag = 'incint';
incint.name = 'Intercept';
incint.help = {['By default, an intercept is always added to the model. If the ',...
'covariates supplied by the user include a constant effect, the ',...
'intercept may be omitted.']};
incint.labels = {'Include Intercept','Omit Intercept'};
incint.values = {1,0};
incint.val = {1};
% ---------------------------------------------------------------------
% mreg Multiple regression
% ---------------------------------------------------------------------
mreg = cfg_branch;
mreg.tag = 'mreg';
mreg.name = 'Multiple regression';
mreg.val = {scans generic incint};
mreg.help = {''};
% ---------------------------------------------------------------------
% name Name
% ---------------------------------------------------------------------
name = cfg_entry;
name.tag = 'name';
name.name = 'Name';
name.help = {'Name of factor, eg. ''Repetition'' '};
name.strtype = 's';
name.num = [1 Inf];
% ---------------------------------------------------------------------
% levels Levels
% ---------------------------------------------------------------------
levels = cfg_entry;
levels.tag = 'levels';
levels.name = 'Levels';
levels.help = {'Enter number of levels for this factor, eg. 2'};
levels.strtype = 'e';
levels.num = [Inf 1];
% ---------------------------------------------------------------------
% fact Factor
% ---------------------------------------------------------------------
fact = cfg_branch;
fact.tag = 'fact';
fact.name = 'Factor';
fact.val = {name levels dept variance gmsca ancova };
fact.help = {'Add a new factor to your experimental design'};
% ---------------------------------------------------------------------
% generic Factors
% ---------------------------------------------------------------------
generic = cfg_repeat;
generic.tag = 'generic';
generic.name = 'Factors';
generic.help = {
'Specify your design a factor at a time. '
''
}';
generic.values = {fact };
generic.num = [1 Inf];
% ---------------------------------------------------------------------
% levels Levels
% ---------------------------------------------------------------------
levels = cfg_entry;
levels.tag = 'levels';
levels.name = 'Levels';
levels.help = {
'Enter a vector or scalar that specifies which cell in the factorial design these images belong to. The length of this vector should correspond to the number of factors in the design'
''
'For example, length 2 vectors should be used for two-factor designs eg. the vector [2 3] specifies the cell corresponding to the 2nd-level of the first factor and the 3rd level of the 2nd factor.'
''
}';
levels.strtype = 'e';
levels.num = [Inf 1];
% ---------------------------------------------------------------------
% scans Scans
% ---------------------------------------------------------------------
scans = cfg_files;
scans.tag = 'scans';
scans.name = 'Scans';
scans.help = {'Select the images for this cell. They must all have the same image dimensions, orientation, voxel size etc.'};
scans.filter = 'image';
scans.ufilter = '.*';
scans.num = [1 Inf];
% ---------------------------------------------------------------------
% icell Cell
% ---------------------------------------------------------------------
icell = cfg_branch;
icell.tag = 'icell';
icell.name = 'Cell';
icell.val = {levels scans };
icell.help = {'Enter data for a cell in your design'};
% ---------------------------------------------------------------------
% scell Cell
% ---------------------------------------------------------------------
scell = cfg_branch;
scell.tag = 'icell';
scell.name = 'Cell';
scell.val = {scans };
scell.help = {'Enter data for a cell in your design'};
% ---------------------------------------------------------------------
% generic Specify cells
% ---------------------------------------------------------------------
generic1 = cfg_repeat;
generic1.tag = 'generic';
generic1.name = 'Specify cells';
generic1.help = {
'Enter the scans a cell at a time'
''
}';
generic1.values = {icell };
generic1.num = [1 Inf];
% ---------------------------------------------------------------------
% generic Specify cells
% ---------------------------------------------------------------------
generic2 = cfg_repeat;
generic2.tag = 'generic';
generic2.name = 'Specify cells';
generic2.help = {
'Enter the scans a cell at a time'
''
}';
generic2.values = {scell };
generic2.num = [1 Inf];
% ---------------------------------------------------------------------
% anova ANOVA
% ---------------------------------------------------------------------
anova = cfg_branch;
anova.tag = 'anova';
anova.name = 'One-way ANOVA';
anova.val = {generic2 dept variance gmsca ancova};
anova.help = {
'One-way Analysis of Variance (ANOVA)'
}';
% ---------------------------------------------------------------------
% fd Full factorial
% ---------------------------------------------------------------------
fd = cfg_branch;
fd.tag = 'fd';
fd.name = 'Full factorial';
fd.val = {generic generic1 };
fd.help = {
'This option is best used when you wish to test for all main effects and interactions in one-way, two-way or three-way ANOVAs. Design specification proceeds in 2 stages. Firstly, by creating new factors and specifying the number of levels and name for each. Nonsphericity, ANOVA-by-factor and scaling options can also be specified at this stage. Secondly, scans are assigned separately to each cell. This accomodates unbalanced designs.'
''
'For example, if you wish to test for a main effect in the population from which your subjects are drawn and have modelled that effect at the first level using K basis functions (eg. K=3 informed basis functions) you can use a one-way ANOVA with K-levels. Create a single factor with K levels and then assign the data to each cell eg. canonical, temporal derivative and dispersion derivative cells, where each cell is assigned scans from multiple subjects.'
''
'SPM will also automatically generate the contrasts necessary to test for all main effects and interactions. '
''
}';
% ---------------------------------------------------------------------
% name Name
% ---------------------------------------------------------------------
name = cfg_entry;
name.tag = 'name';
name.name = 'Name';
name.help = {'Name of factor, eg. ''Repetition'' '};
name.strtype = 's';
name.num = [1 Inf];
% ---------------------------------------------------------------------
% fac Factor
% ---------------------------------------------------------------------
fac = cfg_branch;
fac.tag = 'fac';
fac.name = 'Factor';
fac.val = {name dept variance gmsca ancova };
fac.help = {
'Add a new factor to your design.'
''
'If you are using the ''Subjects'' option to specify your scans and conditions, you may wish to make use of the following facility. There are two reserved words for the names of factors. These are ''subject'' and ''repl'' (standing for replication). If you use these factor names then SPM can automatically create replication and/or subject factors without you having to type in an extra entry in the condition vector.'
''
'For example, if you wish to model Subject and Task effects (two factors), under Subjects->Subject->Conditions you can type in simply [1 2 1 2] to specify eg. just the ''Task'' factor level. You do not need to eg. for the 4th subject enter the matrix [1 4; 2 4; 1 4; 2 4]. '
''
}';
% ---------------------------------------------------------------------
% generic Factors
% ---------------------------------------------------------------------
generic = cfg_repeat;
generic.tag = 'generic';
generic.name = 'Factors';
generic.help = {
'Specify your design a factor at a time.'
''
}';
generic.values = {fac };
generic.num = [1 Inf];
% ---------------------------------------------------------------------
% scans Scans
% ---------------------------------------------------------------------
scans = cfg_files;
scans.tag = 'scans';
scans.name = 'Scans';
scans.help = {'Select the images to be analysed. They must all have the same image dimensions, orientation, voxel size etc.'};
scans.filter = 'image';
scans.ufilter = '.*';
scans.num = [1 Inf];
% ---------------------------------------------------------------------
% conds Conditions
% ---------------------------------------------------------------------
conds = cfg_entry;
conds.tag = 'conds';
conds.name = 'Conditions';
conds.help = {''};
conds.strtype = 'e';
conds.num = [Inf Inf];
% ---------------------------------------------------------------------
% fsubject Subject
% ---------------------------------------------------------------------
fsubject = cfg_branch;
fsubject.tag = 'fsubject';
fsubject.name = 'Subject';
fsubject.val = {scans conds };
fsubject.help = {'Enter data and conditions for a new subject'};
% ---------------------------------------------------------------------
% generic Subjects
% ---------------------------------------------------------------------
generic1 = cfg_repeat;
generic1.tag = 'generic';
generic1.name = 'Subjects';
generic1.help = {''};
generic1.values = {fsubject };
generic1.num = [1 Inf];
% ---------------------------------------------------------------------
% scans Scans
% ---------------------------------------------------------------------
scans = cfg_files;
scans.tag = 'scans';
scans.name = 'Scans';
scans.help = {'Select the images to be analysed. They must all have the same image dimensions, orientation, voxel size etc.'};
scans.filter = 'image';
scans.ufilter = '.*';
scans.num = [1 Inf];
% ---------------------------------------------------------------------
% imatrix Factor matrix
% ---------------------------------------------------------------------
imatrix = cfg_entry;
imatrix.tag = 'imatrix';
imatrix.name = 'Factor matrix';
imatrix.help = {'Specify factor/level matrix as a nscan-by-4 matrix. Note that the first column of I is reserved for the internal replication factor and must not be used for experimental factors.'};
imatrix.strtype = 'e';
imatrix.num = [Inf Inf];
% ---------------------------------------------------------------------
% specall Specify all
% ---------------------------------------------------------------------
specall = cfg_branch;
specall.tag = 'specall';
specall.name = 'Specify all';
specall.val = {scans imatrix };
specall.help = {
'Specify (i) all scans in one go and (ii) all conditions using a factor matrix, I. This option is for ''power users''. The matrix I must have four columns and as as many rows as scans. It has the same format as SPM''s internal variable SPM.xX.I. '
''
'The first column of I denotes the replication number and entries in the other columns denote the levels of each experimental factor.'
''
'So, for eg. a two-factor design the first column denotes the replication number and columns two and three have entries like 2 3 denoting the 2nd level of the first factor and 3rd level of the second factor. The 4th column in I would contain all 1s.'
}';
% ---------------------------------------------------------------------
% fsuball Specify Subjects or all Scans & Factors
% ---------------------------------------------------------------------
fsuball = cfg_choice;
fsuball.tag = 'fsuball';
fsuball.name = 'Specify Subjects or all Scans & Factors';
fsuball.val = {generic1 };
fsuball.help = {''};
fsuball.values = {generic1 specall };
% ---------------------------------------------------------------------
% fnum Factor number
% ---------------------------------------------------------------------
fnum = cfg_entry;
fnum.tag = 'fnum';
fnum.name = 'Factor number';
fnum.help = {'Enter the number of the factor.'};
fnum.strtype = 'e';
fnum.num = [1 1];
% ---------------------------------------------------------------------
% fmain Main effect
% ---------------------------------------------------------------------
fmain = cfg_branch;
fmain.tag = 'fmain';
fmain.name = 'Main effect';
fmain.val = {fnum };
fmain.help = {'Add a main effect to your design matrix'};
% ---------------------------------------------------------------------
% fnums Factor numbers
% ---------------------------------------------------------------------
fnums = cfg_entry;
fnums.tag = 'fnums';
fnums.name = 'Factor numbers';
fnums.help = {'Enter the numbers of the factors of this (two-way) interaction.'};
fnums.strtype = 'e';
fnums.num = [2 1];
% ---------------------------------------------------------------------
% inter Interaction
% ---------------------------------------------------------------------
inter = cfg_branch;
inter.tag = 'inter';
inter.name = 'Interaction';
inter.val = {fnums };
inter.help = {'Add an interaction to your design matrix'};
% ---------------------------------------------------------------------
% maininters Main effects & Interactions
% ---------------------------------------------------------------------
maininters = cfg_repeat;
maininters.tag = 'maininters';
maininters.name = 'Main effects & Interactions';
maininters.help = {''};
maininters.values = {fmain inter };
maininters.num = [1 Inf];
% ---------------------------------------------------------------------
% anovaw ANOVA within subject
% ---------------------------------------------------------------------
anovaw = cfg_branch;
anovaw.tag = 'anovaw';
anovaw.name = 'One-way ANOVA - within subject';
anovaw.val = {generic1 deptn variance gmsca ancova};
anovaw.help = {
'One-way Analysis of Variance (ANOVA) - within subject'
}';
% ---------------------------------------------------------------------
% fblock Flexible factorial
% ---------------------------------------------------------------------
fblock = cfg_branch;
fblock.tag = 'fblock';
fblock.name = 'Flexible factorial';
fblock.val = {generic fsuball maininters };
fblock.help = {
'Create a design matrix a block at a time by specifying which main effects and interactions you wish to be included.'
''
'This option is best used for one-way, two-way or three-way ANOVAs but where you do not wish to test for all possible main effects and interactions. This is perhaps most useful for PET where there is usually not enough data to test for all possible effects. Or for 3-way ANOVAs where you do not wish to test for all of the two-way interactions. A typical example here would be a group-by-drug-by-task analysis where, perhaps, only (i) group-by-drug or (ii) group-by-task interactions are of interest. In this case it is only necessary to have two-blocks in the design matrix - one for each interaction. The three-way interaction can then be tested for using a contrast that computes the difference between (i) and (ii).'
''
'Design specification then proceeds in 3 stages. Firstly, factors are created and names specified for each. Nonsphericity, ANOVA-by-factor and scaling options can also be specified at this stage.'
''
'Secondly, a list of scans is produced along with a factor matrix, I. This is an nscan x 4 matrix of factor level indicators (see xX.I below). The first factor must be ''replication'' but the other factors can be anything. Specification of I and the scan list can be achieved in one of two ways (a) the ''Specify All'' option allows I to be typed in at the user interface or (more likely) loaded in from the matlab workspace. All of the scans are then selected in one go. (b) the ''Subjects'' option allows you to enter scans a subject at a time. The corresponding experimental conditions (ie. levels of factors) are entered at the same time. SPM will then create the factor matrix I. This style of interface is similar to that available in SPM2.'
''
'Thirdly, the design matrix is built up a block at a time. Each block can be a main effect or a (two-way) interaction. '
''
}';
% ---------------------------------------------------------------------
% des Design
% ---------------------------------------------------------------------
des = cfg_choice;
des.tag = 'des';
des.name = 'Design';
des.val = {t1 };
des.help = {''};
des.values = {t1 t2 pt mreg anova anovaw fd fblock };
% ---------------------------------------------------------------------
% c Vector
% ---------------------------------------------------------------------
c = cfg_entry;
c.tag = 'c';
c.name = 'Vector';
c.help = {
'Vector of covariate values.'
'Enter the covariate values ''''per subject'''' (i.e. all for subject 1, then all for subject 2, etc). Importantly, the ordering of the cells of a factorial design has to be the same for all subjects in order to be consistent with the ordering of the covariate values.'
}';
c.strtype = 'e';
c.num = [Inf 1];
% ---------------------------------------------------------------------
% cname Name
% ---------------------------------------------------------------------
cname = cfg_entry;
cname.tag = 'cname';
cname.name = 'Name';
cname.help = {'Name of covariate'};
cname.strtype = 's';
cname.num = [1 Inf];
% ---------------------------------------------------------------------
% iCFI Interactions
% ---------------------------------------------------------------------
iCFI = cfg_menu;
iCFI.tag = 'iCFI';
iCFI.name = 'Interactions';
iCFI.help = {
'For each covariate you have defined, there is an opportunity to create an additional regressor that is the interaction between the covariate and a chosen experimental factor. '
''
}';
iCFI.labels = {
'None'
'With Factor 1'
'With Factor 2'
'With Factor 3'
}';
iCFI.values = {1 2 3 4};
iCFI.val = {1};
% ---------------------------------------------------------------------
% iCC Centering
% ---------------------------------------------------------------------
iCC = cfg_menu;
iCC.tag = 'iCC';
iCC.name = 'Centering';
iCC.help = {
'The appropriate centering option is usually the one that corresponds to the interaction chosen, and ensures that main effects of the interacting factor aren''t affected by the covariate. You are advised to choose this option, unless you have other modelling considerations. '
''
}';
iCC.labels = {
'Overall mean'
'Factor 1 mean'
'Factor 2 mean'
'Factor 3 mean'
'No centering'
'User specified value'
'As implied by ANCOVA'
'GM'
}';
iCC.values = {1 2 3 4 5 6 7 8};
iCC.val = {1};
% ---------------------------------------------------------------------
% cov Covariate
% ---------------------------------------------------------------------
cov = cfg_branch;
cov.tag = 'cov';
cov.name = 'Covariate';
cov.val = {c cname iCFI iCC };
cov.help = {'Add a new covariate to your experimental design'};
% ---------------------------------------------------------------------
% generic Covariates
% ---------------------------------------------------------------------
generic = cfg_repeat;
generic.tag = 'generic';
generic.name = 'Covariates';
generic.help = {
'This option allows for the specification of covariates and nuisance variables. Unlike SPM94/5/6, where the design was partitioned into effects of interest and nuisance effects for the computation of adjusted data and the F-statistic (which was used to thresh out voxels where there appeared to be no effects of interest), SPM does not partition the design in this way anymore. The only remaining distinction between effects of interest (including covariates) and nuisance effects is their location in the design matrix, which we have retained for continuity. Pre-specified design matrix partitions can be entered. '
''
}';
generic.values = {cov };
generic.num = [0 Inf];
% ---------------------------------------------------------------------
% tm_none None
% ---------------------------------------------------------------------
tm_none = cfg_const;
tm_none.tag = 'tm_none';
tm_none.name = 'None';
tm_none.val = {1};
tm_none.help = {'No threshold masking'};
% ---------------------------------------------------------------------
% athresh Threshold
% ---------------------------------------------------------------------
athresh = cfg_entry;
athresh.tag = 'athresh';
athresh.name = 'Threshold';
athresh.help = {
'Enter the absolute value of the threshold.'
''
}';
athresh.strtype = 'e';
athresh.num = [1 1];
athresh.val = {100};
% ---------------------------------------------------------------------
% tma Absolute
% ---------------------------------------------------------------------
tma = cfg_branch;
tma.tag = 'tma';
tma.name = 'Absolute';
tma.val = {athresh };
tma.help = {
'Images are thresholded at a given value and only voxels at which all images exceed the threshold are included. '
''
'This option allows you to specify the absolute value of the threshold.'
''
}';
% ---------------------------------------------------------------------
% rthresh Threshold
% ---------------------------------------------------------------------
rthresh = cfg_entry;
rthresh.tag = 'rthresh';
rthresh.name = 'Threshold';
rthresh.help = {
'Enter the threshold as a proportion of the global value'
''
}';
rthresh.strtype = 'e';
rthresh.num = [1 1];
rthresh.val = {.8};
% ---------------------------------------------------------------------
% tmr Relative
% ---------------------------------------------------------------------
tmr = cfg_branch;
tmr.tag = 'tmr';
tmr.name = 'Relative';
tmr.val = {rthresh };
tmr.help = {
'Images are thresholded at a given value and only voxels at which all images exceed the threshold are included. '
''
'This option allows you to specify the value of the threshold as a proportion of the global value. '
''
}';
% ---------------------------------------------------------------------
% tm Threshold masking
% ---------------------------------------------------------------------
tm = cfg_choice;
tm.tag = 'tm';
tm.name = 'Threshold masking';
tm.val = {tm_none };
tm.help = {
'Images are thresholded at a given value and only voxels at which all images exceed the threshold are included. '
''
}';
tm.values = {tm_none tma tmr };
% ---------------------------------------------------------------------
% im Implicit Mask
% ---------------------------------------------------------------------
im = cfg_menu;
im.tag = 'im';
im.name = 'Implicit Mask';
im.help = {
'An "implicit mask" is a mask implied by a particular voxel value. Voxels with this mask value are excluded from the analysis. '
''
'For image data-types with a representation of NaN (see spm_type.m), NaN''s is the implicit mask value, (and NaN''s are always masked out). '
''
'For image data-types without a representation of NaN, zero is the mask value, and the user can choose whether zero voxels should be masked out or not.'
''
'By default, an implicit mask is used. '
''
}';
im.labels = {
'Yes'
'No'
}';
im.values = {1 0};
im.val = {1};
% ---------------------------------------------------------------------
% em Explicit Mask
% ---------------------------------------------------------------------
em = cfg_files;
em.tag = 'em';
em.name = 'Explicit Mask';
em.val = {{''}};
em.help = {
'Explicit masks are other images containing (implicit) masks that are to be applied to the current analysis.'
''
'All voxels with value NaN (for image data-types with a representation of NaN), or zero (for other data types) are excluded from the analysis. '
''
'Explicit mask images can have any orientation and voxel/image size. Nearest neighbour interpolation of a mask image is used if the voxel centers of the input images do not coincide with that of the mask image.'
''
}';
em.filter = 'image';
em.ufilter = '.*';
em.num = [0 1];
% ---------------------------------------------------------------------
% masking Masking
% ---------------------------------------------------------------------
masking = cfg_branch;
masking.tag = 'masking';
masking.name = 'Masking';
masking.val = {tm im em };
masking.help = {
'The mask specifies the voxels within the image volume which are to be assessed. SPM supports three methods of masking (1) Threshold, (2) Implicit and (3) Explicit. The volume analysed is the intersection of all masks.'
''
}';
% ---------------------------------------------------------------------
% g_omit Omit
% ---------------------------------------------------------------------
g_omit = cfg_const;
g_omit.tag = 'g_omit';
g_omit.name = 'Omit';
g_omit.val = {1};
g_omit.help = {'Omit'};
% ---------------------------------------------------------------------
% global_uval Global values
% ---------------------------------------------------------------------
global_uval = cfg_entry;
global_uval.tag = 'global_uval';
global_uval.name = 'Global values';
global_uval.help = {
'Enter the vector of global values'
''
}';
global_uval.strtype = 'e';
global_uval.num = [Inf 1];
% ---------------------------------------------------------------------
% g_user User
% ---------------------------------------------------------------------
g_user = cfg_branch;
g_user.tag = 'g_user';
g_user.name = 'User';
g_user.val = {global_uval };
g_user.help = {
'User defined global effects (enter your own '
'vector of global values)'
}';
% ---------------------------------------------------------------------
% g_mean Mean
% ---------------------------------------------------------------------
g_mean = cfg_const;
g_mean.tag = 'g_mean';
g_mean.name = 'Mean';
g_mean.val = {1};
g_mean.help = {
'SPM standard mean voxel value'
''
'This defines the global mean via a two-step process. Firstly, the overall mean is computed. Voxels with values less than 1/8 of this value are then deemed extra-cranial and get masked out. The mean is then recomputed on the remaining voxels.'
''
}';
% ---------------------------------------------------------------------
% globalc Global calculation
% ---------------------------------------------------------------------
globalc = cfg_choice;
globalc.tag = 'globalc';
globalc.name = 'Global calculation';
globalc.val = {g_omit };
globalc.help = {
'This option is only used for PET data.'
''
'There are three methods for estimating global effects (1) Omit (assumming no other options requiring the global value chosen) (2) User defined (enter your own vector of global values) (3) Mean: SPM standard mean voxel value (within per image fullmean/8 mask) '
''
}';
globalc.values = {g_omit g_user g_mean };
% ---------------------------------------------------------------------
% gmsca_no No
% ---------------------------------------------------------------------
gmsca_no = cfg_const;
gmsca_no.tag = 'gmsca_no';
gmsca_no.name = 'No';
gmsca_no.val = {1};
gmsca_no.help = {'No overall grand mean scaling'};
% ---------------------------------------------------------------------
% gmscv Grand mean scaled value
% ---------------------------------------------------------------------
gmscv = cfg_entry;
gmscv.tag = 'gmscv';
gmscv.name = 'Grand mean scaled value';
gmscv.help = {
'The default value of 50, scales the global flow to a physiologically realistic value of 50ml/dl/min.'
''
}';
gmscv.strtype = 'e';
gmscv.num = [Inf 1];
gmscv.val = {50};
% ---------------------------------------------------------------------
% gmsca_yes Yes
% ---------------------------------------------------------------------
gmsca_yes = cfg_branch;
gmsca_yes.tag = 'gmsca_yes';
gmsca_yes.name = 'Yes';
gmsca_yes.val = {gmscv };
gmsca_yes.help = {
'Scaling of the overall grand mean simply scales all the data by a common factor such that the mean of all the global values is the value specified. For qualitative data, this puts the data into an intuitively accessible scale without altering the statistics. '
''
}';
% ---------------------------------------------------------------------
% gmsca Overall grand mean scaling
% ---------------------------------------------------------------------
gmsca = cfg_choice;
gmsca.tag = 'gmsca';
gmsca.name = 'Overall grand mean scaling';
gmsca.val = {gmsca_no };
gmsca.help = {
'Scaling of the overall grand mean simply scales all the data by a common factor such that the mean of all the global values is the value specified. For qualitative data, this puts the data into an intuitively accessible scale without altering the statistics. '
''
'When proportional scaling global normalisation is used each image is separately scaled such that it''s global value is that specified (in which case the grand mean is also implicitly scaled to that value). So, to proportionally scale each image so that its global value is eg. 20, select <Yes> then type in 20 for the grand mean scaled value.'
''
'When using AnCova or no global normalisation, with data from different subjects or sessions, an intermediate situation may be appropriate, and you may be given the option to scale group, session or subject grand means separately. '
''
}';
gmsca.values = {gmsca_no gmsca_yes };
% ---------------------------------------------------------------------
% glonorm Normalisation
% ---------------------------------------------------------------------
glonorm = cfg_menu;
glonorm.tag = 'glonorm';
glonorm.name = 'Normalisation';
glonorm.help = {
'Global nuisance effects are usually accounted for either by scaling the images so that they all have the same global value (proportional scaling), or by including the global covariate as a nuisance effect in the general linear model (AnCova). Much has been written on which to use, and when. Basically, since proportional scaling also scales the variance term, it is appropriate for situations where the global measurement predominantly reflects gain or sensitivity. Where variance is constant across the range of global values, linear modelling in an AnCova approach has more flexibility, since the model is not restricted to a simple proportional regression. '
''
'''Ancova by subject'' or ''Ancova by effect'' options are implemented using the ANCOVA options provided where each experimental factor (eg. subject or effect), is defined. These allow eg. different subjects to have different relationships between local and global measurements. '
''
'Since differences between subjects may be due to gain and sensitivity effects, AnCova by subject could be combined with "grand mean scaling by subject" (an option also provided where each experimental factor is originally defined) to obtain a combination of between subject proportional scaling and within subject AnCova. '
''
}';
glonorm.labels = {
'None'
'Proportional'
'ANCOVA'
}';
glonorm.values = {1 2 3};
glonorm.val = {1};
% ---------------------------------------------------------------------
% globalm Global normalisation
% ---------------------------------------------------------------------
globalm = cfg_branch;
globalm.tag = 'globalm';
globalm.name = 'Global normalisation';
globalm.val = {gmsca glonorm };
globalm.help = {
'This option is only used for PET data.'
''
'Global nuisance effects are usually accounted for either by scaling the images so that they all have the same global value (proportional scaling), or by including the global covariate as a nuisance effect in the general linear model (AnCova). Much has been written on which to use, and when. Basically, since proportional scaling also scales the variance term, it is appropriate for situations where the global measurement predominantly reflects gain or sensitivity. Where variance is constant across the range of global values, linear modelling in an AnCova approach has more flexibility, since the model is not restricted to a simple proportional regression. '
''
'''Ancova by subject'' or ''Ancova by effect'' options are implemented using the ANCOVA options provided where each experimental factor (eg. subject or effect), is defined. These allow eg. different subjects to have different relationships between local and global measurements. '
''
'Since differences between subjects may be due to gain and sensitivity effects, AnCova by subject could be combined with "grand mean scaling by subject" (an option also provided where each experimental factor is originally defined) to obtain a combination of between subject proportional scaling and within subject AnCova. '
''
}';
% ---------------------------------------------------------------------
% factorial_design Factorial design specification
% ---------------------------------------------------------------------
factorial_design = cfg_exbranch;
factorial_design.tag = 'factorial_design';
factorial_design.name = 'Factorial design specification';
factorial_design.val = {dir des generic masking globalc globalm };
factorial_design.help = {
'This interface is used for setting up analyses of PET data. It is also used for ''2nd level'' or ''random effects'' analysis which allow one to make a population inference. First level models can be used to produce appropriate summary data, which can then be used as raw data for a second-level analysis. For example, a simple t-test on contrast images from the first-level turns out to be a random-effects analysis with random subject effects, inferring for the population based on a particular sample of subjects.'
''
'This interface configures the design matrix, describing the general linear model, data specification, and other parameters necessary for the statistical analysis. These parameters are saved in a configuration file (SPM.mat), which can then be passed on to spm_spm.m which estimates the design. This is achieved by pressing the ''Estimate'' button. Inference on these estimated parameters is then handled by the SPM results section. '
''
'A separate interface handles design configuration for fMRI time series.'
''
'Various data and parameters need to be supplied to specify the design (1) the image files, (2) indicators of the corresponding condition/subject/group (2) any covariates, nuisance variables, or design matrix partitions (3) the type of global normalisation (if any) (4) grand mean scaling options (5) thresholds and masks defining the image volume to analyse. The interface supports a comprehensive range of options for all these parameters.'
''
}';
factorial_design.prog = @spm_run_factorial_design;
factorial_design.vout = @vout_stats;
%-------------------------------------------------------------------------
%-------------------------------------------------------------------------
function dep = vout_stats(job)
dep(1) = cfg_dep;
dep(1).sname = 'SPM.mat File';
dep(1).src_output = substruct('.','spmmat');
dep(1).tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}});
%dep(2) = cfg_dep;
%dep(2).sname = 'SPM Variable';
%dep(2).src_output = substruct('.','spmvar');
%dep(2).tgt_spec = cfg_findspec({{'strtype','e'}});
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_con.m
|
.m
|
antx-master/xspm8/config/spm_cfg_con.m
| 33,800 |
utf_8
|
79fe74a6a2a79a4f4215918ab982042d
|
function con = spm_cfg_con
% SPM Configuration file for contrast specification
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% $Id: spm_cfg_con.m 3993 2010-07-13 11:59:32Z volkmar $
rev = '$Rev: 3993 $';
% ---------------------------------------------------------------------
% spmmat Select SPM.mat
% ---------------------------------------------------------------------
spmmat = cfg_files;
spmmat.tag = 'spmmat';
spmmat.name = 'Select SPM.mat';
spmmat.help = {'Select SPM.mat file for contrasts'};
spmmat.filter = 'mat';
spmmat.ufilter = '^SPM\.mat$';
spmmat.num = [1 1];
% ---------------------------------------------------------------------
% name Name
% ---------------------------------------------------------------------
name = cfg_entry;
name.tag = 'name';
name.name = 'Name';
name.help = {'Name of contrast'};
name.strtype = 's';
name.num = [1 Inf];
% ---------------------------------------------------------------------
% convec T contrast vector
% ---------------------------------------------------------------------
convec = cfg_entry;
convec.tag = 'convec';
convec.name = 'T contrast vector';
convec.help = {'Enter T contrast vector. This is done similarly to the contrast manager. A 1 x n vector should be entered for T-contrasts.'};
convec.strtype = 'e';
convec.num = [1 Inf];
% ---------------------------------------------------------------------
% sessrep Replicate over sessions
% ---------------------------------------------------------------------
sessrep = cfg_menu;
sessrep.tag = 'sessrep';
sessrep.name = 'Replicate over sessions';
sessrep.val = {'none'};
sessrep.help = {
'If there are multiple sessions with identical conditions, one might want to specify contrasts which are identical over sessions. This can be done automatically based on the contrast spec for one session.'
'Contrasts can be either replicated (thus testing average effects over sessions) or created per session. In both cases, zero padding up to the length of each session and the block effects is done automatically. In addition, weights of replicated contrasts can be scaled by the number of sessions. This allows to use the same contrast manager batch for fMRI analyses with a variable number of sessions. The scaled contrasts can then be compared in a 2nd level model without a need for further adjustment of effect sizes.'
}';
sessrep.labels = {
'Don''t replicate'
'Replicate'
'Replicate&Scale'
'Create per session'
'Both: Replicate + Create per session'
'Both: Replicate&Scale + Create per session'
}';
sessrep.values = {
'none'
'repl'
'replsc'
'sess'
'both'
'bothsc'
}';
% ---------------------------------------------------------------------
% tcon T-contrast
% ---------------------------------------------------------------------
tcon = cfg_branch;
tcon.tag = 'tcon';
tcon.name = 'T-contrast';
tcon.val = {name convec sessrep };
tcon.help = {
'* Simple one-dimensional contrasts for an SPM{T}'
''
'A simple contrast for an SPM{T} tests the null hypothesis c''B=0 against the one-sided alternative c''B>0, where c is a column vector. '
''
' Note that throughout SPM, the transpose of the contrast weights is used for display and input. That is, you''ll enter and visualise c''. For an SPM{T} this will be a row vector.'
''
'For example, if you have a design in which the first two columns of the design matrix correspond to the effects for "baseline" and "active" conditions respectively, then a contrast with weights c''=[-1,+1,0,...] (with zero weights for any other parameters) tests the hypothesis that there is no "activation" (the parameters for both conditions are the same), against the alternative that there is some activation (i.e. the parameter for the "active" condition is greater than that for the "baseline" condition). The resulting SPM{T} (created by spm_getSPM.m) is a statistic image, with voxel values the value of the t-statistic for the specified contrast at that location. Areas of the SPM{T} with high voxel values indicate evidence for "activation". To look for areas of relative "de-activation", the inverse contrast could be used c''=[+1,-1,0,...].'
''
'Similarly, if you have a design where the third column in the design matrix is a covariate, then the corresponding parameter is essentially a regression slope, and a contrast with weights c''=[0,0,1,0,...] (with zero weights for all parameters but the third) tests the hypothesis of zero regression slope, against the alternative of a positive slope. This is equivalent to a test no correlation, against the alternative of positive correlation. If there are other terms in the model beyond a constant term and the covariate, then this correlation is apartial correlation, the correlation between the data Y and the covariate, after accounting for the other effects.'
}';
% ---------------------------------------------------------------------
% name Name
% ---------------------------------------------------------------------
name = cfg_entry;
name.tag = 'name';
name.name = 'Name';
name.help = {'Name of contrast'};
name.strtype = 's';
name.num = [1 Inf];
% ---------------------------------------------------------------------
% convec F contrast vector
% ---------------------------------------------------------------------
convec = cfg_entry;
convec.tag = 'convec';
convec.name = 'F contrast vector';
convec.help = {'Enter F contrast vector. This is done similarly to the contrast manager. One or multiline contrasts may be entered.'};
convec.strtype = 'e';
convec.num = [Inf Inf];
% ---------------------------------------------------------------------
% generic Contrast vectors
% ---------------------------------------------------------------------
generic = cfg_repeat;
generic.tag = 'generic';
generic.name = 'Contrast vectors';
generic.help = {'F contrasts are defined by a series of vectors.'};
generic.values = {convec };
generic.num = [1 Inf];
% ---------------------------------------------------------------------
% sessrep Replicate over sessions
% ---------------------------------------------------------------------
sessrep = cfg_menu;
sessrep.tag = 'sessrep';
sessrep.name = 'Replicate over sessions';
sessrep.val = {'none'};
sessrep.help = {
'If there are multiple sessions with identical conditions, one might want to specify contrasts which are identical over sessions. This can be done automatically based on the contrast spec for one session.'
'Contrasts can be either replicated (either testing average effects over sessions or per-session/condition effects) or created per session. In both cases, zero padding up to the length of each session and the block effects is done automatically.'
}';
sessrep.labels = {
'Don''t replicate'
'Replicate (average over sessions)'
'Replicate (no averaging)'
'Create per session'
'Both - ''Per session'' and ''Replicate (average over sessions)'''
}';
sessrep.values = {
'none'
'repl'
'replna'
'sess'
'both'
}';
% ---------------------------------------------------------------------
% fcon F-contrast
% ---------------------------------------------------------------------
fcon = cfg_branch;
fcon.tag = 'fcon';
fcon.name = 'F-contrast';
fcon.val = {name generic sessrep };
fcon.help = {
'* Linear constraining matrices for an SPM{F}'
''
'The null hypothesis c''B=0 can be thought of as a (linear) constraint on the full model under consideration, yielding a reduced model. Taken from the viewpoint of two designs, with the full model an extension of the reduced model, the null hypothesis is that the additional terms in the full model are redundent.'
''
'Statistical inference proceeds by comparing the additional variance explained by full design over and above the reduced design to the error variance (of the full design), an "Extra Sum-of-Squares" approach yielding an F-statistic for each voxel, whence an SPM{F}.'
''
'This is useful in a number of situations:'
''
'* Two sided tests'
''
'The simplest use of F-contrasts is to effect a two-sided test of a simple linear contrast c''B, where c is a column vector. The SPM{F} is the square of the corresponding SPM{T}. High values of the SPM{F} therefore indicate evidence against the null hypothesis c''B=0 in favour of the two-sided alternative c''B~=0.'
''
'* General linear hypotheses'
''
'Where the contrast weights is a matrix, the rows of the (transposed) contrast weights matrix c'' must define contrasts in their own right, and the test is effectively simultaneously testing the null hypotheses associated with the individual component contrasts with weights defined in the rows. The null hypothesis is still c''B=0, but since c is a matrix, 0 here is a zero vector rather than a scalar zero, asserting that under the null hypothesis all the component hypotheses are true.'
''
'For example: Suppose you have a language study with 3 word categories (A,B & C), and would like to test whether there is any difference at all between the three levels of the "word category" factor.'
''
'The design matrix might look something like:'
''
' [ 1 0 0 ..]'
' [ : : : ..]'
' [ 1 0 0 ..]'
' [ 0 1 0 ..]'
' X = [ : : : ..]'
' [ 0 1 0 ..]'
' [ 0 0 1 ..]'
' [ : : : ..]'
' [ 0 0 1 ..]'
' [ 0 0 0 ..]'
' [ : : : ..]'
''
' ...with the three levels of the "word category" factor modelled in the first three columns of the design matrix.'
''
'The matrix of contrast weights will look like:'
''
' c'' = [1 -1 0 ...;'
' 0 1 -1 ...]'
''
'Reading the contrasts weights in each row of c'', we see that row 1 states that category A elicits the same response as category B, row 2 that category B elicits the same response as category C, and hence together than categories A, B & C all elicit the same response.'
''
'The alternative hypothesis is simply that the three levels are not all the same, i.e. that there is some difference in the paraeters for the three levels of the factor: The first and the second categories produce different brain responses, OR the second and third categories, or both.'
''
'In other words, under the null hypothesis (the categories produce the same brain responses), the model reduces to one in which the three level "word category" factor can be replaced by a single "word" effect, since there is no difference in the parameters for each category. The corresponding design matrix would have the first three columns replaced by a single column that is the sum (across rows) of the first three columns in the design matric above, modelling the brain response to a word, whatever is the category. The F-contrast above is in fact testing the hypothesis that this reduced design doesn''t account for significantly less variance than the full design with an effect for each word category.'
''
'Another way of seeing that, is to consider a reparameterisation of the model, where the first column models effects common to all three categories, with the second and third columns modelling the differences between the three conditions, for example:'
''
' [ 1 1 0 ..]'
' [ : : : ..]'
' [ 1 1 0 ..]'
' [ 1 0 1 ..]'
' X = [ : : : ..]'
' [ 1 0 1 ..]'
' [ 1 -1 -1 ..]'
' [ : : : ..]'
' [ 1 -1 -1 ..]'
' [ 0 0 0 ..]'
' [ : : : ..]'
''
'In this case, an equivalent F contrast is of the form'
' c'' = [ 0 1 0 ...;'
' 0 0 1 ...]'
'and would be exactly equivalent to the previous contrast applied to the previous design. In this latter formulation, you are asking whewher the two columns modelling the "interaction space" account for a significant amount of variation (variance) of the data. Here the component contrasts in the rows of c'' are simply specifying that the parameters for the corresponding rows are are zero, and it is clear that the F-test is comparing this full model with a reduced model in which the second and third columns of X are omitted.'
''
' Note the difference between the following two F-contrasts:'
' c'' = [ 0 1 0 ...; (1)'
' 0 0 1 ...]'
' and'
' c'' = [ 0 1 1 ...] (2)'
''
' The first is an F-contrast, testing whether either of the parameters for the effects modelled in the 2nd & 3rd columns of the design matrix are significantly different from zero. Under the null hypothesis c''B=0, the first contrast imposes a two-dimensional constraint on the design. The second contrast tests whether the SUM of the parameters for the 2nd & 3rd columns is significantly different from zero. Under the null hypothesis c''B=0, this second contrast only imposes a one dimensional constraint on the design.'
''
' An example of the difference between the two is that the first contrast would be sensitive to the situation where the 2nd & 3rd parameters were +a and -a, for some constant a, wheras the second contrast would not detect this, since the parameters sum to zero.'
''
'The test for an effect of the factor "word category" is an F-test with 3-1=2 "dimensions", or degrees of freedom.'
''
'* Testing the significance of effects modelled by multiple columns'
''
'A conceptially similar situation arises when one wonders whether a set of coufound effects are explaining any variance in the data. One important advantage of testing the with F contrasts rather than one by one using SPM{T}''s is the following. Say you have two covariates that you would like to know whether they can "predict" the brain responses, and these two are correlated (even a small correlation would be important in this instance). Testing one and then the other may lead you to conclude that there is no effect. However, testing with an F test the two covariates may very well show a not suspected effect. This is because by testing one covariate after the other, one never tests for what is COMMON to these covariates (see Andrade et al, Ambiguous results in functional neuroimaging, NeuroImage, 1999).'
''
''
'More generally, F-tests reflect the usual analysis of variance, while t-tests are traditionally post hoc tests, useful to see in which direction is an effect going (positive or negative). The introduction of F-tests can also be viewed as a first means to do model selection.'
''
''
'Technically speaking, an F-contrast defines a number of directions (as many as the rank of the contrast) in the space spanned by the column vectors of the design matrix. These directions are simply given by X*c if the vectors of X are orthogonal, if not, the space define by c is a bit more complex and takes care of the correlation within the design matrix. In essence, an F-contrast is defining a reduced model by imposing some linear constraints (that have to be estimable, see below) on the parameters estimates. Sometimes, this reduced model is simply made of a subset of the column of the original design matrix but generally, it is defined by a combination of those columns. (see spm_FcUtil for what (I hope) is an efficient handling of F-contrats computation).'
}';
% ---------------------------------------------------------------------
% name Name
% ---------------------------------------------------------------------
name = cfg_entry;
name.tag = 'name';
name.name = 'Name';
name.help = {'Name of contrast'};
name.strtype = 's';
name.num = [1 Inf];
% ---------------------------------------------------------------------
% conweight Contrast weight
% ---------------------------------------------------------------------
conweight = cfg_entry;
conweight.tag = 'conweight';
conweight.name = 'Contrast weight';
conweight.help = {'The contrast weight for the selected column.'};
conweight.strtype = 'e';
conweight.num = [1 1];
% ---------------------------------------------------------------------
% colcond Condition #
% ---------------------------------------------------------------------
colcond = cfg_entry;
colcond.tag = 'colcond';
colcond.name = 'Condition #';
colcond.help = {'Select which condition function set is to be contrasted.'};
colcond.strtype = 'e';
colcond.num = [1 1];
% ---------------------------------------------------------------------
% colbf Basis function #
% ---------------------------------------------------------------------
colbf = cfg_entry;
colbf.tag = 'colbf';
colbf.name = 'Basis function #';
colbf.help = {'Select which basis function from the basis function set is to be contrasted.'};
colbf.strtype = 'e';
colbf.num = [1 1];
% ---------------------------------------------------------------------
% colmod Parametric modulation #
% ---------------------------------------------------------------------
colmod = cfg_entry;
colmod.tag = 'colmod';
colmod.name = 'Parametric modulation #';
colmod.help = {'Select which parametric modulation is to be contrasted. If there is no time/parametric modulation, enter "1". If there are both time and parametric modulations, then time modulation comes before parametric modulation.'};
colmod.strtype = 'e';
colmod.num = [1 1];
% ---------------------------------------------------------------------
% colmodord Parametric modulation order
% ---------------------------------------------------------------------
colmodord = cfg_entry;
colmodord.tag = 'colmodord';
colmodord.name = 'Parametric modulation order';
colmodord.help = {
'Order of parametric modulation to be contrasted. '
''
'0 - the basis function itself, 1 - 1st order mod etc'
}';
colmodord.strtype = 'e';
colmodord.num = [1 1];
% ---------------------------------------------------------------------
% colconds Contrast entry
% ---------------------------------------------------------------------
colconds = cfg_branch;
colconds.tag = 'colconds';
colconds.name = 'Contrast entry';
colconds.val = {conweight colcond colbf colmod colmodord };
colconds.help = {''};
% ---------------------------------------------------------------------
% generic T contrast for conditions
% ---------------------------------------------------------------------
generic = cfg_repeat;
generic.tag = 'generic';
generic.name = 'T contrast for conditions';
generic.help = {'Assemble your contrast column by column.'};
generic.values = {colconds };
generic.num = [1 Inf];
% ---------------------------------------------------------------------
% colreg T contrast for extra regressors
% ---------------------------------------------------------------------
colreg = cfg_entry;
colreg.tag = 'colreg';
colreg.name = 'T contrast for extra regressors';
colreg.help = {'Enter T contrast vector for extra regressors.'};
colreg.strtype = 'e';
colreg.num = [1 Inf];
% ---------------------------------------------------------------------
% coltype Contrast columns
% ---------------------------------------------------------------------
coltype = cfg_choice;
coltype.tag = 'coltype';
coltype.name = 'Contrast columns';
coltype.val = {generic };
coltype.help = {'Contrasts can be specified either over conditions or over extra regressors.'};
coltype.values = {generic colreg };
% ---------------------------------------------------------------------
% sessions Session(s)
% ---------------------------------------------------------------------
sessions = cfg_entry;
sessions.tag = 'sessions';
sessions.name = 'Session(s)';
sessions.help = {'Enter session number(s) for which this contrast should be created. If more than one session number is specified, the contrast will be an average contrast over the specified conditions or regressors from these sessions.'};
sessions.strtype = 'e';
sessions.num = [1 Inf];
% ---------------------------------------------------------------------
% tconsess T-contrast (cond/sess based)
% ---------------------------------------------------------------------
tconsess = cfg_branch;
tconsess.tag = 'tconsess';
tconsess.name = 'T-contrast (cond/sess based)';
tconsess.val = {name coltype sessions };
tconsess.help = {
'Define a contrast in terms of conditions or regressors instead of columns of the design matrix. This allows to create contrasts automatically even if some columns are not always present (e.g. parametric modulations).'
''
'Each contrast column can be addressed by specifying'
'* session number'
'* condition number'
'* basis function number'
'* parametric modulation number and'
'* parametric modulation order.'
''
'If the design is specified without time or parametric modulation, SPM creates a "pseudo-modulation" with order zero. To put a contrast weight on a basis function one therefore has to enter "1" for parametric modulation number and "0" for parametric modulation order.'
''
'Time and parametric modulations are not distinguished internally. If time modulation is present, it will be parametric modulation "1", and additional parametric modulations will be numbered starting with "2".'
''
'* Simple one-dimensional contrasts for an SPM{T}'
''
'A simple contrast for an SPM{T} tests the null hypothesis c''B=0 against the one-sided alternative c''B>0, where c is a column vector. '
''
' Note that throughout SPM, the transpose of the contrast weights is used for display and input. That is, you''ll enter and visualise c''. For an SPM{T} this will be a row vector.'
''
'For example, if you have a design in which the first two columns of the design matrix correspond to the effects for "baseline" and "active" conditions respectively, then a contrast with weights c''=[-1,+1,0,...] (with zero weights for any other parameters) tests the hypothesis that there is no "activation" (the parameters for both conditions are the same), against the alternative that there is some activation (i.e. the parameter for the "active" condition is greater than that for the "baseline" condition). The resulting SPM{T} (created by spm_getSPM.m) is a statistic image, with voxel values the value of the t-statistic for the specified contrast at that location. Areas of the SPM{T} with high voxel values indicate evidence for "activation". To look for areas of relative "de-activation", the inverse contrast could be used c''=[+1,-1,0,...].'
''
'Similarly, if you have a design where the third column in the design matrix is a covariate, then the corresponding parameter is essentially a regression slope, and a contrast with weights c''=[0,0,1,0,...] (with zero weights for all parameters but the third) tests the hypothesis of zero regression slope, against the alternative of a positive slope. This is equivalent to a test no correlation, against the alternative of positive correlation. If there are other terms in the model beyond a constant term and the covariate, then this correlation is apartial correlation, the correlation between the data Y and the covariate, after accounting for the other effects.'
}';
% ---------------------------------------------------------------------
% consess Contrast Sessions
% ---------------------------------------------------------------------
consess = cfg_repeat;
consess.tag = 'consess';
consess.name = 'Contrast Sessions';
consess.help = {
'For general linear model Y = XB + E with data Y, desgin matrix X, parameter vector B, and (independent) errors E, a contrast is a linear combination of the parameters c''B. Usually c is a column vector, defining a simple contrast of the parameters, assessed via an SPM{T}. More generally, c can be a matrix (a linear constraining matrix), defining an "F-contrast" assessed via an SPM{F}.'
''
'The vector/matrix c contains the contrast weights. It is this contrast weights vector/matrix that must be specified to define the contrast. The null hypothesis is that the linear combination c''B is zero. The order of the parameters in the parameter (column) vector B, and hence the order to which parameters are referenced in the contrast weights vector c, is determined by the construction of the design matrix.'
''
'There are two types of contrast in SPM: simple contrasts for SPM{T}, and "F-contrasts" for SPM{F}.'
''
'For a thorough theoretical treatment, see the Human Brain Function book and the statistical literature referenced therein.'
''
''
'* Non-orthogonal designs'
''
'Note that parameters zero-weighted in the contrast are still included in the model. This is particularly important if the design is not orthogonal (i.e. the columns of the design matrix are not orthogonal). In effect, the significance of the contrast is assessed *after* accounting for the other effects in the design matrix. Thus, if two covariates are correlated, testing the significance of the parameter associated with one will only test for the part that is not present in the second covariate. This is a general point that is also true for F-contrasts. See Andrade et al, Ambiguous results in functional neuroimaging, NeuroImage, 1999, for a full description of the effect of non othogonal design testing.'
''
''
'* Estimability'
''
'The contrast c''B is estimated by c''b, where b are the parameter estimates given by b=pinv(X)*Y.'
''
'However, if a design is rank-deficient (i.e. the columns of the design matrix are not linearly independent), then the parameters are not unique, and not all linear combinations of the parameter are valid contrasts, since contrasts must be uniquely estimable.'
''
'A weights vector defines a valid contrast if and only if it can be constructed as a linear combination of the rows of the design matrix. That is c'' (the transposed contrast vector - a row vector) is in the row-space of the design matrix.'
''
'Usually, a valid contrast will have weights that sum to zero over the levels of a factor (such as condition).'
''
'A simple example is a simple two condition design including a constant, with design matrix'
''
' [ 1 0 1 ]'
' [ : : : ]'
' X = [ 1 0 1 ]'
' [ 0 1 1 ]'
' [ : : : ]'
' [ 0 1 1 ]'
''
'The first column corresponds to condition 1, the second to condition 2, and the third to a constant (mean) term. Although there are three columns to the design matrix, the design only has two degrees of freedom, since any one column can be derived from the other two (for instance, the third column is the sum of the first two). There is no unique set of parameters for this model, since for any set of parameters adding a constant to the two condition effects and subtracting it from the constant effect yields another set of viable parameters. However, the difference between the two condition effects is uniquely estimated, so c''=[-1,+1,0] does define a contrast.'
''
'If a parameter is estimable, then the weights vector with a single "1" corresponding to that parameter (and zero elsewhere) defines a valid contrast.'
''
''
'* Multiple comparisons'
''
'Note that SPM implements no corrections to account for you looking at multiple contrasts.'
''
'If you are interested in a set of hypotheses that together define a consistent question, then you should account for this when assessing the individual contrasts. A simple Bonferroni approach would assess N simultaneous contrasts at significance level alpha/N, where alpha is the chosen significance level (usually 0.05).'
''
'For two sided t-tests using SPM{T}s, the significance level should be halved. When considering both SPM{T}s produced by a contrast and it''s inverse (the contrast with negative weights), to effect a two-sided test to look for both "increases" and "decreases", you should review each SPM{T} at at level 0.05/2 rather than 0.05. (Or consider an F-contrast!)'
''
''
'* Contrast images and ESS images'
''
'For a simple contrast, SPM (spm_getSPM.m) writes a contrast image: con_????.{img,nii}, with voxel values c''b. (The ???? in the image names are replaced with the contrast number.) These contrast images (for appropriate contrasts) are suitable summary images of an effect at this level, and can be used as input at a higher level when effecting a random effects analysis. See spm_RandFX.man for further details.'
''
'For an F-contrast, SPM (spm_getSPM.m) writes the Extra Sum-of-Squares (the difference in the residual sums of squares for the full and reduced model) as ess_????.{img,nii}. (Note that the ess_????.{img,nii} and SPM{T,F}_????.{img,nii} images are not suitable input for a higher level analysis.)'
}';
consess.values = {tcon fcon tconsess };
consess.num = [0 Inf];
% ---------------------------------------------------------------------
% delete Delete existing contrasts
% ---------------------------------------------------------------------
delete = cfg_menu;
delete.tag = 'delete';
delete.name = 'Delete existing contrasts';
delete.help = {''};
delete.labels = {
'Yes'
'No'
}';
delete.values = {1 0};
delete.val = {0};
% ---------------------------------------------------------------------
% con Contrast Manager
% ---------------------------------------------------------------------
con = cfg_exbranch;
con.tag = 'con';
con.name = 'Contrast Manager';
con.val = {spmmat consess delete };
con.help = {'Set up T and F contrasts.'};
con.prog = @spm_run_con;
con.vout = @vout_stats;
%-------------------------------------------------------------------------
%-------------------------------------------------------------------------
function dep = vout_stats(job)
dep(1) = cfg_dep;
dep(1).sname = 'SPM.mat File';
dep(1).src_output = substruct('.','spmmat');
dep(1).tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}});
%dep(2) = cfg_dep;
%dep(2).sname = 'SPM Variable';
%dep(2).src_output = substruct('.','spmvar');
%dep(2).tgt_spec = cfg_findspec({{'strtype','e'}});
dep(2) = cfg_dep;
dep(2).sname = 'All Con Images';
dep(2).src_output = substruct('.','con');
dep(2).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
dep(3) = cfg_dep;
dep(3).sname = 'All Stats Images';
dep(3).src_output = substruct('.','spm');
dep(3).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_eeg_inv_headmodel.m
|
.m
|
antx-master/xspm8/config/spm_cfg_eeg_inv_headmodel.m
| 8,296 |
utf_8
|
375927f6701902a6fefe76d39a8bcab7
|
function headmodel = spm_cfg_eeg_inv_headmodel
% configuration file for specifying the head model for source
% reconstruction
%_______________________________________________________________________
% Copyright (C) 2010 Wellcome Trust Centre for Neuroimaging
% Vladimir Litvak
% $Id: spm_cfg_eeg_inv_headmodel.m 5988 2014-05-15 12:24:42Z vladimir $
D = cfg_files;
D.tag = 'D';
D.name = 'M/EEG datasets';
D.filter = 'mat';
D.num = [1 Inf];
D.help = {'Select the M/EEG mat files.'};
val = cfg_entry;
val.tag = 'val';
val.name = 'Inversion index';
val.strtype = 'n';
val.help = {'Index of the cell in D.inv where the results will be stored.'};
val.val = {1};
comment = cfg_entry;
comment.tag = 'comment';
comment.name = 'Comment';
comment.strtype = 's';
comment.help = {'User-specified information about this inversion'};
comment.val = {''};
template = cfg_const;
template.tag = 'template';
template.name = 'Template';
template.val = {1};
mri = cfg_files;
mri.tag = 'mri';
mri.name = 'Individual structural image';
mri.filter = 'image';
mri.ufilter = '.*';
mri.num = [1 1];
mri.help = {'Select the subject''s structural image'};
meshes = cfg_choice;
meshes.tag = 'meshes';
meshes.name = 'Mesh source';
meshes.values = {template, mri};
meshes.val = {template};
meshres = cfg_menu;
meshres.tag = 'meshres';
meshres.name = 'Mesh resolution';
meshres.help = {'Specify the resolution of the cortical mesh'};
meshres.labels = {'coarse', 'normal', 'fine'};
meshres.values = {1, 2, 3};
meshres.val = {2};
meshing = cfg_branch;
meshing.tag = 'meshing';
meshing.name = 'Meshes';
meshing.help = {'Create head meshes for building the head model'};
meshing.val = {meshes, meshres};
fidname = cfg_entry;
fidname.tag = 'fidname';
fidname.name = 'M/EEG fiducial label';
fidname.strtype = 's';
fidname.help = {'Label of a fiducial point (as specified in the M/EEG dataset)'};
type = cfg_entry;
type.tag = 'type';
type.name = 'Type MNI coordinates';
type.strtype = 'r';
type.num = [1 3];
type.help = {'Type the coordinates corresponding to the fiducial in the structural image.'};
fid = fopen(fullfile(spm('dir'), 'EEGtemplates', 'fiducials.sfp') ,'rt');
fidtable =textscan(fid ,'%s %f %f %f');
fclose(fid);
select = cfg_menu;
select.tag = 'select';
select.name = 'Select from a list';
select.help = {'Select the corresponding fiducial point from a pre-specified list.'};
select.labels = fidtable{1}';
select.values = fidtable{1}';
specification = cfg_choice;
specification.tag = 'specification';
specification.name = 'How to specify?';
specification.values = {select, type};
fiducial = cfg_branch;
fiducial.tag = 'fiducial';
fiducial.name = 'Fiducial';
fiducial.help = {'Specify fiducial for coregistration'};
fiducial.val = {fidname, specification};
fiducials = cfg_repeat;
fiducials.tag = 'fiducials';
fiducials.name = 'Fiducials';
fiducials.help = {'Specify fiducials for coregistration (at least 3 fiducials need to be specified)'};
fiducials.num = [3 Inf];
fiducials.values = {fiducial};
fiducials.val = {fiducial fiducial fiducial};
useheadshape = cfg_menu;
useheadshape.tag = 'useheadshape';
useheadshape.name = 'Use headshape points?';
useheadshape.help = {'Use headshape points (if available)'};
useheadshape.labels = {'yes', 'no'};
useheadshape.values = {1, 0};
useheadshape.val = {0};
coregspecify = cfg_branch;
coregspecify.tag = 'coregspecify';
coregspecify.name = 'Specify coregistration parameters';
coregspecify.val = {fiducials, useheadshape};
coregdefault = cfg_const;
coregdefault.tag = 'coregdefault';
coregdefault.name = 'Sensor locations are in MNI space already';
coregdefault.help = {'No coregistration is necessary because default EEG sensor locations were used'};
coregdefault.val = {1};
coregistration = cfg_choice;
coregistration.tag = 'coregistration';
coregistration.name = 'Coregistration';
coregistration.values = {coregspecify, coregdefault};
coregistration.val = {coregspecify};
eeg = cfg_menu;
eeg.tag = 'eeg';
eeg.name = 'EEG head model';
eeg.help = {'Select the head model type to use for EEG (if present)'};
eeg.labels = {'EEG BEM', '3-Shell Sphere (experimental)'};
eeg.values = {'EEG BEM', '3-Shell Sphere (experimental)'};
eeg.val = {'EEG BEM'};
meg = cfg_menu;
meg.tag = 'meg';
meg.name = 'MEG head model';
meg.help = {'Select the head model type to use for MEG (if present)'};
meg.labels = {'Single Sphere', 'MEG Local Spheres', 'Single Shell'};
meg.values = {'Single Sphere', 'MEG Local Spheres', 'Single Shell'};
meg.val = {'Single Sphere'};
forward = cfg_branch;
forward.tag = 'forward';
forward.name = 'Forward model';
forward.val = {eeg, meg};
headmodel = cfg_exbranch;
headmodel.tag = 'headmodel';
headmodel.name = 'M/EEG head model specification';
headmodel.val = {D, val, comment, meshing, coregistration, forward};
headmodel.help = {'Specify M/EEG head model for forward computation'};
headmodel.prog = @specify_headmodel;
headmodel.vout = @vout_specify_headmodel;
headmodel.modality = {'EEG'};
function out = specify_headmodel(job)
out.D = {};
%- Loop over input datasets
%--------------------------------------------------------------------------
for i = 1:numel(job.D)
D = spm_eeg_load(job.D{i});
[ok, D] = check(D, '3d');
if ~isfield(D,'inv')
val = 1;
elseif numel(D.inv)<job.val
val = numel(D.inv) + 1;
else
val = job.val;
end
if val ~= job.val
error(sprintf('Cannot use the user-specified inversion index %d for dataset ', job.val, i));
end
D.val = val;
%-Meshes
%--------------------------------------------------------------------------
if ~isfield(D,'inv')
D.inv = {struct('mesh', [])};
end
D.inv{val}.date = strvcat(date,datestr(now,15));
D.inv{val}.comment = {job.comment};
if isfield(job.meshing.meshes, 'template')
sMRI = 1;
else
sMRI = job.meshing.meshes.mri{1};
end
D = spm_eeg_inv_mesh_ui(D, val, sMRI, job.meshing.meshres);
%-Coregistration
%--------------------------------------------------------------------------
if isfield(job.coregistration, 'coregdefault')
D = spm_eeg_inv_datareg_ui(D);
else
meegfid = D.fiducials;
selection = spm_match_str(meegfid.fid.label, {job.coregistration.coregspecify.fiducial.fidname});
meegfid.fid.pnt = meegfid.fid.pnt(selection, :);
meegfid.fid.label = meegfid.fid.label(selection);
mrifid = [];
mrifid.pnt = D.inv{val}.mesh.fid.pnt;
mrifid.fid.pnt = [];
mrifid.fid.label = {job.coregistration.coregspecify.fiducial.fidname}';
for j = 1:numel(job.coregistration.coregspecify.fiducial)
if isfield(job.coregistration.coregspecify.fiducial(j).specification, 'select')
lbl = job.coregistration.coregspecify.fiducial(j).specification.select;
ind = strmatch(lbl, D.inv{val}.mesh.fid.fid.label);
mrifid.fid.pnt(j, :) = D.inv{val}.mesh.fid.fid.pnt(ind, :);
else
mrifid.fid.pnt(j, :) = job.coregistration.coregspecify.fiducial(j).specification.type;
end
end
D = spm_eeg_inv_datareg_ui(D, D.val, meegfid, mrifid, job.coregistration.coregspecify.useheadshape);
end
%-Compute forward model
%----------------------------------------------------------------------
D.inv{val}.forward = struct([]);
for j = 1:numel(D.inv{val}.datareg)
switch D.inv{val}.datareg(j).modality
case 'EEG'
D.inv{D.val}.forward(j).voltype = job.forward.eeg;
case 'MEG'
D.inv{D.val}.forward(j).voltype = job.forward.meg;
end
end
D = spm_eeg_inv_forward(D);
for j = 1:numel(D.inv{val}.forward)
spm_eeg_inv_checkforward(D, D.val, j);
end
save(D);
out.D{i, 1} = fullfile(D.path, D.fname);
end
function dep = vout_specify_headmodel(job)
% Output is always in field "D", no matter how job is structured
dep = cfg_dep;
dep.sname = 'M/EEG dataset(s) with a forward model';
% reference field "D" from output
dep.src_output = substruct('.','D');
% this can be entered into any evaluated input
dep.tgt_spec = cfg_findspec({{'filter','mat'}});
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_eeg_average.m
|
.m
|
antx-master/xspm8/config/spm_cfg_eeg_average.m
| 3,037 |
utf_8
|
dd74140584689604aeafa61c63166da8
|
function S = spm_cfg_eeg_average
% configuration file for M/EEG epoching
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Stefan Kiebel
% $Id: spm_cfg_eeg_average.m 3881 2010-05-07 21:02:57Z vladimir $
rev = '$Rev: 3881 $';
D = cfg_files;
D.tag = 'D';
D.name = 'File Name';
D.filter = 'mat';
D.num = [1 1];
D.help = {'Select the M/EEG mat file.'};
standard = cfg_const;
standard.tag = 'standard';
standard.name = 'Standard';
standard.val = {false};
ks = cfg_entry;
ks.tag = 'ks';
ks.name = 'Offset of the weighting function';
ks.strtype = 'r';
ks.val = {3};
ks.num = [1 1];
ks.help = {'Parameter determining the how far the values should be from the median, '...
'to be considered outliers (the larger, the farther).'};
bycondition = cfg_menu;
bycondition.tag = 'bycondition';
bycondition.name = 'Compute weights by condition';
bycondition.help = {'Compute weights for each condition separately or for all conditions together.'};
bycondition.labels = {'Yes', 'No'};
bycondition.values = {true, false};
bycondition.val = {true};
savew = cfg_menu;
savew.tag = 'savew';
savew.name = 'Save weights';
savew.help = {'Save weights in a separate dataset for quality control.'};
savew.labels = {'Yes', 'No'};
savew.values = {true, false};
savew.val = {true};
robust = cfg_branch;
robust.tag = 'robust';
robust.name = 'Robust';
robust.val = {ks, bycondition, savew};
userobust = cfg_choice;
userobust.tag = 'userobust';
userobust.name = 'Averaging type';
userobust.help = {'choose between using standard and robust averaging'};
userobust.values = {standard, robust};
userobust.val = {standard};
plv = cfg_menu;
plv.tag = 'plv';
plv.name = 'Compute phase-locking value';
plv.help = {'Compute phase-locking value rather than average the phase',...
'This option is only relevant for TF-phase datasets'};
plv.labels = {'Yes', 'No'};
plv.values = {true, false};
plv.val = {false};
S = cfg_exbranch;
S.tag = 'average';
S.name = 'M/EEG Averaging';
S.val = {D, userobust, plv};
S.help = {'Average epoched EEG/MEG data.'};
S.prog = @eeg_average;
S.vout = @vout_eeg_average;
S.modality = {'EEG'};
function out = eeg_average(job)
% construct the S struct
S.D = job.D{1};
if isfield(job.userobust, 'robust')
S.robust = job.userobust.robust;
else
S.robust = false;
end
S.review = false;
S.circularise = job.plv;
out.D = spm_eeg_average(S);
out.Dfname = {fullfile(out.D.path, out.D.fname)};
function dep = vout_eeg_average(job)
% Output is always in field "D", no matter how job is structured
dep = cfg_dep;
dep.sname = 'Average Data';
% reference field "D" from output
dep.src_output = substruct('.','D');
% this can be entered into any evaluated input
dep.tgt_spec = cfg_findspec({{'strtype','e'}});
dep(2) = cfg_dep;
dep(2).sname = 'Averaged Datafile';
% reference field "Dfname" from output
dep(2).src_output = substruct('.','Dfname');
% this can be entered into any file selector
dep(2).tgt_spec = cfg_findspec({{'filter','mat'}});
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_eeg_fuse.m
|
.m
|
antx-master/xspm8/config/spm_cfg_eeg_fuse.m
| 1,316 |
utf_8
|
f68fede02ad0b7e98d3e5bcffb4067f1
|
function S = spm_cfg_eeg_fuse
% configuration file for fusing M/EEG files
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Vladimir Litvak
% $Id: spm_cfg_eeg_fuse.m 3881 2010-05-07 21:02:57Z vladimir $
rev = '$Rev: 3881 $';
D = cfg_files;
D.tag = 'D';
D.name = 'File Names';
D.filter = 'mat';
D.num = [2 Inf];
D.help = {'Select the M/EEG mat files.'};
S = cfg_exbranch;
S.tag = 'fuse';
S.name = 'M/EEG Fusion';
S.val = {D};
S.help = {'Fuse EEG/MEG data.'};
S.prog = @eeg_fuse;
S.vout = @vout_eeg_fuse;
S.modality = {'EEG'};
function out = eeg_fuse(job)
% construct the S struct
S.D = strvcat(job.D{:});
out.D = spm_eeg_fuse(S);
out.Dfname = {fullfile(out.D.path, out.D.fname)};
function dep = vout_eeg_fuse(job)
% Output is always in field "D", no matter how job is structured
dep = cfg_dep;
dep.sname = 'Fused Data';
% reference field "D" from output
dep.src_output = substruct('.','D');
% this can be entered into any evaluated input
dep.tgt_spec = cfg_findspec({{'strtype','e'}});
dep(2) = cfg_dep;
dep(2).sname = 'Fused Datafile';
% reference field "Dfname" from output
dep(2).src_output = substruct('.','Dfname');
% this can be entered into any file selector
dep(2).tgt_spec = cfg_findspec({{'filter','mat'}});
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_reorient.m
|
.m
|
antx-master/xspm8/config/spm_cfg_reorient.m
| 5,240 |
utf_8
|
2ea92b7d5abbfb7cc208d7967030afa3
|
function reorient = spm_cfg_reorient
% SPM Configuration file
% automatically generated by the MATLABBATCH utility function GENCODE
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% $Id: spm_cfg_reorient.m 4380 2011-07-05 11:27:12Z volkmar $
rev = '$Rev: 4380 $';
% ---------------------------------------------------------------------
% srcfiles Images to reorient
% ---------------------------------------------------------------------
srcfiles = cfg_files;
srcfiles.tag = 'srcfiles';
srcfiles.name = 'Images to reorient';
srcfiles.help = {'Select images to reorient.'};
srcfiles.filter = 'image';
srcfiles.ufilter = '.*';
srcfiles.num = [0 Inf];
% ---------------------------------------------------------------------
% transM Reorientation Matrix
% ---------------------------------------------------------------------
transM = cfg_entry;
transM.tag = 'transM';
transM.name = 'Reorientation Matrix';
transM.help = {
'Enter a valid 4x4 matrix for reorientation.'
''
'Example: This will L-R flip the images.'
''
' -1 0 0 0; 0 1 0 0; 0 0 1 0; 0 0 0 1'
}';
transM.strtype = 'e';
transM.num = [4 4];
% ---------------------------------------------------------------------
% transprm Reorientation Parameters
% ---------------------------------------------------------------------
transprm = cfg_entry;
transprm.tag = 'transprm';
transprm.name = 'Reorientation Parameters';
transprm.help = {
'Enter 12 reorientation parameters.'
'P(1) - x translation'
'P(2) - y translation'
'P(3) - z translation'
'P(4) - x rotation about - {pitch} (radians)'
'P(5) - y rotation about - {roll} (radians)'
'P(6) - z rotation about - {yaw} (radians)'
'P(7) - x scaling'
'P(8) - y scaling'
'P(9) - z scaling'
'P(10) - x affine'
'P(11) - y affine'
'P(12) - z affine'
'Parameters are entered as listed above and then processed by spm_matrix.'
''
'Example: This will L-R flip the images (extra spaces are inserted between each group for illustration purposes).'
''
' 0 0 0 0 0 0 -1 1 1 0 0 0'
''
}';
transprm.strtype = 'e';
transprm.num = [1 12];
% ---------------------------------------------------------------------
% transform Reorient by
% ---------------------------------------------------------------------
transform = cfg_choice;
transform.tag = 'transform';
transform.name = 'Reorient by';
transform.val = {transM };
transform.help = {'Specify reorientation parameters - either 12 parameters or a 4x4 transformation matrix. The resulting transformation will be left-multiplied to the voxel-to-world transformation of each image and the new transformation will be written to the image header.'};
transform.values = {transM transprm };
% ---------------------------------------------------------------------
% 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 reoriented image file(s). If this is left ' ...
'empty, the original files will be overwritten.']};
prefix.strtype = 's';
prefix.num = [0 Inf];
% This should not be hardcoded here
prefix.val = {''};
% Final solution: defaults setting
% prefix.def = @(val)spm_get_defaults('reorient.prefix', val{:});
% The following 3 lines should go into spm_defaults.m
% % Reorient defaults
% %=======================================================================
% defaults.reorient.prefix = ''; % Output filename prefix ('' == overwrite)
% ---------------------------------------------------------------------
% reorient Reorient Images
% ---------------------------------------------------------------------
reorient = cfg_exbranch;
reorient.tag = 'reorient';
reorient.name = 'Reorient Images';
reorient.val = {srcfiles transform prefix};
reorient.help = {'This facility allows to reorient images in a batch. The reorientation parameters can be given either as a 4x4 matrix or as parameters as defined for spm_matrix.m. The new image orientation will be computed by PRE-multiplying the original orientation matrix with the supplied matrix.'};
reorient.prog = @spm_run_reorient;
reorient.vout = @vout;
% ---------------------------------------------------------------------
% ---------------------------------------------------------------------
function dep = vout(job)
dep = cfg_dep;
dep.sname = 'Reoriented Images';
dep.src_output = substruct('.','files');
dep.tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_fmri_design.m
|
.m
|
antx-master/xspm8/config/spm_cfg_fmri_design.m
| 41,034 |
utf_8
|
7c2e3c73979ddfcadfb52dc27f1888c9
|
function fmri_design = spm_cfg_fmri_design
% SPM Configuration file for fMRI model specification (design only)
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% $Id: spm_cfg_fmri_design.m 3691 2010-01-20 17:08:30Z guillaume $
rev = '$Rev: 3691 $';
% ---------------------------------------------------------------------
% dir Directory
% ---------------------------------------------------------------------
dir = cfg_files;
dir.tag = 'dir';
dir.name = 'Directory';
dir.help = {'Select a directory where the SPM.mat file containing the specified design matrix will be written.'};
dir.filter = 'dir';
dir.ufilter = '.*';
dir.num = [1 1];
% ---------------------------------------------------------------------
% units Units for design
% ---------------------------------------------------------------------
units = cfg_menu;
units.tag = 'units';
units.name = 'Units for design';
units.help = {'The onsets of events or blocks can be specified in either scans or seconds.'};
units.labels = {
'Scans'
'Seconds'
}';
units.values = {
'scans'
'secs'
}';
% ---------------------------------------------------------------------
% RT Interscan interval
% ---------------------------------------------------------------------
RT = cfg_entry;
RT.tag = 'RT';
RT.name = 'Interscan interval';
RT.help = {'Interscan interval, TR, (specified in seconds). This is the time between acquiring a plane of one volume and the same plane in the next volume. It is assumed to be constant throughout.'};
RT.strtype = 'e';
RT.num = [1 1];
% ---------------------------------------------------------------------
% fmri_t Microtime resolution
% ---------------------------------------------------------------------
fmri_t = cfg_entry;
fmri_t.tag = 'fmri_t';
fmri_t.name = 'Microtime resolution';
fmri_t.help = {
'The microtime resolution, t, is the number of time-bins per scan used when building regressors. '
''
'Do not change this parameter unless you have a long TR and wish to shift regressors so that they are aligned to a particular slice. '
}';
fmri_t.strtype = 'e';
fmri_t.num = [1 1];
fmri_t.def = @(val)spm_get_defaults('stats.fmri.fmri_t', val{:});
% ---------------------------------------------------------------------
% fmri_t0 Microtime onset
% ---------------------------------------------------------------------
fmri_t0 = cfg_entry;
fmri_t0.tag = 'fmri_t0';
fmri_t0.name = 'Microtime onset';
fmri_t0.help = {
'The microtime onset, t0, is the first time-bin at which the regressors are resampled to coincide with data acquisition. If t0 = 1 then the regressors will be appropriate for the first slice. If you want to temporally realign the regressors so that they match responses in the middle slice then make t0 = t/2 (assuming there is a negligible gap between volume acquisitions). '
''
'Do not change the default setting unless you have a long TR. '
}';
fmri_t0.strtype = 'e';
fmri_t0.num = [1 1];
fmri_t0.def = @(val)spm_get_defaults('stats.fmri.fmri_t0', val{:});
% ---------------------------------------------------------------------
% timing Timing parameters
% ---------------------------------------------------------------------
timing = cfg_branch;
timing.tag = 'timing';
timing.name = 'Timing parameters';
timing.val = {units RT fmri_t fmri_t0 };
timing.help = {
'Specify various timing parameters needed to construct the design matrix. This includes the units of the design specification and the interscan interval.'
''
'Also, with longs TRs you may want to shift the regressors so that they are aligned to a particular slice. This is effected by changing the microtime resolution and onset. '
}';
% ---------------------------------------------------------------------
% nscan Number of scans
% ---------------------------------------------------------------------
nscan = cfg_entry;
nscan.tag = 'nscan';
nscan.name = 'Number of scans';
nscan.help = {'Specify the number of scans for this session.The actual scans must be specified in a separate batch job ''fMRI data specification''.'};
nscan.strtype = 'e';
nscan.num = [1 1];
% ---------------------------------------------------------------------
% name Name
% ---------------------------------------------------------------------
name = cfg_entry;
name.tag = 'name';
name.name = 'Name';
name.help = {'Condition Name'};
name.strtype = 's';
name.num = [1 Inf];
% ---------------------------------------------------------------------
% onset Onsets
% ---------------------------------------------------------------------
onset = cfg_entry;
onset.tag = 'onset';
onset.name = 'Onsets';
onset.help = {'Specify a vector of onset times for this condition type. '};
onset.strtype = 'e';
onset.num = [Inf 1];
% ---------------------------------------------------------------------
% duration Durations
% ---------------------------------------------------------------------
duration = cfg_entry;
duration.tag = 'duration';
duration.name = 'Durations';
duration.help = {'Specify the event durations. Epoch and event-related responses are modeled in exactly the same way but by specifying their different durations. Events are specified with a duration of 0. If you enter a single number for the durations it will be assumed that all trials conform to this duration. If you have multiple different durations, then the number must match the number of onset times.'};
duration.strtype = 'e';
duration.num = [Inf 1];
% ---------------------------------------------------------------------
% tmod Time Modulation
% ---------------------------------------------------------------------
tmod = cfg_menu;
tmod.tag = 'tmod';
tmod.name = 'Time Modulation';
tmod.help = {
'This option allows for the characterisation of linear or nonlinear time effects. For example, 1st order modulation would model the stick functions and a linear change of the stick function heights over time. Higher order modulation will introduce further columns that contain the stick functions scaled by time squared, time cubed etc.'
''
'Interactions or response modulations can enter at two levels. Firstly the stick function itself can be modulated by some parametric variate (this can be time or some trial-specific variate like reaction time) modeling the interaction between the trial and the variate or, secondly interactions among the trials themselves can be modeled using a Volterra series formulation that accommodates interactions over time (and therefore within and between trial types).'
}';
tmod.labels = {
'No Time Modulation'
'1st order Time Modulation'
'2nd order Time Modulation'
'3rd order Time Modulation'
'4th order Time Modulation'
'5th order Time Modulation'
'6th order Time Modulation'
}';
tmod.values = {0 1 2 3 4 5 6};
tmod.val = {0};
% ---------------------------------------------------------------------
% name Name
% ---------------------------------------------------------------------
name1 = cfg_entry;
name1.tag = 'name';
name1.name = 'Name';
name1.help = {'Enter a name for this parameter.'};
name1.strtype = 's';
name1.num = [1 Inf];
% ---------------------------------------------------------------------
% param Values
% ---------------------------------------------------------------------
param = cfg_entry;
param.tag = 'param';
param.name = 'Values';
param.help = {'Enter a vector of values, one for each occurence of the event.'};
param.strtype = 'e';
param.num = [Inf 1];
% ---------------------------------------------------------------------
% poly Polynomial Expansion
% ---------------------------------------------------------------------
poly = cfg_menu;
poly.tag = 'poly';
poly.name = 'Polynomial Expansion';
poly.help = {'For example, 1st order modulation would model the stick functions and a linear change of the stick function heights over different values of the parameter. Higher order modulation will introduce further columns that contain the stick functions scaled by parameter squared, cubed etc.'};
poly.labels = {
'1st order'
'2nd order'
'3rd order'
'4th order'
'5th order'
'6th order'
}';
poly.values = {1 2 3 4 5 6};
% ---------------------------------------------------------------------
% pmod Parameter
% ---------------------------------------------------------------------
pmod = cfg_branch;
pmod.tag = 'pmod';
pmod.name = 'Parameter';
pmod.val = {name1 param poly };
pmod.help = {
'Model interractions with user specified parameters. This allows nonlinear effects relating to some other measure to be modelled in the design matrix.'
''
'Interactions or response modulations can enter at two levels. Firstly the stick function itself can be modulated by some parametric variate (this can be time or some trial-specific variate like reaction time) modeling the interaction between the trial and the variate or, secondly interactions among the trials themselves can be modeled using a Volterra series formulation that accommodates interactions over time (and therefore within and between trial types).'
}';
% ---------------------------------------------------------------------
% generic Parametric Modulations
% ---------------------------------------------------------------------
generic2 = cfg_repeat;
generic2.tag = 'generic';
generic2.name = 'Parametric Modulations';
generic2.help = {'The stick function itself can be modulated by some parametric variate (this can be time or some trial-specific variate like reaction time) modeling the interaction between the trial and the variate. The events can be modulated by zero or more parameters.'};
generic2.values = {pmod };
generic2.num = [0 Inf];
% ---------------------------------------------------------------------
% cond Condition
% ---------------------------------------------------------------------
cond = cfg_branch;
cond.tag = 'cond';
cond.name = 'Condition';
cond.val = {name onset duration tmod generic2 };
cond.check = @cond_check;
cond.help = {'An array of input functions is contructed, specifying occurrence events or epochs (or both). These are convolved with a basis set at a later stage to give regressors that enter into the design matrix. Interactions of evoked responses with some parameter (time or a specified variate) enter at this stage as additional columns in the design matrix with each trial multiplied by the [expansion of the] trial-specific parameter. The 0th order expansion is simply the main effect in the first column.'};
% ---------------------------------------------------------------------
% generic Conditions
% ---------------------------------------------------------------------
generic1 = cfg_repeat;
generic1.tag = 'generic';
generic1.name = 'Conditions';
generic1.help = {'You are allowed to combine both event- and epoch-related responses in the same model and/or regressor. Any number of condition (event or epoch) types can be specified. Epoch and event-related responses are modeled in exactly the same way by specifying their onsets [in terms of onset times] and their durations. Events are specified with a duration of 0. If you enter a single number for the durations it will be assumed that all trials conform to this duration.For factorial designs, one can later associate these experimental conditions with the appropriate levels of experimental factors. '};
generic1.values = {cond };
generic1.num = [0 Inf];
% ---------------------------------------------------------------------
% multi Multiple conditions
% ---------------------------------------------------------------------
multi = cfg_files;
multi.tag = 'multi';
multi.name = 'Multiple conditions';
multi.val{1} = {''};
multi.help = {
'Select the *.mat file containing details of your multiple experimental conditions. '
''
'If you have multiple conditions then entering the details a condition at a time is very inefficient. This option can be used to load all the required information in one go. You will first need to create a *.mat file containing the relevant information. '
''
'This *.mat file must include the following cell arrays (each 1 x n): names, onsets and durations. eg. names=cell(1,5), onsets=cell(1,5), durations=cell(1,5), then names{2}=''SSent-DSpeak'', onsets{2}=[3 5 19 222], durations{2}=[0 0 0 0], contain the required details of the second condition. These cell arrays may be made available by your stimulus delivery program, eg. COGENT. The duration vectors can contain a single entry if the durations are identical for all events.'
''
'Time and Parametric effects can also be included. For time modulation include a cell array (1 x n) called tmod. It should have a have a single number in each cell. Unused cells may contain either a 0 or be left empty. The number specifies the order of time modulation from 0 = No Time Modulation to 6 = 6th Order Time Modulation. eg. tmod{3} = 1, modulates the 3rd condition by a linear time effect.'
''
'For parametric modulation include a structure array, which is up to 1 x n in size, called pmod. n must be less than or equal to the number of cells in the names/onsets/durations cell arrays. The structure array pmod must have the fields: name, param and poly. Each of these fields is in turn a cell array to allow the inclusion of one or more parametric effects per column of the design. The field name must be a cell array containing strings. The field param is a cell array containing a vector of parameters. Remember each parameter must be the same length as its corresponding onsets vector. The field poly is a cell array (for consistency) with each cell containing a single number specifying the order of the polynomial expansion from 1 to 6.'
''
'Note that each condition is assigned its corresponding entry in the structure array (condition 1 parametric modulators are in pmod(1), condition 2 parametric modulators are in pmod(2), etc. Within a condition multiple parametric modulators are accessed via each fields cell arrays. So for condition 1, parametric modulator 1 would be defined in pmod(1).name{1}, pmod(1).param{1}, and pmod(1).poly{1}. A second parametric modulator for condition 1 would be defined as pmod(1).name{2}, pmod(1).param{2} and pmod(1).poly{2}. If there was also a parametric modulator for condition 2, then remember the first modulator for that condition is in cell array 1: pmod(2).name{1}, pmod(2).param{1}, and pmod(2).poly{1}. If some, but not all conditions are parametrically modulated, then the non-modulated indices in the pmod structure can be left blank. For example, if conditions 1 and 3 but not condition 2 are modulated, then specify pmod(1) and pmod(3). Similarly, if conditions 1 and 2 are modulated but there are 3 conditions overall, it is only necessary for pmod to be a 1 x 2 structure array.'
''
'EXAMPLE:'
'Make an empty pmod structure: '
' pmod = struct(''name'',{''''},''param'',{},''poly'',{});'
'Specify one parametric regressor for the first condition: '
' pmod(1).name{1} = ''regressor1'';'
' pmod(1).param{1} = [1 2 4 5 6];'
' pmod(1).poly{1} = 1;'
'Specify 2 parametric regressors for the second condition: '
' pmod(2).name{1} = ''regressor2-1'';'
' pmod(2).param{1} = [1 3 5 7]; '
' pmod(2).poly{1} = 1;'
' pmod(2).name{2} = ''regressor2-2'';'
' pmod(2).param{2} = [2 4 6 8 10];'
' pmod(2).poly{2} = 1;'
''
'The parametric modulator should be mean corrected if appropriate. Unused structure entries should have all fields left empty.'
}';
multi.filter = 'mat';
multi.ufilter = '.*';
multi.num = [0 1];
% ---------------------------------------------------------------------
% name Name
% ---------------------------------------------------------------------
name = cfg_entry;
name.tag = 'name';
name.name = 'Name';
name.help = {'Enter name of regressor eg. First movement parameter'};
name.strtype = 's';
name.num = [1 Inf];
% ---------------------------------------------------------------------
% val Value
% ---------------------------------------------------------------------
val = cfg_entry;
val.tag = 'val';
val.name = 'Value';
val.help = {'Enter the vector of regressor values'};
val.strtype = 'e';
val.num = [Inf 1];
% ---------------------------------------------------------------------
% regress Regressor
% ---------------------------------------------------------------------
regress = cfg_branch;
regress.tag = 'regress';
regress.name = 'Regressor';
regress.val = {name val };
regress.help = {'regressor'};
% ---------------------------------------------------------------------
% generic Regressors
% ---------------------------------------------------------------------
generic2 = cfg_repeat;
generic2.tag = 'generic';
generic2.name = 'Regressors';
generic2.help = {'Regressors are additional columns included in the design matrix, which may model effects that would not be convolved with the haemodynamic response. One such example would be the estimated movement parameters, which may confound the data.'};
generic2.values = {regress };
generic2.num = [0 Inf];
% ---------------------------------------------------------------------
% multi_reg Multiple regressors
% ---------------------------------------------------------------------
multi_reg = cfg_files;
multi_reg.tag = 'multi_reg';
multi_reg.name = 'Multiple regressors';
multi_reg.val{1} = {''};
multi_reg.help = {
'Select the *.mat/*.txt file containing details of your multiple regressors. '
''
'If you have multiple regressors eg. realignment parameters, then entering the details a regressor at a time is very inefficient. This option can be used to load all the required information in one go. '
''
'You will first need to create a *.mat file containing a matrix R or a *.txt file containing the regressors. Each column of R will contain a different regressor. When SPM creates the design matrix the regressors will be named R1, R2, R3, ..etc.'
}';
multi_reg.filter = 'mat';
multi_reg.ufilter = '.*';
multi_reg.num = [0 1];
% ---------------------------------------------------------------------
% hpf High-pass filter
% ---------------------------------------------------------------------
hpf = cfg_entry;
hpf.tag = 'hpf';
hpf.name = 'High-pass filter';
hpf.help = {'The default high-pass filter cutoff is 128 seconds.Slow signal drifts with a period longer than this will be removed. Use ''explore design'' to ensure this cut-off is not removing too much experimental variance. High-pass filtering is implemented using a residual forming matrix (i.e. it is not a convolution) and is simply to a way to remove confounds without estimating their parameters explicitly. The constant term is also incorporated into this filter matrix.'};
hpf.strtype = 'e';
hpf.num = [1 1];
hpf.def = @(val)spm_get_defaults('stats.fmri.hpf', val{:});
% ---------------------------------------------------------------------
% sess Subject/Session
% ---------------------------------------------------------------------
sess = cfg_branch;
sess.tag = 'sess';
sess.name = 'Subject/Session';
sess.val = {nscan generic1 multi generic2 multi_reg hpf };
sess.check = @sess_check;
sess.help = {'The design matrix for fMRI data consists of one or more separable, session-specific partitions. These partitions are usually either one per subject, or one per fMRI scanning session for that subject.'};
% ---------------------------------------------------------------------
% generic Data & Design
% ---------------------------------------------------------------------
generic = cfg_repeat;
generic.tag = 'generic';
generic.name = 'Data & Design';
generic.help = {
'The design matrix defines the experimental design and the nature of hypothesis testing to be implemented. The design matrix has one row for each scan and one column for each effect or explanatory variable. (e.g. regressor or stimulus function). '
''
'This allows you to build design matrices with separable session-specific partitions. Each partition may be the same (in which case it is only necessary to specify it once) or different. Responses can be either event- or epoch related, where the latter model involves prolonged and possibly time-varying responses to state-related changes in experimental conditions. Event-related response are modelled in terms of responses to instantaneous events. Mathematically they are both modelled by convolving a series of delta (stick) or box-car functions, encoding the input or stimulus function. with a set of hemodynamic basis functions.'
}';
generic.values = {sess };
generic.num = [1 Inf];
% ---------------------------------------------------------------------
% name Name
% ---------------------------------------------------------------------
name = cfg_entry;
name.tag = 'name';
name.name = 'Name';
name.help = {'Name of factor, eg. ''Repetition'' '};
name.strtype = 's';
name.num = [1 Inf];
% ---------------------------------------------------------------------
% levels Levels
% ---------------------------------------------------------------------
levels = cfg_entry;
levels.tag = 'levels';
levels.name = 'Levels';
levels.help = {'Enter number of levels for this factor, eg. 2'};
levels.strtype = 'e';
levels.num = [Inf 1];
% ---------------------------------------------------------------------
% fact Factor
% ---------------------------------------------------------------------
fact = cfg_branch;
fact.tag = 'fact';
fact.name = 'Factor';
fact.val = {name levels };
fact.help = {'Add a new factor to your experimental design'};
% ---------------------------------------------------------------------
% generic Factorial design
% ---------------------------------------------------------------------
generic1 = cfg_repeat;
generic1.tag = 'generic';
generic1.name = 'Factorial design';
generic1.help = {
'If you have a factorial design then SPM can automatically generate the contrasts necessary to test for the main effects and interactions. '
''
'This includes the F-contrasts necessary to test for these effects at the within-subject level (first level) and the simple contrasts necessary to generate the contrast images for a between-subject (second-level) analysis.'
''
'To use this option, create as many factors as you need and provide a name and number of levels for each. SPM assumes that the condition numbers of the first factor change slowest, the second factor next slowest etc. It is best to write down the contingency table for your design to ensure this condition is met. This table relates the levels of each factor to the conditions. '
''
'For example, if you have 2-by-3 design your contingency table has two rows and three columns where the the first factor spans the rows, and the second factor the columns. The numbers of the conditions are 1,2,3 for the first row and 4,5,6 for the second. '
}';
generic1.values = {fact };
generic1.num = [0 Inf];
% ---------------------------------------------------------------------
% derivs Model derivatives
% ---------------------------------------------------------------------
derivs = cfg_menu;
derivs.tag = 'derivs';
derivs.name = 'Model derivatives';
derivs.help = {'Model HRF Derivatives. The canonical HRF combined with time and dispersion derivatives comprise an ''informed'' basis set, as the shape of the canonical response conforms to the hemodynamic response that is commonly observed. The incorporation of the derivate terms allow for variations in subject-to-subject and voxel-to-voxel responses. The time derivative allows the peak response to vary by plus or minus a second and the dispersion derivative allows the width of the response to vary. The informed basis set requires an SPM{F} for inference. T-contrasts over just the canonical are perfectly valid but assume constant delay/dispersion. The informed basis set compares favourably with eg. FIR bases on many data sets. '};
derivs.labels = {
'No derivatives'
'Time derivatives'
'Time and Dispersion derivatives'
}';
derivs.values = {[0 0] [1 0] [1 1]};
derivs.val = {[0 0]};
% ---------------------------------------------------------------------
% hrf Canonical HRF
% ---------------------------------------------------------------------
hrf = cfg_branch;
hrf.tag = 'hrf';
hrf.name = 'Canonical HRF';
hrf.val = {derivs };
hrf.help = {'Canonical Hemodynamic Response Function. This is the default option. Contrasts of these effects have a physical interpretation and represent a parsimonious way of characterising event-related responses. This option is also useful if you wish to look separately at activations and deactivations (this is implemented using a t-contrast with a +1 or -1 entry over the canonical regressor). '};
% ---------------------------------------------------------------------
% length Window length
% ---------------------------------------------------------------------
length = cfg_entry;
length.tag = 'length';
length.name = 'Window length';
length.help = {'Post-stimulus window length (in seconds)'};
length.strtype = 'e';
length.num = [1 1];
% ---------------------------------------------------------------------
% order Order
% ---------------------------------------------------------------------
order = cfg_entry;
order.tag = 'order';
order.name = 'Order';
order.help = {'Number of basis functions'};
order.strtype = 'e';
order.num = [1 1];
% ---------------------------------------------------------------------
% fourier Fourier Set
% ---------------------------------------------------------------------
fourier = cfg_branch;
fourier.tag = 'fourier';
fourier.name = 'Fourier Set';
fourier.val = {length order };
fourier.help = {'Fourier basis functions. This option requires an SPM{F} for inference.'};
% ---------------------------------------------------------------------
% length Window length
% ---------------------------------------------------------------------
length = cfg_entry;
length.tag = 'length';
length.name = 'Window length';
length.help = {'Post-stimulus window length (in seconds)'};
length.strtype = 'e';
length.num = [1 1];
% ---------------------------------------------------------------------
% order Order
% ---------------------------------------------------------------------
order = cfg_entry;
order.tag = 'order';
order.name = 'Order';
order.help = {'Number of basis functions'};
order.strtype = 'e';
order.num = [1 1];
% ---------------------------------------------------------------------
% fourier_han Fourier Set (Hanning)
% ---------------------------------------------------------------------
fourier_han = cfg_branch;
fourier_han.tag = 'fourier_han';
fourier_han.name = 'Fourier Set (Hanning)';
fourier_han.val = {length order };
fourier_han.help = {'Fourier basis functions with Hanning Window - requires SPM{F} for inference.'};
% ---------------------------------------------------------------------
% length Window length
% ---------------------------------------------------------------------
length = cfg_entry;
length.tag = 'length';
length.name = 'Window length';
length.help = {'Post-stimulus window length (in seconds)'};
length.strtype = 'e';
length.num = [1 1];
% ---------------------------------------------------------------------
% order Order
% ---------------------------------------------------------------------
order = cfg_entry;
order.tag = 'order';
order.name = 'Order';
order.help = {'Number of basis functions'};
order.strtype = 'e';
order.num = [1 1];
% ---------------------------------------------------------------------
% gamma Gamma Functions
% ---------------------------------------------------------------------
gamma = cfg_branch;
gamma.tag = 'gamma';
gamma.name = 'Gamma Functions';
gamma.val = {length order };
gamma.help = {'Gamma basis functions - requires SPM{F} for inference.'};
% ---------------------------------------------------------------------
% length Window length
% ---------------------------------------------------------------------
length = cfg_entry;
length.tag = 'length';
length.name = 'Window length';
length.help = {'Post-stimulus window length (in seconds)'};
length.strtype = 'e';
length.num = [1 1];
% ---------------------------------------------------------------------
% order Order
% ---------------------------------------------------------------------
order = cfg_entry;
order.tag = 'order';
order.name = 'Order';
order.help = {'Number of basis functions'};
order.strtype = 'e';
order.num = [1 1];
% ---------------------------------------------------------------------
% fir Finite Impulse Response
% ---------------------------------------------------------------------
fir = cfg_branch;
fir.tag = 'fir';
fir.name = 'Finite Impulse Response';
fir.val = {length order };
fir.help = {'Finite impulse response - requires SPM{F} for inference.'};
% ---------------------------------------------------------------------
% bases Basis Functions
% ---------------------------------------------------------------------
bases = cfg_choice;
bases.tag = 'bases';
bases.name = 'Basis Functions';
bases.val = {hrf };
bases.help = {'The most common choice of basis function is the Canonical HRF with or without time and dispersion derivatives. '};
bases.values = {hrf fourier fourier_han gamma fir };
% ---------------------------------------------------------------------
% volt Model Interactions (Volterra)
% ---------------------------------------------------------------------
volt = cfg_menu;
volt.tag = 'volt';
volt.name = 'Model Interactions (Volterra)';
volt.help = {
'Generalized convolution of inputs (U) with basis set (bf).'
''
'For first order expansions the causes are simply convolved (e.g. stick functions) in U.u by the basis functions in bf to create a design matrix X. For second order expansions new entries appear in ind, bf and name that correspond to the interaction among the orginal causes. The basis functions for these efects are two dimensional and are used to assemble the second order kernel. Second order effects are computed for only the first column of U.u.'
'Interactions or response modulations can enter at two levels. Firstly the stick function itself can be modulated by some parametric variate (this can be time or some trial-specific variate like reaction time) modeling the interaction between the trial and the variate or, secondly interactions among the trials themselves can be modeled using a Volterra series formulation that accommodates interactions over time (and therefore within and between trial types).'
}';
volt.labels = {
'Do not model Interactions'
'Model Interactions'
}';
volt.values = {1 2};
volt.val = {1};
% ---------------------------------------------------------------------
% global Global normalisation
% ---------------------------------------------------------------------
xGlobal = cfg_menu;
xGlobal.tag = 'global';
xGlobal.name = 'Global normalisation';
xGlobal.help = {'Global intensity normalisation'};
xGlobal.labels = {
'Scaling'
'None'
}';
xGlobal.values = {
'Scaling'
'None'
}';
xGlobal.val = {'None'};
% ---------------------------------------------------------------------
% cvi Serial correlations
% ---------------------------------------------------------------------
cvi = cfg_menu;
cvi.tag = 'cvi';
cvi.name = 'Serial correlations';
cvi.help = {
'Serial correlations in fMRI time series due to aliased biorhythms and unmodelled neuronal activity can be accounted for using an autoregressive AR(1) model during Classical (ReML) parameter estimation. '
''
'This estimate assumes the same correlation structure for each voxel, within each session. ReML estimates are then used to correct for non-sphericity during inference by adjusting the statistics and degrees of freedom appropriately. The discrepancy between estimated and actual intrinsic (i.e. prior to filtering) correlations are greatest at low frequencies. Therefore specification of the high-pass filter is particularly important. '
''
'Serial correlation can be ignored if you choose the ''none'' option. Note that the above options only apply if you later specify that your model will be estimated using the Classical (ReML) approach. If you choose Bayesian estimation these options will be ignored. For Bayesian estimation, the choice of noisemodel (AR model order) is made under the estimation options. '
}';
cvi.labels = {
'none'
'AR(1)'
}';
cvi.values = {
'none'
'AR(1)'
}';
cvi.def = @(val)spm_get_defaults('stats.fmri.cvi', val{:});
% ---------------------------------------------------------------------
% fmri_design fMRI model specification (design only)
% ---------------------------------------------------------------------
fmri_design = cfg_exbranch;
fmri_design.tag = 'fmri_design';
fmri_design.name = 'fMRI model specification (design only)';
fmri_design.val = {dir timing generic generic1 bases volt xGlobal cvi };
fmri_design.help = {
'Statistical analysis of fMRI data uses a mass-univariate approach based on General Linear Models (GLMs). It comprises the following steps (1) specification of the GLM design matrix, fMRI data files and filtering (2) estimation of GLM paramaters using classical or Bayesian approaches and (3) interrogation of results using contrast vectors to produce Statistical Parametric Maps (SPMs) or Posterior Probability Maps (PPMs).'
''
'The design matrix defines the experimental design and the nature of hypothesis testing to be implemented. The design matrix has one row for each scan and one column for each effect or explanatory variable. (eg. regressor or stimulus function). You can build design matrices with separable session-specific partitions. Each partition may be the same (in which case it is only necessary to specify it once) or different. '
''
'Responses can be either event- or epoch related, the only distinction is the duration of the underlying input or stimulus function. Mathematically they are both modeled by convolving a series of delta (stick) or box functions (u), indicating the onset of an event or epoch with a set of basis functions. These basis functions model the hemodynamic convolution, applied by the brain, to the inputs. This convolution can be first-order or a generalized convolution modeled to second order (if you specify the Volterra option). The same inputs are used by the Hemodynamic model or Dynamic Causal Models which model the convolution explicitly in terms of hidden state variables. '
''
'Basis functions can be used to plot estimated responses to single events once the parameters (i.e. basis function coefficients) have been estimated. The importance of basis functions is that they provide a graceful transition between simple fixed response models (like the box-car) and finite impulse response (FIR) models, where there is one basis function for each scan following an event or epoch onset. The nice thing about basis functions, compared to FIR models, is that data sampling and stimulus presentation does not have to be synchronized thereby allowing a uniform and unbiased sampling of peri-stimulus time.'
''
'Event-related designs may be stochastic or deterministic. Stochastic designs involve one of a number of trial-types occurring with a specified probability at successive intervals in time. These probabilities can be fixed (stationary designs) or time-dependent (modulated or non-stationary designs). The most efficient designs obtain when the probabilities of every trial type are equal. A critical issue in stochastic designs is whether to include null events If you wish to estimate the evoked response to a specific event type (as opposed to differential responses) then a null event must be included (even if it is not modeled explicitly).'
''
'In SPM, analysis of data from multiple subjects typically proceeds in two stages using models at two ''levels''. The ''first level'' models are used to implement a within-subject analysis. Typically there will be as many first level models as there are subjects. Analysis proceeds as described using the ''Specify first level'' and ''Estimate'' options. The results of these analyses can then be presented as ''case studies''. More often, however, one wishes to make inferences about the population from which the subjects were drawn. This is an example of a ''Random-Effects (RFX) analysis'' (or, more properly, a mixed-effects analysis). In SPM, RFX analysis is implemented using the ''summary-statistic'' approach where contrast images from each subject are used as summary measures of subject responses. These are then entered as data into a ''second level'' model. '
}';
fmri_design.prog = @spm_run_fmri_design;
fmri_design.vout = @vout_stats;
fmri_design.modality = {'FMRI'};
%-------------------------------------------------------------------------
%------------------------------------------------------------------------
function t = cond_check(job)
t = {};
if (numel(job.onset) ~= numel(job.duration)) && (numel(job.duration)~=1),
t = {sprintf('"%s": Number of event onsets (%d) does not match the number of durations (%d).',...
job.name, numel(job.onset),numel(job.duration))};
end;
for i=1:numel(job.pmod),
if numel(job.onset) ~= numel(job.pmod(i).param),
t = {t{:}, sprintf('"%s" & "%s":Number of event onsets (%d) does not equal the number of parameters (%d).',...
job.name, job.pmod(i).name, numel(job.onset),numel(job.pmod(i).param))};
end;
end;
return;
%-------------------------------------------------------------------------
%-------------------------------------------------------------------------
function t = sess_check(sess)
t = {};
for i=1:numel(sess.regress),
if sess.nscan ~= numel(sess.regress(i).val),
t = {t{:}, sprintf('Num scans (%d) ~= Num regress[%d] (%d).',numel(sess.nscan),i,numel(sess.regress(i).val))};
end;
end;
return;
%-------------------------------------------------------------------------
%-------------------------------------------------------------------------
function dep = vout_stats(job)
dep(1) = cfg_dep;
dep(1).sname = 'SPM.mat File';
dep(1).src_output = substruct('.','spmmat');
dep(1).tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}});
%dep(2) = cfg_dep;
%dep(2).sname = 'SPM Variable';
%dep(2).src_output = substruct('.','spmvar');
%dep(2).tgt_spec = cfg_findspec({{'strtype','e'}});
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_voi.m
|
.m
|
antx-master/xspm8/config/spm_cfg_voi.m
| 14,416 |
utf_8
|
a2ccb5fea6f79b4ec5ddf31f014ce87a
|
function voi = spm_cfg_voi
% SPM Configuration file for VOIs
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Guillaume Flandin
% $Id: spm_cfg_voi.m 4513 2011-10-07 17:26:41Z guillaume $
% -------------------------------------------------------------------------
% spmmat Select SPM.mat
% -------------------------------------------------------------------------
spmmat = cfg_files;
spmmat.tag = 'spmmat';
spmmat.name = 'Select SPM.mat';
spmmat.help = {'Select SPM.mat file. If empty, use the SPM.mat selected above.'};
spmmat.filter = 'mat';
spmmat.ufilter = '^SPM\.mat$';
spmmat.num = [0 1];
spmmat.val = {{''}};
% -------------------------------------------------------------------------
% contrast Contrast
% -------------------------------------------------------------------------
contrast = cfg_entry;
contrast.tag = 'contrast';
contrast.name = 'Contrast';
contrast.help = {'Index of contrast. If more than one index is entered, a conjunction analysis is performed.'};
contrast.strtype = 'e';
contrast.num = [1 Inf];
% -------------------------------------------------------------------------
% conjunction Conjunction Number
% -------------------------------------------------------------------------
conjunction = cfg_entry;
conjunction.tag = 'conjunction';
conjunction.name = 'Conjunction number';
conjunction.help = {'Conjunction number. Unused if a simple contrast is entered.'
'For Conjunction Null, enter 1.'
'For Global Null, enter the number of selected contrasts.'
'For Intermediate, enter the number of selected contrasts minus the number of effects under the Null.'}';
conjunction.strtype = 'e';
conjunction.num = [1 1];
conjunction.val = {1};
% -------------------------------------------------------------------------
% threshdesc Threshold type
% -------------------------------------------------------------------------
threshdesc = cfg_menu;
threshdesc.tag = 'threshdesc';
threshdesc.name = 'Threshold type';
threshdesc.help = {''};
threshdesc.labels = {'FWE' 'none'};
threshdesc.values = {'FWE' 'none'};
threshdesc.val = {'none'};
% -------------------------------------------------------------------------
% thresh Threshold
% -------------------------------------------------------------------------
thresh = cfg_entry;
thresh.tag = 'thresh';
thresh.name = 'Threshold';
thresh.help = {''};
thresh.strtype = 'e';
thresh.num = [1 1];
thresh.val = {0.001};
% -------------------------------------------------------------------------
% extent Extent (voxels)
% -------------------------------------------------------------------------
extent = cfg_entry;
extent.tag = 'extent';
extent.name = 'Extent (voxels)';
extent.help = {''};
extent.strtype = 'e';
extent.num = [1 1];
extent.val = {0};
% -------------------------------------------------------------------------
% contrast Contrast
% -------------------------------------------------------------------------
contrastm = cfg_entry;
contrastm.tag = 'contrast';
contrastm.name = 'Contrast';
contrastm.help = {'Indices of contrast(s).'};
contrastm.strtype = 'e';
contrastm.num = [1 Inf];
% -------------------------------------------------------------------------
% threshm Threshold
% -------------------------------------------------------------------------
threshm = cfg_entry;
threshm.tag = 'thresh';
threshm.name = 'Uncorrected mask p-value';
threshm.help = {''};
threshm.strtype = 'e';
threshm.num = [1 1];
threshm.val = {0.05};
% -------------------------------------------------------------------------
% mtype Nature of mask
% -------------------------------------------------------------------------
mtype = cfg_menu;
mtype.tag = 'mtype';
mtype.name = 'Nature of mask';
mtype.help = {''};
mtype.labels = {'Inclusive' 'Exclusive'};
mtype.values = {0 1};
% -------------------------------------------------------------------------
% mask Mask definition
% -------------------------------------------------------------------------
mask = cfg_branch;
mask.tag = 'mask';
mask.name = 'Mask definition';
mask.val = {contrastm threshm mtype};
mask.help = {''};
% -------------------------------------------------------------------------
% generic Masking
% -------------------------------------------------------------------------
generic = cfg_repeat;
generic.tag = 'generic';
generic.name = 'Masking';
generic.help = {''};
generic.values = {mask};
generic.num = [0 1];
% -------------------------------------------------------------------------
% map Thresholded SPM
% -------------------------------------------------------------------------
map = cfg_branch;
map.tag = 'spm';
map.name = 'Thresholded SPM';
map.val = {spmmat contrast conjunction threshdesc thresh extent generic};
map.help = {'Thresholded SPM'}';
% -------------------------------------------------------------------------
% fix Movement of centre: fixed
% -------------------------------------------------------------------------
fix = cfg_const;
fix.tag = 'fixed';
fix.name = 'Fixed';
fix.val = { 1 };
fix.help = {'Fixed centre'};
% -------------------------------------------------------------------------
% mp SPM index
% -------------------------------------------------------------------------
mp = cfg_entry;
mp.tag = 'spm';
mp.name = 'SPM index';
mp.help = {'SPM index'};
mp.strtype = 'e';
mp.num = [1 1];
% -------------------------------------------------------------------------
% mskexp Expression
% -------------------------------------------------------------------------
mskexp = cfg_entry;
mskexp.tag = 'mask';
mskexp.name = 'Mask expression';
mskexp.help = {'Example expressions (f):'};
mskexp.strtype = 's';
mskexp.num = [0 Inf];
mskexp.val = {''};
% -------------------------------------------------------------------------
% glob Movement of centre: Global maxima
% -------------------------------------------------------------------------
glob = cfg_branch;
glob.tag = 'global';
glob.name = 'Global maxima';
glob.val = { mp mskexp };
glob.help = {'Global maxima'};
% -------------------------------------------------------------------------
% loc Movement of centre: Nearest local maxima
% -------------------------------------------------------------------------
loc = cfg_branch;
loc.tag = 'local';
loc.name = 'Nearest local maxima';
loc.val = { mp mskexp };
loc.help = {'Nearest local maxima'};
% -------------------------------------------------------------------------
% supra Movement of centre: Nearest suprathreshold maxima
% -------------------------------------------------------------------------
supra = cfg_branch;
supra.tag = 'supra';
supra.name = 'Nearest suprathreshold maxima';
supra.val = { mp mskexp };
supra.help = {'Nearest suprathreshold maxima.'};
% -------------------------------------------------------------------------
% mvt Movement of centre
% -------------------------------------------------------------------------
mvt = cfg_choice;
mvt.tag = 'move';
mvt.name = 'Movement of centre';
mvt.help = {'Movement of centre.'};
mvt.values = {fix glob loc supra};
mvt.val = { fix };
% -------------------------------------------------------------------------
% centre Centre of Sphere/Box
% -------------------------------------------------------------------------
centre = cfg_entry;
centre.tag = 'centre';
centre.name = 'Centre';
centre.help = {'Centre [x y z] {mm}.'};
centre.strtype = 'e';
centre.num = [1 3];
% -------------------------------------------------------------------------
% radius Radius of Sphere
% -------------------------------------------------------------------------
radius = cfg_entry;
radius.tag = 'radius';
radius.name = 'Radius';
radius.help = {'Sphere radius (mm).'};
radius.strtype = 'e';
radius.num = [1 1];
% -------------------------------------------------------------------------
% sphere Sphere
% -------------------------------------------------------------------------
sphere = cfg_branch;
sphere.tag = 'sphere';
sphere.name = 'Sphere';
sphere.val = {centre radius mvt};
sphere.help = {'Sphere.'}';
% -------------------------------------------------------------------------
% dim Box Dimension
% -------------------------------------------------------------------------
dim = cfg_entry;
dim.tag = 'dim';
dim.name = 'Dimensions';
dim.help = {'Box dimensions [x y z] {mm}.'};
dim.strtype = 'e';
dim.num = [1 3];
% -------------------------------------------------------------------------
% box Box
% -------------------------------------------------------------------------
box = cfg_branch;
box.tag = 'box';
box.name = 'Box';
box.val = {centre dim mvt};
box.help = {'Box.'}';
% -------------------------------------------------------------------------
% image Image
% -------------------------------------------------------------------------
image = cfg_files;
image.tag = 'image';
image.name = 'Image file';
image.help = {'Select image.'};
image.filter = 'image';
image.ufilter = '.*';
image.num = [1 1];
% -------------------------------------------------------------------------
% threshold Threshold
% -------------------------------------------------------------------------
threshold = cfg_entry;
threshold.tag = 'threshold';
threshold.name = 'Threshold';
threshold.help = {'Threshold.'};
threshold.strtype = 'e';
threshold.num = [1 1];
threshold.val = {0.5};
% -------------------------------------------------------------------------
% mask Mask
% -------------------------------------------------------------------------
mask = cfg_branch;
mask.tag = 'mask';
mask.name = 'Mask Image';
mask.val = {image threshold};
mask.help = {'Mask Image.'}';
% -------------------------------------------------------------------------
% list List of labels
% -------------------------------------------------------------------------
list = cfg_entry;
list.tag = 'list';
list.name = 'List of labels';
list.help = {'List of labels.'};
list.strtype = 'e';
list.num = [1 Inf];
% -------------------------------------------------------------------------
% label Label Image
% -------------------------------------------------------------------------
label = cfg_branch;
label.tag = 'label';
label.name = 'Label Image';
label.val = {image list};
label.help = {'Label Image.'}';
% -------------------------------------------------------------------------
% roi ROI
% -------------------------------------------------------------------------
roi = cfg_repeat;
roi.tag = 'roi';
roi.name = 'Region(s) of Interest';
roi.help = {'Region(s) of Interest'};
roi.values = {map sphere box mask label};
roi.num = [1 Inf];
% -------------------------------------------------------------------------
% expression Expression
% -------------------------------------------------------------------------
expression = cfg_entry;
expression.tag = 'expression';
expression.name = 'Expression';
expression.help = {['Expression to be evaluated, using i1, i2, ...',...
'and logical operators (&, |, ~)']};
expression.strtype = 's';
expression.num = [2 Inf];
% -------------------------------------------------------------------------
% spmmat Select SPM.mat
% -------------------------------------------------------------------------
spmmat = cfg_files;
spmmat.tag = 'spmmat';
spmmat.name = 'Select SPM.mat';
spmmat.help = {'Select SPM.mat file'};
spmmat.filter = 'mat';
spmmat.ufilter = '^SPM\.mat$';
spmmat.num = [1 1];
% -------------------------------------------------------------------------
% adjust Contrast used to adjust data
% -------------------------------------------------------------------------
adjust = cfg_entry;
adjust.tag = 'adjust';
adjust.name = 'Adjust data';
adjust.help = {'Index of F-contrast used to adjust data. Enter ''0'' for no adjustment. Enter ''NaN'' for adjusting for everything.'}';
adjust.strtype = 'e';
adjust.num = [1 1];
% -------------------------------------------------------------------------
% session Session index
% -------------------------------------------------------------------------
session = cfg_entry;
session.tag = 'session';
session.name = 'Which session';
session.help = {'Enter the session number from which you want to extract data.'}';
session.strtype = 'e';
session.num = [1 1];
% -------------------------------------------------------------------------
% name Name of VOI
% -------------------------------------------------------------------------
name = cfg_entry;
name.tag = 'name';
name.name = 'Name of VOI';
name.help = {['Name of the VOI mat file that will be saved in the ' ...
'same directory than the SPM.mat file. A ''VOI_'' prefix will be added. ' ...
'' ...
'A binary NIfTI image of the VOI will also be saved.']};
name.strtype = 's';
name.num = [1 Inf];
% -------------------------------------------------------------------------
% voi VOI
% -------------------------------------------------------------------------
voi = cfg_exbranch;
voi.tag = 'voi';
voi.name = 'Volume of Interest';
voi.val = {spmmat adjust session name roi expression};
voi.help = {' VOI time-series extraction of adjusted data (& local eigenimage analysis).'};
voi.prog = @spm_run_voi;
voi.vout = @vout_voi;
%--------------------------------------------------------------------------
%--------------------------------------------------------------------------
function dep = vout_voi(varargin)
dep(1) = cfg_dep;
dep(1).sname = ' VOI mat File';
dep(1).src_output = substruct('.','voimat');
dep(1).tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}});
dep(2) = cfg_dep;
dep(2).sname = ' VOI Image File';
dep(2).src_output = substruct('.','voiimg');
dep(2).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_defs.m
|
.m
|
antx-master/xspm8/config/spm_cfg_defs.m
| 12,082 |
utf_8
|
d7106895556ec79d85dcffa5211d3048
|
function conf = spm_cfg_defs
% Configuration file for deformation jobs.
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_cfg_defs.m 4136 2010-12-09 22:22:28Z guillaume $
hsummary = {[...
'This is a utility for working with deformation fields. ',...
'They can be loaded, inverted, combined etc, and the results ',...
'either saved to disk, or applied to some image.']};
hinv = {[...
'Creates the inverse of a deformation field. ',...
'Deformations are assumed to be one-to-one, in which case they ',...
'have a unique inverse. If y'':A->B is the inverse of y:B->A, then ',...
'y'' o y = y o y'' = Id, where Id is the identity transform.'],...
'',...
'Deformations are inverted using the method described in the appendix of:',...
[' * Ashburner J, Andersson JLR & Friston KJ (2000) ',...
'"Image Registration using a Symmetric Prior - in Three-Dimensions." ',...
'Human Brain Mapping 9(4):212-225']};
hcomp = {[...
'Deformation fields can be thought of as mappings. ',...
'These can be combined by the operation of "composition", which is ',...
'usually denoted by a circle "o". ',...
'Suppose x:A->B and y:B->C are two mappings, where A, B and C refer ',...
'to domains in 3 dimensions. ',...
'Each element a in A points to element x(a) in B. ',...
'This in turn points to element y(x(a)) in C, so we have a mapping ',...
'from A to C. ',...
'The composition of these mappings is denoted by yox:A->C. ',...
'Compositions can be combined in an associative way, such that zo(yox) = (zoy)ox.'],...
'',[...
'In this utility, the left-to-right order of the compositions is ',...
'from top to bottom (note that the rightmost deformation would ',...
'actually be applied first). ',...
'i.e. ...((first o second) o third)...o last. The resulting deformation field will ',...
'have the same domain as the first deformation specified, and will map ',...
'to voxels in the codomain of the last specified deformation field.']};
hsn = {[...
'Spatial normalisation, and the unified segmentation model of ',...
'SPM5 save a parameterisation of deformation fields. These consist ',...
'of a combination of an affine transform, and nonlinear warps that ',...
'are parameterised by a linear combination of cosine transform ',...
'basis functions. These are saved in *_sn.mat files, which can be ',...
'converted to deformation fields.']};
hvox = {[...
'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.']};
hbb = {[...
'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.']};
himgr = {[...
'Deformations can be thought of as vector fields. These can be represented ',...
'by three-volume images.']};
himgw = {[...
'Save the result as a three-volume image. "y_" will be prepended to the ',...
'filename. The result will be written to the current directory.']};
happly = {[...
'Apply the resulting deformation field to some images. ',...
'The warped images will be written to the current directory, and the ',...
'filenames prepended by "w". Note that trilinear interpolation is used ',...
'to resample the data, so the original values in the images will ',...
'not be preserved.']};
hmatname = {...
'Specify the _sn.mat to be used.'};
himg = {...
'Specify the image file on which to base the dimensions, orientation etc.'};
hid = {[...
'This option generates an identity transform, but this can be useful for ',...
'changing the dimensions of the resulting deformation (and any images that ',...
'are generated from it). Dimensions, orientation etc are derived from ',...
'an image.']};
def = files('Deformation Field','def','.*y_.*\.nii$',[1 1]);
def.help = himgr;
matname = files('Parameter File','matname','.*_sn\.mat$',[1 1]);
matname.help = hmatname;
vox = entry('Voxel sizes','vox','e',[1 3]);
vox.val = {[NaN NaN NaN]};
vox.help = hvox;
bb = entry('Bounding box','bb','e',[2 3]);
bb.val = {[NaN NaN NaN;NaN NaN NaN]};
bb.help = hbb;
sn2def = branch('Imported _sn.mat','sn2def',{matname,vox,bb});
sn2def.help = hsn;
img = files('Image to base Id on','space','image',[1 1]);
img.help = himg;
id = branch('Identity (Reference Image)','id',{img});
id.help = hid;
voxid = entry('Voxel sizes','vox','e',[1 3]);
bbid = entry('Bounding box','bb','e',[2 3]);
idbbvox = branch('Identity (Bounding Box and Voxel Size)','idbbvox',{voxid, bbid});
id.help = hid;
ffield = files('Flow field','flowfield','nifti',[1 1]);
ffield.ufilter = '^u_.*';
ffield.help = {...
['The flow field stores the deformation information. '...
'The same field can be used for both forward or backward deformations '...
'(or even, in principle, half way or exaggerated deformations).']};
%------------------------------------------------------------------------
forbak = mnu('Forward/Backwards','times',{'Backward','Forward'},{[1 0],[0 1]});
forbak.val = {[1 0]};
forbak.help = {[...
'The direction of the DARTEL flow. '...
'Note that a backward transform will warp an individual subject''s '...
'to match the template (ie maps from template to individual). '...
'A forward transform will warp the template image to the individual.']};
%------------------------------------------------------------------------
K = mnu('Time Steps','K',...
{'1','2','4','8','16','32','64','128','256','512'},...
{0,1,2,3,4,5,6,7,8,9});
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.']};
%------------------------------------------------------------------------
drtl = branch('DARTEL flow','dartel',{ffield,forbak,K});
drtl.help = {'Imported DARTEL flow field.'};
%------------------------------------------------------------------------
other = {sn2def,drtl,def,id,idbbvox};
img = files('Image to base inverse on','space','image',[1 1]);
img.help = himg;
comp0 = repeat('Composition','comp',other);
comp0.help = hcomp;
iv0 = branch('Inverse','inv',{comp0,img});
iv0.help = hinv;
comp1 = repeat('Composition','comp',{other{:},iv0,comp0});
comp1.num = [1 Inf];
comp1.help = hcomp;
iv1 = branch('Inverse','inv',{comp1,img});
iv1.help = hinv;
comp2 = repeat('Composition','comp',{other{:},iv1,comp1});
comp2.num = [1 Inf];
comp2.help = hcomp;
iv2 = branch('Inverse','inv',{comp2,img});
iv2.help = hinv;
comp = repeat('Composition','comp',{other{:},iv2,comp2});
comp.num = [1 Inf];
comp.help = hcomp;
saveas = entry('Save as','ofname','s',[0 Inf]);
saveas.val = {''};
saveas.help = himgw;
applyto = files('Apply to','fnames','image',[0 Inf]);
applyto.val = {''};
applyto.help = happly;
savepwd = cfg_const;
savepwd.name = 'Current directory';
savepwd.tag = 'savepwd';
savepwd.val = {1};
savepwd.help = {['All created files (deformation fields and warped images) ' ...
'are written to the current directory.']};
savesrc = cfg_const;
savesrc.name = 'Source directories';
savesrc.tag = 'savesrc';
savesrc.val = {1};
savesrc.help = {['The combined deformation field is written into the ' ...
'directory of the first deformation field, warped images ' ...
'are written to the same directories as the source ' ...
'images.']};
savedef = cfg_const;
savedef.name = 'Source directory (deformation)';
savedef.tag = 'savedef';
savedef.val = {1};
savedef.help = {['The combined deformation field and the warped images ' ...
'are written into the directory of the first deformation ' ...
'field.']};
saveusr = files('Output directory','saveusr','dir',[1 1]);
saveusr.help = {['The combined deformation field and the warped images ' ...
'are written into the specified directory.']};
savedir = cfg_choice;
savedir.name = 'Output destination';
savedir.tag = 'savedir';
savedir.values = {savepwd savesrc savedef saveusr};
savedir.val = {savepwd};
interp = cfg_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'};
interp.values = {0,1,2,3,4,5,6,7};
interp.def = @(val)spm_get_defaults('normalise.write.interp',val{:});
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).']
}';
conf = exbranch('Deformations','defs',{comp,saveas,applyto,savedir,interp});
conf.prog = @spm_defs;
conf.vout = @vout;
conf.help = hsummary;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function vo = vout(job)
vo = [];
if ~isempty(job.ofname) && ~isequal(job.ofname,'<UNDEFINED>')
vo = cfg_dep;
vo.sname = 'Combined deformation';
vo.src_output = substruct('.','def');
vo.tgt_spec = cfg_findspec({{'filter','image','filter','nifti'}});
end
if ~isempty(job.fnames) && ~isequal(job.fnames, {''})
if isempty(vo), vo = cfg_dep; else vo(end+1) = cfg_dep; end
vo(end).sname = 'Warped images';
vo(end).src_output = substruct('.','warped');
vo(end).tgt_spec = cfg_findspec({{'filter','image'}});
end
return;
%_______________________________________________________________________
%_______________________________________________________________________
function entry_item = entry(name, tag, strtype, num)
entry_item = cfg_entry;
entry_item.name = name;
entry_item.tag = tag;
entry_item.strtype = strtype;
entry_item.num = num;
function files_item = files(name, tag, fltr, num)
files_item = cfg_files;
files_item.name = name;
files_item.tag = tag;
files_item.filter = fltr;
files_item.num = num;
function branch_item = branch(name, tag, val)
branch_item = cfg_branch;
branch_item.name = name;
branch_item.tag = tag;
branch_item.val = val;
function exbranch_item = exbranch(name, tag, val)
exbranch_item = cfg_exbranch;
exbranch_item.name = name;
exbranch_item.tag = tag;
exbranch_item.val = val;
function repeat_item = repeat(name, tag, values)
repeat_item = cfg_repeat;
repeat_item.name = name;
repeat_item.tag = tag;
repeat_item.values = values;
function menu_item = mnu(name, tag, labels, values)
menu_item = cfg_menu;
menu_item.name = name;
menu_item.tag = tag;
menu_item.labels = labels;
menu_item.values = values;
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_coreg.m
|
.m
|
antx-master/xspm8/config/spm_cfg_coreg.m
| 15,295 |
utf_8
|
d33c81d106b8fca36404ed99f363be34
|
function coreg = spm_cfg_coreg
% SPM Configuration file for Coregister
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% $Id: spm_cfg_coreg.m 4380 2011-07-05 11:27:12Z volkmar $
% ---------------------------------------------------------------------
% ref Reference Image
% ---------------------------------------------------------------------
ref = cfg_files;
ref.tag = 'ref';
ref.name = 'Reference Image';
ref.help = {'This is the image that is assumed to remain stationary (sometimes known as the target or template image), while the source image is moved to match it.'};
ref.filter = 'image';
ref.ufilter = '.*';
ref.num = [1 1];
% ---------------------------------------------------------------------
% source Source Image
% ---------------------------------------------------------------------
source = cfg_files;
source.tag = 'source';
source.name = 'Source Image';
source.help = {'This is the image that is jiggled about to best match the reference.'};
source.filter = 'image';
source.ufilter = '.*';
source.num = [1 1];
% ---------------------------------------------------------------------
% other Other Images
% ---------------------------------------------------------------------
other = cfg_files;
other.tag = 'other';
other.name = 'Other Images';
other.val = {{''}};
other.help = {'These are any images that need to remain in alignment with the source image.'};
other.filter = 'image';
other.ufilter = '.*';
other.num = [0 Inf];
% ---------------------------------------------------------------------
% cost_fun Objective Function
% ---------------------------------------------------------------------
cost_fun = cfg_menu;
cost_fun.tag = 'cost_fun';
cost_fun.name = 'Objective Function';
cost_fun.help = {'Registration involves finding parameters that either maximise or minimise some objective function. For inter-modal registration, use Mutual Information/* \cite{collignon95,wells96}*/, Normalised Mutual Information/* \cite{studholme99}*/, or Entropy Correlation Coefficient/* \cite{maes97}*/.For within modality, you could also use Normalised Cross Correlation.'};
cost_fun.labels = {
'Mutual Information'
'Normalised Mutual Information'
'Entropy Correlation Coefficient'
'Normalised Cross Correlation'
}';
cost_fun.values = {
'mi'
'nmi'
'ecc'
'ncc'
}';
cost_fun.def = @(val)spm_get_defaults('coreg.estimate.cost_fun', val{:});
% ---------------------------------------------------------------------
% sep Separation
% ---------------------------------------------------------------------
sep = cfg_entry;
sep.tag = 'sep';
sep.name = 'Separation';
sep.help = {'The average distance between sampled points (in mm). Can be a vector to allow a coarse registration followed by increasingly fine ones.'};
sep.strtype = 'e';
sep.num = [1 Inf];
sep.def = @(val)spm_get_defaults('coreg.estimate.sep', val{:});
% ---------------------------------------------------------------------
% tol Tolerances
% ---------------------------------------------------------------------
tol = cfg_entry;
tol.tag = 'tol';
tol.name = 'Tolerances';
tol.help = {'The accuracy for each parameter. Iterations stop when differences between successive estimates are less than the required tolerance.'};
tol.strtype = 'e';
tol.num = [1 12];
tol.def = @(val)spm_get_defaults('coreg.estimate.tol', val{:});
% ---------------------------------------------------------------------
% fwhm Histogram Smoothing
% ---------------------------------------------------------------------
fwhm = cfg_entry;
fwhm.tag = 'fwhm';
fwhm.name = 'Histogram Smoothing';
fwhm.help = {'Gaussian smoothing to apply to the 256x256 joint histogram. Other information theoretic coregistration methods use fewer bins, but Gaussian smoothing seems to be more elegant.'};
fwhm.strtype = 'e';
fwhm.num = [1 2];
fwhm.def = @(val)spm_get_defaults('coreg.estimate.fwhm', val{:});
% ---------------------------------------------------------------------
% eoptions Estimation Options
% ---------------------------------------------------------------------
eoptions = cfg_branch;
eoptions.tag = 'eoptions';
eoptions.name = 'Estimation Options';
eoptions.val = {cost_fun sep tol fwhm };
eoptions.help = {'Various registration options, which are passed to the Powell optimisation algorithm/* \cite{press92}*/.'};
% ---------------------------------------------------------------------
% estimate Coreg: Estimate
% ---------------------------------------------------------------------
estimate = cfg_exbranch;
estimate.tag = 'estimate';
estimate.name = 'Coregister: Estimate';
estimate.val = {ref source other eoptions };
estimate.help = {
'The registration method used here is based on work by Collignon et al/* \cite{collignon95}*/. The original interpolation method described in this paper has been changed in order to give a smoother cost function. The images are also smoothed slightly, as is the histogram. This is all in order to make the cost function as smooth as possible, to give faster convergence and less chance of local minima.'
''
'At the end of coregistration, the voxel-to-voxel affine transformation matrix is displayed, along with the histograms for the images in the original orientations, and the final orientations. The registered images are displayed at the bottom.'
''
'Registration parameters are stored in the headers of the "source" and the "other" images.'
}';
estimate.prog = @spm_run_coreg_estimate;
estimate.vout = @vout_estimate;
% ---------------------------------------------------------------------
% ref Image Defining Space
% ---------------------------------------------------------------------
refwrite = cfg_files;
refwrite.tag = 'ref';
refwrite.name = 'Image Defining Space';
refwrite.help = {'This is analogous to the reference image. Images are resliced to match this image (providing they have been coregistered first).'};
refwrite.filter = 'image';
refwrite.ufilter = '.*';
refwrite.num = [1 1];
% ---------------------------------------------------------------------
% source Images to Reslice
% ---------------------------------------------------------------------
source = cfg_files;
source.tag = 'source';
source.name = 'Images to Reslice';
source.help = {'These images are resliced to the same dimensions, voxel sizes, orientation etc as the space defining image.'};
source.filter = 'image';
source.ufilter = '.*';
source.num = [1 Inf];
% ---------------------------------------------------------------------
% interp Interpolation
% ---------------------------------------------------------------------
interp = cfg_menu;
interp.tag = 'interp';
interp.name = 'Interpolation';
interp.help = {'The method by which the images are sampled when being written in a different space. Nearest Neighbour is fastest, but not normally recommended. It can be useful for re-orienting images while preserving the original intensities (e.g. an image consisting of labels). Bilinear Interpolation is OK for PET, or realigned and re-sliced fMRI. If subject movement (from an fMRI time series) is included in the transformations then it may be better to use a higher degree approach. Note that higher degree B-spline interpolation/* \cite{thevenaz00a,unser93a,unser93b}*/ is slower because it uses more neighbours.'};
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};
interp.def = @(val)spm_get_defaults('coreg.write.interp', val{:});
% ---------------------------------------------------------------------
% wrap Wrapping
% ---------------------------------------------------------------------
wrap = cfg_menu;
wrap.tag = 'wrap';
wrap.name = 'Wrapping';
wrap.help = {
'These are typically:'
' No wrapping - for PET or images that have already been spatially transformed.'
' Wrap in Y - for (un-resliced) MRI where phase encoding is in the Y direction (voxel space).'
}';
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('coreg.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('coreg.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 resliced image file(s). Default prefix is ''r''.'};
prefix.strtype = 's';
prefix.num = [1 Inf];
prefix.def = @(val)spm_get_defaults('coreg.write.prefix', val{:});
% ---------------------------------------------------------------------
% roptions Reslice Options
% ---------------------------------------------------------------------
roptions = cfg_branch;
roptions.tag = 'roptions';
roptions.name = 'Reslice Options';
roptions.val = {interp wrap mask prefix };
roptions.help = {'Various reslicing options.'};
% ---------------------------------------------------------------------
% write Coreg: Reslice
% ---------------------------------------------------------------------
write = cfg_exbranch;
write.tag = 'write';
write.name = 'Coregister: Reslice';
write.val = {refwrite source roptions };
write.help = {'Reslice images to match voxel-for-voxel with an image defining some space. The resliced images are named the same as the originals except that they are prefixed by ''r''.'};
write.prog = @spm_run_coreg_reslice;
write.vout = @vout_reslice;
% ---------------------------------------------------------------------
% source Source Image
% ---------------------------------------------------------------------
source = cfg_files;
source.tag = 'source';
source.name = 'Source Image';
source.help = {'This is the image that is jiggled about to best match the reference.'};
source.filter = 'image';
source.ufilter = '.*';
source.num = [1 1];
% ---------------------------------------------------------------------
% estwrite Coreg: Estimate & Reslice
% ---------------------------------------------------------------------
estwrite = cfg_exbranch;
estwrite.tag = 'estwrite';
estwrite.name = 'Coregister: Estimate & Reslice';
estwrite.val = {ref source other eoptions roptions };
estwrite.help = {
'The registration method used here is based on work by Collignon et al/* \cite{collignon95}*/. The original interpolation method described in this paper has been changed in order to give a smoother cost function. The images are also smoothed slightly, as is the histogram. This is all in order to make the cost function as smooth as possible, to give faster convergence and less chance of local minima.'
''
'At the end of coregistration, the voxel-to-voxel affine transformation matrix is displayed, along with the histograms for the images in the original orientations, and the final orientations. The registered images are displayed at the bottom.'
''
'Registration parameters are stored in the headers of the "source" and the "other" images. These images are also resliced to match the source image voxel-for-voxel. The resliced images are named the same as the originals except that they are prefixed by ''r''.'
}';
estwrite.prog = @spm_run_coreg_estwrite;
estwrite.vout = @vout_estwrite;
% ---------------------------------------------------------------------
% coreg Coreg
% ---------------------------------------------------------------------
coreg = cfg_choice;
coreg.tag = 'coreg';
coreg.name = 'Coregister';
coreg.help = {
'Within-subject registration using a rigid-body model. A rigid-body transformation (in 3D) can be parameterised by three translations and three rotations about the different axes.'
''
'You get the options of estimating the transformation, reslicing images according to some rigid-body transformations, or estimating and applying rigid-body transformations.'
}';
coreg.values = {estimate write estwrite };
%coreg.num = [1 Inf];
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function dep = vout_estimate(job)
dep(1) = cfg_dep;
dep(1).sname = 'Coregistered Images';
dep(1).src_output = substruct('.','cfiles');
dep(1).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
dep(2) = cfg_dep;
dep(2).sname = 'Coregistration Matrix';
dep(2).src_output = substruct('.','M');
dep(2).tgt_spec = cfg_findspec({{'strtype','r'}});
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function dep = vout_reslice(job)
dep(1) = cfg_dep;
dep(1).sname = 'Resliced Images';
dep(1).src_output = substruct('.','rfiles');
dep(1).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function dep = vout_estwrite(job)
depe = vout_estimate(job);
depc = vout_reslice(job);
dep = [depe depc];
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_spm_surf.m
|
.m
|
antx-master/xspm8/config/spm_cfg_spm_surf.m
| 3,180 |
utf_8
|
bfb0cbe3b4a7af4aec50af905110631c
|
function spm_surf_node = spm_cfg_spm_surf
% SPM Configuration file
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% $Id: spm_cfg_spm_surf.m 3081 2009-04-22 20:15:38Z guillaume $
rev = '$Rev: 3081 $';
% ---------------------------------------------------------------------
% data Grey+white matter image
% ---------------------------------------------------------------------
data = cfg_files;
data.tag = 'data';
data.name = 'Grey and white matter images';
data.help = {'Images to create rendering/surface from (grey and white matter segments).'};
data.filter = 'image';
data.ufilter = '.*';
data.num = [1 Inf];
% ---------------------------------------------------------------------
% mode Output
% ---------------------------------------------------------------------
mode = cfg_menu;
mode.tag = 'mode';
mode.name = 'Output';
mode.help = {''};
mode.labels = {'Save Rendering'
'Save Extracted Surface'
'Save Rendering and Surface'}';
mode.values = {1 2 3};
mode.val = {3};
% ---------------------------------------------------------------------
% thresh Surface isovalue(s)
% ---------------------------------------------------------------------
thresh = cfg_entry;
thresh.tag = 'thresh';
thresh.name = 'Surface isovalue(s)';
thresh.help = {'Enter one or more values at which isosurfaces through the input images will be computed.'};
thresh.strtype = 'e';
thresh.val = {0.5};
thresh.num = [1 Inf];
% ---------------------------------------------------------------------
% spm_surf Create Rendering/Surface
% ---------------------------------------------------------------------
spm_surf_node = cfg_exbranch;
spm_surf_node.tag = 'spm_surf';
spm_surf_node.name = 'Create Rendering/Surface';
spm_surf_node.val = { data mode thresh};
spm_surf_node.help = {''};
spm_surf_node.prog = @spm_surf;
spm_surf_node.vout = @vout_surf;
% ---------------------------------------------------------------------
%
% ---------------------------------------------------------------------
function dep = vout_surf(job)
% fail silently, if job.mode or job.thresh can not be evaluated
try
cdep = 1;
if any(job.mode==[1 3]),
dep(cdep) = cfg_dep;
dep(cdep).sname = 'Render .mat File';
dep(cdep).src_output = substruct('.','rendfile');
dep(cdep).tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}});
cdep = cdep+1;
end
if any(job.mode==[2 3]),
for k=1:numel(job.thresh)
if any(job.mode==[2 3]),
dep(cdep) = cfg_dep;
dep(cdep).sname = sprintf('Surface .gii File (thr=%.02f)', ...
job.thresh(k));
dep(cdep).src_output = substruct('.','surffile', '()',{k});
dep(cdep).tgt_spec = cfg_findspec({{'filter','mesh','strtype','e'}});
cdep = cdep+1;
end
end
end
catch
% something failed, no dependencies
dep = [];
end
|
github
|
philippboehmsturm/antx-master
|
spm_run_voi.m
|
.m
|
antx-master/xspm8/config/spm_run_voi.m
| 7,634 |
utf_8
|
028d2bd9767100793c0c5af2426d1a0b
|
function out = spm_run_voi(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.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Guillaume Flandin
% $Id: spm_run_voi.m 4269 2011-03-29 16:03:43Z guillaume $
fprintf('## Note: this VOI facility is in a beta version. ##\n');
fprintf('## Interface and features might change in the future. ##\n');
%-Load SPM.mat
%--------------------------------------------------------------------------
swd = spm_str_manip(job.spmmat{1},'H');
load(fullfile(swd,'SPM.mat'));
SPM.swd = swd;
%-Initialise VOI voxels coordinates
%--------------------------------------------------------------------------
[x,y,z] = ndgrid(1:SPM.xVol.DIM(1),1:SPM.xVol.DIM(2),1:SPM.xVol.DIM(3));
XYZ = [x(:),y(:),z(:)]'; clear x y z
XYZmm = SPM.xVol.M(1:3,:) * [XYZ;ones(1,size(XYZ,2))];
%-Estimate VOIs
%--------------------------------------------------------------------------
voi = cell(1,numel(job.roi));
for i=1:numel(job.roi)
voi = roi_estim(XYZmm,i,job,SPM,voi);
end
%-Evaluate resulting VOI
%--------------------------------------------------------------------------
voi = roi_eval(voi,job.expression);
%-Save VOI as image
%--------------------------------------------------------------------------
V = struct('fname', fullfile(swd, ['VOI_' job.name '.' spm_get_defaults('images.format')]), ...
'dim', SPM.xVol.DIM', ...
'dt', [spm_type('uint8') spm_platform('bigend')], ...
'mat', SPM.xVol.M, ...
'pinfo', [1 0 0]', ...
'descrip', 'VOI');
V = spm_create_vol(V);
for i=1:V.dim(3)
V = spm_write_plane(V,voi(:,:,i),i);
end
%-Extract VOI time-series
%--------------------------------------------------------------------------
xY.name = job.name;
xY.Ic = job.adjust;
xY.Sess = job.session;
xY.xyz = []'; % irrelevant here
xY.def = 'mask';
xY.spec = V;
xSPM.XYZmm = XYZmm;
xSPM.XYZ = XYZ;
xSPM.M = SPM.xVol.M; % irrelevant here
if ~isempty(xY.Ic), cwd = pwd; cd(SPM.swd); end % to find beta images
[Y,xY] = spm_regions(xSPM,SPM,[],xY);
if ~isempty(xY.Ic), cd(cwd); end
%-Export results
%--------------------------------------------------------------------------
assignin('base','Y',Y);
assignin('base','xY',xY);
if isfield(SPM,'Sess'), s = sprintf('_%i',xY.Sess); else s = ''; end
out.voimat = cellstr(fullfile(swd,['VOI_' job.name s '.mat']));
out.voiimg = cellstr(V.fname);
%==========================================================================
function voi = roi_estim(xyz,n,job,SPM,voi)
if ~isempty(voi{n}), return; end
voi{n} = false(SPM.xVol.DIM');
Q = ones(1,size(xyz,2));
switch char(fieldnames(job.roi{n}))
case 'sphere'
%----------------------------------------------------------------------
c = get_centre(xyz,n,job,SPM,voi);
r = job.roi{n}.sphere.radius;
voi{n}(sum((xyz - c*Q).^2) <= r^2) = true;
case 'box'
%----------------------------------------------------------------------
c = get_centre(xyz,n,job,SPM,voi);
d = job.roi{n}.box.dim(:);
voi{n}(all(abs(xyz - c*Q) <= d*Q/2)) = true;
case 'spm'
%----------------------------------------------------------------------
if isempty(job.roi{n}.spm.spmmat{1})
job.roi{n}.spm.spmmat = job.spmmat;
end
[SPM1,xSPM] = getSPM(job.roi{n}.spm);
voi1 = zeros(SPM1.xVol.DIM');
voi1(sub2ind(SPM1.xVol.DIM',xSPM.XYZ(1,:),xSPM.XYZ(2,:),xSPM.XYZ(3,:))) = 1;
XYZ = SPM1.xVol.iM(1:3,:)*[xyz; Q];
voi{n}(spm_sample_vol(voi1, XYZ(1,:), XYZ(2,:), XYZ(3,:),0) > 0) = true;
case 'mask'
%----------------------------------------------------------------------
v = spm_vol(job.roi{n}.mask.image{1});
t = job.roi{n}.mask.threshold;
iM = inv(v.mat);
XYZ = iM(1:3,:)*[xyz; Q];
voi{n}(spm_sample_vol(v, XYZ(1,:), XYZ(2,:), XYZ(3,:),0) > t) = true;
case 'label'
%----------------------------------------------------------------------
v = spm_vol(job.roi{n}.label.image{1});
l = job.roi{n}.label.list;
iM = inv(v.mat);
XYZ = iM(1:3,:)*[xyz; Q];
voi{n}(ismember(spm_sample_vol(v, XYZ(1,:), XYZ(2,:), XYZ(3,:),0),l)) = true;
end
%==========================================================================
function voi = roi_eval(voi,expr)
for i=1:numel(voi)
eval(sprintf('i%d=voi{%d};',i,i));
end
try
eval(['voi=' expr ';']);
catch
error('The expression cannot be evaluated.');
end
%==========================================================================
function idx = roi_expr(expr)
e = regexp(expr,'i\d+','match');
idx = zeros(1,numel(e));
for i=1:numel(e)
idx(i) = str2num(e{i}(2:end));
end
%==========================================================================
function [SPM, xSPM] = getSPM(s)
xSPM.swd = spm_str_manip(s.spmmat{1},'H');
xSPM.Ic = s.contrast;
xSPM.n = s.conjunction;
xSPM.u = s.thresh;
xSPM.thresDesc = s.threshdesc;
xSPM.k = s.extent;
xSPM.title = '';
xSPM.Im = [];
if ~isempty(s.mask)
xSPM.Im = s.mask.contrast;
xSPM.pm = s.mask.thresh;
xSPM.Ex = s.mask.mtype;
end
[SPM,xSPM] = spm_getSPM(xSPM);
%==========================================================================
function c = get_centre(xyz,n,job,SPM,voi)
t = char(fieldnames(job.roi{n}));
c = job.roi{n}.(t).centre(:);
mv = char(fieldnames(job.roi{n}.(t).move));
if strcmp(mv,'fixed'), return; end
m = job.roi{n}.(t).move.(mv).spm;
e = job.roi{n}.(t).move.(mv).mask;
k = union(roi_expr(e), m);
for i=1:numel(k)
voi = roi_estim(xyz,k(i),job,SPM,voi);
end
try
if isempty(job.roi{m}.spm.spmmat{1})
job.roi{m}.spm.spmmat = job.spmmat;
end
catch
error('The SPM index does not correspond to a Thresholded SPM ROI.');
end
[mySPM, xSPM] = getSPM(job.roi{m}.spm);
XYZmm = xSPM.XYZmm;
XYZ = SPM.xVol.iM(1:3,:)*[XYZmm;ones(1,size(XYZmm,2))];
Z = xSPM.Z;
if ~isempty(e)
R = spm_sample_vol(uint8(roi_eval(voi,e)), ...
XYZ(1,:), XYZ(2,:), XYZ(3,:),0) > 0;
XYZ = XYZ(:,R);
XYZmm = xSPM.XYZmm(:,R);
Z = xSPM.Z(R);
end
[N, Z, M] = spm_max(Z,XYZ);
if isempty(Z)
warning('No voxel survived. Default to user-specified centre.');
return
end
str = '[%3.0f %3.0f %3.0f]';
switch mv
case 'global'
[i,j] = max(Z);
nc = SPM.xVol.M(1:3,:)*[M(:,j);1];
str = sprintf(['centre moved to global maxima ' str],nc);
case 'local'
XYZmm = SPM.xVol.M(1:3,:)*[M;ones(1,size(M,2))];
nc = spm_XYZreg('NearestXYZ',c,XYZmm);
str = sprintf(['centre moved from ' str ' to ' str],c,nc);
case 'supra'
nc = spm_XYZreg('NearestXYZ',c,XYZmm);
str = sprintf(['centre moved from ' str ' to ' str],c,nc);
otherwise
error(sprintf('Unknown option: ''%s''.',mv));
end
c = nc;
fprintf([' ' upper(t(1)) t(2:end) ' ' str '\n']); %-#
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_eeg_merge.m
|
.m
|
antx-master/xspm8/config/spm_cfg_eeg_merge.m
| 2,920 |
utf_8
|
5724987e1f048f63b75ae6f68520be28
|
function S = spm_cfg_eeg_merge
% configuration file for merging of M/EEG files
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Stefan Kiebel, Volkmar Glauche
% $Id: spm_cfg_eeg_merge.m 3881 2010-05-07 21:02:57Z vladimir $
rev = '$Rev: 3881 $';
D = cfg_files;
D.tag = 'D';
D.name = 'File Names';
D.filter = 'mat';
D.num = [2 Inf];
D.help = {'Select the M/EEG mat files.'};
file = cfg_entry;
file.tag = 'file';
file.name = 'Files to which the rule applies';
file.strtype = 's';
file.val = {'.*'};
file.help = {'Regular expression to match the files to which the rule applies (default - all)'};
labelorg = cfg_entry;
labelorg.tag = 'labelorg';
labelorg.name = 'Original labels to which the rule applies';
labelorg.strtype = 's';
labelorg.val = {'.*'};
labelorg.help = {'Regular expression to match the original condition labels to which the rule applies (default - all)'};
labelnew = cfg_entry;
labelnew.tag = 'labelnew';
labelnew.name = 'New label for the merged file';
labelnew.strtype = 's';
labelnew.val = {'#labelorg#'};
labelnew.help = {['New condition label for the merged file. Special tokens can be used as part of the name. '...
'#file# will be replaced by the name of the original file, #labelorg# will be replaced by the original '...
'condition labels.']};
rule = cfg_branch;
rule.tag = 'rule';
rule.name = 'Recoding rule';
rule.val = {file, labelorg, labelnew};
rule.help = {'Recoding rule. The default means that all trials will keep their original label.'};
rules = cfg_repeat;
rules.tag = 'unused';
rules.name = 'Condition label recoding rules';
rules.values = {rule};
rules.num = [1 Inf];
rules.val = {rule};
rules.help = {['Specify the rules for translating condition labels from ' ...
'the original files to the merged file. Multiple rules can be specified. The later ' ...
'rules have precedence. Trials not matched by any of the rules will keep their original labels.']};
S = cfg_exbranch;
S.tag = 'merge';
S.name = 'M/EEG Merging';
S.val = {D, rules};
S.help = {'Merge EEG/MEG data.'};
S.prog = @eeg_merge;
S.vout = @vout_eeg_merge;
S.modality = {'EEG'};
function out = eeg_merge(job)
% construct the S struct
S.D = strvcat(job.D{:});
S.recode = job.rule;
out.D = spm_eeg_merge(S);
out.Dfname = {fullfile(out.D.path, out.D.fname)};
function dep = vout_eeg_merge(job)
% Output is always in field "D", no matter how job is structured
dep = cfg_dep;
dep.sname = 'Merged Data';
% reference field "D" from output
dep.src_output = substruct('.','D');
% this can be entered into any evaluated input
dep.tgt_spec = cfg_findspec({{'strtype','e'}});
dep(2) = cfg_dep;
dep(2).sname = 'Merged Datafile';
% reference field "Dfname" from output
dep(2).src_output = substruct('.','Dfname');
% this can be entered into any file selector
dep(2).tgt_spec = cfg_findspec({{'filter','mat'}});
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_eeg_artefact.m
|
.m
|
antx-master/xspm8/config/spm_cfg_eeg_artefact.m
| 2,704 |
utf_8
|
9be0b57d491daf05b39ef0bb0e836673
|
function S = spm_cfg_eeg_artefact
% configuration file for M/EEG artefact detection
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Vladimir Litvak
% $Id: spm_cfg_eeg_artefact.m 3881 2010-05-07 21:02:57Z vladimir $
rev = '$Rev: 3881 $';
D = cfg_files;
D.tag = 'D';
D.name = 'File Name';
D.filter = 'mat';
D.num = [1 1];
D.help = {'Select the EEG mat file.'};
badchanthresh = cfg_entry;
badchanthresh.tag = 'badchanthresh';
badchanthresh.name = 'Bad channel threshold';
badchanthresh.strtype = 'r';
badchanthresh.num = [1 1];
badchanthresh.val = {0.2};
badchanthresh.help = {'Fraction of trials with artefacts ', ...
'above which an M/EEG channel is declared as bad.'};
artefact_funs = dir(fullfile(spm('dir'), 'spm_eeg_artefact_*.m'));
artefact_funs = {artefact_funs(:).name};
fun = cfg_choice;
fun.tag = 'fun';
fun.name = 'Detection algorithm';
for i = 1:numel(artefact_funs)
fun.values{i} = feval(spm_str_manip(artefact_funs{i}, 'r'));
end
methods = cfg_branch;
methods.tag = 'methods';
methods.name = 'Method';
methods.val = {spm_cfg_eeg_channel_selector, fun};
methodsrep = cfg_repeat;
methodsrep.tag = 'methodsrep';
methodsrep.name = 'How to look for artefacts';
methodsrep.help = {'Choose channels and methods for artefact detection'};
methodsrep.values = {methods};
methodsrep.num = [1 Inf];
S = cfg_exbranch;
S.tag = 'artefact';
S.name = 'M/EEG Artefact detection';
S.val = {D, badchanthresh, methodsrep};
S.help = {'Detect artefacts in epoched M/EEG data.'};
S.prog = @eeg_artefact;
S.vout = @vout_eeg_artefact;
S.modality = {'EEG'};
function out = eeg_artefact(job)
% construct the S struct
S.D = job.D{1};
S.badchanthresh = job.badchanthresh;
for i = 1:numel(job.methods)
S.methods(i).channels = spm_cfg_eeg_channel_selector(job.methods(i).channels);
fun = fieldnames(job.methods(i).fun);
fun = fun{1};
S.methods(i).fun = fun;
S.methods(i).settings = getfield(job.methods(i).fun, fun);
end
out.D = spm_eeg_artefact(S);
out.Dfname = {fullfile(out.D.path, out.D.fname)};
function dep = vout_eeg_artefact(job)
% Output is always in field "D", no matter how job is structured
dep = cfg_dep;
dep.sname = 'Artefact detection';
% reference field "D" from output
dep.src_output = substruct('.','D');
% this can be entered into any evaluated input
dep.tgt_spec = cfg_findspec({{'strtype','e'}});
dep(2) = cfg_dep;
dep(2).sname = 'Artefact-detected Datafile';
% reference field "Dfname" from output
dep(2).src_output = substruct('.','Dfname');
% this can be entered into any file selector
dep(2).tgt_spec = cfg_findspec({{'filter','mat'}});
|
github
|
philippboehmsturm/antx-master
|
spm_run_fmri_spec.m
|
.m
|
antx-master/xspm8/config/spm_run_fmri_spec.m
| 11,586 |
utf_8
|
323408725405fe269ac8eb5e2e667b6c
|
function out = spm_run_fmri_spec(job)
% Set up the design matrix and run a design.
% 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.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% $Id: spm_run_fmri_spec.m 4185 2011-02-01 18:46:18Z guillaume $
original_dir = pwd;
my_cd(job.dir);
%-Ask about overwriting files from previous analyses
%--------------------------------------------------------------------------
if exist(fullfile(job.dir{1},'SPM.mat'),'file')
str = { 'Current directory contains existing SPM file:',...
'Continuing will overwrite existing file!'};
if spm_input(str,1,'bd','stop|continue',[1,0],1,mfilename);
fprintf('%-40s: %30s\n\n',...
'Abort... (existing SPM file)',spm('time'));
return
end
end
% If we've gotten to this point we're committed to overwriting files.
% Delete them so we don't get stuck in spm_spm
%--------------------------------------------------------------------------
files = {'^mask\..{3}$','^ResMS\..{3}$','^RPV\..{3}$',...
'^beta_.{4}\..{3}$','^con_.{4}\..{3}$','^ResI_.{4}\..{3}$',...
'^ess_.{4}\..{3}$', '^spm\w{1}_.{4}\..{3}$'};
for i=1:length(files)
j = spm_select('List',pwd,files{i});
for k=1:size(j,1)
spm_unlink(deblank(j(k,:)));
end
end
% Variables
%--------------------------------------------------------------------------
SPM.xY.RT = job.timing.RT;
SPM.xY.P = [];
% Slice timing
%--------------------------------------------------------------------------
% The following lines have the side effect of modifying the global
% defaults variable. This is necessary to pass job.timing.fmri_t to
% spm_hrf.m. The original values are saved here and restored at the end
% of this function, after the design has been specified. The original
% values may not be restored if this function crashes.
olddefs.stats.fmri.fmri_t = spm_get_defaults('stats.fmri.fmri_t');
olddefs.stats.fmri.fmri_t0 = spm_get_defaults('stats.fmri.fmri_t0');
spm_get_defaults('stats.fmri.t', job.timing.fmri_t);
spm_get_defaults('stats.fmri.t0', job.timing.fmri_t0);
% Basis function variables
%--------------------------------------------------------------------------
SPM.xBF.UNITS = job.timing.units;
SPM.xBF.dt = job.timing.RT/job.timing.fmri_t;
SPM.xBF.T = job.timing.fmri_t;
SPM.xBF.T0 = job.timing.fmri_t0;
% Basis functions
%--------------------------------------------------------------------------
if strcmp(fieldnames(job.bases),'hrf')
if all(job.bases.hrf.derivs == [0 0])
SPM.xBF.name = 'hrf';
elseif all(job.bases.hrf.derivs == [1 0])
SPM.xBF.name = 'hrf (with time derivative)';
elseif all(job.bases.hrf.derivs == [1 1])
SPM.xBF.name = 'hrf (with time and dispersion derivatives)';
else
error('Unrecognized hrf derivative choices.')
end
else
nambase = fieldnames(job.bases);
if ischar(nambase)
nam=nambase;
else
nam=nambase{1};
end
switch nam,
case 'fourier',
SPM.xBF.name = 'Fourier set';
case 'fourier_han',
SPM.xBF.name = 'Fourier set (Hanning)';
case 'gamma',
SPM.xBF.name = 'Gamma functions';
case 'fir',
SPM.xBF.name = 'Finite Impulse Response';
otherwise
error('Unrecognized hrf derivative choices.')
end
SPM.xBF.length = job.bases.(nam).length;
SPM.xBF.order = job.bases.(nam).order;
end
SPM.xBF = spm_get_bf(SPM.xBF);
if isempty(job.sess),
SPM.xBF.Volterra = false;
else
SPM.xBF.Volterra = job.volt;
end
for i = 1:numel(job.sess),
sess = job.sess(i);
% Image filenames
%----------------------------------------------------------------------
SPM.nscan(i) = numel(sess.scans);
SPM.xY.P = strvcat(SPM.xY.P,sess.scans{:});
U = [];
% Augment the singly-specified conditions with the multiple
% conditions specified in a .mat file provided by the user
%----------------------------------------------------------------------
if ~isempty(sess.multi{1})
try
multicond = load(sess.multi{1});
catch
error('Cannot load %s',sess.multi{1});
end
if ~(isfield(multicond,'names')&&isfield(multicond,'onsets')&&...
isfield(multicond,'durations')) || ...
~all([numel(multicond.names),numel(multicond.onsets), ...
numel(multicond.durations)]==numel(multicond.names))
error(['Multiple conditions MAT-file ''%s'' is invalid.\n',...
'File must contain names, onsets, and durations '...
'cell arrays of equal length.\n'],sess.multi{1});
end
%-contains three cell arrays: names, onsets and durations
for j=1:length(multicond.onsets)
cond.name = multicond.names{j};
cond.onset = multicond.onsets{j};
cond.duration = multicond.durations{j};
% Mutiple Conditions Time Modulation
%--------------------------------------------------------------
% initialise the variable.
cond.tmod = 0;
if isfield(multicond,'tmod');
try
cond.tmod = multicond.tmod{j};
catch
error('Error specifying time modulation.');
end
end
% Mutiple Conditions Parametric Modulation
%--------------------------------------------------------------
% initialise the parametric modulation variable.
cond.pmod = [];
if isfield(multicond,'pmod')
% only access existing modulators
try
% check if there is a parametric modulator. this allows
% pmod structures with fewer entries than conditions.
% then check whether any cells are filled in.
if (j <= numel(multicond.pmod)) && ...
~isempty(multicond.pmod(j).name)
% we assume that the number of cells in each
% field of pmod is the same (or should be).
for ii = 1:numel(multicond.pmod(j).name)
cond.pmod(ii).name = multicond.pmod(j).name{ii};
cond.pmod(ii).param = multicond.pmod(j).param{ii};
cond.pmod(ii).poly = multicond.pmod(j).poly{ii};
end
end;
catch
error('Error specifying parametric modulation.');
end
end
sess.cond(end+1) = cond;
end
end
% Configure the input structure array
%----------------------------------------------------------------------
for j = 1:length(sess.cond),
cond = sess.cond(j);
U(j).name = {cond.name};
U(j).ons = cond.onset(:);
U(j).dur = cond.duration(:);
if length(U(j).dur) == 1
U(j).dur = U(j).dur*ones(size(U(j).ons));
elseif length(U(j).dur) ~= length(U(j).ons)
error('Mismatch between number of onset and number of durations.')
end
P = [];
q1 = 0;
if cond.tmod>0,
% time effects
P(1).name = 'time';
P(1).P = U(j).ons*job.timing.RT/60;
P(1).h = cond.tmod;
q1 = 1;
end;
if ~isempty(cond.pmod)
for q = 1:numel(cond.pmod),
% Parametric effects
q1 = q1 + 1;
P(q1).name = cond.pmod(q).name;
P(q1).P = cond.pmod(q).param(:);
P(q1).h = cond.pmod(q).poly;
end;
end
if isempty(P)
P.name = 'none';
P.h = 0;
end
U(j).P = P;
end
SPM.Sess(i).U = U;
% User specified regressors
%----------------------------------------------------------------------
C = [];
Cname = cell(1,numel(sess.regress));
for q = 1:numel(sess.regress),
Cname{q} = sess.regress(q).name;
C = [C, sess.regress(q).val(:)];
end
% Augment the singly-specified regressors with the multiple regressors
% specified in the regressors.mat file
%----------------------------------------------------------------------
if ~strcmp(sess.multi_reg,'')
tmp = load(char(sess.multi_reg{:}));
if isstruct(tmp) && isfield(tmp,'R')
R = tmp.R;
elseif isnumeric(tmp)
% load from e.g. text file
R = tmp;
else
warning('Can''t load user specified regressors in %s', ...
char(sess.multi_reg{:}));
R = [];
end
C = [C, R];
nr = size(R,2);
nq = length(Cname);
for inr=1:nr,
Cname{inr+nq} = ['R',int2str(inr)];
end
end
SPM.Sess(i).C.C = C;
SPM.Sess(i).C.name = Cname;
end
% Factorial design
%--------------------------------------------------------------------------
if isfield(job,'fact')
if ~isempty(job.fact)
NC=length(SPM.Sess(1).U); % Number of conditions
CheckNC=1;
for i=1:length(job.fact)
SPM.factor(i).name=job.fact(i).name;
SPM.factor(i).levels=job.fact(i).levels;
CheckNC=CheckNC*SPM.factor(i).levels;
end
if ~(CheckNC==NC)
disp('Error in fmri_spec job: factors do not match conditions');
return
end
end
else
SPM.factor=[];
end
% Globals
%--------------------------------------------------------------------------
SPM.xGX.iGXcalc = job.global;
SPM.xGX.sGXcalc = 'mean voxel value';
SPM.xGX.sGMsca = 'session specific';
% High Pass filter
%--------------------------------------------------------------------------
for i = 1:numel(job.sess),
SPM.xX.K(i).HParam = job.sess(i).hpf;
end
% Autocorrelation
%--------------------------------------------------------------------------
SPM.xVi.form = job.cvi;
% Let SPM configure the design
%--------------------------------------------------------------------------
SPM = spm_fmri_spm_ui(SPM);
if ~isempty(job.mask)&&~isempty(job.mask{1})
SPM.xM.VM = spm_vol(job.mask{:});
SPM.xM.xs.Masking = [SPM.xM.xs.Masking, '+explicit mask'];
end
%-Save SPM.mat
%--------------------------------------------------------------------------
fprintf('%-40s: ','Saving SPM configuration') %-#
if spm_check_version('matlab','7') >= 0
save('SPM.mat','-V6','SPM');
else
save('SPM.mat','SPM');
end;
fprintf('%30s\n','...SPM.mat saved') %-#
out.spmmat{1} = fullfile(pwd, 'SPM.mat');
my_cd(original_dir); % Change back dir
spm_get_defaults('stats.fmri.fmri_t',olddefs.stats.fmri.fmri_t); % Restore old timing
spm_get_defaults('stats.fmri.fmri_t0',olddefs.stats.fmri.fmri_t0); % parameters
fprintf('Done\n')
return
%==========================================================================
function my_cd(jobDir)
if ~isempty(jobDir)
try
cd(char(jobDir));
catch
error('Failed to change directory. Aborting run.')
end
end
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_realign.m
|
.m
|
antx-master/xspm8/config/spm_cfg_realign.m
| 22,762 |
utf_8
|
91e216ef099732fd3b42a4b8561c487c
|
function realign = spm_cfg_realign
% SPM Configuration file
% automatically generated by the MATLABBATCH utility function GENCODE
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% $Id: spm_cfg_realign.m 4152 2011-01-11 14:13:35Z volkmar $
rev = '$Rev: 4152 $';
% ---------------------------------------------------------------------
% data Session
% ---------------------------------------------------------------------
data = cfg_files;
data.tag = 'data';
data.name = 'Session';
data.help = {'Select scans for this session. In the coregistration step, the sessions are first realigned to each other, by aligning the first scan from each session to the first scan of the first session. Then the images within each session are aligned to the first image of the session. The parameter estimation is performed this way because it is assumed (rightly or not) that there may be systematic differences in the images between sessions.'};
data.filter = 'image';
data.ufilter = '.*';
data.num = [1 Inf];
% ---------------------------------------------------------------------
% generic Data
% ---------------------------------------------------------------------
generic = cfg_repeat;
generic.tag = 'generic';
generic.name = 'Data';
generic.help = {'Add new sessions for this subject. In the coregistration step, the sessions are first realigned to each other, by aligning the first scan from each session to the first scan of the first session. Then the images within each session are aligned to the first image of the session. The parameter estimation is performed this way because it is assumed (rightly or not) that there may be systematic differences in the images between sessions.'};
generic.values = {data };
generic.num = [1 Inf];
% ---------------------------------------------------------------------
% quality Quality
% ---------------------------------------------------------------------
quality = cfg_entry;
quality.tag = 'quality';
quality.name = 'Quality';
quality.help = {'Quality versus speed trade-off. Highest quality (1) gives most precise results, whereas lower qualities gives faster realignment. The idea is that some voxels contribute little to the estimation of the realignment parameters. This parameter is involved in selecting the number of voxels that are used.'};
quality.strtype = 'r';
quality.num = [1 1];
quality.extras = [0 1];
quality.def = @(val)spm_get_defaults('realign.estimate.quality', val{:});
% ---------------------------------------------------------------------
% sep Separation
% ---------------------------------------------------------------------
sep = cfg_entry;
sep.tag = 'sep';
sep.name = 'Separation';
sep.help = {'The separation (in mm) between the points sampled in the reference image. Smaller sampling distances gives more accurate results, but will be slower.'};
sep.strtype = 'e';
sep.num = [1 1];
sep.def = @(val)spm_get_defaults('realign.estimate.sep', val{:});
% ---------------------------------------------------------------------
% fwhm Smoothing (FWHM)
% ---------------------------------------------------------------------
fwhm = cfg_entry;
fwhm.tag = 'fwhm';
fwhm.name = 'Smoothing (FWHM)';
fwhm.help = {
'The FWHM of the Gaussian smoothing kernel (mm) applied to the images before estimating the realignment parameters.'
''
' * PET images typically use a 7 mm kernel.'
''
' * MRI images typically use a 5 mm kernel.'
}';
fwhm.strtype = 'e';
fwhm.num = [1 1];
fwhm.def = @(val)spm_get_defaults('realign.estimate.fwhm', val{:});
% ---------------------------------------------------------------------
% rtm Num Passes
% ---------------------------------------------------------------------
rtm = cfg_menu;
rtm.tag = 'rtm';
rtm.name = 'Num Passes';
rtm.help = {
'Register to first: Images are registered to the first image in the series. Register to mean: A two pass procedure is used in order to register the images to the mean of the images after the first realignment.'
''
'PET images are typically registered to the mean. This is because PET data are more noisy than fMRI and there are fewer of them, so time is less of an issue.'
''
'MRI images are typically registered to the first image. The more accurate way would be to use a two pass procedure, but this probably wouldn''t improve the results so much and would take twice as long to run.'
}';
rtm.labels = {
'Register to first'
'Register to mean'
}';
rtm.values = {0 1};
rtm.def = @(val)spm_get_defaults('realign.estimate.rtm', val{:});
% ---------------------------------------------------------------------
% interp Interpolation
% ---------------------------------------------------------------------
interp = cfg_menu;
interp.tag = 'interp';
interp.name = 'Interpolation';
interp.help = {'The method by which the images are sampled when estimating the optimum transformation. Higher degree interpolation methods provide the better interpolation, but they are slower because they use more neighbouring voxels /* \cite{thevenaz00a,unser93a,unser93b}*/. '};
interp.labels = {
'Trilinear (1st Degree)'
'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 = {1 2 3 4 5 6 7};
interp.def = @(val)spm_get_defaults('realign.estimate.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).'
}';
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.estimate.wrap', val{:});
% ---------------------------------------------------------------------
% weight Weighting
% ---------------------------------------------------------------------
weight = cfg_files;
weight.tag = 'weight';
weight.name = 'Weighting';
weight.val = {''};
weight.help = {'The option of providing a weighting image to weight each voxel of the reference image differently when estimating the realignment parameters. The weights are proportional to the inverses of the standard deviations. This would be used, for example, when there is a lot of extra-brain motion - e.g., during speech, or when there are serious artifacts in a particular region of the images.'};
weight.filter = 'image';
weight.ufilter = '.*';
weight.num = [0 1];
% ---------------------------------------------------------------------
% eoptions Estimation Options
% ---------------------------------------------------------------------
eoptions = cfg_branch;
eoptions.tag = 'eoptions';
eoptions.name = 'Estimation Options';
eoptions.val = {quality sep fwhm rtm interp wrap weight };
eoptions.help = {'Various registration options. If in doubt, simply keep the default values.'};
% ---------------------------------------------------------------------
% estimate Realign: Estimate
% ---------------------------------------------------------------------
estimate = cfg_exbranch;
estimate.tag = 'estimate';
estimate.name = 'Realign: Estimate';
estimate.val = {generic eoptions };
estimate.help = {
'This routine realigns a time-series of images acquired from the same subject using a least squares approach and a 6 parameter (rigid body) spatial transformation/* \cite{friston95a}*/. The first image in the list specified by the user is used as a reference to which all subsequent scans are realigned. The reference scan does not have to the the first chronologically and it may be wise to chose a "representative scan" in this role.'
''
'The aim is primarily to remove movement artefact in fMRI and PET time-series (or more generally longitudinal studies). The headers are modified for each of the input images, such that. they reflect the relative orientations of the data. The details of the transformation are displayed in the results window as plots of translation and rotation. A set of realignment parameters are saved for each session, named rp_*.txt. These can be modelled as confounds within the general linear model/* \cite{friston95a}*/.'
}';
estimate.prog = @spm_run_realign_estimate;
estimate.vout = @vout_estimate;
% ---------------------------------------------------------------------
% data Images
% ---------------------------------------------------------------------
data = cfg_files;
data.tag = 'data';
data.name = 'Images';
data.help = {'Select scans to reslice to match the first.'};
data.filter = 'image';
data.ufilter = '.*';
data.num = [1 Inf];
% ---------------------------------------------------------------------
% which Resliced images
% ---------------------------------------------------------------------
which = cfg_menu;
which.tag = 'which';
which.name = 'Resliced images';
which.help = {
'All Images (1..n) : This reslices all the images - including the first image selected - which will remain in its original position.'
''
'Images 2..n : Reslices images 2..n only. Useful for if you wish to reslice (for example) a PET image to fit a structural MRI, without creating a second identical MRI volume.'
''
'All Images + Mean Image : In addition to reslicing the images, it also creates a mean of the resliced image.'
''
'Mean Image Only : Creates the mean resliced image only.'
}';
which.labels = {
' All Images (1..n)'
'Images 2..n'
' All Images + Mean Image'
' Mean Image Only'
}';
which.values = {[2 0] [1 0] [2 1] [0 1]};
which.def = @(val)spm_get_defaults('realign.write.which', val{:});
% ---------------------------------------------------------------------
% interp Interpolation
% ---------------------------------------------------------------------
interp = cfg_menu;
interp.tag = 'interp';
interp.name = 'Interpolation';
interp.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. Fourier Interpolation/* \cite{eddy96,cox99}*/ is another option, but note that it is only implemented for purely rigid body transformations. Voxel sizes must all be identical and isotropic.'};
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'
'Fourier Interpolation'
}';
interp.values = {0 1 2 3 4 5 6 7 Inf};
interp.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.'
' Wrap in Y - for (un-resliced) MRI where phase encoding is in the Y direction (voxel space).'
}';
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 resliced image file(s). Default prefix is ''r''.'};
prefix.strtype = 's';
prefix.num = [1 Inf];
prefix.def = @(val)spm_get_defaults('realign.write.prefix', val{:});
% ---------------------------------------------------------------------
% roptions Reslice Options
% ---------------------------------------------------------------------
roptions = cfg_branch;
roptions.tag = 'roptions';
roptions.name = 'Reslice Options';
roptions.val = {which interp wrap mask prefix };
roptions.help = {'Various reslicing options. If in doubt, simply keep the default values.'};
% ---------------------------------------------------------------------
% write Realign: Reslice
% ---------------------------------------------------------------------
write = cfg_exbranch;
write.tag = 'write';
write.name = 'Realign: Reslice';
write.val = {data roptions };
write.help = {'This function reslices a series of registered images such that they match the first image selected voxel-for-voxel. The resliced images are named the same as the originals, except that they are prefixed by ''r''.'};
write.prog = @spm_run_realign_reslice;
write.vout = @vout_reslice;
% ---------------------------------------------------------------------
% data Session
% ---------------------------------------------------------------------
data = cfg_files;
data.tag = 'data';
data.name = 'Session';
data.help = {'Select scans for this session. In the coregistration step, the sessions are first realigned to each other, by aligning the first scan from each session to the first scan of the first session. Then the images within each session are aligned to the first image of the session. The parameter estimation is performed this way because it is assumed (rightly or not) that there may be systematic differences in the images between sessions.'};
data.filter = 'image';
data.ufilter = '.*';
data.num = [1 Inf];
% ---------------------------------------------------------------------
% generic Data
% ---------------------------------------------------------------------
generic = cfg_repeat;
generic.tag = 'generic';
generic.name = 'Data';
generic.help = {'Add new sessions for this subject. In the coregistration step, the sessions are first realigned to each other, by aligning the first scan from each session to the first scan of the first session. Then the images within each session are aligned to the first image of the session. The parameter estimation is performed this way because it is assumed (rightly or not) that there may be systematic differences in the images between sessions.'};
generic.values = {data };
generic.num = [1 Inf];
% ---------------------------------------------------------------------
% estwrite Realign: Estimate & Reslice
% ---------------------------------------------------------------------
estwrite = cfg_exbranch;
estwrite.tag = 'estwrite';
estwrite.name = 'Realign: Estimate & Reslice';
estwrite.val = {generic eoptions roptions };
estwrite.help = {
'This routine realigns a time-series of images acquired from the same subject using a least squares approach and a 6 parameter (rigid body) spatial transformation/* \cite{friston95a}*/. The first image in the list specified by the user is used as a reference to which all subsequent scans are realigned. The reference scan does not have to be the first chronologically and it may be wise to chose a "representative scan" in this role.'
''
'The aim is primarily to remove movement artefact in fMRI and PET time-series (or more generally longitudinal studies) /* \cite{ashburner97bir}*/. The headers are modified for each of the input images, such that. they reflect the relative orientations of the data. The details of the transformation are displayed in the results window as plots of translation and rotation. A set of realignment parameters are saved for each session, named rp_*.txt. After realignment, the images are resliced such that they match the first image selected voxel-for-voxel. The resliced images are named the same as the originals, except that they are prefixed by ''r''.'
}';
estwrite.prog = @spm_run_realign_estwrite;
estwrite.vout = @vout_estwrite;
% ---------------------------------------------------------------------
% realign Realign
% ---------------------------------------------------------------------
realign = cfg_choice;
realign.tag = 'realign';
realign.name = 'Realign';
realign.help = {'Within-subject registration of image time series.'};
realign.values = {estimate write estwrite };
%realign.num = [1 Inf];
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function dep = vout_reslice(job)
if job.roptions.which(1) > 0
dep(1) = cfg_dep;
dep(1).sname = 'Resliced Images';
dep(1).src_output = substruct('.','rfiles');
dep(1).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
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;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function dep = vout_estimate(job)
for k=1:numel(job.data)
cdep(1) = cfg_dep;
cdep(1).sname = sprintf('Realignment Param File (Sess %d)', k);
cdep(1).src_output = substruct('.','sess', '()',{k}, '.','rpfile');
cdep(1).tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}});
cdep(2) = cfg_dep;
cdep(2).sname = sprintf('Realigned Images (Sess %d)', k);
cdep(2).src_output = substruct('.','sess', '()',{k}, '.','cfiles');
cdep(2).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
if k == 1
dep = cdep;
else
dep = [dep cdep];
end;
end;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function dep = vout_estwrite(job)
for k=1:numel(job.data)
cdep(1) = cfg_dep;
cdep(1).sname = sprintf('Realignment Param File (Sess %d)', k);
cdep(1).src_output = substruct('.','sess', '()',{k}, '.','rpfile');
cdep(1).tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}});
cdep(2) = cfg_dep;
cdep(2).sname = sprintf('Realigned Images (Sess %d)', k);
cdep(2).src_output = substruct('.','sess', '()',{k}, '.','cfiles');
cdep(2).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
if job.roptions.which(1) > 0
cdep(3) = cfg_dep;
cdep(3).sname = sprintf('Resliced Images (Sess %d)', k);
cdep(3).src_output = substruct('.','sess', '()',{k}, '.','rfiles');
cdep(3).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
|
spm_cfg_smooth.m
|
.m
|
antx-master/xspm8/config/spm_cfg_smooth.m
| 4,201 |
utf_8
|
09740f4ae4c4a5c7260951bcb875e841
|
function smooth = spm_cfg_smooth
% SPM Configuration file for Smooth
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% $Id: spm_cfg_smooth.m 3691 2010-01-20 17:08:30Z guillaume $
rev = '$Rev: 3691 $';
% ---------------------------------------------------------------------
% data Images to Smooth
% ---------------------------------------------------------------------
data = cfg_files;
data.tag = 'data';
data.name = 'Images to Smooth';
data.help = {'Specify the images to smooth. The smoothed images are written to the same subdirectories as the original *.img and are prefixed with a ''s'' (i.e. s*.img). The prefix can be changed by an option setting.'};
data.filter = 'image';
data.ufilter = '.*';
data.num = [0 Inf];
% ---------------------------------------------------------------------
% fwhm FWHM
% ---------------------------------------------------------------------
fwhm = cfg_entry;
fwhm.tag = 'fwhm';
fwhm.name = 'FWHM';
fwhm.help = {'Specify the full-width at half maximum (FWHM) of the Gaussian smoothing kernel in mm. Three values should be entered, denoting the FWHM in the x, y and z directions.'};
fwhm.strtype = 'e';
fwhm.num = [1 3];
fwhm.def = @(val)spm_get_defaults('smooth.fwhm', val{:});
% ---------------------------------------------------------------------
% dtype Data Type
% ---------------------------------------------------------------------
dtype = cfg_menu;
dtype.tag = 'dtype';
dtype.name = 'Data Type';
dtype.help = {'Data-type of output images. SAME indicates the same datatype as the original images.'};
dtype.labels = {
'SAME'
'UINT8 - unsigned char'
'INT16 - signed short'
'INT32 - signed int'
'FLOAT32 - single prec. float'
'FLOAT64 - double prec. float'
}';
dtype.values = {0 spm_type('uint8') spm_type('int16') spm_type('int32') spm_type('float32') spm_type('float64')};
dtype.val = {0};
% ---------------------------------------------------------------------
% im Implicit masking
% ---------------------------------------------------------------------
im = cfg_menu;
im.tag = 'im';
im.name = 'Implicit masking';
im.help = {'An "implicit mask" is a mask implied by a particular voxel value (0 for images with integer type, NaN for float images).'
'If set to ''Yes'', the implicit masking of the input image is preserved in the smoothed image.'};
im.labels = {'Yes' 'No'};
im.values = {1 0};
im.val = {0};
% ---------------------------------------------------------------------
% 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 smoothed image file(s). Default prefix is ''s''.'};
prefix.strtype = 's';
prefix.num = [1 Inf];
prefix.def = @(val)spm_get_defaults('smooth.prefix', val{:});
% ---------------------------------------------------------------------
% smooth Smooth
% ---------------------------------------------------------------------
smooth = cfg_exbranch;
smooth.tag = 'smooth';
smooth.name = 'Smooth';
smooth.val = {data fwhm dtype im prefix};
smooth.help = {'This is for smoothing (or convolving) image volumes with a Gaussian kernel of a specified width. It is used as a preprocessing step to suppress noise and effects due to residual differences in functional and gyral anatomy during inter-subject averaging.'};
smooth.prog = @spm_run_smooth;
smooth.vout = @vout;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function dep = vout(varargin)
% Output file names will be saved in a struct with field .files
dep(1) = cfg_dep;
dep(1).sname = 'Smoothed Images';
dep(1).src_output = substruct('.','files');
dep(1).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_eeg_epochs.m
|
.m
|
antx-master/xspm8/config/spm_cfg_eeg_epochs.m
| 3,555 |
utf_8
|
b602c570d73c2f10fa1a3f0efe68015e
|
function S = spm_cfg_eeg_epochs
% configuration file for M/EEG epoching
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Stefan Kiebel
% $Id: spm_cfg_eeg_epochs.m 3881 2010-05-07 21:02:57Z vladimir $
rev = '$Rev: 3881 $';
D = cfg_files;
D.tag = 'D';
D.name = 'File Name';
D.filter = 'mat';
D.num = [1 1];
D.help = {'Select the EEG mat file.'};
% input via trl file
trlfile = cfg_files;
trlfile.tag = 'trlfile';
trlfile.name = 'File Name';
trlfile.filter = 'mat';
trlfile.num = [1 1];
trlfile.help = {'Select the trialfile mat file.'};
padding = cfg_entry;
padding.tag = 'padding';
padding.name = 'Padding';
padding.strtype = 'r';
padding.num = [1 1];
padding.help = {'Enter padding [s]: the additional time period around each trial',...
'for which the events are saved with the trial (to let the',...
'user keep and use for analysis events which are outside'};
epochinfo = cfg_branch;
epochinfo.tag = 'epochinfo';
epochinfo.name = 'Epoch information';
epochinfo.val = {trlfile padding};
% input via trialdef
timewindow = cfg_entry;
timewindow.tag = 'timewindow';
timewindow.name = 'Timing';
timewindow.strtype = 'r';
timewindow.num = [1 2];
timewindow.help = {'start and end of epoch [ms]'};
conditionlabel = cfg_entry;
conditionlabel.tag = 'conditionlabel';
conditionlabel.name = 'Condition label';
conditionlabel.strtype = 's';
eventtype = cfg_entry;
eventtype.tag = 'eventtype';
eventtype.name = 'Event type';
eventtype.strtype = 's';
eventvalue = cfg_entry;
eventvalue.tag = 'eventvalue';
eventvalue.name = 'Event value';
eventvalue.strtype = 'e';
trialdef = cfg_branch;
trialdef.tag = 'trialdef';
trialdef.name = 'Trial';
trialdef.val = {conditionlabel, eventtype, eventvalue};
define1 = cfg_repeat;
define1.tag = 'unused';
define1.name = 'Trial definitions';
define1.values = {trialdef};
define = cfg_branch;
define.tag = 'define';
define.name = 'Define trial';
define.val = {timewindow define1};
trlchoice = cfg_choice;
trlchoice.tag = 'trialchoice';
trlchoice.name = 'Choose a way how to define trials';
trlchoice.help = {'Choose one of the two options how to define trials'}';
trlchoice.values = {epochinfo define};
S = cfg_exbranch;
S.tag = 'epoch';
S.name = 'M/EEG Epoching';
S.val = {D trlchoice};
S.help = {'Epoch continuous EEG/MEG data.'};
S.prog = @eeg_epochs;
S.vout = @vout_eeg_epochs;
S.modality = {'EEG'};
function out = eeg_epochs(job)
% construct the S struct
S.D = job.D{1};
if isfield(job.trialchoice, 'define')
S.pretrig = job.trialchoice.define.timewindow(1);
S.posttrig = job.trialchoice.define.timewindow(2);
S.trialdef = job.trialchoice.define.trialdef;
else
S.epochinfo = job.trialchoice.epochinfo;
S.epochinfo.trlfile = S.epochinfo.trlfile{1};
end
% set review and save options both to 0 to not pop up something
S.reviewtrials = 0;
S.save = 0;
out.D = spm_eeg_epochs(S);
out.Dfname = {fullfile(out.D.path, out.D.fname)};
function dep = vout_eeg_epochs(job)
% Output is always in field "D", no matter how job is structured
dep = cfg_dep;
dep.sname = 'Epoched Data';
% reference field "D" from output
dep.src_output = substruct('.','D');
% this can be entered into any evaluated input
dep.tgt_spec = cfg_findspec({{'strtype','e'}});
dep(2) = cfg_dep;
dep(2).sname = 'Epoched Datafile';
% reference field "Dfname" from output
dep(2).src_output = substruct('.','Dfname');
% this can be entered into any file selector
dep(2).tgt_spec = cfg_findspec({{'filter','mat'}});
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_imcalc.m
|
.m
|
antx-master/xspm8/config/spm_cfg_imcalc.m
| 8,938 |
utf_8
|
27ef890fb5b522b50c01dd5e37434086
|
function imcalc = spm_cfg_imcalc
% SPM Configuration file for ImCalc
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% $Id: spm_cfg_imcalc.m 4385 2011-07-08 16:53:38Z guillaume $
% ---------------------------------------------------------------------
% input Input Images
% ---------------------------------------------------------------------
input = cfg_files;
input.tag = 'input';
input.name = 'Input Images';
input.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.'};
input.filter = 'image';
input.ufilter = '.*';
input.num = [1 Inf];
% ---------------------------------------------------------------------
% output Output Filename
% ---------------------------------------------------------------------
output = cfg_entry;
output.tag = 'output';
output.name = 'Output Filename';
output.help = {'The output image is written to current working directory unless a valid full pathname is given. If a path name is given here, the output directory setting will be ignored.'};
output.strtype = 's';
output.num = [1 Inf];
output.val = {'output.img'};
% ---------------------------------------------------------------------
% outdir Output Directory
% ---------------------------------------------------------------------
outdir = cfg_files;
outdir.tag = 'outdir';
outdir.name = 'Output Directory';
outdir.val{1} = {''};
outdir.help = {'Files produced by this function will be written into this output directory. If no directory is given, images will be written to current working directory. If both output filename and output directory contain a directory, then output filename takes precedence.'};
outdir.filter = 'dir';
outdir.ufilter = '.*';
outdir.num = [0 1];
% ---------------------------------------------------------------------
% 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 + ...'''
' * Sum of n images (when reading data into a data-matrix - use dmtx arg)'
' f = ''sum(X)'''
}';
expression.strtype = 's';
expression.num = [2 Inf];
% ---------------------------------------------------------------------
% dmtx Data Matrix
% ---------------------------------------------------------------------
dmtx = cfg_menu;
dmtx.tag = 'dmtx';
dmtx.name = 'Data Matrix';
dmtx.help = {'If the dmtx flag is set, then images are read into a data matrix X (rather than into separate variables i1, i2, i3,...). The data matrix should be referred to as X, and contains images in rows. Computation is plane by plane, so in data-matrix mode, X is a NxK matrix, where N is the number of input images [prod(size(Vi))], and K is the number of voxels per plane [prod(Vi(1).dim(1:2))].'};
dmtx.labels = {
'No - don''t read images into data matrix'
'Yes - read images into data matrix'
}';
dmtx.values = {0 1};
dmtx.val = {0};
% ---------------------------------------------------------------------
% mask Masking
% ---------------------------------------------------------------------
mask = cfg_menu;
mask.tag = 'mask';
mask.name = 'Masking';
mask.help = {'For data types without a representation of NaN, implicit zero masking assumes 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.'};
mask.labels = {
'No implicit zero mask'
'Implicit zero mask'
'NaNs should be zeroed'
}';
mask.values = {0 1 -1};
mask.val = {0};
% ---------------------------------------------------------------------
% interp Interpolation
% ---------------------------------------------------------------------
interp = cfg_menu;
interp.tag = 'interp';
interp.name = 'Interpolation';
interp.help = {
'With images of different sizes and orientations, the size and orientation of the first is used for the output image. A warning is given in this situation. Images are sampled into this orientation using the interpolation specified by the hold parameter.'
''
'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.'
' Sinc Interpolation'
' - Better quality (but slower) interpolation, especially'
' with higher degrees.'
}';
interp.labels = {
'Nearest neighbour'
'Trilinear'
'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};
interp.val = {1};
% ---------------------------------------------------------------------
% dtype Data Type
% ---------------------------------------------------------------------
dtype = cfg_menu;
dtype.tag = 'dtype';
dtype.name = 'Data Type';
dtype.help = {'Data-type of output image'};
dtype.labels = {
'UINT8 - unsigned char'
'INT16 - signed short'
'INT32 - signed int'
'FLOAT32 - single prec. float'
'FLOAT64 - double prec. float'
}';
dtype.values = {spm_type('uint8') spm_type('int16') spm_type('int32') ...
spm_type('float32') spm_type('float64')};
dtype.val = {spm_type('int16')};
% ---------------------------------------------------------------------
% options Options
% ---------------------------------------------------------------------
options = cfg_branch;
options.tag = 'options';
options.name = 'Options';
options.val = {dmtx mask interp dtype };
options.help = {'Options for image calculator'};
% ---------------------------------------------------------------------
% imcalc Image Calculator
% ---------------------------------------------------------------------
imcalc = cfg_exbranch;
imcalc.tag = 'imcalc';
imcalc.name = 'Image Calculator';
imcalc.val = {input output outdir expression options };
imcalc.help = {'The image calculator is for performing user-specified algebraic manipulations on a set of images, with the result being written out as an image. The user is prompted to supply images to work on, a filename for the output image, and the expression to evaluate. The expression should be a standard MATLAB expression, within which the images should be referred to as i1, i2, i3,... etc.'};
imcalc.prog = @my_spm_imcalc_ui;
imcalc.vout = @vout;
% =====================================================================
function out = my_spm_imcalc_ui(job)
%-Decompose job structure and run spm_imcalc_ui with arguments
%----------------------------------------------------------------------
flags = {job.options.dmtx, job.options.mask, job.options.dtype, job.options.interp};
[p,nam,ext,num] = spm_fileparts(job.output);
if isempty(p)
if isempty(job.outdir{1})
p = pwd;
else
p = job.outdir{1};
end
end
if isempty(ext)
ext = ['.' spm_get_defaults('images.format')];
end
if isempty(num)
num = ',1';
end
out.files{1} = fullfile(p,[nam ext num]);
spm_imcalc_ui(strvcat(job.input{:}),out.files{1},job.expression,flags);
% =====================================================================
function dep = vout(job)
dep = cfg_dep;
if ~ischar(job.output) || strcmp(job.output, '<UNDEFINED>')
dep.sname = 'Imcalc Computed Image';
else
dep.sname = sprintf('Imcalc Computed Image: %s', job.output);
end
dep.src_output = substruct('.','files');
dep.tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_eeg_montage.m
|
.m
|
antx-master/xspm8/config/spm_cfg_eeg_montage.m
| 1,898 |
utf_8
|
634d67c28180cedd128491a4bb51ecc8
|
function S = spm_cfg_eeg_montage
% configuration file for reading montage files
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Stefan Kiebel
% $Id: spm_cfg_eeg_montage.m 4212 2011-02-23 17:50:55Z vladimir $
D = cfg_files;
D.tag = 'D';
D.name = 'File Name';
D.filter = 'mat';
D.num = [1 1];
D.help = {'Select the EEG mat file.'};
montage = cfg_files;
montage.tag = 'montage';
montage.name = 'Montage file name';
montage.filter = 'mat';
montage.num = [1 1];
montage.help = {'Select a montage file.'};
keepothers = cfg_menu;
keepothers.tag = 'keepothers';
keepothers.name = 'Keep other channels';
keepothers.labels = {'Yes', 'No'};
keepothers.values = {'yes', 'no'};
keepothers.val = {'no'};
keepothers.help = {'Specify whether you want to keep channels that are not contributing to the new channels'};
S = cfg_exbranch;
S.tag = 'montage';
S.name = 'M/EEG Montage';
S.val = {D montage keepothers};
S.help = {'Apply a montage (linear transformation) to EEG/MEG data.'};
S.prog = @eeg_montage;
S.vout = @vout_eeg_montage;
S.modality = {'EEG'};
function out = eeg_montage(job)
% construct the S struct
S.D = job.D{1};
S.montage = job.montage{1};
S.keepothers = job.keepothers;
out.D = spm_eeg_montage(S);
out.Dfname = {fullfile(out.D.path, out.D.fname)};
function dep = vout_eeg_montage(job)
% Output is always in field "D", no matter how job is structured
dep = cfg_dep;
dep.sname = 'montaged data';
% reference field "D" from output
dep.src_output = substruct('.','D');
% this can be entered into any evaluated input
dep.tgt_spec = cfg_findspec({{'strtype','e'}});
dep(2) = cfg_dep;
dep(2).sname = 'Montaged Datafile';
% reference field "Dfname" from output
dep(2).src_output = substruct('.','Dfname');
% this can be entered into any file selector
dep(2).tgt_spec = cfg_findspec({{'filter','mat'}});
|
github
|
philippboehmsturm/antx-master
|
spm_run_fmri_data.m
|
.m
|
antx-master/xspm8/config/spm_run_fmri_data.m
| 2,029 |
utf_8
|
1c5c4ccd6eaa0935710083844d6d4453
|
function out = spm_run_fmri_data(job)
% Set up the design matrix and run a design.
% 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.
%_________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% $Id: spm_run_fmri_data.m 4185 2011-02-01 18:46:18Z guillaume $
spm('defaults','FMRI');
original_dir = pwd;
[p n e v] = spm_fileparts(job.spmmat{1});
my_cd(p);
load(job.spmmat{1});
% Image filenames
%-------------------------------------------------------------------------
SPM.xY.P = strvcat(job.scans);
% Let SPM configure the design
%-------------------------------------------------------------------------
SPM = spm_fmri_spm_ui(SPM);
if ~isempty(job.mask)&&~isempty(job.mask{1})
SPM.xM.VM = spm_vol(job.mask{:});
SPM.xM.xs.Masking = [SPM.xM.xs.Masking, '+explicit mask'];
end
%-Save SPM.mat
%-------------------------------------------------------------------------
fprintf('%-40s: ','Saving SPM configuration') %-#
if spm_check_version('matlab','7') >= 0
save('SPM.mat','-V6','SPM');
else
save('SPM.mat','SPM');
end
fprintf('%30s\n','...SPM.mat saved') %-#
out.spmmat{1} = fullfile(pwd, 'SPM.mat');
my_cd(original_dir); % Change back dir
fprintf('Done\n')
return
%-------------------------------------------------------------------------
%-------------------------------------------------------------------------
function my_cd(varargin)
% jobDir must be the actual directory to change to, NOT the job structure.
jobDir = varargin{1};
if ~isempty(jobDir)
try
cd(char(jobDir));
fprintf('Changing directory to: %s\n',char(jobDir));
catch
error('Failed to change directory. Aborting run.')
end
end
return;
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_cdir.m
|
.m
|
antx-master/xspm8/config/spm_cfg_cdir.m
| 1,978 |
utf_8
|
c3726e2ba4926748da2ed831cb5bd1ce
|
function cdir = spm_cfg_cdir
% SPM Configuration file for 'cd'
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% $Id: spm_cfg_cdir.m 4907 2012-09-06 19:33:21Z guillaume $
rev = '$Rev: 4907 $';
% ---------------------------------------------------------------------
% directory Select a directory
% ---------------------------------------------------------------------
directory = cfg_files;
directory.tag = 'directory';
directory.name = 'Select a directory';
directory.help = {'Select a directory to change to.'};
directory.filter = 'dir';
directory.ufilter = '.*';
directory.num = [1 1];
% ---------------------------------------------------------------------
% cdir Change Directory (Deprecated)
% ---------------------------------------------------------------------
cdir = cfg_exbranch;
cdir.tag = 'cdir';
cdir.name = 'Change Directory (DEPRECATED)';
cdir.val = {directory };
cdir.help = {
'This module is DEPRECATED and has been moved to BasicIO.'
'Jobs which are ready to run may continue using it, but the module inputs can not be changed via GUI.'
'Please switch to the BasicIO module instead.'
'This module will be REMOVED in the next major release of SPM.'
''
'This facility allows programming a directory change.'
}';
cdir.prog = @my_job_cd;
cdir.hidden = true;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function my_job_cd(varargin)
% job can be a job structure or the directory to change to.
warning('"spm.util.cdir" is DEPRECATED and will be REMOVED in the next major release of SPM. Use BasicIO instead.');
job = varargin{1};
if isstruct(job)
jobDir = job.directory;
else
jobDir = job;
end
if ~isempty(jobDir)
cd(char(jobDir));
fprintf('New working directory: %s\n', char(jobDir));
end
|
github
|
philippboehmsturm/antx-master
|
spm_run_preproc.m
|
.m
|
antx-master/xspm8/config/spm_run_preproc.m
| 2,209 |
utf_8
|
6527bf563f7e57ac5f3cc404fa7e12ce
|
function out = spm_run_preproc(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.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% $Id: spm_run_preproc.m 4185 2011-02-01 18:46:18Z guillaume $
job.opts.tpm = char(job.opts.tpm);
if isfield(job.opts,'msk'),
job.opts.msk = char(job.opts.msk);
end;
for i=1:numel(job.data),
res = spm_preproc(job.data{i},job.opts);
[out(1).sn{i},out(1).isn{i}] = spm_prep2sn(res);
[pth,nam] = spm_fileparts(job.data{i});
out(1).snfile{i} = fullfile(pth,[nam '_seg_sn.mat']);
savefields(out(1).snfile{i},out(1).sn{i});
out(1).isnfile{i} = fullfile(pth,[nam '_seg_inv_sn.mat']);
savefields(out(1).isnfile{i},out(1).isn{i});
end;
spm_preproc_write(cat(2,out.sn{:}),job.output);
% Guess filenames
opts = job.output;
sopts = [opts.GM;opts.WM;opts.CSF];
for i=1:numel(job.data)
[pth,nam,ext,num] = spm_fileparts(job.data{i});
if opts.biascor,
out(1).biascorr{i,1} = ...
fullfile(pth, sprintf('m%s%s', nam, ext));
end;
for k1=1:3,
if sopts(k1,3),
out(1).(sprintf('c%d',k1)){i,1} = ...
fullfile(pth, sprintf('c%d%s%s', k1, nam, ext));
end;
if sopts(k1,2),
out(1).(sprintf('wc%d',k1)){i,1} = ...
fullfile(pth, sprintf('wc%d%s%s', k1, nam, ext));
end;
if sopts(k1,1),
out(1).(sprintf('mwc%d',k1)){i,1} = ...
fullfile(pth, sprintf('mwc%d%s%s', k1, nam, ext));
end;
end;
end;
return;
%==========================================================================
function savefields(fnam,p)
if length(p)>1, error('Can''t save fields.'); end
fn = fieldnames(p);
if numel(fn)==0, return; end
for i=1:length(fn)
eval([fn{i} '= p.' fn{i} ';']);
end
if spm_check_version('matlab','7') >= 0
save(fnam,'-V6',fn{:});
else
save(fnam,fn{:});
end
return;
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_eeg_filter.m
|
.m
|
antx-master/xspm8/config/spm_cfg_eeg_filter.m
| 2,437 |
utf_8
|
a82fcc280506266a693b6e8d2b0ff67f
|
function S = spm_cfg_eeg_filter
% configuration file for EEG Filtering
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Stefan Kiebel
% $Id: spm_cfg_eeg_filter.m 4212 2011-02-23 17:50:55Z vladimir $
rev = '$Rev: 4212 $';
D = cfg_files;
D.tag = 'D';
D.name = 'File Name';
D.filter = 'mat';
D.num = [1 1];
D.help = {'Select the EEG mat file.'};
typ = cfg_menu;
typ.tag = 'type';
typ.name = 'Filter type';
typ.labels = {'Butterworth', 'FIR'};
typ.values = {'butterworth', 'fir'};
typ.val = {'butterworth'};
typ.help = {'Select the filter type.'};
band = cfg_menu;
band.tag = 'band';
band.name = 'Filter band';
band.labels = {'Lowpass', 'Highpass', 'Bandpass', 'Stopband'};
band.values = {'low' 'high' 'bandpass' 'stop'};
band.val = {'low'};
band.help = {'Select the filter band.'};
PHz = cfg_entry;
PHz.tag = 'PHz';
PHz.name = 'Cutoff';
PHz.strtype = 'r';
PHz.num = [1 inf];
PHz.help = {'Enter the filter cutoff'};
dir = cfg_menu;
dir.tag = 'dir';
dir.name = 'Filter direction';
dir.labels = {'Zero phase', 'Forward', 'Backward'};
dir.values = {'twopass', 'onepass', 'onepass-reverse'};
dir.val = {'twopass'};
dir.help = {'Select the filter direction.'};
order = cfg_entry;
order.tag = 'order';
order.name = 'Filter order';
order.val = {5};
order.strtype = 'n';
order.num = [1 1];
order.help = {'Enter the filter order'};
flt = cfg_branch;
flt.tag = 'filter';
flt.name = 'Filter';
flt.val = {typ band PHz dir order};
S = cfg_exbranch;
S.tag = 'filter';
S.name = 'M/EEG Filter';
S.val = {D flt};
S.help = {'Low-pass filters EEG/MEG epoched data.'};
S.prog = @eeg_filter;
S.vout = @vout_eeg_filter;
S.modality = {'EEG'};
function out = eeg_filter(job)
% construct the S struct
S.D = job.D{1};
S.filter = job.filter;
out.D = spm_eeg_filter(S);
out.Dfname = {fullfile(out.D.path, out.D.fname)};
function dep = vout_eeg_filter(job)
% Output is always in field "D", no matter how job is structured
dep = cfg_dep;
dep.sname = 'Filtered Data';
% reference field "D" from output
dep.src_output = substruct('.','D');
% this can be entered into any evaluated input
dep.tgt_spec = cfg_findspec({{'strtype','e'}});
dep(2) = cfg_dep;
dep(2).sname = 'Filtered Datafile';
% reference field "Dfname" from output
dep(2).src_output = substruct('.','Dfname');
% this can be entered into any file selector
dep(2).tgt_spec = cfg_findspec({{'filter','mat'}});
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_eeg_bc.m
|
.m
|
antx-master/xspm8/config/spm_cfg_eeg_bc.m
| 2,077 |
utf_8
|
cd9810ba021ab48f80a52d739c741c00
|
function S = spm_cfg_eeg_bc
% configuration file for baseline correction
%__________________________________________________________________________
% Copyright (C) 2009 Wellcome Trust Centre for Neuroimaging
% Vladimir Litvak
% $Id: spm_cfg_eeg_bc.m 3818 2010-04-13 14:36:31Z vladimir $
%--------------------------------------------------------------------------
% D
%--------------------------------------------------------------------------
D = cfg_files;
D.tag = 'D';
D.name = 'File Name';
D.filter = 'mat';
D.num = [1 1];
D.help = {'Select the M/EEG mat file.'};
%--------------------------------------------------------------------------
% time
%--------------------------------------------------------------------------
time = cfg_entry;
time.tag = 'time';
time.name = 'Baseline';
time.help = {'Start and stop of baseline [ms].'};
time.strtype = 'e';
time.num = [1 2];
%--------------------------------------------------------------------------
% S
%--------------------------------------------------------------------------
S = cfg_exbranch;
S.tag = 'bc';
S.name = 'M/EEG Baseline correction';
S.val = {D, time};
S.help = {'Baseline correction of M/EEG time data'}';
S.prog = @eeg_bc;
S.vout = @vout_eeg_bc;
S.modality = {'EEG'};
%==========================================================================
function out = eeg_bc(job)
% construct the S struct
S.D = job.D{1};
S.time = job.time;
out.D = spm_eeg_bc(S);
out.Dfname = {fullfile(out.D.path,out.D.fname)};
%==========================================================================
function dep = vout_eeg_bc(job)
% return dependencies
dep(1) = cfg_dep;
dep(1).sname = 'Baseline corrected M/EEG data';
dep(1).src_output = substruct('.','D');
dep(1).tgt_spec = cfg_findspec({{'strtype','e'}});
dep(2) = cfg_dep;
dep(2).sname = 'Baseline corrected M/EEG datafile';
dep(2).src_output = substruct('.','Dfname');
dep(2).tgt_spec = cfg_findspec({{'filter','mat'}});
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_eeg_review.m
|
.m
|
antx-master/xspm8/config/spm_cfg_eeg_review.m
| 780 |
utf_8
|
53451e3a49cf80ec8eabbec3f903689a
|
function S = spm_cfg_eeg_review
% configuration file for M/EEG reviewing tool
%__________________________________________________________________________
% Copyright (C) 2010 Wellcome Trust Centre for Neuroimaging
% Vladimir Litvak
% $Id: spm_cfg_eeg_review.m 3881 2010-05-07 21:02:57Z vladimir $
rev = '$Rev: 3881 $';
D = cfg_files;
D.tag = 'D';
D.name = 'File Name';
D.filter = 'mat';
D.num = [1 1];
D.help = {'Select the EEG mat file.'};
S = cfg_exbranch;
S.tag = 'review';
S.name = 'M/EEG Display';
S.val = {D};
S.help = {'Run the reviewing tool with the given dataset as input.'};
S.prog = @eeg_review;
S.modality = {'EEG'};
%==========================================================================
function eeg_review(job)
spm_eeg_review(spm_eeg_load(job.D{1}));
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_eeg_tf.m
|
.m
|
antx-master/xspm8/config/spm_cfg_eeg_tf.m
| 3,334 |
utf_8
|
d3bf9980666e47b4f76cce8420c31fb6
|
function S = spm_cfg_eeg_tf
% configuration file for M/EEG time-frequency analysis
%__________________________________________________________________________
% Copyright (C) 2010 Wellcome Trust Centre for Neuroimaging
% Vladimir Litvak
% $Id: spm_cfg_eeg_tf.m 4257 2011-03-18 15:28:29Z vladimir $
rev = '$Rev: 4257 $';
D = cfg_files;
D.tag = 'D';
D.name = 'File Name';
D.filter = 'mat';
D.num = [1 1];
D.help = {'Select the EEG mat file.'};
timewin = cfg_entry;
timewin.tag = 'timewin';
timewin.name = 'Time window';
timewin.strtype = 'r';
timewin.num = [1 2];
timewin.val = {[-Inf Inf]};
timewin.help = {'Time window (ms)'};
frequencies = cfg_entry;
frequencies.tag = 'frequencies';
frequencies.name = 'Frequencies of interest';
frequencies.strtype = 'r';
frequencies.num = [0 Inf];
frequencies.val = {[]};
frequencies.help = {'Frequencies of interest (as a vector), if empty 1-48 with optimal frequency bins ~1 Hz or above resolution'};
specest_funs = dir(fullfile(spm('dir'), 'spm_eeg_specest_*.m'));
specest_funs = {specest_funs(:).name};
phase = cfg_menu;
phase.tag = 'phase';
phase.name = 'Save phase';
phase.help = {'Save phase as well as power'};
phase.labels = {'yes', 'no'};
phase.values = {1, 0};
phase.val = {0};
method = cfg_choice;
method.tag = 'method';
method.name = 'Spectral estimation ';
for i = 1:numel(specest_funs)
method.values{i} = feval(spm_str_manip(specest_funs{i}, 'r'));
end
S = cfg_exbranch;
S.tag = 'analysis';
S.name = 'M/EEG Time-Frequency analysis';
S.val = {D, spm_cfg_eeg_channel_selector, frequencies, timewin, method, phase};
S.help = {'Perform time-frequency analysis of epoched M/EEG data.'};
S.prog = @eeg_tf;
S.vout = @vout_eeg_tf;
S.modality = {'EEG'};
%==========================================================================
function out = eeg_tf(job)
% construct the S struct
S = [];
S.D = job.D{1};
S.channels = spm_cfg_eeg_channel_selector(job.channels);
S.frequencies = job.frequencies;
S.timewin = job.timewin;
S.phase = job.phase;
S.method = cell2mat(fieldnames(job.method));
S.settings = getfield(job.method, S.method);
[Dtf, Dtph] = spm_eeg_tf(S);
out.Dtf = Dtf;
out.Dtfname = {Dtf.fname};
out.Dtph = Dtph;
if ~isempty(Dtph)
out.Dtphname = {Dtph.fname};
else
out.Dtphname = {''};
end
%==========================================================================
function dep = vout_eeg_tf(job)
% return dependencies
dep(1) = cfg_dep;
dep(1).sname = 'M/EEG time-frequency power dataset';
dep(1).src_output = substruct('.','Dtf');
% this can be entered into any evaluated input
dep(1).tgt_spec = cfg_findspec({{'strtype','e'}});
dep(2) = cfg_dep;
dep(2).sname = 'M/EEG time-frequency power dataset';
dep(2).src_output = substruct('.','Dtfname');
% this can be entered into any file selector
dep(2).tgt_spec = cfg_findspec({{'filter','mat'}});
dep(3) = cfg_dep;
dep(3).sname = 'M/EEG time-frequency phase dataset';
dep(3).src_output = substruct('.','Dtph');
% this can be entered into any evaluated input
dep(3).tgt_spec = cfg_findspec({{'strtype','e'}});
dep(4) = cfg_dep;
dep(4).sname = 'M/EEG time-frequency phase dataset';
dep(4).src_output = substruct('.','Dtphname');
% this can be entered into any file selector
dep(4).tgt_spec = cfg_findspec({{'filter','mat'}});
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_ecat.m
|
.m
|
antx-master/xspm8/config/spm_cfg_ecat.m
| 2,223 |
utf_8
|
bf0ab8263e35bd042da8e4331a6ef6ba
|
function ecat = spm_cfg_ecat
% SPM Configuration file for ECAT Import
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% $Id: spm_cfg_ecat.m 3691 2010-01-20 17:08:30Z guillaume $
rev = '$Rev: 3691 $';
% ---------------------------------------------------------------------
% data ECAT files
% ---------------------------------------------------------------------
data = cfg_files;
data.tag = 'data';
data.name = 'ECAT files';
data.help = {'Select the ECAT files to convert.'};
data.filter = 'any';
data.ufilter = '.*v';
data.num = [1 Inf];
% ---------------------------------------------------------------------
% ext Output image format
% ---------------------------------------------------------------------
ext = cfg_menu;
ext.tag = 'ext';
ext.name = 'Output image format';
ext.help = {'Output files can be written as .img + .hdr, or the two can be combined into a .nii file.'};
ext.labels = {
'Two file (img+hdr) NIfTI'
'Single file (nii) NIfTI'
}';
ext.values = {
'img'
'nii'
}';
ext.def = @(val)spm_get_defaults('images.format', val{:});
% ---------------------------------------------------------------------
% opts Options
% ---------------------------------------------------------------------
opts = cfg_branch;
opts.tag = 'opts';
opts.name = 'Options';
opts.val = {ext };
opts.help = {'Conversion options'};
% ---------------------------------------------------------------------
% ecat ECAT Import
% ---------------------------------------------------------------------
ecat = cfg_exbranch;
ecat.tag = 'ecat';
ecat.name = 'ECAT Import';
ecat.val = {data opts };
ecat.help = {'ECAT 7 Conversion. ECAT 7 is the image data format used by the more recent CTI PET scanners.'};
ecat.prog = @convert_ecat;
ecat.modality = {'PET'};
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function convert_ecat(job)
for i=1:length(job.data),
spm_ecat2nifti(job.data{i},job.opts);
end;
return;
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_realignunwarp.m
|
.m
|
antx-master/xspm8/config/spm_cfg_realignunwarp.m
| 35,630 |
utf_8
|
1d4f758948fa9a2af3f66637e97f5b84
|
function realignunwarp = spm_cfg_realignunwarp
% SPM Configuration file
% automatically generated by the MATLABBATCH utility function GENCODE
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% $Id: spm_cfg_realignunwarp.m 4152 2011-01-11 14:13:35Z volkmar $
rev = '$Rev: 4152 $';
% ---------------------------------------------------------------------
% scans Images
% ---------------------------------------------------------------------
scans = cfg_files;
scans.tag = 'scans';
scans.name = 'Images';
scans.help = {
'Select scans for this session. '
'In the coregistration step, the sessions are first realigned to each other, by aligning the first scan from each session to the first scan of the first session. Then the images within each session are aligned to the first image of the session. The parameter estimation is performed this way because it is assumed (rightly or not) that there may be systematic differences in the images between sessions.'
}';
scans.filter = 'image';
scans.ufilter = '.*';
scans.num = [1 Inf];
% ---------------------------------------------------------------------
% pmscan Phase map (vdm* file)
% ---------------------------------------------------------------------
pmscan = cfg_files;
pmscan.tag = 'pmscan';
pmscan.name = 'Phase map (vdm* file)';
pmscan.help = {'Select pre-calculated phase map, or leave empty for no phase correction. The vdm* file is assumed to be already in alignment with the first scan of the first session.'};
pmscan.filter = 'image';
pmscan.ufilter = '^vdm5_.*';
pmscan.num = [0 1];
pmscan.val = {''};
% ---------------------------------------------------------------------
% data Session
% ---------------------------------------------------------------------
data = cfg_branch;
data.tag = 'data';
data.name = 'Session';
data.val = {scans pmscan };
data.help = {
'Only add similar session data to a realign+unwarp branch, i.e., choose Data or Data+phase map for all sessions, but don''t use them interchangeably.'
''
'In the coregistration step, the sessions are first realigned to each other, by aligning the first scan from each session to the first scan of the first session. Then the images within each session are aligned to the first image of the session. The parameter estimation is performed this way because it is assumed (rightly or not) that there may be systematic differences in the images between sessions.'
}';
% ---------------------------------------------------------------------
% generic Data
% ---------------------------------------------------------------------
generic = cfg_repeat;
generic.tag = 'generic';
generic.name = 'Data';
generic.help = {'Data sessions to unwarp.'};
generic.values = {data };
generic.num = [1 Inf];
% ---------------------------------------------------------------------
% quality Quality
% ---------------------------------------------------------------------
quality = cfg_entry;
quality.tag = 'quality';
quality.name = 'Quality';
quality.help = {'Quality versus speed trade-off. Highest quality (1) gives most precise results, whereas lower qualities gives faster realignment. The idea is that some voxels contribute little to the estimation of the realignment parameters. This parameter is involved in selecting the number of voxels that are used.'};
quality.strtype = 'r';
quality.num = [1 1];
quality.extras = [0 1];
quality.def = @(val)spm_get_defaults('realign.estimate.quality', val{:});
% ---------------------------------------------------------------------
% sep Separation
% ---------------------------------------------------------------------
sep = cfg_entry;
sep.tag = 'sep';
sep.name = 'Separation';
sep.help = {'The separation (in mm) between the points sampled in the reference image. Smaller sampling distances gives more accurate results, but will be slower.'};
sep.strtype = 'e';
sep.num = [1 1];
sep.def = @(val)spm_get_defaults('realign.estimate.sep', val{:});
% ---------------------------------------------------------------------
% fwhm Smoothing (FWHM)
% ---------------------------------------------------------------------
fwhm = cfg_entry;
fwhm.tag = 'fwhm';
fwhm.name = 'Smoothing (FWHM)';
fwhm.help = {
'The FWHM of the Gaussian smoothing kernel (mm) applied to the images before estimating the realignment parameters.'
''
' * PET images typically use a 7 mm kernel.'
''
' * MRI images typically use a 5 mm kernel.'
}';
fwhm.strtype = 'e';
fwhm.num = [1 1];
fwhm.def = @(val)spm_get_defaults('realign.estimate.fwhm', val{:});
% ---------------------------------------------------------------------
% rtm Num Passes
% ---------------------------------------------------------------------
rtm = cfg_menu;
rtm.tag = 'rtm';
rtm.name = 'Num Passes';
rtm.help = {
'Register to first: Images are registered to the first image in the series. Register to mean: A two pass procedure is used in order to register the images to the mean of the images after the first realignment.'
''
' * PET images are typically registered to the mean.'
''
' * MRI images are typically registered to the first image.'
}';
rtm.labels = {
'Register to first'
'Register to mean'
}';
rtm.values = {0 1};
rtm.def = @(val)spm_get_defaults('unwarp.estimate.rtm', val{:});
% ---------------------------------------------------------------------
% einterp Interpolation
% ---------------------------------------------------------------------
einterp = cfg_menu;
einterp.tag = 'einterp';
einterp.name = 'Interpolation';
einterp.help = {'The method by which the images are sampled when estimating the optimum transformation. Higher degree interpolation methods provide the better interpolation, but they are slower because they use more neighbouring voxels /* \cite{thevenaz00a,unser93a,unser93b}*/. '};
einterp.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'
}';
einterp.values = {0 1 2 3 4 5 6 7};
einterp.def = @(val)spm_get_defaults('realign.estimate.interp', val{:});
% ---------------------------------------------------------------------
% ewrap Wrapping
% ---------------------------------------------------------------------
ewrap = cfg_menu;
ewrap.tag = 'ewrap';
ewrap.name = 'Wrapping';
ewrap.help = {
'These are typically: '
['* No wrapping - for images that have already been ' ...
'spatially transformed.']
['* Wrap in Y - for (un-resliced) MRI where phase ' ...
'encoding is in the Y direction (voxel space).']
}';
ewrap.labels = {
'No wrap'
'Wrap X'
'Wrap Y'
'Wrap X & Y'
'Wrap Z '
'Wrap X & Z'
'Wrap Y & Z'
'Wrap X, Y & Z'
}';
ewrap.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]};
ewrap.def = @(val)spm_get_defaults('realign.estimate.wrap', val{:});
% ---------------------------------------------------------------------
% weight Weighting
% ---------------------------------------------------------------------
weight = cfg_files;
weight.tag = 'weight';
weight.name = 'Weighting';
weight.val = {''};
weight.help = {'The option of providing a weighting image to weight each voxel of the reference image differently when estimating the realignment parameters. The weights are proportional to the inverses of the standard deviations. For example, when there is a lot of extra-brain motion - e.g., during speech, or when there are serious artifacts in a particular region of the images.'};
weight.filter = 'image';
weight.ufilter = '.*';
weight.num = [0 1];
% ---------------------------------------------------------------------
% eoptions Estimation Options
% ---------------------------------------------------------------------
eoptions = cfg_branch;
eoptions.tag = 'eoptions';
eoptions.name = 'Estimation Options';
eoptions.val = {quality sep fwhm rtm einterp ewrap weight };
eoptions.help = {'Various registration options that could be modified to improve the results. Whenever possible, the authors of SPM try to choose reasonable settings, but sometimes they can be improved.'};
% ---------------------------------------------------------------------
% basfcn Basis Functions
% ---------------------------------------------------------------------
basfcn = cfg_menu;
basfcn.tag = 'basfcn';
basfcn.name = 'Basis Functions';
basfcn.help = {'Number of basis functions to use for each dimension. If the third dimension is left out, the order for that dimension is calculated to yield a roughly equal spatial cut-off in all directions. Default: [12 12 *]'};
basfcn.labels = {
'8x8x*'
'10x10x*'
'12x12x*'
'14x14x*'
}';
basfcn.values = {[8 8] [10 10] [12 12] [14 14]};
basfcn.def = @(val)spm_get_defaults('unwarp.estimate.basfcn', val{:});
% ---------------------------------------------------------------------
% regorder Regularisation
% ---------------------------------------------------------------------
regorder = cfg_menu;
regorder.tag = 'regorder';
regorder.name = 'Regularisation';
regorder.help = {
'Unwarp looks for the solution that maximises the likelihood (minimises the variance) while simultaneously maximising the smoothness of the estimated field (c.f. Lagrange multipliers). This parameter determines how to balance the compromise between these (i.e. the value of the multiplier). Test it on your own data (if you can be bothered) or go with the defaults. '
''
'Regularisation of derivative fields is based on the regorder''th (spatial) derivative of the field. The choices are 0, 1, 2, or 3. Default: 1'
}';
regorder.labels = {
'0'
'1'
'2'
'3'
}';
regorder.values = {0 1 2 3};
regorder.def = @(val)spm_get_defaults('unwarp.estimate.regorder', val{:});
% ---------------------------------------------------------------------
% lambda Reg. Factor
% ---------------------------------------------------------------------
lambda = cfg_menu;
lambda.tag = 'lambda';
lambda.name = 'Reg. Factor';
lambda.help = {'Regularisation factor. Default: Medium.'};
lambda.labels = {
'A little'
'Medium'
'A lot'
}';
lambda.values = {10000 100000 1000000};
lambda.def = @(val)spm_get_defaults('unwarp.estimate.regwgt', val{:});
% ---------------------------------------------------------------------
% jm Jacobian deformations
% ---------------------------------------------------------------------
jm = cfg_menu;
jm.tag = 'jm';
jm.name = 'Jacobian deformations';
jm.help = {'In the defaults there is also an option to include Jacobian intensity modulation when estimating the fields. "Jacobian intensity modulation" refers to the dilution/concentration of intensity that ensue as a consequence of the distortions. Think of a semi-transparent coloured rubber sheet that you hold against a white background. If you stretch a part of the sheet (induce distortions) you will see the colour fading in that particular area. In theory it is a brilliant idea to include also these effects when estimating the field (see e.g. Andersson et al, NeuroImage 20:870-888). In practice for this specific problem it is NOT a good idea. Default: No'};
jm.labels = {
'Yes'
'No'
}';
jm.values = {1 0};
jm.def = @(val)spm_get_defaults('unwarp.estimate.jm', val{:});
% ---------------------------------------------------------------------
% fot First-order effects
% ---------------------------------------------------------------------
fot = cfg_entry;
fot.tag = 'fot';
fot.name = 'First-order effects';
fot.help = {
'Theoretically (ignoring effects of shimming) one would expect the field to depend only on subject out-of-plane rotations. Hence the default choice ("Pitch and Roll", i.e., [4 5]). Go with that unless you have very good reasons to do otherwise'
''
'Vector of first order effects to model. Movements to be modelled are referred to by number. 1= x translation; 2= y translation; 3= z translation 4 = x rotation, 5 = y rotation and 6 = z rotation.'
''
'To model pitch & roll enter: [4 5]'
''
'To model all movements enter: [1:6]'
''
'Otherwise enter a customised set of movements to model'
}';
fot.strtype = 'e';
fot.num = [1 Inf];
fot.def = @(val)spm_get_defaults('unwarp.estimate.foe', val{:});
% ---------------------------------------------------------------------
% sot Second-order effects
% ---------------------------------------------------------------------
sot = cfg_entry;
sot.tag = 'sot';
sot.name = 'Second-order effects';
sot.help = {
'List of second order terms to model second derivatives of. This is entered as a vector of movement parameters similar to first order effects, or leave blank for NONE'
''
'Movements to be modelled are referred to by number:'
''
'1= x translation; 2= y translation; 3= z translation 4 = x rotation, 5 = y rotation and 6 = z rotation.'
''
'To model the interaction of pitch & roll enter: [4 5]'
''
'To model all movements enter: [1:6]'
''
'The vector will be expanded into an n x 2 matrix of effects. For example [4 5] will be expanded to:'
''
'[ 4 4'
''
' 4 5'
''
' 5 5 ]'
}';
sot.strtype = 'e';
sot.num = [Inf Inf];
sot.def = @(val)spm_get_defaults('unwarp.estimate.soe', val{:});
% ---------------------------------------------------------------------
% uwfwhm Smoothing for unwarp (FWHM)
% ---------------------------------------------------------------------
uwfwhm = cfg_entry;
uwfwhm.tag = 'uwfwhm';
uwfwhm.name = 'Smoothing for unwarp (FWHM)';
uwfwhm.help = {'FWHM (mm) of smoothing filter applied to images prior to estimation of deformation fields.'};
uwfwhm.strtype = 'r';
uwfwhm.num = [1 1];
uwfwhm.def = @(val)spm_get_defaults('unwarp.estimate.fwhm', val{:});
% ---------------------------------------------------------------------
% rem Re-estimate movement params
% ---------------------------------------------------------------------
rem = cfg_menu;
rem.tag = 'rem';
rem.name = 'Re-estimate movement params';
rem.help = {'Re-estimation means that movement-parameters should be re-estimated at each unwarping iteration. Default: Yes.'};
rem.labels = {
'Yes'
'No'
}';
rem.values = {1 0};
rem.def = @(val)spm_get_defaults('unwarp.estimate.rem', val{:});
% ---------------------------------------------------------------------
% noi Number of Iterations
% ---------------------------------------------------------------------
noi = cfg_entry;
noi.tag = 'noi';
noi.name = 'Number of Iterations';
noi.help = {'Maximum number of iterations. Default: 5.'};
noi.strtype = 'n';
noi.num = [1 1];
noi.def = @(val)spm_get_defaults('unwarp.estimate.noi', val{:});
% ---------------------------------------------------------------------
% expround Taylor expansion point
% ---------------------------------------------------------------------
expround = cfg_menu;
expround.tag = 'expround';
expround.name = 'Taylor expansion point';
expround.help = {'Point in position space to perform Taylor-expansion around. Choices are (''First'', ''Last'' or ''Average''). ''Average'' should (in principle) give the best variance reduction. If a field-map acquired before the time-series is supplied then expansion around the ''First'' MIGHT give a slightly better average geometric fidelity.'};
expround.labels = {
'Average'
'First'
'Last'
}';
expround.values = {
'Average'
'First'
'Last'
}';
expround.def = @(val)spm_get_defaults('unwarp.estimate.expround', val{:});
% ---------------------------------------------------------------------
% uweoptions Unwarp Estimation Options
% ---------------------------------------------------------------------
uweoptions = cfg_branch;
uweoptions.tag = 'uweoptions';
uweoptions.name = 'Unwarp Estimation Options';
uweoptions.val = {basfcn regorder lambda jm fot sot uwfwhm rem noi expround };
uweoptions.help = {'Various registration & unwarping estimation options.'};
% ---------------------------------------------------------------------
% uwwhich Reslices images (unwarp)?
% ---------------------------------------------------------------------
uwwhich = cfg_menu;
uwwhich.tag = 'uwwhich';
uwwhich.name = 'Resliced images (unwarp)?';
uwwhich.help = {
'All Images (1..n) '
' This reslices and unwarps all the images. '
' '
'All Images + Mean Image '
' In addition to reslicing the images, it also creates a mean of the resliced images.'
}';
uwwhich.labels = {
' All Images (1..n)'
' All Images + Mean Image'
}';
uwwhich.values = {[2 0] [2 1]};
uwwhich.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 = {
'These are typically: '
['* No wrapping - for images that have already been ' ...
'spatially transformed.']
['* Wrap in Y - for (un-resliced) MRI where phase ' ...
'encoding is in the Y direction (voxel space).']
}';
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 smoothed image file(s). Default prefix is ''u''.'};
prefix.strtype = 's';
prefix.num = [1 Inf];
prefix.def = @(val)spm_get_defaults('unwarp.write.prefix', val{:});
% ---------------------------------------------------------------------
% uwroptions Unwarp Reslicing Options
% ---------------------------------------------------------------------
uwroptions = cfg_branch;
uwroptions.tag = 'uwroptions';
uwroptions.name = 'Unwarp Reslicing Options';
uwroptions.val = {uwwhich rinterp wrap mask prefix };
uwroptions.help = {'Various registration & unwarping estimation options.'};
% ---------------------------------------------------------------------
% realignunwarp Realign & Unwarp
% ---------------------------------------------------------------------
realignunwarp = cfg_exbranch;
realignunwarp.tag = 'realignunwarp';
realignunwarp.name = 'Realign & Unwarp';
realignunwarp.val = {generic eoptions uweoptions uwroptions };
realignunwarp.help = {
'Within-subject registration and unwarping of time series.'
''
'The realignment part of this routine realigns a time-series of images acquired from the same subject using a least squares approach and a 6 parameter (rigid body) spatial transformation. The first image in the list specified by the user is used as a reference to which all subsequent scans are realigned. The reference scan does not have to the the first chronologically and it may be wise to chose a "representative scan" in this role.'
''
'The aim is primarily to remove movement artefact in fMRI and PET time-series (or more generally longitudinal studies). ".mat" files are written for each of the input images. The details of the transformation are displayed in the results window as plots of translation and rotation. A set of realignment parameters are saved for each session, named rp_*.txt.'
''
'In the coregistration step, the sessions are first realigned to each other, by aligning the first scan from each session to the first scan of the first session. Then the images within each session are aligned to the first image of the session. The parameter estimation is performed this way because it is assumed (rightly or not) that there may be systematic differences in the images between sessions.'
'The paper/* \cite{ja_geometric}*/ is unfortunately a bit old now and describes none of the newer features. Hopefully we''ll have a second paper out any decade now.'
''
'See also spm_uw_estimate.m for a detailed description of the implementation. Even after realignment there is considerable variance in fMRI time series that covary with, and is most probably caused by, subject movements/* \cite{ja_geometric}*/. It is also the case that this variance is typically large compared to experimentally induced variance. Anyone interested can include the estimated movement parameters as covariates in the design matrix, and take a look at an F-contrast encompassing those columns. It is quite dramatic. The result is loss of sensitivity, and if movements are correlated to task specificity. I.e. we may mistake movement induced variance for true activations. The problem is well known, and several solutions have been suggested. A quite pragmatic (and conservative) solution is to include the estimated movement parameters (and possibly squared) as covariates in the design matrix. Since we typically have loads of degrees of freedom in fMRI we can usually afford this. The problems occur when movements are correlated with the task, since the strategy above will discard "good" and "bad" variance alike (i.e. remove also "true" activations.'
''
'The "covariate" strategy described above was predicated on a model where variance was assumed to be caused by "spin history" effects, but will work pretty much equally good/bad regardless of what the true underlying cause is. Others have assumed that the residual variance is caused mainly by errors introduced by the interpolation kernel in the resampling step of the realignment. One has tried to solve this through higher order resampling (huge Sinc kernels, or k-space resampling). Unwarp is based on a different hypothesis regarding the residual variance. EPI images are not particularly faithful reproductions of the object, and in particular there are severe geometric distortions in regions where there is an air-tissue interface (e.g. orbitofrontal cortex and the anterior medial temporal lobes). In these areas in particular the observed image is a severely warped version of reality, much like a funny mirror at a fair ground. When one moves in front of such a mirror ones image will distort in different ways and ones head may change from very elongated to seriously flattened. If we were to take digital snapshots of the reflection at these different positions it is rather obvious that realignment will not suffice to bring them into a common space.'
''
'The situation is similar with EPI images, and an image collected for a given subject position will not be identical to that collected at another. We call this effect susceptibility-by-movement interaction. Unwarp is predicated on the assumption that the susceptibility-by- movement interaction is responsible for a sizable part of residual movement related variance.'
''
'Assume that we know how the deformations change when the subject changes position (i.e. we know the derivatives of the deformations with respect to subject position). That means that for a given time series and a given set of subject movements we should be able to predict the "shape changes" in the object and the ensuing variance in the time series. It also means that, in principle, we should be able to formulate the inverse problem, i.e. given the observed variance (after realignment) and known (estimated) movements we should be able to estimate how deformations change with subject movement. We have made an attempt at formulating such an inverse model, and at solving for the "derivative fields". A deformation field can be thought of as little vectors at each position in space showing how that particular location has been deflected. A "derivative field" is then the rate of change of those vectors with respect to subject movement. Given these "derivative fields" we should be able to remove the variance caused by the susceptibility-by-movement interaction. Since the underlying model is so restricted we would also expect experimentally induced variance to be preserved. Our experiments have also shown this to be true.'
''
'In theory it should be possible to estimate also the "static" deformation field, yielding an unwarped (to some true geometry) version of the time series. In practise that doesn''t really seem to work. Hence, the method deals only with residual movement related variance induced by the susceptibility-by-movement interaction. This means that the time-series will be undistorted to some "average distortion" state rather than to the true geometry. If one wants additionally to address the issue of anatomical fidelity one should combine Unwarp with a measured fieldmap.'
''
'The description above can be thought of in terms of a Taylor expansion of the field as a function of subject movement. Unwarp alone will estimate the first (and optionally second, see below) order terms of this expansion. It cannot estimate the zeroth order term (the distortions common to all scans in the time series) since that doesn''t introduce (almost) any variance in the time series. The measured fieldmap takes the role of the zeroth order term. Refer to the FieldMap toolbox and the documents FieldMap.man and FieldMap_principles.man for a description of how to obtain fieldmaps in the format expected by Unwarp.'
''
'If we think of the field as a function of subject movement it should in principle be a function of six variables since rigid body movement has six degrees of freedom. However, the physics of the problem tells us that the field should not depend on translations nor on rotation in a plane perpendicular to the magnetic flux. Hence it should in principle be sufficient to model the field as a function of out-of-plane rotations (i.e. pitch and roll). One can object to this in terms of the effects of shimming (object no longer immersed in a homogenous field) that introduces a dependence on all movement parameters. In addition SPM/Unwarp cannot really tell if the transversal slices it is being passed are really perpendicular to the flux or not. In practice it turns out thought that it is never (at least we haven''t seen any case) necessary to include more than Pitch and Roll. This is probably because the individual movement parameters are typically highly correlated anyway, which in turn is probably because most heads that we scan are attached to a neck around which rotations occur. On the subject of Taylor expansion we should mention that there is the option to use a second-order expansion (through the defaults) interface. This implies estimating also the rate-of-change w.r.t. to some movement parameter of the rate-of-change of the field w.r.t. some movement parameter (colloquially known as a second derivative). It can be quite interesting to watch (and it is amazing that it is possible) but rarely helpful/necessary.'
''
'In the defaults there is also an option to include Jacobian intensity modulation when estimating the fields. "Jacobian intensity modulation" refers to the dilution/concentration of intensity that ensue as a consequence of the distortions. Think of a semi-transparent coloured rubber sheet that you hold against a white background. If you stretch a part of the sheet (induce distortions) you will see the colour fading in that particular area. In theory it is a brilliant idea to include also these effects when estimating the field (see e.g. Andersson et al, NeuroImage 20:870-888). In practice for this specific problem it is NOT a good idea.'
''
'It should be noted that this is a method intended to correct data afflicted by a particular problem. If there is little movement in your data to begin with this method will do you little good. If on the other hand there is appreciable movement in your data (>1deg) it will remove some of that unwanted variance. If, in addition, movements are task related it will do so without removing all your "true" activations. The method attempts to minimise total (across the image volume) variance in the data set. It should be realised that while (for small movements) a rather limited portion of the total variance is removed, the susceptibility-by-movement interaction effects are quite localised to "problem" areas. Hence, for a subset of voxels in e.g. frontal-medial and orbitofrontal cortices and parts of the temporal lobes the reduction can be quite dramatic (>90). The advantages of using Unwarp will also depend strongly on the specifics of the scanner and sequence by which your data has been acquired. When using the latest generation scanners distortions are typically quite small, and distortion-by-movement interactions consequently even smaller. A small check list in terms of distortions is '
'a) Fast gradients->short read-out time->small distortions '
'b) Low field (i.e. <3T)->small field changes->small distortions '
'c) Low res (64x64)->short read-out time->small distortions '
'd) SENSE/SMASH->short read-out time->small distortions '
'If you can tick off all points above chances are you have minimal distortions to begin with and you can say "sod Unwarp" (but not to our faces!).'
}';
realignunwarp.prog = @spm_run_realignunwarp;
realignunwarp.vout = @vout_rureslice;
realignunwarp.modality = {
'PET'
'FMRI'
'VBM'
}';
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function dep = vout_rureslice(job)
for k=1:numel(job.data)
cdep(1) = cfg_dep;
cdep(1).sname = sprintf('Unwarp Params Variable (Sess %d)', k);
cdep(1).src_output = substruct('.','sess', '()',{k}, '.','ds');
cdep(1).tgt_spec = cfg_findspec({{'class','cfg_entry'},{'strtype','e'}});
cdep(2) = cfg_dep;
cdep(2).sname = sprintf('Unwarp Params File (Sess %d)', k);
cdep(2).src_output = substruct('.','sess', '()',{k}, '.','dsfile');
cdep(2).tgt_spec = cfg_findspec({{'filter','any','strtype','e'}});
if job.uwroptions.uwwhich(1) == 2
cdep(3) = cfg_dep;
cdep(3).sname = sprintf('Unwarped Images (Sess %d)', k);
cdep(3).src_output = substruct('.','sess', '()',{k}, '.','uwrfiles');
cdep(3).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
end;
if k == 1
dep = cdep;
else
dep = [dep cdep];
end;
end;
if job.uwroptions.uwwhich(2),
dep(end+1) = cfg_dep;
dep(end).sname = 'Unwarped Mean Image';
dep(end).src_output = substruct('.','meanuwr');
dep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
end;
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_eeg_downsample.m
|
.m
|
antx-master/xspm8/config/spm_cfg_eeg_downsample.m
| 1,627 |
utf_8
|
b15f0a9d9a0b53425bd6ba4bc8d7a13e
|
function S = spm_cfg_eeg_downsample
% configuration file for M/EEG downsampling
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Stefan Kiebel
% $Id: spm_cfg_eeg_downsample.m 3881 2010-05-07 21:02:57Z vladimir $
rev = '$Rev: 3881 $';
D = cfg_files;
D.tag = 'D';
D.name = 'File Name';
D.filter = 'mat';
D.num = [1 1];
D.help = {'Select the M/EEG mat file.'};
fsample_new = cfg_entry;
fsample_new.tag = 'fsample_new';
fsample_new.name = 'New sampling rate';
fsample_new.strtype = 'r';
fsample_new.num = [1 1];
fsample_new.help = {'Input the new sampling rate [Hz].'};
S = cfg_exbranch;
S.tag = 'downsample';
S.name = 'M/EEG Downsampling';
S.val = {D fsample_new};
S.help = {'Downsample EEG/MEG data.'};
S.prog = @eeg_downsample;
S.vout = @vout_eeg_downsample;
S.modality = {'EEG'};
function out = eeg_downsample(job)
% construct the S struct
S.D = job.D{1};
S.fsample_new = job.fsample_new;
out.D = spm_eeg_downsample(S);
out.Dfname = {fullfile(out.D.path, out.D.fname)};
function dep = vout_eeg_downsample(job)
% Output is always in field "D", no matter how job is structured
dep = cfg_dep;
dep.sname = 'Downsampled data';
% reference field "D" from output
dep.src_output = substruct('.','D');
% this can be entered into any evaluated input
dep.tgt_spec = cfg_findspec({{'strtype','e'}});
dep(2) = cfg_dep;
dep(2).sname = 'Downsampled Datafile';
% reference field "Dfname" from output
dep(2).src_output = substruct('.','Dfname');
% this can be entered into any file selector
dep(2).tgt_spec = cfg_findspec({{'filter','mat'}});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.