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_DesMtx.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_DesMtx.m
| 32,503 |
utf_8
|
3378b7ab974fe4c63802be7041a77998
|
function [X,Pnames,Index,idx,jdx,kdx]=spm_DesMtx(varargin)
% Design matrix construction from factor level and covariate vectors
% FORMAT [X,Pnames] = spm_DesMtx(<FCLevels-Constraint-FCnames> list)
% FORMAT [X,Pnames,Index,idx,jdx,kdx] = spm_DesMtx(FCLevels,Constraint,FCnames)
%
% <FCLevels-Constraints-FCnames>
% - set of arguments specifying a portion of design matrix (see below)
% - FCnames parameter, or Constraint and FCnames parameters, are optional
% - a list of multiple <FCLevels-Constraint-FCnames> triples can be
% specified, where FCnames or Constraint-FCnames may be omitted
% within any triple. The program then works recursively.
%
% X - design matrix
% Pnames - paramater names as (constructed from FCnames) - a cellstr
% Index - integer index of factor levels
% - only returned when computing a single design matrix partition
%
% idx,jdx,kdx - reference vectors mapping I & Index (described below)
% - only returned when computing a single design matrix partition
% for unconstrained factor effects ('-' or '~')
%
% ----------------
% - Utilities:
%
% FORMAT i = spm_DesMtx('pds',v,m,n)
% Patterned data setting function - inspired by MINITAB's "SET" command
% v - base pattern vector
% m - (scalar natural number) #replications of elements of v [default 1]
% n - (scalar natural number) #repeats of pattern [default 1]
% i - resultant pattern vector, with v's elements replicated m times,
% the resulting vector repeated n times.
%
% FORMAT [nX,nPnames] = spm_DesMtx('sca',X1,Pnames1,X2,Pnames2,...)
% Produces a scaled design matrix nX with max(abs(nX(:))<=1, suitable
% for imaging with: image((nX+1)*32)
% X1,X2,... - Design matrix partitions
% Pnames1, Pnames2,... - Corresponding parameter name string mtx/cellstr (opt)
% nX - Scaled design matrix
% nPnames - Concatenated parameter names for columns of nX
%
% FORMAT Fnames = spm_DesMtx('Fnames',Pnames)
% Converts parameter names into suitable filenames
% Pnames - string mtx/cellstr containing parameter names
% Fnames - filenames derived from Pnames. (cellstr)
%
% FORMAT TPnames = spm_DesMtx('TeXnames',Pnames)
% Removes '*'s and '@'s from Pnames, so TPnames suitable for TeX interpretation
% Pnames - string mtx/cellstr containing parameter names
% TPnames - TeX-ified parameter names
%
% FORMAT Map = spm_DesMtx('ParMap',aMap)
% Returns Nx2 cellstr mapping (greek TeX) parameters to English names,
% using the notation established in the SPMcourse notes.
% aMap - (optional) Mx2 cellstr of additional or over-ride mappings
% Map - cellstr of parameter names (col1) and corresponding English names (col2)
%
% FORMAT EPnames = spm_DesMtx('ETeXnames',Pnames,aMap)
% Translates greek (TeX) parameter names into English using mapping given by
% spm_DesMtx('ParMap',aMap)
% Pnames - string mtx/cellstr containing parameter names
% aMap - (optional) Mx2 cellstr of additional or over-ride mappings
% EPnames - cellstr of converted parameter names
%_______________________________________________________________________
%
% Returns design matrix corresponding to given vectors containing
% levels of a factor; two way interactions; covariates (n vectors);
% ready-made sections of design matrix; and factor by covariate
% interactions.
%
% The specification for the design matrix is passed in sets of arguments,
% each set corresponding to a particular Factor/Covariate/&c., specifying
% a section of the design matrix. The set of arguments consists of the
% FCLevels matrix (Factor/Covariate levels), an optional constraint string,
% and an optional (string) name matrix containing the names of the
% Factor/Covariate/&c.
%
% MAIN EFFECTS: For a main effect, or single factor, the FCLevels
% matrix is an integer vector whose values represent the levels of the
% factor. The integer factor levels need not be positive, nor in
% order. In the '~' constraint types (below), a factor level of zero
% is ignored (treated as no effect), and no corresponding column of
% design matrix is created. Effects for the factor levels are entered
% into the design matrix *in increasing order* of the factor levels.
% Check Pnames to find out which columns correspond to which levels of
% the factor.
%
% TWO WAY INTERACTIONS: For a two way interaction effect between two
% factors, the FCLevels matrix is an nx2 integer matrix whose columns
% indicate the levels of the two factors. An effect is included for
% each unique combination of the levels of the two factors. Again,
% factor levels must be integer, though not necessarily positive.
% Zero levels are ignored in the '~' constraint types described below.
%
% CONSTRAINTS: Each FactorLevels vector/matrix may be followed by an
% (optional) ConstraintString.
%
% ConstraintStrings for main effects are:
% '-' - No Constraint
% '~' - Ignore zero level of factor
% (I.e. cornerPoint constraint on zero level,
% (same as '.0', except zero level is always ignored,
% (even if factor only has zero level, in which case
% (an empty DesMtx results and a warning is given
% '+0' - sum-to-zero constraint
% '+0m' - Implicit sum-to-zero constraint
% '.' - CornerPoint constraint
% '.0' - CornerPoint constraint applied to zero factor level
% (warns if there is no zero factor level)
% Constraints for two way interaction effects are
% '-' - No Constraints
% '~' - Ignore zero level of any factor
% (I.e. cornerPoint constraint on zero level,
% (same as '.ij0', except zero levels are always ignored
% '+i0','+j0','+ij0' - sum-to-zero constraints
% '.i', '.j', '.ij' - CornerPoint constraints
% '.i0','.j0','.ij0' - CornerPoint constraints applied to zero factor level
% (warns if there is no zero factor level)
% '+i0m', '+j0m' - Implicit sum-to-zero constraints
%
% With the exception of the "ignore zero" '~' constraint, constraints
% are only applied if there are sufficient factor levels. CornerPoint
% and explicit sum-to-zero Constraints are applied to the last level of
% the factor.
%
% The implicit sum-to-zero constraints "mean correct" appropriate rows
% of the relevant design matrix block. For a main effect, constraint
% '+0m' "mean corrects" the main effect block across columns,
% corresponding to factor effects B_i, where B_i = B'_i - mean(B'_i) :
% The B'_i are the fitted parameters, effectively *relative* factor
% parameters, relative to their mean. This leads to a rank deficient
% design matrix block. If Matlab's pinv, which implements a
% Moore-Penrose pseudoinverse, is used to solve the least squares
% problem, then the solution with smallest L2 norm is found, which has
% mean(B'_i)=0 provided the remainder of the design is unique (design
% matrix blocks of full rank). In this case therefore the B_i are
% identically the B'_i - the mean correction imposes the constraint.
%
%
% COVARIATES: The FCLevels matrix here is an nxc matrix whose columns
% contain the covariate values. An effect is included for each covariate.
% Covariates are identified by ConstraintString 'C'.
%
%
% PRE-SPECIFIED DESIGN BLOCKS: ConstraintString 'X' identifies a
% ready-made bit of design matrix - the effect is the same as 'C'.
%
%
% FACTOR BY COVARIATE INTERACTIONS: are identified by ConstraintString
% 'FxC'. The last column is understood to contain the covariate. Other
% columns are taken to contain integer FactorLevels vectors. The
% (unconstrained) interaction of the factors is interacted with the
% covariate. Zero factor levels are ignored if ConstraintString '~FxC'
% is used.
%
%
% NAMES: Each Factor/Covariate can be 'named', by passing a name
% string. Pass a string matrix, or cell array (vector) of strings,
% with rows (cells) naming the factors/covariates in the respective
% columns of the FCLevels matrix. These names default to <Fac>, <Cov>,
% <Fac1>, <Fac2> &c., and are used in the construction of the Pnames
% parameter names.
% E.g. for an interaction, spm_DesMtx([F1,F2],'+ij0',['subj';'cond'])
% giving parameter names such as subj*cond_{1,2} etc...
%
% Pnames returns a string matrix whose successive rows describe the
% effects parameterised in the corresponding columns of the design
% matrix. `Fac1*Fac2_{2,3}' would refer to the parameter for the
% interaction of the two factors Fac1 & Fac2, at the 2nd level of the
% former and the 3rd level of the latter. Other forms are
% - Simple main effect (level 1) : <Fac>_{1}
% - Three way interaction (level 1,2,3) : <Fac1>*<Fac2>*<Fac3>_{1,2,3}
% - Two way factor interaction by covariate interaction :
% : <Cov>@<Fac1>*<Fac2>_{1,1}
% - Column 3 of prespecified DesMtx block (if unnamed)
% : <X> [1]
% The special characters `_*()[]{}' are recognised by the scaling
% function (spm_DesMtx('sca',...), and should therefore be avoided
% when naming effects and covariates.
%
%
% INDEX: An Integer Index matrix is returned if only a single block of
% design matrix is being computed (single set of parameters). It
% indexes the actual order of the effect levels in the design matrix block.
% (Factor levels are introduced in order, regardless of order of
% appearence in the factor index matrices, so that the parameters
% vector has a sensible order.) This is used to aid recursion.
%
% Similarly idx,jdx & kdx are indexes returned for a single block of
% design matrix consisting of unconstrained factor effects ('-' or '~').
% These indexes map I and Index (in a similar fashion to the `unique`
% function) as follows:
% - idx & jdx are such that I = Index(:,jdx)' and Index = I(idx,:)'
% where vector I is given as a column vector
% - If the "ignore zeros" constraint '~' is used, then kdx indexes the
% non-zero (combinations) of factor levels, such that
% I(kdx,:) = Index(:,jdx)' and Index == I(kdx(idx),:)'
%
% ----------------
%
% The "patterned data setting" (spm_DesMtx('pds'...) is a simple
% utility for setting patterned indicator vectors, inspired by
% MINITAB's "SET" command.
%
% The vector v has it's elements replicated m times, and the resulting
% vector is itself repeated n times, giving a resultant vector i of
% length n*m*length(v)
%
% Examples:
% spm_DesMtx('pds',1:3) % = [1,2,3]
% spm_DesMtx('pds',1:3,2) % = [1,1,2,2,3,3]
% spm_DesMtx('pds',1:3,2,3) % = [1,1,2,2,3,3,1,1,2,2,3,3,1,1,2,2,3,3]
% NB: MINITAB's "SET" command has syntax n(v)m:
%
% ----------------
%
% The design matrix scaling feature is designed to return a scaled
% version of a design matrix, with values in [-1,1], suitable for
% visualisation. Special care is taken to apply the same normalisation
% to blocks of design matrix reflecting a single effect, to preserve
% appropriate relationships between columns. Identification of effects
% corresponding to columns of design matrix portions is via the parameter
% names matrices. The design matrix may be passed in any number of
% parts, provided the corresponding parameter names are given. It is
% assummed that the block representing an effect is contained within a
% single partition. Partitions supplied without corresponding parameter
% names are scaled on a column by column basis, the parameters labelled as
% <UnSpec> in the returned nPnames matrix.
%
% Effects are identified using the special characters `_*()[]{}' used in
% parameter naming as follows: (here ? is a wildcard)
% - ?(?) - general block (column normalised)
% - ?[?] - specific block (block normalised)
% - ?_{?} - main effect or interaction of main effects
% - ?@?_{?} - factor by covariate interaction
% Blocks are identified by looking for runs of parameters of the same type
% with the same names: E.g. a block of main effects for factor 'Fac1'
% would have names like Fac1_{?}.
%
% Scaling is as follows:
% * fMRI blocks are scaled around zero to lie in [-1,1]
% * No scaling is carried out if max(abs(tX(:))) is in [.4,1]
% This protects dummy variables from normalisation, even if
% using implicit sum-to-zero constraints.
% * If the block has a single value, it's replaced by 1's
% * FxC blocks are normalised so the covariate values cover [-1,1]
% but leaving zeros as zero.
% * Otherwise, block is scaled to cover [-1,1].
%
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Andrew Holmes
% $Id: spm_DesMtx.m 4137 2010-12-15 17:18:32Z guillaume $
%-Parse arguments for recursive construction of design matrices
%=======================================================================
if nargin==0 error('Insufficient arguments'), end
if ischar(varargin{1})
%-Non-recursive action string usage
Constraint=varargin{1};
elseif nargin>=2 && ~(ischar(varargin{2}) || iscell(varargin{2}))
[X1,Pnames1]=spm_DesMtx(varargin{1});
[X2,Pnames2]=spm_DesMtx(varargin{2:end});
X=[X1,X2]; Pnames=[Pnames1;Pnames2];
return
elseif nargin>=3 && ~(ischar(varargin{3}) || iscell(varargin{3}))
[X1,Pnames1]=spm_DesMtx(varargin{1:2});
[X2,Pnames2]=spm_DesMtx(varargin{3:end});
X=[X1,X2]; Pnames=[Pnames1;Pnames2];
return
elseif nargin>=4
[X1,Pnames1]=spm_DesMtx(varargin{1:3});
[X2,Pnames2]=spm_DesMtx(varargin{4:end});
X=[X1,X2]; Pnames=[Pnames1;Pnames2];
return
else
%-If I is a vector, make it a column vector
I=varargin{1}; if size(I,1)==1, I=I'; end
%-Sort out constraint and Factor/Covariate name parameters
if nargin<2, Constraint='-'; else Constraint=varargin{2}; end
if isempty(I), Constraint='mt'; end
if nargin<3, FCnames={}; else FCnames=varargin{3}; end
if char(FCnames), FCnames=cellstr(FCnames); end
end
switch Constraint, case 'mt' %-Empty I case
%=======================================================================
X = [];
Pnames = {};
Index = [];
case {'C','X'} %-Covariate effect, or ready-made design matrix
%=======================================================================
%-I contains a covariate (C), or is to be inserted "as is" (X)
X = I;
%-Construct parameter name index
%-----------------------------------------------------------------------
if isempty(FCnames)
if strcmp(Constraint,'C'), FCnames={'<Cov>'}; else FCnames={'<X>'}; end
end
if length(FCnames)==1 && size(X,2)>1
Pnames = cell(size(X,2),1);
for i=1:size(X,2)
Pnames{i} = sprintf('%s [%d]',FCnames{1},i);
end
elseif length(FCnames)~=size(X,2)
error('FCnames doesn''t match covariate/X matrix')
else
Pnames = FCnames;
end
case {'-(1)','~(1)'} %-Simple main effect ('~' ignores zero levels)
%=======================================================================
%-Sort out arguments
%-----------------------------------------------------------------------
if size(I,2)>1, error('Simple main effect requires vector index'), end
if any(I~=floor(I)), error('Non-integer indicator vector'), end
if isempty(FCnames), FCnames = {'<Fac>'};
elseif length(FCnames)>1, error('Too many FCnames'), end
nXrows = size(I,1);
% Sort out unique factor levels - ignore zero level in '~(1)' usage
%-----------------------------------------------------------------------
if Constraint(1)~='~'
[Index,idx,jdx] = unique(I');
kdx = [1:nXrows];
else
[Index,idx,jdx] = unique(I(I~=0)');
kdx = find(I~=0)';
if isempty(Index)
X=[]; Pnames={}; Index=[];
warning(['factor has only zero level - ',...
'returning empty DesMtx partition'])
return
end
end
%-Set up unconstrained X matrix & construct parameter name index
%-----------------------------------------------------------------------
nXcols = length(Index);
%-Columns in ascending order of corresponding factor level
X = zeros(nXrows,nXcols);
Pnames = cell(nXcols,1);
for ii=1:nXcols %-ii indexes i in Index
X(:,ii) = I==Index(ii);
%-Can't use: for i=Index, X(:,i) = I==i; end
% in case Index has holes &/or doesn't start at 1!
Pnames{ii} = sprintf('%s_{%d}',FCnames{1},Index(ii));
end
%-Don't append effect level if only one level
if nXcols==1, Pnames=FCnames; end
case {'-','~'} %-Main effect / interaction ('~' ignores zero levels)
%=======================================================================
if size(I,2)==1
%-Main effect - process directly
[X,Pnames,Index,idx,jdx,kdx] = spm_DesMtx(I,[Constraint,'(1)'],FCnames);
return
end
if any((I(:))~=floor(I(:))), error('Non-integer indicator vector'), end
% Sort out unique factor level combinations & build design matrix
%-----------------------------------------------------------------------
%-Make "raw" index to unique effects
nI = I - ones(size(I,1),1)*min(I);
tmp = max(I)-min(I)+1;
tmp = [fliplr(cumprod(tmp(end:-1:2))),1];
rIndex = sum(nI.*(ones(size(I,1),1)*tmp),2)+1;
%-Ignore combinations where any factor has level zero in '~' usage
if Constraint(1)=='~'
rIndex(any(I==0,2))=0;
if all(rIndex==0)
X=[]; Pnames={}; Index=[];
warning(['no non-zero factor level combinations - ',...
'returning empty DesMtx partition'])
return
end
end
%-Build design matrix based on unique factor combinations
[X,null,sIndex,idx,jdx,kdx]=spm_DesMtx(rIndex,[Constraint,'(1)']);
%-Sort out Index matrix
Index = I(kdx(idx),:)';
%-Construct parameter name index
%-----------------------------------------------------------------------
if isempty(FCnames)
tmp = ['<Fac1>',sprintf('*<Fac%d>',2:size(I,2))];
elseif length(FCnames)==size(I,2)
tmp = [FCnames{1},sprintf('*%s',FCnames{2:end})];
else
error('#FCnames mismatches #Factors in interaction')
end
Pnames = cell(size(Index,2),1);
for c = 1:size(Index,2)
Pnames{c} = ...
[sprintf('%s_{%d',tmp,Index(1,c)),sprintf(',%d',Index(2:end,c)),'}'];
end
case {'FxC','-FxC','~FxC'} %-Factor dependent covariate effect
% ('~' ignores zero factor levels)
%=======================================================================
%-Check
%-----------------------------------------------------------------------
if size(I,2)==1, error('FxC requires multi-column I'), end
F = I(:,1:end-1);
C = I(:,end);
if ~all(all(F==floor(F),1),2)
error('non-integer indicies in F partition of FxC'), end
if isempty(FCnames)
Fnames = '';
Cnames = '<Cov>';
elseif length(FCnames)==size(I,2)
Fnames = FCnames(1:end-1);
Cnames = FCnames{end};
else
error('#FCnames mismatches #Factors+#Cov in FxC')
end
%-Set up design matrix X & names matrix - ignore zero levels if '~FxC' use
%-----------------------------------------------------------------------
if Constraint(1)~='~', [X,Pnames,Index] = spm_DesMtx(F,'-',Fnames);
else [X,Pnames,Index] = spm_DesMtx(F,'~',Fnames); end
X = X.*(C*ones(1,size(X,2)));
Pnames = cellstr([repmat([Cnames,'@'],size(Index,2),1),char(Pnames)]);
case {'.','.0','+0','+0m'} %-Constrained simple main effect
%=======================================================================
if size(I,2)~=1, error('Simple main effect requires vector index'), end
[X,Pnames,Index] = spm_DesMtx(I,'-(1)',FCnames);
%-Impose constraint if more than one effect
%-----------------------------------------------------------------------
%-Apply uniqueness constraints ('.' & '+0') to last effect, which is
% in last column, since column i corresponds to level Index(i)
%-'.0' corner point constraint is applied to zero factor level only
nXcols = size(X,2);
zCol = find(Index==0);
if nXcols==1 && ~strcmp(Constraint,'.0')
error('only one level: can''t constrain')
elseif strcmp(Constraint,'.')
X(:,nXcols)=[]; Pnames(nXcols)=[]; Index(nXcols)=[];
elseif strcmp(Constraint,'.0')
zCol = find(Index==0);
if isempty(zCol), warning('no zero level to constrain')
elseif nXcols==1, error('only one level: can''t constrain'), end
X(:,zCol)=[]; Pnames(zCol)=[]; Index(zCol)=[];
elseif strcmp(Constraint,'+0')
X(find(X(:,nXcols)),:)=-1;
X(:,nXcols)=[]; Pnames(nXcols)=[]; Index(nXcols)=[];
elseif strcmp(Constraint,'+0m')
X = X - 1/nXcols;
end
case {'.i','.i0','.j','.j0','.ij','.ij0','+i0','+j0','+ij0','+i0m','+j0m'}
%-Two way interaction effects
%=======================================================================
if size(I,2)~=2, error('Two way interaction requires Nx2 index'), end
[X,Pnames,Index] = spm_DesMtx(I,'-',FCnames);
%-Implicit sum to zero
%-----------------------------------------------------------------------
if any(strcmp(Constraint,{'+i0m','+j0m'}))
SumIToZero = strcmp(Constraint,'+i0m');
SumJToZero = strcmp(Constraint,'+j0m');
if SumIToZero %-impose implicit SumIToZero constraints
Js = sort(Index(2,:)); Js = Js([1,1+find(diff(Js))]);
for j = Js
rows = find(I(:,2)==j);
cols = find(Index(2,:)==j);
if length(cols)==1
error('Only one level: Can''t constrain')
end
X(rows,cols) = X(rows,cols) - 1/length(cols);
end
end
if SumJToZero %-impose implicit SumJToZero constraints
Is = sort(Index(1,:)); Is = Is([1,1+find(diff(Is))]);
for i = Is
rows = find(I(:,1)==i);
cols = find(Index(1,:)==i);
if length(cols)==1
error('Only one level: Can''t constrain')
end
X(rows,cols) = X(rows,cols) - 1/length(cols);
end
end
%-Explicit sum to zero
%-----------------------------------------------------------------------
elseif any(strcmp(Constraint,{'+i0','+j0','+ij0'}))
SumIToZero = any(strcmp(Constraint,{'+i0','+ij0'}));
SumJToZero = any(strcmp(Constraint,{'+j0','+ij0'}));
if SumIToZero %-impose explicit SumIToZero constraints
i = max(Index(1,:));
if i==min(Index(1,:))
error('Only one i level: Can''t constrain'), end
cols = find(Index(1,:)==i); %-columns to delete
for c=cols
j=Index(2,c);
t_cols=find(Index(2,:)==j);
t_rows=find(X(:,c));
%-This ij equals -sum(ij) over other i
% (j fixed for this col c).
%-So subtract weight of this ij factor from
% weights for all other ij factors for this j
% to impose the constraint.
X(t_rows,t_cols) = X(t_rows,t_cols)...
-X(t_rows,c)*ones(1,length(t_cols));
%-( Next line would do it, but only first time round, when all )
% ( weights are 1, and only one weight per row for this j. )
% X(t_rows,t_cols)=-1*ones(length(t_rows),length(t_cols));
end
%-delete columns
X(:,cols)=[]; Pnames(cols)=[]; Index(:,cols)=[];
end
if SumJToZero %-impose explicit SumJToZero constraints
j = max(Index(2,:));
if j==min(Index(2,:))
error('Only one j level: Can''t constrain'), end
cols=find(Index(2,:)==j);
for c=cols
i=Index(1,c);
t_cols=find(Index(1,:)==i);
t_rows=find(X(:,c));
X(t_rows,t_cols) = X(t_rows,t_cols)...
-X(t_rows,c)*ones(1,length(t_cols));
end
%-delete columns
X(:,cols)=[]; Pnames(cols)=[]; Index(:,cols)=[];
end
%-Corner point constraints
%-----------------------------------------------------------------------
elseif any(strcmp(Constraint,{'.i','.i0','.j','.j0','.ij','.ij0'}))
CornerPointI = any(strcmp(Constraint,{'.i','.i0','.ij','.ij0'}));
CornerPointJ = any(strcmp(Constraint,{'.j','.j0','.ij','.ij0'}));
if CornerPointI %-impose CornerPointI constraints
if Constraint(end)~='0', i = max(Index(1,:));
else i = 0; end
cols=find(Index(1,:)==i); %-columns to delete
if isempty(cols)
warning('no zero i level to constrain')
elseif all(Index(1,:)==i)
error('only one i level: can''t constrain')
end
%-delete columns
X(:,cols)=[]; Pnames(cols)=[]; Index(:,cols)=[];
end
if CornerPointJ %-impose CornerPointJ constraints
if Constraint(end)~='0', j = max(Index(2,:));
else j = 0; end
cols=find(Index(2,:)==j);
if isempty(cols)
warning('no zero j level to constrain')
elseif all(Index(2,:)==j)
error('only one j level: can''t constrain')
end
X(:,cols)=[]; Pnames(cols)=[]; Index(:,cols)=[];
end
end
case {'PDS','pds'} %-Patterned data set utility
%=======================================================================
% i = spm_DesMtx('pds',v,m,n)
if nargin<4, n=1; else n=varargin{4}; end
if nargin<3, m=1; else m=varargin{3}; end
if nargin<2, varargout={[]}; return, else v=varargin{2}; end
if any([size(n),size(m)])>1, error('n & m must be scalars'), end
if any(([m,n]~=floor([m,n]))|([m,n]<1))
error('n & m must be natural numbers'), end
if sum(size(v)>1)>1, error('v must be a vector'), end
%-Computation
%-----------------------------------------------------------------------
si = ones(1,ndims(v)); si(find(size(v)>1))=n*m*length(v);
X = reshape(repmat(v(:)',m,n),si);
case {'Sca','sca'} %-Scale DesMtx for imaging
%=======================================================================
nX = []; nPnames = {}; Carg = 2;
%-Loop through the arguments accumulating scaled design matrix nX
%-----------------------------------------------------------------------
while(Carg <= nargin)
rX = varargin{Carg}; Carg=Carg+1;
if Carg<=nargin && ~isempty(varargin{Carg}) && ...
(ischar(varargin{Carg}) || iscellstr(varargin{Carg}))
rPnames = char(varargin{Carg}); Carg=Carg+1;
else %-No names to work out blocks from - normalise by column
rPnames = repmat('<UnSpec>',size(rX,2),1);
end
%-Pad out rPnames with 20 spaces to permit looking past line ends
rPnames = [rPnames,repmat(' ',size(rPnames,1),20)];
while(~isempty(rX))
if size(rX,2)>1 && max([1,find(rPnames(1,:)=='(')]) < ...
max([0,find(rPnames(1,:)==')')])
%-Non-specific block: find the rest & column normalise round zero
%===============================================================
c1 = max(find(rPnames(1,:)=='('));
d = any(diff(abs(rPnames(:,1:c1))),2)...
| ~any(rPnames(2:end,c1+1:end)==')',2);
t = min(find([d;1]));
%-Normalise columns of block around zero
%-------------------------------------------------------
tmp = size(nX,2);
nX = [nX, zeros(size(rX,1),t)];
for i=1:t
if ~any(rX(:,i))
nX(:,tmp+i) = 0;
else
nX(:,tmp+i) = rX(:,i)/max(abs(rX(:,i)));
end
end
nPnames = [nPnames; cellstr(rPnames(1:t,:))];
rX(:,1:t) = []; rPnames(1:t,:)=[];
elseif size(rX,2)>1 && max([1,find(rPnames(1,:)=='[')]) < ...
max([0,find(rPnames(1,:)==']')])
%-Block: find the rest & normalise together
%===============================================================
c1 = max(find(rPnames(1,:)=='['));
d = any(diff(abs(rPnames(:,1:c1))),2)...
| ~any(rPnames(2:end,c1+1:end)==']',2);
t = min(find([d;1]));
%-Normalise block
%-------------------------------------------------------
nX = [nX,sf_tXsca(rX(:,1:t))];
nPnames = [nPnames; cellstr(rPnames(1:t,:))];
rX(:,1:t) = []; rPnames(1:t,:)=[];
elseif size(rX,2)>1 && max([1,strfind(rPnames(1,:),'_{')]) < ...
max([0,find(rPnames(1,:)=='}')])
%-Factor, interaction of factors, or FxC: find the rest...
%===============================================================
c1 = max(strfind(rPnames(1,:),'_{'));
d = any(diff(abs(rPnames(:,1:c1+1))),2)...
| ~any(rPnames(2:end,c1+2:end)=='}',2);
t = min(find([d;1]));
%-Normalise block
%-------------------------------------------------------
tX = rX(:,1:t);
if any(rPnames(1,1:c1)=='@') %-FxC interaction
C = tX(tX~=0);
tX(tX~=0) = 2*(C-min(C))/max(C-min(C))-1;
nX = [nX,tX];
else %-Straight interaction
nX = [nX,sf_tXsca(tX)];
end
nPnames = [nPnames; cellstr(rPnames(1:t,:))];
rX(:,1:t) = []; rPnames(1:t,:)=[];
else %-Dunno! Just column normalise
%===============================================================
nX = [nX,sf_tXsca(rX(:,1))];
nPnames = [nPnames; cellstr(rPnames(1,:))];
rX(:,1) = []; rPnames(1,:)=[];
end
end
end
X = nX;
Pnames = nPnames;
case {'Fnames','fnames'} %-Turn parameter names into valid filenames
%=======================================================================
% Fnames = spm_DesMtx('FNames',Pnames)
if nargin<2, varargout={''}; return, end
Fnames = varargin{2};
for i=1:numel(Fnames)
str = Fnames{i};
str(str==',')='x'; %-',' to 'x'
str(str=='*')='-'; %-'*' to '-'
str(str=='@')='-'; %-'@' to '-'
str(str==' ')='_'; %-' ' to '_'
str(str=='/')=''; %- delete '/'
str(str=='.')=''; %- delete '.'
Fnames{i} = str;
end
Fnames = spm_str_manip(Fnames,'v'); %- retain only legal characters
X = Fnames;
case {'TeXnames','texnames'} %-Remove '@' & '*' for TeX interpretation
%=======================================================================
% TPnames = spm_DesMtx('TeXnames',Pnames)
if nargin<2, varargout={''}; return, end
TPnames = varargin{2};
for i=1:prod(size(TPnames))
str = TPnames{i};
str(str=='*')=''; %- delete '*'
str(str=='@')=''; %- delete '@'
TPnames{i} = str;
end
X = TPnames;
case {'ParMap','parmap'} %-Parameter mappings: greek to english
%=======================================================================
% Map = spm_DesMtx('ParMap',aMap)
Map = { '\mu', 'const';...
'\theta', 'repl';...
'\alpha', 'cond';...
'\gamma', 'subj';...
'\rho', 'covint';...
'\zeta', 'global';...
'\epsilon', 'error'};
if nargin<2, aMap={}; else aMap = varargin{2}; end
if isempty(aMap), X=Map; return, end
if ~(iscellstr(aMap) && ndims(aMap)==2), error('aMap must be an nx2 cellstr'), end
for i=1:size(aMap,1)
j = find(strcmp(aMap{i,1},Map(:,1)));
if isempty(j)
Map=[aMap(i,:); Map];
else
Map(j,2) = aMap(i,2);
end
end
X = Map;
case {'ETeXNames','etexnames'} %-Search & replace: for Englishifying TeX
%=======================================================================
% EPnames = spm_DesMtx('TeXnames',Pnames,aMap)
if nargin<2, varargout={''}; return, end
if nargin<3, aMap={}; else aMap = varargin{3}; end
Map = spm_DesMtx('ParMap',aMap);
EPnames = varargin{2};
for i=1:size(Map,1)
EPnames = strrep(EPnames,Map{i,1},Map{i,2});
end
X = EPnames;
otherwise %-Mis-specified arguments - ERROR
%=======================================================================
if ischar(varargin{1})
error('unrecognised action string')
else
error('unrecognised constraint type')
end
%=======================================================================
end
%=======================================================================
% - S U B F U N C T I O N S
%=======================================================================
function nX = sf_tXsca(tX)
if nargin==0, nX=[]; return, end
if abs(max(abs(tX(:)))-0.7)<(.3+1e-10)
nX = tX;
elseif all(tX(:)==tX(1))
nX = ones(size(tX));
elseif max(abs(tX(:)))<1e-10
nX = zeros(size(tX));
else
nX = 2*(tX-min(tX(:)))/max(tX(:)-min(tX(:)))-1;
end
|
github
|
philippboehmsturm/antx-master
|
fdmar_gaus.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/fdmar_gaus.m
| 170 |
utf_8
|
eac4694c452b8f98050d5ab6c0c4f1e8
|
%change distribution of x to a gaussian distributed x
function Xgaus = fdmar_gaus(X)
[y,ind]=sort(X);
[y,ind2]=sort(ind);
Xgaus=norminv(ind2/(length(ind2)+1),0,1);
end
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_review_callbacks.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_eeg_review_callbacks.m
| 76,822 |
utf_8
|
b03008689db948693909fa44381632bb
|
function [varargout] = spm_eeg_review_callbacks(varargin)
% Callbacks of the M/EEG Review facility
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Jean Daunizeau
% $Id: spm_eeg_review_callbacks.m 3646 2009-12-16 16:01:03Z jean $
spm('pointer','watch');
drawnow expose
try
D = get(spm_figure('FindWin','Graphics'),'userdata');
handles = D.PSD.handles;
end
switch varargin{1}
%% File I/O
case 'file'
switch varargin{2}
case 'save'
D0 = D;
D = meeg(rmfield(D,'PSD'));
save(D);
D = D0;
D.PSD.D0 = rmfield(D,'PSD');
set(D.PSD.handles.hfig,'userdata',D)
set(D.PSD.handles.BUTTONS.pop1,...
'BackgroundColor',[0.8314 0.8157 0.7843])
case 'saveHistory'
spm_eeg_history(D);
end
%% Get information from MEEG object
case 'get'
switch varargin{2}
case 'VIZU'
visuSensors = varargin{3};
VIZU.visuSensors = visuSensors;
VIZU.montage.clab = {D.channels(visuSensors).label};
if strcmp(D.transform.ID,'time')
M = sparse(length(visuSensors),length(D.channels));
M(sub2ind(size(M),1:length(visuSensors),visuSensors(:)')) = 1;
nts = min([2e2,D.Nsamples]);
decim = max([floor(D.Nsamples./nts),1]);
data = D.data.y(visuSensors,1:decim:D.Nsamples,:);
sd = mean(abs(data(:)-mean(data(:))));%std(data(:));
offset = (0:1:length(visuSensors)-1)'*(sd+eps)/2;
v_data = 0.25.*data +repmat(offset,[1 size(data,2) size(data,3)]);
ma = max(v_data(:))+sd;
mi = min(v_data(:))-sd;
ylim = [mi ma];
VIZU.visu_scale = 0.25;
VIZU.FontSize = 10;
VIZU.visu_offset = sd;
VIZU.offset = offset;
VIZU.ylim = ylim;
VIZU.ylim0 = ylim;
VIZU.figname = 'main visualization window';
VIZU.montage.M = M;
VIZU.y2 = permute(sum(data.^2,1),[2 3 1]);
VIZU.sci = size(VIZU.y2,1)./D.Nsamples;
else
nts = min([2e2,D.Nsamples*length(D.transform.frequencies)]);
decim = max([floor(D.Nsamples*length(D.transform.frequencies)./nts),1]);
data = D.data.y(visuSensors,:,1:decim:D.Nsamples,:);
VIZU.ylim = [min(data(:)) max(data(:))];
end
varargout{1} = VIZU;
return
case 'commentInv'
invN = varargin{3};
str = getInfo4Inv(D,invN);
varargout{1} = str;
return
case 'dataInfo'
str = getInfo4Data(D);
varargout{1} = str;
return
case 'uitable'
D = getUItable(D);
case 'prep'
Finter = spm_figure('GetWin','Interactive');
D = struct(get(Finter, 'UserData'));
D0 = D.other(1).D0;
D.other = rmfield(D.other,{'PSD','D0'});
d1 = rmfield(D,'history');
d0 = rmfield(D0,'history');
if isequal(d1,d0)
% The objects only differ by their history
% => remove last operation from modified object
D.history(end) = [];
end
spm_eeg_review(D);
hf = spm_figure('FindWin','Graphics');
D = get(hf,'userdata');
D.PSD.D0 = D0;
set(hf,'userdata',D);
spm_eeg_review_callbacks('visu','update')
spm_clf(Finter)
end
%% Visualization callbacks
case 'visu'
switch varargin{2}
%% Switch main uitabs: EEG/MEG/OTHER/INFO/SOURCE
case 'main'
try
D.PSD.VIZU.fromTab = D.PSD.VIZU.modality;
catch
D.PSD.VIZU.fromTab = [];
end
switch varargin{3}
case 'eeg'
D.PSD.VIZU.modality = 'eeg';
case 'meg'
D.PSD.VIZU.modality = 'meg';
case 'megplanar'
D.PSD.VIZU.modality = 'megplanar';
case 'other'
D.PSD.VIZU.modality = 'other';
case 'source'
D.PSD.VIZU.modality = 'source';
case 'info';
D.PSD.VIZU.modality = 'info';
try
D.PSD.VIZU.info = varargin{4};
end
case 'standard'
D.PSD.VIZU.type = 1;
case 'scalp'
D.PSD.VIZU.type = 2;
end
try,D.PSD.VIZU.xlim = get(handles.axes(1),'xlim');end
[D] = spm_eeg_review_switchDisplay(D);
try
updateDisp(D,1);
catch
set(D.PSD.handles.hfig,'userdata',D);
end
%% Switch from 'standard' to 'scalp' display type
case 'switch'
mod = get(gcbo,'userdata');
if ~isequal(mod,D.PSD.VIZU.type)
if mod == 1
spm_eeg_review_callbacks('visu','main','standard')
else
spm_eeg_review_callbacks('visu','main','scalp')
end
end
%% Update display
case 'update'
try D = varargin{3};end
updateDisp(D)
%% Scalp interpolation
case 'scalp_interp'
if ~isempty([D.channels(:).X_plot2D])
x = round(mean(get(handles.axes(1),'xlim')));
ylim = get(handles.axes(1),'ylim');
if D.PSD.VIZU.type==1
in.hl = line('parent',handles.axes,...
'xdata',[x;x],...
'ydata',[ylim(1);ylim(2)]);
end
switch D.PSD.type
case 'continuous'
trN = 1;
case 'epoched'
trN = D.PSD.trials.current(1);
in.trN = trN;
end
in.gridTime = (1:D.Nsamples).*1e3./D.Fsample + D.timeOnset.*1e3;
in.unit = 'ms';
in.x = x;
in.handles = handles;
switch D.PSD.VIZU.modality
case 'eeg'
I = D.PSD.EEG.I;
in.type = 'EEG';
case 'meg'
I = D.PSD.MEG.I;
in.type = 'MEG';
case 'megplanar'
I = D.PSD.MEGPLANAR.I;
in.type = 'MEGPLANAR';
case 'other'
I = D.PSD.other.I;
in.type = 'other';
end
I = intersect(I,find(~[D.channels.bad]));
try
pos(:,1) = [D.channels(I).X_plot2D]';
pos(:,2) = [D.channels(I).Y_plot2D]';
labels = {D.channels(I).label};
y = D.data.y(I,:,trN);
in.min = min(y(:));
in.max = max(y(:));
in.ind = I;
y = y(:,x);
spm_eeg_plotScalpData(y,pos,labels,in);
try
D.PSD.handles.hli = in.hl;
set(D.PSD.handles.hfig,'userdata',D);
end
catch
msgbox('Get 2d positions for these channels!')
end
else
msgbox('Get 2d positions for EEG/MEG channels!')
end
%% Display sensor positions (and canonical cortical mesh)
case 'sensorPos'
% get canonical mesh
mco = fullfile(spm('Dir'),'canonical','cortex_5124.surf.gii');
msc = fullfile(spm('Dir'),'canonical','scalp_2562.surf.gii');
% get and plot 3D sensor positions
try % EEG
try
for i=1:numel(D.other.inv{end}.datareg)
if isequal(D.other.inv{end}.datareg(i).modality,'EEG')
pos3d = spm_eeg_inv_transform_points(...
D.other.inv{end}.datareg(i).toMNI,...
D.other.inv{end}.datareg(i).sensors.pnt);
end
end
opt.figname = 'Coregistred EEG sensor positions';
catch
pos3d = [D.sensors.eeg.pnt];
pos3d = pos3d(D.PSD.EEG.I,:);
opt.figname = 'Uncoregistred EEG sensor positions';
end
pos3d(1,:);
% display canonical mesh
o = spm_eeg_render(mco,opt);
opt.hfig = o.handles.fi;
opt.ParentAxes = o.handles.ParentAxes;
o = spm_eeg_render(msc,opt);
set(o.handles.p,'FaceAlpha',0.75)
set(o.handles.transp,'value',0.75)
% display sensor position
figure(o.handles.fi);
set(opt.ParentAxes,'nextplot','add')
plot3(opt.ParentAxes,...
pos3d(:,1),pos3d(:,2),pos3d(:,3),'.');
try
labels = D.PSD.EEG.VIZU.montage.clab;
text(pos3d(:,1),pos3d(:,2),pos3d(:,3),...
labels,...
'parent',opt.ParentAxes);
end
axis(opt.ParentAxes,'equal')
axis(opt.ParentAxes,'tight')
axis(opt.ParentAxes,'off')
end
try % MEG
clear opt pos3d o labels
try % multimodal EEG/MEG
for i=1:numel(D.other.inv{end}.datareg)
if isequal(D.other.inv{end}.datareg(i).modality,'MEG')
pos3d = spm_eeg_inv_transform_points(...
D.other.inv{end}.datareg(i).toMNI,...
D.other.inv{end}.datareg(i).sensors.pnt);
end
end
opt.figname = 'Coregistred MEG sensor positions';
catch
pos3d = [D.sensors.meg.pnt];
opt.figname = 'Uncoregistred MEG sensor positions';
end
pos3d(1,:);
% display canonical mesh
o = spm_eeg_render(mco,opt);
opt.hfig = o.handles.fi;
opt.ParentAxes = o.handles.ParentAxes;
o = spm_eeg_render(msc,opt);
set(o.handles.p,'FaceAlpha',0.75)
set(o.handles.transp,'value',0.75)
% display sensor position
figure(o.handles.fi);
set(opt.ParentAxes,'nextplot','add')
plot3(opt.ParentAxes,...
pos3d(:,1),pos3d(:,2),pos3d(:,3),'.');
try
labels = cat(2,...
D.PSD.MEG.VIZU.montage.clab,...
D.PSD.MEGPLANAR.VIZU.montage.clab);
text(pos3d(:,1),pos3d(:,2),pos3d(:,3),...
labels,...
'parent',opt.ParentAxes);
end
axis(opt.ParentAxes,'equal')
axis(opt.ParentAxes,'tight')
axis(opt.ParentAxes,'off')
end
%% Update display for 'SOURCE' main tab
case 'inv'
cla(D.PSD.handles.axes2,'reset')
D.PSD.source.VIZU.current = varargin{3};
updateDisp(D);
%% Check xlim when resizing display window using 'standard'
%% display type
case 'checkXlim'
xlim = varargin{3};
ud = get(D.PSD.handles.gpa,'userdata');
xm = mean(xlim);
sw = abs(diff(xlim));
if sw <= ud.v.minSizeWindow
sw = ud.v.minSizeWindow;
elseif sw >= ud.v.nt
sw = ud.v.maxSizeWindow;
elseif sw >= ud.v.maxSizeWindow
sw = ud.v.maxSizeWindow;
end
if xlim(1) <= 1 && xlim(end) >= ud.v.nt
xlim = [1,ud.v.nt];
elseif xlim(1) <= 1
xlim = [1,sw];
elseif xlim(end) >= ud.v.nt
xlim = [ud.v.nt-sw+1,ud.v.nt];
end
% Restrain buttons usage:
if isequal(xlim,[1,ud.v.nt])
set(D.PSD.handles.BUTTONS.vb3,'enable','off')
set(handles.BUTTONS.slider_step,'visible','off')
set(D.PSD.handles.BUTTONS.goPlusOne,'visible','off');
set(D.PSD.handles.BUTTONS.goMinusOne,'visible','off');
else
set(handles.BUTTONS.slider_step,...
'min',sw/2,'max',ud.v.nt-sw/2+1,...
'value',mean(xlim),...
'sliderstep',.1*[sw/(ud.v.nt-1) 4*sw/(ud.v.nt-1)],...
'visible','on');
set(D.PSD.handles.BUTTONS.goPlusOne,'visible','on');
set(D.PSD.handles.BUTTONS.goMinusOne,'visible','on');
if isequal(sw,ud.v.maxSizeWindow)
set(D.PSD.handles.BUTTONS.vb3,'enable','off')
set(D.PSD.handles.BUTTONS.vb4,'enable','on')
elseif isequal(sw,ud.v.minSizeWindow)
set(D.PSD.handles.BUTTONS.vb4,'enable','off')
set(D.PSD.handles.BUTTONS.vb3,'enable','on')
else
set(D.PSD.handles.BUTTONS.vb4,'enable','on')
set(D.PSD.handles.BUTTONS.vb3,'enable','on')
end
if xlim(1) == 1
set(D.PSD.handles.BUTTONS.goMinusOne,...
'visible','on','enable','off');
set(D.PSD.handles.BUTTONS.goPlusOne,...
'visible','on','enable','on');
elseif xlim(2) == ud.v.nt
set(D.PSD.handles.BUTTONS.goPlusOne,...
'visible','on','enable','off');
set(D.PSD.handles.BUTTONS.goMinusOne,...
'visible','on','enable','on');
else
set(D.PSD.handles.BUTTONS.goPlusOne,...
'visible','on','enable','on');
set(D.PSD.handles.BUTTONS.goMinusOne,...
'visible','on','enable','on');
end
end
if nargout >= 1
varargout{1} = xlim;
else
D.PSD.VIZU.xlim = xlim;
set(D.PSD.handles.hfig,'userdata',D)
end
%% Contrast/intensity rescaling
case 'iten_sc'
switch D.PSD.VIZU.modality
case 'eeg'
D.PSD.EEG.VIZU.visu_scale = varargin{3}*D.PSD.EEG.VIZU.visu_scale;
case 'meg'
D.PSD.MEG.VIZU.visu_scale = varargin{3}*D.PSD.MEG.VIZU.visu_scale;
case 'megplanar'
D.PSD.MEGPLANAR.VIZU.visu_scale = varargin{3}*D.PSD.MEGPLANAR.VIZU.visu_scale;
case 'other'
D.PSD.other.VIZU.visu_scale = varargin{3}*D.PSD.other.VIZU.visu_scale;
end
updateDisp(D,3);
%% Resize plotted data window ('standard' display type)
case 'time_w'
% Get current plotted data window range and limits
xlim = get(handles.axes(1),'xlim');
sw = varargin{3}*diff(xlim);
xm = mean(xlim);
xlim = xm + 0.5*[-sw,sw];
xlim = spm_eeg_review_callbacks('visu','checkXlim',xlim);
D.PSD.VIZU.xlim = xlim;
updateDisp(D,4)
%% Scroll through data ('standard' display type)
case 'slider_t'
offset = get(gco,'value');
updateDisp(D)
%% Scroll through data page by page ('standard' display type)
case 'goOne'
% Get current plotted data window range and limits
xlim = get(handles.axes(1),'xlim');
sw = diff(xlim);
xlim = xlim +varargin{3}*sw;
xlim = spm_eeg_review_callbacks('visu','checkXlim',xlim);
D.PSD.VIZU.xlim = xlim;
updateDisp(D,4)
%% Zoom
case 'zoom'
switch D.PSD.VIZU.type
case 1 % 'standard' display type
if ~isempty(D.PSD.handles.zoomh)
switch get(D.PSD.handles.zoomh,'enable')
case 'on'
set(D.PSD.handles.zoomh,'enable','off')
case 'off'
set(D.PSD.handles.zoomh,'enable','on')
end
else
if get(D.PSD.handles.BUTTONS.vb5,'value')
zoom on;
else
zoom off;
end
%set(D.PSD.handles.BUTTONS.vb5,'value',~val);
end
case 2 % 'scalp' display type
set(D.PSD.handles.BUTTONS.vb5,'value',1)
switch D.PSD.VIZU.modality
case 'eeg'
VIZU = D.PSD.EEG.VIZU;
case 'meg'
VIZU = D.PSD.MEG.VIZU;
case 'megplanar'
VIZU = D.PSD.MEGPLANAR.VIZU;
case 'other'
VIZU = D.PSD.other.VIZU;
end
try axes(D.PSD.handles.scale);end
[x] = ginput(1);
indAxes = get(gco,'userdata');
if ~~indAxes
hf = figure('color',[1 1 1]);
chanLabel = D.channels(VIZU.visuSensors(indAxes)).label;
if D.channels(VIZU.visuSensors(indAxes)).bad
chanLabel = [chanLabel,' (BAD)'];
end
set(hf,'name',['channel ',chanLabel])
ha2 = axes('parent',hf,...
'nextplot','add',...
'XGrid','on','YGrid','on');
trN = D.PSD.trials.current(:);
Ntrials = length(trN);
if strcmp(D.transform.ID,'time')
leg = cell(Ntrials,1);
col = lines;
col = repmat(col(1:7,:),floor(Ntrials./7)+1,1);
hp = get(handles.axes(indAxes),'children');
pst = (0:1/D.Fsample:(D.Nsamples-1)/D.Fsample) + D.timeOnset;
pst = pst*1e3; % in msec
for i=1:Ntrials
datai = get(hp(Ntrials-i+1),'ydata')./VIZU.visu_scale;
plot(ha2,pst,datai,'color',col(i,:));
leg{i} = D.PSD.trials.TrLabels{trN(i)};
end
legend(leg)
set(ha2,'xlim',[min(pst),max(pst)],...
'ylim',get(D.PSD.handles.axes(indAxes),'ylim'))
xlabel(ha2,'time (in ms after time onset)')
unit = 'unknown';
try
unit = D.channels(VIZU.visuSensors(indAxes)).units;
end
if isequal(unit,'unknown')
ylabel(ha2,'field intensity ')
else
ylabel(ha2,['field intensity (in ',unit,')'])
end
title(ha2,['channel ',chanLabel,...
' (',D.channels(VIZU.visuSensors(indAxes)).type,')'])
else % time-frequency data
datai = squeeze(D.data.y(VIZU.visuSensors(indAxes),:,:,trN(1)));
pst = (0:1/D.Fsample:(D.Nsamples-1)/D.Fsample) + D.timeOnset;
pst = pst*1e3; % in msec
if any(size(datai)==1)
hp2 = plot(datai,...
'parent',ha2);
set(ha2,'xtick',1:10:length(pst),'xticklabel',pst(1:10:length(pst)),...
'xlim',[1 length(pst)]);
xlabel(ha2,'time (in ms after time onset)')
ylabel(ha2,'power in frequency space')
title(ha2,['channel ',chanLabel,...
' (',D.channels(VIZU.visuSensors(indAxes)).type,')',...
' -- frequency: ',num2str(D.transform.frequencies),' Hz'])
else
nx = max([1,length(pst)./10]);
xtick = floor(1:nx:length(pst));
ny = max([1,length(D.transform.frequencies)./10]);
ytick = floor(1:ny:length(D.transform.frequencies));
hp2 = image(datai,...
'CDataMapping','scaled',...
'parent',ha2);
colormap(ha2,jet)
colorbar('peer',ha2)
set(ha2,...
'xtick',xtick,...
'xticklabel',pst(xtick),...
'xlim',[0.5 length(pst)+0.5],...
'ylim',[0.5 size(datai,1)+0.5],...
'ytick',ytick,...
'yticklabel',D.transform.frequencies(ytick));
xlabel(ha2,'time (in ms after time onset)')
ylabel(ha2,'frequency (in Hz)')
title(ha2,['channel ',chanLabel,...
' (',D.channels(VIZU.visuSensors(indAxes)).type,')'])
caxis(ha2,VIZU.ylim)
end
end
axes(ha2)
end
set(D.PSD.handles.BUTTONS.vb5,'value',0)
end
otherwise;disp('unknown command !')
end
%% Events callbacks accessible from uicontextmenu
%% ('standard' display type when playing with 'continuous' data)
case 'menuEvent'
Nevents = length(D.trials.events);
x = [D.trials.events.time]';
x(:,2) = [D.trials.events.duration]';
x(:,2) = sum(x,2);
% Find the index of the selected event
currentEvent = get(gco,'userdata');
eventType = D.trials.events(currentEvent).type;
eventValue = D.trials.events(currentEvent).value;
tit = ['Current event is selection #',num2str(currentEvent),...
' /',num2str(Nevents),' (type= ',eventType,', value=',num2str(eventValue),').'];
switch varargin{2}
% Execute actions accessible from the event contextmenu : click
case 'click'
% Highlight the selected event
hh = findobj('selected','on');
set(hh,'selected','off');
set(gco,'selected','on')
% Prompt basic information on the selected event
disp(tit)
% Execute actions accessible from the event contextmenu : edit event properties
case 'EventProperties'
set(gco,'selected','on')
% Build GUI for manipulating the event properties
stc = cell(4,1);
default = cell(4,1);
stc{1} = 'Current event is a selection of type...';
stc{2} = 'Current event has value...';
stc{3} = 'Starts at (sec)...';
stc{4} = 'Duration (sec)...';
default{1} = eventType;
default{2} = num2str(eventValue);
default{3} = num2str(x(currentEvent,1));
default{4} = num2str(abs(diff(x(currentEvent,:))));
answer = inputdlg(stc,tit,1,default);
if ~isempty(answer)
try
eventType = answer{1};
eventValue = str2double(answer{2});
D.trials.events(currentEvent).time = str2double(answer{3});
D.trials.events(currentEvent).duration = str2double(answer{4});
D.trials.events(currentEvent).type = eventType;
D.trials.events(currentEvent).value = eventValue;
end
updateDisp(D,2,currentEvent)
end
% Execute actions accessible from the event contextmenu : go to next/previous event
case 'goto'
here = mean(x(currentEvent,:));
values = [D.trials.events.value];
xm = mean(x(values==eventValue,:),2);
if varargin{3} == 0
ind = find(xm < here);
else
ind = find(xm > here);
end
if ~isempty(ind)
if varargin{3} == 0
offset = round(max(xm(ind))).*D.Fsample;
else
offset = round(min(xm(ind))).*D.Fsample;
end
xlim0 = get(handles.axes,'xlim');
if ~isequal(xlim0,[1 D.Nsamples])
length_window = round(xlim0(2)-xlim0(1));
if offset < round(0.5*length_window)
offset = round(0.5*length_window);
set(handles.BUTTONS.slider_step,'value',1);
elseif offset > D.Nsamples-round(0.5*length_window)
offset = D.Nsamples-round(0.5*length_window)-1;
set(handles.BUTTONS.slider_step,'value',get(handles.BUTTONS.slider_step,'max'));
else
set(handles.BUTTONS.slider_step,'value',offset);
end
xlim = [offset-round(0.5*length_window) offset+round(0.5*length_window)];
xlim(1) = max([xlim(1) 1]);
xlim(2) = min([xlim(2) D.Nsamples]);
D.PSD.VIZU.xlim = xlim;
updateDisp(D,4)
end
end
% Execute actions accessible from the event contextmenu : delete event
case 'deleteEvent'
D.trials.events(currentEvent) = [];
updateDisp(D,2)
end
%% Events callbacks
case 'select'
switch varargin{2}
%% Switch to another trial (when playing with 'epoched' data)
case 'switch'
trN = get(gco,'value');
if ~strcmp(D.PSD.VIZU.modality,'source') && D.PSD.VIZU.type == 2
handles = rmfield(D.PSD.handles,'PLOT');
D.PSD.handles = handles;
else
try cla(D.PSD.handles.axes2,'reset');end
end
D.PSD.trials.current = trN;
status = any([D.trials(trN).bad]);
try
if status
str = 'declare as not bad';
else
str = 'declare as bad';
end
ud = get(D.PSD.handles.BUTTONS.badEvent,'userdata');
set(D.PSD.handles.BUTTONS.badEvent,...
'tooltipstring',str,...
'cdata',ud.img{2-status},'userdata',ud)
end
updateDisp(D,1)
%% Switch event to 'bad' (when playing with 'epoched' data)
case 'bad'
trN = D.PSD.trials.current;
status = any([D.trials(trN).bad]);
str1 = 'not bad';
str2 = 'bad';
if status
bad = 0;
lab = [' (',str1,')'];
str = ['declare as ',str2];
else
bad = 1;
lab = [' (',str2,')'];
str = ['declare as ',str1];
end
nt = length(trN);
for i=1:nt
D.trials(trN(i)).bad = bad;
D.PSD.trials.TrLabels{trN(i)} = ['Trial ',num2str(trN(i)),...
': ',D.trials(trN(i)).label,lab];
end
set(D.PSD.handles.BUTTONS.list1,'string',D.PSD.trials.TrLabels);
ud = get(D.PSD.handles.BUTTONS.badEvent,'userdata');
set(D.PSD.handles.BUTTONS.badEvent,...
'tooltipstring',str,...
'cdata',ud.img{2-bad},'userdata',ud)
set(D.PSD.handles.hfig,'userdata',D)
%% Add an event to current selection
%% (when playing with 'continuous' data)
case 'add'
[x,tmp] = ginput(1);
x = round(x);
x(1) = min([max([1 x(1)]) D.Nsamples]);
Nevents = length(D.trials.events);
D.trials.events(Nevents+1).time = x./D.Fsample;
D.trials.events(Nevents+1).duration = 0;
D.trials.events(Nevents+1).type = 'Manual';
D.PSD.handles.PLOT.e(Nevents+1) = 0;
if Nevents > 0
D.trials.events(Nevents+1).value = D.trials.events(Nevents).value;
else
D.trials.events(Nevents+1).value = 0;
end
% Enable tools on selections
set(handles.BUTTONS.sb2,'enable','on');
set(handles.BUTTONS.sb3,'enable','on');
% Update display
updateDisp(D,2,Nevents+1)
%% scroll through data upto next event
%% (when playing with 'continuous' data)
case 'goto'
here = get(handles.BUTTONS.slider_step,'value');
x = [D.trials.events.time]';
xm = x.*D.Fsample;
if varargin{3} == 0
ind = find(xm > here+1);
else
ind = find(xm < here-1);
end
if ~isempty(ind)
if varargin{3} == 1
offset = round(max(xm(ind)));
else
offset = round(min(xm(ind)));
end
xlim0 = get(handles.axes,'xlim');
if ~isequal(xlim0,[1 D.Nsamples])
length_window = round(xlim0(2)-xlim0(1));
if offset < round(0.5*length_window)
offset = round(0.5*length_window);
set(handles.BUTTONS.slider_step,'value',1);
elseif offset > D.Nsamples-round(0.5*length_window)
offset = D.Nsamples-round(0.5*length_window)-1;
set(handles.BUTTONS.slider_step,'value',get(handles.BUTTONS.slider_step,'max'));
else
set(handles.BUTTONS.slider_step,'value',offset);
end
xlim = [offset-round(0.5*length_window) offset+round(0.5*length_window)];
xlim(1) = max([xlim(1) 1]);
xlim(2) = min([xlim(2) D.Nsamples]);
D.PSD.VIZU.xlim = xlim;
set(handles.BUTTONS.slider_step,'value',offset);
updateDisp(D,4)
end
end
end
%% Edit callbacks (from spm_eeg_prep_ui)
case 'edit'
switch varargin{2}
case 'prep'
try rotate3d off;end
spm_eeg_prep_ui;
Finter = spm_figure('GetWin','Interactive');
D0 = D.PSD.D0;
D = rmfield(D,'PSD');
if isempty(D.other)
D.other = struct([]);
end
D.other(1).PSD = 1;
D.other(1).D0 = D0;
D = meeg(D);
set(Finter, 'UserData', D);
hc = get(Finter,'children');
delete(hc(end)); % get rid of 'file' uimenu...
%... and add an 'OK' button:
uicontrol(Finter,...
'style','pushbutton','string','OK',...
'callback','spm_eeg_review_callbacks(''get'',''prep'')',...
'tooltipstring','Update data informations in ''SPM Graphics'' window',...
'BusyAction','cancel',...
'Interruptible','off',...
'Tag','EEGprepUI');
spm_eeg_prep_ui('update_menu')
delete(setdiff(findobj(Finter), [Finter; findobj(Finter,'Tag','EEGprepUI')]));
figure(Finter);
end
end
% Check changes in the meeg object
if isstruct(D)&& isfield(D,'PSD') && ...
isfield(D.PSD,'D0')
d1 = rmfield(D,{'history','PSD'});
d0 = rmfield(D.PSD.D0,'history');
if isequal(d1,d0)
set(D.PSD.handles.BUTTONS.pop1,...
'BackgroundColor',[0.8314 0.8157 0.7843])
else
set(D.PSD.handles.BUTTONS.pop1,...
'BackgroundColor',[1 0.5 0.5])
end
end
spm('pointer','arrow');
drawnow expose
%% Main update display
function [] = updateDisp(D,flags,in)
% This function updates the display of the data and events.
if ~exist('flag','var')
flag = 0;
end
if ~exist('in','var')
in = [];
end
handles = D.PSD.handles;
% Create intermediary display variables : events
figure(handles.hfig)
% Get current event
try
trN = D.PSD.trials.current;
catch
trN = 1;
end
if ~strcmp(D.PSD.VIZU.modality,'source')
switch D.PSD.VIZU.modality
case 'eeg'
VIZU = D.PSD.EEG.VIZU;
case 'meg'
VIZU = D.PSD.MEG.VIZU;
case 'megplanar'
VIZU = D.PSD.MEGPLANAR.VIZU;
case 'other'
VIZU = D.PSD.other.VIZU;
case 'info'
return
end
switch D.PSD.VIZU.type
case 1
% Create new data to display
% - switch from scalp to standard displays
% - switch from EEG/MEG/OTHER/info/inv
if ismember(1,flags)
% delete previous axes...
try
delete(D.PSD.handles.axes)
delete(D.PSD.handles.gpa)
delete(D.PSD.handles.BUTTONS.slider_step)
end
% gather info for core display function
options.hp = handles.hfig;
options.Fsample = D.Fsample;
options.timeOnset = D.timeOnset;
options.M = VIZU.visu_scale*full(VIZU.montage.M);
options.bad = [D.channels(VIZU.visuSensors(:)).bad];
if strcmp(D.PSD.type,'continuous') && ~isempty(D.trials.events)
trN = 1;
Nevents = length(D.trials.events);
x1 = {D.trials.events(:).type}';
x2 = {D.trials.events(:).value}';
if ~iscellstr(x1)
[y1,i1,j1] = unique(cell2mat(x1));
else
[y1,i1,j1] = unique(x1);
end
if ~iscellstr(x2)
[y2,i2,j2] = unique(cell2mat(x2));
else
[y2,i2,j2] = unique(x2);
end
A = [j1(:),j2(:)];
[ya,ia,ja] = unique(A,'rows');
options.events = rmfield(D.trials.events,{'duration','value'});
for i=1:length(options.events)
options.events(i).time = options.events(i).time.*D.Fsample;% +1;
options.events(i).type = ja(i);
end
end
if strcmp(D.PSD.type,'continuous')
options.minSizeWindow = 200;
try
options.itw = round(D.PSD.VIZU.xlim(1):D.PSD.VIZU.xlim(2));
end
elseif strcmp(D.PSD.type,'epoched')
options.minSizeWindow = 20;
try
options.itw = round(D.PSD.VIZU.xlim(1):D.PSD.VIZU.xlim(2));
catch
options.itw = 1:D.Nsamples;
end
else
try
options.itw = round(D.PSD.VIZU.xlim(1):D.PSD.VIZU.xlim(2));
catch
options.itw = 1:D.Nsamples;
end
options.minSizeWindow = 20;
end
options.minY = min(VIZU.ylim)-eps;
options.maxY = max(VIZU.ylim)+eps;
options.ds = 5e2;
options.pos1 = [0.08 0.11 0.86 0.79];
options.pos2 = [0.08 0.07 0.86 0.025];
options.pos3 = [0.08 0.02 0.86 0.02];
options.maxSizeWindow = 1e5;
options.tag = 'plotEEG';
options.offset = VIZU.offset;
options.ytick = VIZU.offset;
options.yticklabel = VIZU.montage.clab;
options.callback = ['spm_eeg_review_callbacks(''visu'',''checkXlim''',...
',get(ud.v.handles.axes,''xlim''))'];
% Use file_array for 'continuous' data.
if strcmp(D.PSD.type,'continuous')
options.transpose = 1;
ud = spm_DisplayTimeSeries(D.data.y,options);
else
ud = spm_DisplayTimeSeries(D.data.y(:,:,trN(1))',options);
end
% update D
D.PSD.handles.axes = ud.v.handles.axes;
D.PSD.handles.gpa = ud.v.handles.gpa;
D.PSD.handles.BUTTONS.slider_step = ud.v.handles.hslider;
D.PSD.handles.PLOT.p = ud.v.handles.hp;
% Create uicontextmenu for events (if any)
if isfield(options,'events')
D.PSD.handles.PLOT.e = [ud.v.et(:).hp];
axes(D.PSD.handles.axes)
for i=1:length(options.events)
sc.currentEvent = i;
sc.eventType = D.trials(trN(1)).events(i).type;
sc.eventValue = D.trials(trN(1)).events(i).value;
sc.N_select = Nevents;
psd_defineMenuEvent(D.PSD.handles.PLOT.e(i),sc);
end
end
for i=1:length(D.PSD.handles.PLOT.p)
cmenu = uicontextmenu;
uimenu(cmenu,'Label',['channel ',num2str(VIZU.visuSensors(i)),': ',VIZU.montage.clab{i}]);
uimenu(cmenu,'Label',['type: ',D.channels(VIZU.visuSensors(i)).type]);
uimenu(cmenu,'Label',['bad: ',num2str(D.channels(VIZU.visuSensors(i)).bad)],...
'callback',@switchBC,'userdata',i,...
'BusyAction','cancel',...
'Interruptible','off');
set(D.PSD.handles.PLOT.p(i),'uicontextmenu',cmenu);
end
set(D.PSD.handles.hfig,'userdata',D);
spm_eeg_review_callbacks('visu','checkXlim',...
get(D.PSD.handles.axes,'xlim'))
end
% modify events properties (delete,add,time,...)
if ismember(2,flags)
Nevents = length(D.trials.events);
if Nevents < length(D.PSD.handles.PLOT.e)
action = 'delete';
try,delete(D.PSD.handles.PLOT.e),end
try,D.PSD.handles.PLOT.e = [];end
else
action = 'modify';
end
col = lines;
col = col(1:7,:);
x1 = {D.trials.events(:).type}';
x2 = {D.trials.events(:).value}';
if ~iscellstr(x1)
[y1,i1,j1] = unique(cell2mat(x1));
else
[y1,i1,j1] = unique(x1);
end
if ~iscellstr(x2)
[y2,i2,j2] = unique(cell2mat(x2));
else
[y2,i2,j2] = unique(x2);
end
A = [j1(:),j2(:)];
[ya,ia,ja] = unique(A,'rows');
events = rmfield(D.trials.events,{'duration','value'});
switch action
case 'delete'
%spm_progress_bar('Init',Nevents,'Replacing events');
axes(D.PSD.handles.axes)
for i=1:Nevents
events(i).time = D.trials.events(i).time.*D.Fsample;% +1;
events(i).type = ja(i);
events(i).col = mod(events(i).type+7,7)+1;
D.PSD.handles.PLOT.e(i) = plot(D.PSD.handles.axes,...
events(i).time.*[1 1],...
VIZU.ylim,...
'color',col(events(i).col,:),...
'userdata',i,...
'ButtonDownFcn','set(gco,''selected'',''on'')',...
'Clipping','on');
% Add events uicontextmenu
sc.currentEvent = i;
sc.eventType = D.trials(trN(1)).events(i).type;
sc.eventValue = D.trials(trN(1)).events(i).value;
sc.N_select = Nevents;
psd_defineMenuEvent(D.PSD.handles.PLOT.e(i),sc);
%spm_progress_bar('Set',i)
end
%spm_progress_bar('Clear')
case 'modify'
events(in).time = D.trials.events(in).time.*D.Fsample;% +1;
events(in).type = ja(in);
events(in).col = mod(events(in).type+7,7)+1;
D.PSD.handles.PLOT.e(in) = plot(D.PSD.handles.axes,events(in).time.*[1 1],...
VIZU.ylim,'color',col(events(in).col,:));
set(D.PSD.handles.PLOT.e(in),'userdata',in,...
'ButtonDownFcn','set(gco,''selected'',''on'')',...
'Clipping','on');
% Add events uicontextmenu
sc.currentEvent = in;
sc.eventType = D.trials(trN(1)).events(in).type;
sc.eventValue = D.trials(trN(1)).events(in).value;
sc.N_select = Nevents;
psd_defineMenuEvent(D.PSD.handles.PLOT.e(in),sc);
end
set(handles.hfig,'userdata',D);
end
% modify scaling factor
if ismember(3,flags)
ud = get(D.PSD.handles.gpa,'userdata');
ud.v.M = VIZU.visu_scale*full(VIZU.montage.M);
xw = floor(get(ud.v.handles.axes,'xlim'));
xw(1) = max([1,xw(1)]);
if ~ud.v.transpose
My = ud.v.M*ud.y(xw(1):1:xw(2),:)';
else
My = ud.v.M*ud.y(:,xw(1):1:xw(2));
end
for i=1:ud.v.nc
set(ud.v.handles.hp(i),'xdata',xw(1):1:xw(2),'ydata',My(i,:)+ud.v.offset(i))
end
set(ud.v.handles.axes,'ylim',[ud.v.mi ud.v.ma],'xlim',xw);
set(D.PSD.handles.gpa,'userdata',ud);
set(handles.hfig,'userdata',D);
end
% modify plotted time window (goto, ...)
if ismember(4,flags)
ud = get(D.PSD.handles.gpa,'userdata');
xw = floor(D.PSD.VIZU.xlim);
xw(1) = max([1,xw(1)]);
if ~ud.v.transpose
My = ud.v.M*ud.y(xw(1):1:xw(2),:)';
else
My = ud.v.M*ud.y(:,xw(1):1:xw(2));
end
for i=1:ud.v.nc
set(ud.v.handles.hp(i),'xdata',xw(1):1:xw(2),'ydata',My(i,:)+ud.v.offset(i))
end
set(ud.v.handles.axes,'ylim',[ud.v.mi ud.v.ma],'xlim',xw);
set(ud.v.handles.pa,'xdata',[xw,fliplr(xw)]);
set(ud.v.handles.lb,'xdata',[xw(1) xw(1)]);
set(ud.v.handles.rb,'xdata',[xw(2) xw(2)]);
sw = diff(xw);
set(ud.v.handles.hslider,'value',mean(xw),...
'min',1+sw/2,'max',ud.v.nt-sw/2,...
'sliderstep',.1*[sw/(ud.v.nt-1) 4*sw/(ud.v.nt-1)]);
set(handles.hfig,'userdata',D);
end
case 2
if strcmp(D.transform.ID,'time')
Ntrials = length(trN);
v_data = zeros(size(VIZU.montage.M,1),...
size(D.data.y,2),Ntrials);
for i=1:Ntrials
v_datai = full(VIZU.montage.M)*D.data.y(:,:,trN(i));
v_datai = VIZU.visu_scale*(v_datai);
v_data(:,:,i) = v_datai;
end
% Create graphical objects if absent
if ~isfield(handles,'PLOT')
miY = min(v_data(:));
maY = max(v_data(:));
if miY == 0 && maY == 0
miY = -eps;
maY = eps;
else
miY = miY - miY.*1e-3;
maY = maY + maY.*1e-3;
end
for i=1:length(VIZU.visuSensors)
cmenu = uicontextmenu;
uimenu(cmenu,'Label',['channel ',num2str(VIZU.visuSensors(i)),': ',VIZU.montage.clab{i}]);
uimenu(cmenu,'Label',['type: ',D.channels(VIZU.visuSensors(i)).type]);
uimenu(cmenu,'Label',['bad: ',num2str(D.channels(VIZU.visuSensors(i)).bad)],...
'callback',@switchBC,'userdata',i,...
'BusyAction','cancel',...
'Interruptible','off');
status = D.channels(VIZU.visuSensors(i)).bad;
if ~status
color = [1 1 1];
else
color = 0.75*[1 1 1];
end
set(handles.fra(i),'uicontextmenu',cmenu);
set(handles.axes(i),'color',color,...
'ylim',[miY maY]./VIZU.visu_scale);
handles.PLOT.p(:,i) = plot(handles.axes(i),squeeze(v_data(i,:,:)),...
'uicontextmenu',cmenu,'userdata',i,'tag','plotEEG');
end
% Update axes limits and channel names
D.PSD.handles = handles;
else
% scroll through data
for i=1:length(VIZU.visuSensors)
for j=1:Ntrials
set(handles.PLOT.p(j,i),'ydata',v_data(i,:,j));
end
end
end
% Update scale axes
dz = (abs(diff(get(handles.axes(1),'ylim'))))./VIZU.visu_scale;
set(handles.scale,'yticklabel',num2str(dz));
set(handles.hfig,'userdata',D);
axes(D.PSD.handles.scale)
else %---- Time-frequency data !! ----%
for i=1:length(VIZU.visuSensors)
cmenu = uicontextmenu;
uimenu(cmenu,'Label',['channel ',num2str(VIZU.visuSensors(i)),': ',VIZU.montage.clab{i}]);
uimenu(cmenu,'Label',['type: ',D.channels(VIZU.visuSensors(i)).type]);
% uimenu(cmenu,'Label',['bad: ',num2str(D.channels(VIZU.visuSensors(i)).bad)],...
% 'callback',@switchBC,'userdata',i,...
% 'BusyAction','cancel',...
% 'Interruptible','off');
status = D.channels(VIZU.visuSensors(i)).bad;
if ~status
color = [1 1 1];
else
color = 0.75*[1 1 1];
end
datai = squeeze(D.data.y(VIZU.visuSensors(i),:,:,trN(1)));
miY = min(datai(:));
maY = max(datai(:));
if any(size(datai)==1)
D.PSD.handles.PLOT.im(i) = plot(datai,...
'parent',handles.axes(i),...
'tag','plotEEG',...
'userdata',i,...
'hittest','off');
set(handles.axes(i),...
'ylim',[miY maY]);
else
D.PSD.handles.PLOT.im(i) = image(datai,...
'parent',handles.axes(i),...
'CDataMapping','scaled',...
'tag','plotEEG',...
'userdata',i,...
'hittest','off');
end
set(handles.fra(i),'uicontextmenu',cmenu);
end
colormap(jet)
% This normalizes colorbars across channels and trials:
for i=1:length(VIZU.visuSensors)
caxis(handles.axes(i),VIZU.ylim);
end
set(handles.hfig,'userdata',D);
end
end
else % source space
% get model/trial info
VIZU = D.PSD.source.VIZU;
isInv = VIZU.isInv;
Ninv = length(isInv);
invN = VIZU.isInv(D.PSD.source.VIZU.current);
F = VIZU.F;
ID = VIZU.ID;
model = D.other.inv{invN}.inverse;
t0 = get(D.PSD.handles.BUTTONS.slider_step,'value');
tmp = (model.pst-t0).^2;
indTime = find(tmp==min(tmp));
gridTime = model.pst(indTime);
try % simple time scroll
% update time line
set(VIZU.lineTime,'xdata',[gridTime;gridTime]);
% update mesh's texture
tex = VIZU.J(:,indTime);
set(D.PSD.handles.mesh,'facevertexcdata',tex)
set(D.PSD.handles.BUTTONS.slider_step,'value',gridTime)
catch % VIZU.lineTime deleted -> switch to another source recon
% get the inverse model info
str = getInfo4Inv(D,invN);
set(D.PSD.handles.infoText,'string',str);
if Ninv>1
if isnan(ID(invN))
xF = find(isnan(ID));
else
xF = find(abs(ID-ID(invN))<eps);
end
if length(xF)>1
D.PSD.handles.hbar = bar(D.PSD.handles.BMCplot,...
xF ,F(xF)-min(F(xF)),...
'barwidth',0.5,...
'FaceColor',0.5*[1 1 1],...
'visible','off',...
'tag','plotEEG');
D.PSD.handles.BMCcurrent = plot(D.PSD.handles.BMCplot,...
find(xF==invN),0,'ro',...
'visible','off',...
'tag','plotEEG');
set(D.PSD.handles.BMCplot,...
'xtick',xF,...
'xticklabel',D.PSD.source.VIZU.labels(xF),...
'xlim',[0,length(xF)+1]);
drawnow
else
cla(D.PSD.handles.BMCplot);
set(D.PSD.handles.BMCplot,...
'xtick',[],...
'xticklabel',{});
end
end
% get model/trial time series
D.PSD.source.VIZU.J = zeros(model.Nd,size(model.T,1));
D.PSD.source.VIZU.J(model.Is,:) = model.J{trN(1)}*model.T';
D.PSD.source.VIZU.miJ = min(min(D.PSD.source.VIZU.J));
D.PSD.source.VIZU.maJ = max(max(D.PSD.source.VIZU.J));
% modify mesh/texture and add spheres...
tex = D.PSD.source.VIZU.J(:,indTime);
set(D.PSD.handles.axes,'CLim',...
[D.PSD.source.VIZU.miJ D.PSD.source.VIZU.maJ]);
set(D.PSD.handles.mesh,...
'Vertices',D.other.inv{invN}.mesh.tess_mni.vert,...
'Faces',D.other.inv{invN}.mesh.tess_mni.face,...
'facevertexcdata',tex);
try; delete(D.PSD.handles.dipSpheres);end
if isfield(D.other.inv{invN}.inverse,'dipfit') ||...
~isequal(D.other.inv{invN}.inverse.xyz,zeros(1,3))
try
xyz = D.other.inv{invN}.inverse.dipfit.Lpos;
radius = D.other.inv{invN}.inverse.dipfit.radius;
catch
xyz = D.other.inv{invN}.inverse.xyz';
radius = D.other.inv{invN}.inverse.rad(1);
end
Np = size(xyz,2);
[x,y,z] = sphere(20);
axes(D.PSD.handles.axes)
for i=1:Np
D.PSD.handles.dipSpheres(i) = patch(...
surf2patch(x.*radius+xyz(1,i),...
y.*radius+xyz(2,i),z.*radius+xyz(3,i)));
set(D.PSD.handles.dipSpheres(i),'facecolor',[1 1 1],...
'edgecolor','none','facealpha',0.5,...
'tag','dipSpheres');
end
end
% modify time series plot itself
switch D.PSD.source.VIZU.timeCourses
case 1
Jp(1,:) = min(D.PSD.source.VIZU.J,[],1);
Jp(2,:) = max(D.PSD.source.VIZU.J,[],1);
D.PSD.source.VIZU.plotTC = plot(D.PSD.handles.axes2,...
model.pst,Jp','color',0.5*[1 1 1]);
set(D.PSD.handles.axes2,'hittest','off')
% Add virtual electrode
% try
% ve = D.PSD.source.VIZU.ve;
% catch
[mj ve] = max(max(abs(D.PSD.source.VIZU.J),[],2));
D.PSD.source.VIZU.ve =ve;
% end
Jve = D.PSD.source.VIZU.J(D.PSD.source.VIZU.ve,:);
set(D.PSD.handles.axes2,'nextplot','add')
try
qC = model.qC(ve).*diag(model.qV)';
ci = 1.64*sqrt(qC);
D.PSD.source.VIZU.pve2 = plot(D.PSD.handles.axes2,...
model.pst,Jve +ci,'b:',model.pst,Jve -ci,'b:');
end
D.PSD.source.VIZU.pve = plot(D.PSD.handles.axes2,...
model.pst,Jve,'color','b');
set(D.PSD.handles.axes2,'nextplot','replace')
otherwise
% this is meant to be extended for displaying something
% else than just J (e.g. J^2, etc...)
end
grid(D.PSD.handles.axes2,'on')
box(D.PSD.handles.axes2,'on')
xlabel(D.PSD.handles.axes2,'peri-stimulus time (ms)')
ylabel(D.PSD.handles.axes2,'sources intensity')
% add time line repair
set(D.PSD.handles.axes2,...
'ylim',[D.PSD.source.VIZU.miJ,D.PSD.source.VIZU.maJ],...
'xlim',[D.PSD.source.VIZU.pst(1),D.PSD.source.VIZU.pst(end)],...
'nextplot','add');
D.PSD.source.VIZU.lineTime = line('parent',D.PSD.handles.axes2,...
'xdata',[gridTime;gridTime],...
'ydata',[D.PSD.source.VIZU.miJ,D.PSD.source.VIZU.maJ]);
set(D.PSD.handles.axes2,'nextplot','replace',...
'tag','plotEEG');
% change time slider value if out of bounds
set(D.PSD.handles.BUTTONS.slider_step,'value',gridTime)
% update data structure
set(handles.hfig,'userdata',D);
end
end
%% Switch 'bad channel' status
function [] = switchBC(varargin)
ind = get(gcbo,'userdata');
D = get(gcf,'userdata');
switch D.PSD.VIZU.modality
case 'eeg'
I = D.PSD.EEG.I;
VIZU = D.PSD.EEG.VIZU;
case 'meg'
I = D.PSD.MEG.I;
VIZU = D.PSD.MEG.VIZU;
case 'megplanar'
I = D.PSD.MEGPLANAR.I;
VIZU = D.PSD.MEGPLANAR.VIZU;
case 'other'
I = D.PSD.other.I;
VIZU = D.PSD.other.VIZU;
end
status = D.channels(I(ind)).bad;
if status
status = 0;
lineStyle = '-';
color = [1 1 1];
else
status = 1;
lineStyle = ':';
color = 0.75*[1 1 1];
end
D.channels(I(ind)).bad = status;
set(D.PSD.handles.hfig,'userdata',D);
cmenu = uicontextmenu;
uimenu(cmenu,'Label',['channel ',num2str(I(ind)),': ',VIZU.montage.clab{ind}]);
uimenu(cmenu,'Label',['type: ',D.channels(I(ind)).type]);
uimenu(cmenu,'Label',['bad: ',num2str(status)],...
'callback',@switchBC,'userdata',ind,...
'BusyAction','cancel',...
'Interruptible','off');
switch D.PSD.VIZU.type
case 1
set(D.PSD.handles.PLOT.p(ind),'uicontextmenu',cmenu,...
'lineStyle',lineStyle);
% ud = get(D.PSD.handles.axes);
% ud.v.bad(ind) = status;
% set(D.PSD.handles.axes,'userdata',ud);
case 2
set(D.PSD.handles.axes(ind),'Color',color);
set(D.PSD.handles.fra(ind),'uicontextmenu',cmenu);
set(D.PSD.handles.PLOT.p(:,ind),'uicontextmenu',cmenu);
axes(D.PSD.handles.scale)
end
d1 = rmfield(D,{'history','PSD'});
d0 = rmfield(D.PSD.D0,'history');
if isequal(d1,d0)
set(D.PSD.handles.BUTTONS.pop1,...
'BackgroundColor',[0.8314 0.8157 0.7843])
else
set(D.PSD.handles.BUTTONS.pop1,...
'BackgroundColor',[1 0.5 0.5])
end
%% Define menu event
function [] = psd_defineMenuEvent(re,sc)
% This funcion defines the uicontextmenu associated to the selected events.
% All the actions which are accessible using the right mouse click on the
% selected events are a priori defined here.
% Highlighting the selection
set(re,'buttondownfcn','spm_eeg_review_callbacks(''menuEvent'',''click'',0)');
cmenu = uicontextmenu;
set(re,'uicontextmenu',cmenu);
% Display basic info
info = ['--- EVENT #',num2str(sc.currentEvent),' /',...
num2str(sc.N_select),' (type= ',sc.eventType,', value= ',num2str(sc.eventValue),') ---'];
uimenu(cmenu,'label',info,'enable','off');
% Properties editor
uimenu(cmenu,'separator','on','label','Edit event properties',...
'callback','spm_eeg_review_callbacks(''menuEvent'',''EventProperties'',0)',...
'BusyAction','cancel',...
'Interruptible','off');
% Go to next event of the same type
hc = uimenu(cmenu,'label','Go to iso-type closest event');
uimenu(hc,'label','forward','callback','spm_eeg_review_callbacks(''menuEvent'',''goto'',1)',...
'BusyAction','cancel',...
'Interruptible','off');
uimenu(hc,'label','backward','callback','spm_eeg_review_callbacks(''menuEvent'',''goto'',0)',...
'BusyAction','cancel',...
'Interruptible','off');
% Delete action
uimenu(cmenu,'label','Delete event','callback','spm_eeg_review_callbacks(''menuEvent'',''deleteEvent'',0)',...
'BusyAction','cancel',...
'Interruptible','off');
%% Get info about source reconstruction
function str = getInfo4Inv(D,invN)
str{1} = ['Label: ',D.other.inv{invN}.comment{1}];
try
str{2} = ['Date: ',D.other.inv{invN}.date(1,:),', ',D.other.inv{invN}.date(2,:)];
catch
str{2} = ['Date: ',D.other.inv{invN}.date(1,:)];
end
if isfield(D.other.inv{invN}.inverse, 'modality')
mod0 = D.other.inv{invN}.inverse.modality;
if ischar(mod0)
mod = mod0;
else
mod = [];
for i = 1:length(mod0)
mod = [mod,' ',mod0{i}];
end
end
str{3} = ['Modality: ',mod];
else % For backward compatibility
try
mod0 = D.other.inv{invN}.modality;
if ischar(mod0)
mod = mod0;
else
mod = [];
for i = 1:length(mod0)
mod = [mod,' ',mod0{i}];
end
end
str{3} = ['Modality: ',mod];
catch
str{3} = 'Modality: ?';
end
end
if strcmp(D.other.inv{invN}.method,'Imaging')
source = 'distributed';
else
source = 'equivalent current dipoles';
end
str{4} = ['Source model: ',source,' (',D.other.inv{invN}.method,')'];
try
str{5} = ['Nb of included dipoles: ',...
num2str(length(D.other.inv{invN}.inverse.Is)),...
' / ',num2str(D.other.inv{invN}.inverse.Nd)];
catch
str{5} = 'Nb of included dipoles: undefined';
end
try
str{6} = ['Inversion method: ',D.other.inv{invN}.inverse.type];
catch
str{6} = 'Inversion method: undefined';
end
try
try
str{7} = ['Time window: ',...
num2str(floor(D.other.inv{invN}.inverse.woi(1))),...
' to ',num2str(floor(D.other.inv{invN}.inverse.woi(2))),' ms'];
catch
str{7} = ['Time window: ',...
num2str(floor(D.other.inv{invN}.inverse.pst(1))),...
' to ',num2str(floor(D.other.inv{invN}.inverse.pst(end))),' ms'];
end
catch
str{7} = 'Time window: undefined';
end
try
if D.other.inv{invN}.inverse.Han
han = 'yes';
else
han = 'no';
end
str{8} = ['Hanning: ',han];
catch
str{8} = ['Hanning: undefined'];
end
try
if isfield(D.other.inv{invN}.inverse,'lpf')
str{9} = ['Band pass filter: ',num2str(D.other.inv{invN}.inverse.lpf),...
' to ',num2str(D.other.inv{invN}.inverse.hpf), 'Hz'];
else
str{9} = ['Band pass filter: default'];
end
catch
str{9} = 'Band pass filter: undefined';
end
try
str{10} = ['Nb of temporal modes: ',...
num2str(size(D.other.inv{invN}.inverse.T,2))];
catch
str{10} = 'Nb of temporal modes: undefined';
end
try
str{11} = ['Variance accounted for: ',...
num2str(D.other.inv{invN}.inverse.R2),' %'];
catch
str{11} = 'Variance accounted for: undefined';
end
try
str{12} = ['Log model evidence (free energy): ',...
num2str(D.other.inv{invN}.inverse.F)];
catch
str{12} = 'Log model evidence (free energy): undefined';
end
%% Get data info
function str = getInfo4Data(D)
str{1} = ['File name: ',fullfile(D.path,D.fname)];
str{2} = ['Type: ',D.type];
if ~strcmp(D.transform.ID,'time')
str{2} = [str{2},' (time-frequency data, from ',...
num2str(D.transform.frequencies(1)),'Hz to ',...
num2str(D.transform.frequencies(end)),'Hz'];
if strcmp(D.transform.ID,'TF')
str{2} = [str{2},')'];
else
str{2} = [str{2},': phase)'];
end
end
delta_t = D.Nsamples./D.Fsample;
gridTime = (1:D.Nsamples)./D.Fsample + D.timeOnset;
str{3} = ['Number of time samples: ',num2str(D.Nsamples),' (',num2str(delta_t),' sec, from ',...
num2str(gridTime(1)),'s to ',num2str(gridTime(end)),'s)'];
str{4} = ['Time sampling frequency: ',num2str(D.Fsample),' Hz'];
nb = length(find([D.channels.bad]));
str{5} = ['Number of channels: ',num2str(length(D.channels)),' (',num2str(nb),' bad channels)'];
nb = length(find([D.trials.bad]));
if strcmp(D.type,'continuous')
if isfield(D.trials(1),'events')
str{6} = ['Number of events: ',num2str(length(D.trials(1).events))];
else
str{6} = ['Number of events: ',num2str(0)];
end
else
str{6} = ['Number of trials: ',num2str(length(D.trials)),' (',num2str(nb),' bad trials)'];
end
% try,str{7} = ['Time onset: ',num2str(D.timeOnset),' sec'];end
%% extracting data from spm_uitable java object
function [D] = getUItable(D)
ht = D.PSD.handles.infoUItable;
cn = get(ht,'columnNames');
table = get(ht,'data');
% !! there is some redundancy here --> to be optimized...
table2 = spm_uitable('get',ht);
emptyTable = 0;
try
emptyTable = isempty(cell2mat(table2));
end
if length(cn) == 5 % channel info
if ~emptyTable
nc = length(D.channels);
for i=1:nc
if ~isempty(table(i,1))
D.channels(i).label = table(i,1);
end
if ~isempty(table(i,2))
switch lower(table(i,2))
case 'eeg'
D.channels(i).type = 'EEG';
case 'meg'
D.channels(i).type = 'MEG';
case 'megplanar'
D.channels(i).type = 'MEGPLANAR';
case 'megmag'
D.channels(i).type = 'MEGMAG';
case 'meggrad'
D.channels(i).type = 'MEGGRAD';
case 'refmag'
D.channels(i).type = 'REFMAG';
case 'refgrad'
D.channels(i).type = 'REFGRAD';
case 'lfp'
D.channels(i).type = 'LFP';
case 'eog'
D.channels(i).type = 'EOG';
case 'veog'
D.channels(i).type = 'VEOG';
case 'heog'
D.channels(i).type = 'HEOG';
case 'other'
D.channels(i).type = 'Other';
otherwise
D.channels(i).type = 'Other';
end
end
if ~isempty(table(i,3))
switch lower(table(i,3))
case 'yes'
D.channels(i).bad = 1;
otherwise
D.channels(i).bad = 0;
end
end
if ~isempty(table(i,5))
D.channels(i).units = table(i,5);
end
end
% Find indices of channel types (these might have been changed)
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(:)]);
if ~isempty(D.PSD.EEG.I)
[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)
[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)
[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)
[out] = spm_eeg_review_callbacks('get','VIZU',D.PSD.other.I);
D.PSD.other.VIZU = out;
else
D.PSD.other.VIZU = [];
end
else
end
elseif length(cn) == 7
if strcmp(D.type,'continuous')
if ~emptyTable
ne = length(D.trials(1).events);
D.trials = rmfield(D.trials,'events');
j = 0;
for i=1:ne
if isempty(table(i,1))&&...
isempty(table(i,2))&&...
isempty(table(i,3))&&...
isempty(table(i,4))&&...
isempty(table(i,5))&&...
isempty(table(i,6))&&...
isempty(table(i,7))
% Row (ie event) has been cleared/deleted
else
j = j+1;
if ~isempty(table(i,2))
D.trials(1).events(j).type = table(i,2);
end
if ~isempty(table(i,3))
D.trials(1).events(j).value = str2double(table(i,3));
end
if ~isempty(table(i,4))
D.trials(1).events(j).duration = str2double(table(i,4));
end
if ~isempty(table(i,5))
D.trials(1).events(j).time = str2double(table(i,5));
end
end
end
else
D.trials(1).events = [];
delete(ht);
end
else
if ~emptyTable
nt = length(D.trials);
for i=1:nt
if ~isempty(table(i,1))
D.trials(i).label = table(i,1);
end
ne = length(D.trials(i).events);
if ne<2
if ~isempty(table(i,2))
D.trials(i).events.type = table(i,2);
end
if ~isempty(table(i,3))
D.trials(i).events.value = table(i,3);%str2double(table(i,3));
end
end
if ~isempty(table(i,6))
switch lower(table(i,6))
case 'yes'
D.trials(i).bad = 1;
otherwise
D.trials(i).bad = 0;
end
end
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
else
end
end
elseif length(cn) == 3
if ~emptyTable
nt = length(D.trials);
for i=1:nt
if ~isempty(table(i,1))
D.trials(i).label = table(i,1);
end
D.PSD.trials.TrLabels{i} = ['Trial ',num2str(i),' (average of ',...
num2str(D.trials(i).repl),' events): ',D.trials(i).label];
end
else
end
elseif length(cn) == 12 % source reconstructions
if ~emptyTable
if ~~D.PSD.source.VIZU.current
isInv = D.PSD.source.VIZU.isInv;
inv = D.other.inv;
Ninv = length(inv);
D.other = rmfield(D.other,'inv');
oV = D.PSD.source.VIZU;
D.PSD.source = rmfield(D.PSD.source,'VIZU');
pst = [];
j = 0; % counts the total number of final inverse solutions in D
k = 0; % counts the number of original 'imaging' inv sol
l = 0; % counts the number of final 'imaging' inv sol
for i=1:Ninv
if ~ismember(i,isInv) % not 'imaging' inverse solutions
j = j+1;
D.other.inv{j} = inv{i};
else % 'imaging' inverse solutions
k = k+1;
if isempty(table(k,1))&&...
isempty(table(k,2))&&...
isempty(table(k,3))&&...
isempty(table(k,4))&&...
isempty(table(k,5))&&...
isempty(table(k,6))&&...
isempty(table(k,7))&&...
isempty(table(k,8))&&...
isempty(table(k,9))&&...
isempty(table(k,10))&&...
isempty(table(k,11))&&...
isempty(table(k,12))
% Row (ie source reconstruction) has been cleared/deleted
% => erase inverse solution from D struct
else
j = j+1;
l = l+1;
pst = [pst;inv{isInv(k)}.inverse.pst(:)];
D.other.inv{j} = inv{isInv(k)};
D.other.inv{j}.comment{1} = table(k,1);
D.PSD.source.VIZU.isInv(l) = j;
D.PSD.source.VIZU.F(l) = oV.F(k);
D.PSD.source.VIZU.labels{l} = table(k,1);
D.PSD.source.VIZU.callbacks(l) = oV.callbacks(k);
end
end
end
end
if l >= 1
D.other.val = l;
D.PSD.source.VIZU.current = 1;
D.PSD.source.VIZU.pst = unique(pst);
D.PSD.source.VIZU.timeCourses = 1;
else
try D.other = rmfield(D.other,'val');end
D.PSD.source.VIZU.current = 0;
end
else
try D.other = rmfield(D.other,'val');end
try D.other = rmfield(D.other,'inv');end
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 = [];
delete(ht)
end
end
set(D.PSD.handles.hfig,'userdata',D)
spm_eeg_review_callbacks('visu','main','info',D.PSD.VIZU.info)
|
github
|
philippboehmsturm/antx-master
|
spm_imatrix.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_imatrix.m
| 1,545 |
utf_8
|
6bd968e6c68acf278802d6e9a58610fa
|
function P = spm_imatrix(M)
% returns the parameters for creating an affine transformation
% FORMAT P = spm_imatrix(M)
% M - Affine transformation matrix
% P - Parameters (see spm_matrix for definitions)
%___________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner & Stefan Kiebel
% $Id: spm_imatrix.m 1143 2008-02-07 19:33:33Z spm $
% Translations and zooms
%-----------------------------------------------------------------------
R = M(1:3,1:3);
C = chol(R'*R);
P = [M(1:3,4)' 0 0 0 diag(C)' 0 0 0];
if det(R)<0, P(7)=-P(7);end % Fix for -ve determinants
% Shears
%-----------------------------------------------------------------------
C = diag(diag(C))\C;
P(10:12) = C([4 7 8]);
R0 = spm_matrix([0 0 0 0 0 0 P(7:12)]);
R0 = R0(1:3,1:3);
R1 = R/R0;
% This just leaves rotations in matrix R1
%-----------------------------------------------------------------------
%[ c5*c6, c5*s6, s5]
%[-s4*s5*c6-c4*s6, -s4*s5*s6+c4*c6, s4*c5]
%[-c4*s5*c6+s4*s6, -c4*s5*s6-s4*c6, c4*c5]
P(5) = asin(rang(R1(1,3)));
if (abs(P(5))-pi/2)^2 < 1e-9,
P(4) = 0;
P(6) = atan2(-rang(R1(2,1)), rang(-R1(3,1)/R1(1,3)));
else
c = cos(P(5));
P(4) = atan2(rang(R1(2,3)/c), rang(R1(3,3)/c));
P(6) = atan2(rang(R1(1,2)/c), rang(R1(1,1)/c));
end;
return;
% There may be slight rounding errors making b>1 or b<-1.
function a = rang(b)
a = min(max(b, -1), 1);
return;
|
github
|
philippboehmsturm/antx-master
|
spm_affreg.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_affreg.m
| 18,516 |
utf_8
|
0861aa4a29a7aac70856750d2c0af6ff
|
function [M,scal] = spm_affreg(VG,VF,flags,M,scal)
% Affine registration using least squares.
% FORMAT [M,scal] = spm_affreg(VG,VF,flags,M0,scal0)
%
% VG - Vector of template volumes.
% VF - Source volume.
% flags - a structure containing various options. The fields are:
% WG - Weighting volume for template image(s).
% WF - Weighting volume for source image
% Default to [].
% sep - Approximate spacing between sampled points (mm).
% Defaults to 5.
% regtype - regularisation type. Options are:
% 'none' - no regularisation
% 'rigid' - almost rigid body
% 'subj' - inter-subject registration (default).
% 'mni' - registration to ICBM templates
% globnorm - Global normalisation flag (1)
% M0 - (optional) starting estimate. Defaults to eye(4).
% scal0 - (optional) starting estimate.
%
% M - affine transform, such that voxels in VF map to those in
% VG by VG.mat\M*VF.mat
% scal - scaling factors for VG
%
% When only one template is used, then the cost function is approximately
% symmetric, although a linear combination of templates can be used.
% Regularisation is based on assuming a multi-normal distribution for the
% elements of the Henckey Tensor. See:
% "Non-linear Elastic Deformations". R. W. Ogden (Dover), 1984.
% Weighting for the regularisation is determined approximately according
% to:
% "Incorporating Prior Knowledge into Image Registration"
% J. Ashburner, P. Neelin, D. L. Collins, A. C. Evans & K. J. Friston.
% NeuroImage 6:344-352 (1997).
%
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_affreg.m 4152 2011-01-11 14:13:35Z volkmar $
if nargin<5, scal = ones(length(VG),1); end;
if nargin<4, M = eye(4); end;
def_flags = struct('sep',5, 'regtype','subj','WG',[],'WF',[],'globnorm',1,'debug',0);
if nargin < 2 || ~isstruct(flags),
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;
% Check to ensure inputs are valid...
% ---------------------------------------------------------------
if length(VF)>1, error('Can not use more than one source image'); end;
if ~isempty(flags.WF),
if length(flags.WF)>1,
error('Can only use one source weighting image');
end;
if any(any((VF.mat-flags.WF.mat).^2>1e-8)),
error('Source and its weighting image must have same orientation');
end;
if any(any(VF.dim(1:3)-flags.WF.dim(1:3))),
error('Source and its weighting image must have same dimensions');
end;
end;
if ~isempty(flags.WG),
if length(flags.WG)>1,
error('Can only use one template weighting image');
end;
tmp = reshape(cat(3,VG(:).mat,flags.WG.mat),16,length(VG)+length(flags.WG));
else
tmp = reshape(cat(3,VG(:).mat),16,length(VG));
end;
if any(any(diff(tmp,1,2).^2>1e-8)),
error('Reference images must all have the same orientation');
end;
if ~isempty(flags.WG),
tmp = cat(1,VG(:).dim,flags.WG.dim);
else
tmp = cat(1,VG(:).dim);
end;
if any(any(diff(tmp(:,1:3),1,1))),
error('Reference images must all have the same dimensions');
end;
% ---------------------------------------------------------------
% Generate points to sample from, adding some jitter in order to
% make the cost function smoother.
% ---------------------------------------------------------------
rand('state',0); % want the results to be consistant.
dg = VG(1).dim(1:3);
df = VF(1).dim(1:3);
if length(VG)==1,
skip = sqrt(sum(VG(1).mat(1:3,1:3).^2)).^(-1)*flags.sep;
[x1,x2,x3]=ndgrid(1:skip(1):dg(1)-.5, 1:skip(2):dg(2)-.5, 1:skip(3):dg(3)-.5);
x1 = x1 + rand(size(x1))*0.5; x1 = x1(:);
x2 = x2 + rand(size(x2))*0.5; x2 = x2(:);
x3 = x3 + rand(size(x3))*0.5; x3 = x3(:);
end;
skip = sqrt(sum(VF(1).mat(1:3,1:3).^2)).^(-1)*flags.sep;
[y1,y2,y3]=ndgrid(1:skip(1):df(1)-.5, 1:skip(2):df(2)-.5, 1:skip(3):df(3)-.5);
y1 = y1 + rand(size(y1))*0.5; y1 = y1(:);
y2 = y2 + rand(size(y2))*0.5; y2 = y2(:);
y3 = y3 + rand(size(y3))*0.5; y3 = y3(:);
% ---------------------------------------------------------------
if flags.globnorm,
% Scale all images approximately equally
% ---------------------------------------------------------------
for i=1:length(VG),
VG(i).pinfo(1:2,:) = VG(i).pinfo(1:2,:)/spm_global(VG(i));
end;
VF(1).pinfo(1:2,:) = VF(1).pinfo(1:2,:)/spm_global(VF(1));
end;
% ---------------------------------------------------------------
if length(VG)==1,
[G,dG1,dG2,dG3] = spm_sample_vol(VG(1),x1,x2,x3,1);
if ~isempty(flags.WG),
WG = abs(spm_sample_vol(flags.WG,x1,x2,x3,1))+eps;
WG(~isfinite(WG)) = 1;
end;
end;
[F,dF1,dF2,dF3] = spm_sample_vol(VF(1),y1,y2,y3,1);
if ~isempty(flags.WF),
WF = abs(spm_sample_vol(flags.WF,y1,y2,y3,1))+eps;
WF(~isfinite(WF)) = 1;
end;
% ---------------------------------------------------------------
n_main_its = 0;
ss = Inf;
W = [Inf Inf Inf];
est_smo = 1;
% ---------------------------------------------------------------
for iter=1:256,
pss = ss;
p0 = [0 0 0 0 0 0 1 1 1 0 0 0];
% Initialise the cost function and its 1st and second derivatives
% ---------------------------------------------------------------
n = 0;
ss = 0;
Beta = zeros(12+length(VG),1);
Alpha = zeros(12+length(VG));
if length(VG)==1,
% Make the cost function symmetric
% ---------------------------------------------------------------
% Build a matrix to rotate the derivatives by, converting from
% derivatives w.r.t. changes in the overall affine transformation
% matrix, to derivatives w.r.t. the parameters p.
% ---------------------------------------------------------------
dt = 0.0001;
R = eye(13);
MM0 = inv(VG.mat)*inv(spm_matrix(p0))*VG.mat;
for i1=1:12,
p1 = p0;
p1(i1) = p1(i1)+dt;
MM1 = (inv(VG.mat)*inv(spm_matrix(p1))*(VG.mat));
R(1:12,i1) = reshape((MM1(1:3,:)-MM0(1:3,:))/dt,12,1);
end;
% ---------------------------------------------------------------
[t1,t2,t3] = coords((M*VF(1).mat)\VG(1).mat,x1,x2,x3);
msk = find((t1>=1 & t1<=df(1) & t2>=1 & t2<=df(2) & t3>=1 & t3<=df(3)));
if length(msk)<32, error_message; end;
t1 = t1(msk);
t2 = t2(msk);
t3 = t3(msk);
t = spm_sample_vol(VF(1), t1,t2,t3,1);
% Get weights
% ---------------------------------------------------------------
if ~isempty(flags.WF) || ~isempty(flags.WG),
if isempty(flags.WF),
wt = WG(msk);
else
wt = spm_sample_vol(flags.WF(1), t1,t2,t3,1)+eps;
wt(~isfinite(wt)) = 1;
if ~isempty(flags.WG), wt = 1./(1./wt + 1./WG(msk)); end;
end;
wt = sparse(1:length(wt),1:length(wt),wt);
else
% wt = speye(length(msk));
wt = [];
end;
% ---------------------------------------------------------------
clear t1 t2 t3
% Update the cost function and its 1st and second derivatives.
% ---------------------------------------------------------------
[AA,Ab,ss1,n1] = costfun(x1,x2,x3,dG1,dG2,dG3,msk,scal^(-2)*t,G(msk)-(1/scal)*t,wt);
Alpha = Alpha + R'*AA*R;
Beta = Beta + R'*Ab;
ss = ss + ss1;
n = n + n1;
% t = G(msk) - (1/scal)*t;
end;
if 1,
% Build a matrix to rotate the derivatives by, converting from
% derivatives w.r.t. changes in the overall affine transformation
% matrix, to derivatives w.r.t. the parameters p.
% ---------------------------------------------------------------
dt = 0.0001;
R = eye(12+length(VG));
MM0 = inv(M*VF.mat)*spm_matrix(p0)*M*VF.mat;
for i1=1:12,
p1 = p0;
p1(i1) = p1(i1)+dt;
MM1 = (inv(M*VF.mat)*spm_matrix(p1)*M*VF.mat);
R(1:12,i1) = reshape((MM1(1:3,:)-MM0(1:3,:))/dt,12,1);
end;
% ---------------------------------------------------------------
[t1,t2,t3] = coords(VG(1).mat\M*VF(1).mat,y1,y2,y3);
msk = find((t1>=1 & t1<=dg(1) & t2>=1 & t2<=dg(2) & t3>=1 & t3<=dg(3)));
if length(msk)<32, error_message; end;
if length(msk)<32, error_message; end;
t1 = t1(msk);
t2 = t2(msk);
t3 = t3(msk);
t = zeros(length(t1),length(VG));
% Get weights
% ---------------------------------------------------------------
if ~isempty(flags.WF) || ~isempty(flags.WG),
if isempty(flags.WG),
wt = WF(msk);
else
wt = spm_sample_vol(flags.WG(1), t1,t2,t3,1)+eps;
wt(~isfinite(wt)) = 1;
if ~isempty(flags.WF), wt = 1./(1./wt + 1./WF(msk)); end;
end;
wt = sparse(1:length(wt),1:length(wt),wt);
else
wt = speye(length(msk));
end;
% ---------------------------------------------------------------
if est_smo,
% Compute derivatives of residuals in the space of F
% ---------------------------------------------------------------
[ds1,ds2,ds3] = transform_derivs(VG(1).mat\M*VF(1).mat,dF1(msk),dF2(msk),dF3(msk));
for i=1:length(VG),
[t(:,i),dt1,dt2,dt3] = spm_sample_vol(VG(i), t1,t2,t3,1);
ds1 = ds1 - dt1*scal(i); clear dt1
ds2 = ds2 - dt2*scal(i); clear dt2
ds3 = ds3 - dt3*scal(i); clear dt3
end;
dss = [ds1'*wt*ds1 ds2'*wt*ds2 ds3'*wt*ds3];
clear ds1 ds2 ds3
else
for i=1:length(VG),
t(:,i)= spm_sample_vol(VG(i), t1,t2,t3,1);
end;
end;
clear t1 t2 t3
% Update the cost function and its 1st and second derivatives.
% ---------------------------------------------------------------
[AA,Ab,ss2,n2] = costfun(y1,y2,y3,dF1,dF2,dF3,msk,-t,F(msk)-t*scal,wt);
Alpha = Alpha + R'*AA*R;
Beta = Beta + R'*Ab;
ss = ss + ss2;
n = n + n2;
end;
if est_smo,
% Compute a smoothness correction from the residuals and their
% derivatives. This is analagous to the one used in:
% "Analysis of fMRI Time Series Revisited"
% Friston KJ, Holmes AP, Poline JB, Grasby PJ, Williams SCR,
% Frackowiak RSJ, Turner R. Neuroimage 2:45-53 (1995).
% ---------------------------------------------------------------
vx = sqrt(sum(VG(1).mat(1:3,1:3).^2));
pW = W;
W = (2*dss/ss2).^(-.5).*vx;
W = min(pW,W);
if flags.debug, fprintf('\nSmoothness FWHM: %.3g x %.3g x %.3g mm\n', W*sqrt(8*log(2))); end;
if length(VG)==1, dens=2; else dens=1; end;
smo = prod(min(dens*flags.sep/sqrt(2*pi)./W,[1 1 1]));
est_smo=0;
n_main_its = n_main_its + 1;
end;
% Update the parameter estimates
% ---------------------------------------------------------------
nu = n*smo;
sig2 = ss/nu;
[d1,d2] = reg(M,12+length(VG),flags.regtype);
soln = (Alpha/sig2+d2)\(Beta/sig2-d1);
scal = scal - soln(13:end);
M = spm_matrix(p0 + soln(1:12)')*M;
if flags.debug,
fprintf('%d\t%g\n', iter, ss/n);
piccies(VF,VG,M,scal)
end;
% If cost function stops decreasing, then re-estimate smoothness
% and try again. Repeat a few times.
% ---------------------------------------------------------------
ss = ss/n;
if iter>1, spm_plot_convergence('Set',ss); end;
if (pss-ss)/pss < 1e-6,
est_smo = 1;
end;
if n_main_its>3, break; end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [X1,Y1,Z1] = transform_derivs(Mat,X,Y,Z)
% Given the derivatives of a scalar function, return those of the
% affine transformed function
%_______________________________________________________________________
t1 = Mat(1:3,1:3);
t2 = eye(3);
if sum((t1(:)-t2(:)).^2) < 1e-12,
X1 = X;Y1 = Y; Z1 = Z;
else
X1 = Mat(1,1)*X + Mat(1,2)*Y + Mat(1,3)*Z;
Y1 = Mat(2,1)*X + Mat(2,2)*Y + Mat(2,3)*Z;
Z1 = Mat(3,1)*X + Mat(3,2)*Y + Mat(3,3)*Z;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [d1,d2] = reg(M,n,typ)
% Analytically compute the first and second derivatives of a penalty
% function w.r.t. changes in parameters.
if nargin<3, typ = 'subj'; end;
if nargin<2, n = 13; end;
[mu,isig] = spm_affine_priors(typ);
ds = 0.000001;
d1 = zeros(n,1);
d2 = zeros(n);
p0 = [0 0 0 0 0 0 1 1 1 0 0 0];
h0 = penalty(p0,M,mu,isig);
for i=7:12, % derivatives are zero w.r.t. rotations and translations
p1 = p0;
p1(i) = p1(i)+ds;
h1 = penalty(p1,M,mu,isig);
d1(i) = (h1-h0)/ds; % First derivative
for j=7:12,
p2 = p0;
p2(j) = p2(j)+ds;
h2 = penalty(p2,M,mu,isig);
p3 = p1;
p3(j) = p3(j)+ds;
h3 = penalty(p3,M,mu,isig);
d2(i,j) = ((h3-h2)/ds-(h1-h0)/ds)/ds; % Second derivative
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function h = penalty(p,M,mu,isig)
% Return a penalty based on the elements of an affine transformation,
% which is given by:
% spm_matrix(p)*M
%
% The penalty is based on the 6 unique elements of the Hencky tensor
% elements being multinormally distributed.
%_______________________________________________________________________
% Unique elements of symmetric 3x3 matrix.
els = [1 2 3 5 6 9];
T = spm_matrix(p)*M;
T = T(1:3,1:3);
T = 0.5*logm(T'*T);
T = T(els)' - mu;
h = T'*isig*T;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [y1,y2,y3]=coords(M,x1,x2,x3)
% Affine transformation of a set of coordinates.
%_______________________________________________________________________
y1 = M(1,1)*x1 + M(1,2)*x2 + M(1,3)*x3 + M(1,4);
y2 = M(2,1)*x1 + M(2,2)*x2 + M(2,3)*x3 + M(2,4);
y3 = M(3,1)*x1 + M(3,2)*x2 + M(3,3)*x3 + M(3,4);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function A = make_A(x1,x2,x3,dG1,dG2,dG3,t)
% Generate part of a design matrix using the chain rule...
% df/dm = df/dy * dy/dm
% where
% df/dm is the rate of change of intensity w.r.t. affine parameters
% df/dy is the gradient of the image f
% dy/dm crange of position w.r.t. change of parameters
%_______________________________________________________________________
A = [x1.*dG1 x1.*dG2 x1.*dG3 ...
x2.*dG1 x2.*dG2 x2.*dG3 ...
x3.*dG1 x3.*dG2 x3.*dG3 ...
dG1 dG2 dG3 t];
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [AA,Ab,ss,n] = costfun(x1,x2,x3,dG1,dG2,dG3,msk,lastcols,b,wt)
chunk = 10240;
lm = length(msk);
AA = zeros(12+size(lastcols,2));
Ab = zeros(12+size(lastcols,2),1);
ss = 0;
n = 0;
for i=1:ceil(lm/chunk),
ind = (((i-1)*chunk+1):min(i*chunk,lm))';
msk1 = msk(ind);
A1 = make_A(x1(msk1),x2(msk1),x3(msk1),dG1(msk1),dG2(msk1),dG3(msk1),lastcols(ind,:));
b1 = b(ind);
if ~isempty(wt),
wt1 = wt(ind,ind);
AA = AA + A1'*wt1*A1;
%Ab = Ab + A1'*wt1*b1;
Ab = Ab + (b1'*wt1*A1)';
ss = ss + b1'*wt1*b1;
n = n + trace(wt1);
clear wt1
else
AA = AA + A1'*A1;
%Ab = Ab + A1'*b1;
Ab = Ab + (b1'*A1)';
ss = ss + b1'*b1;
n = n + length(msk1);
end;
clear A1 b1 msk1 ind
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function error_message
% Display an error message for when things go wrong.
str = { 'There is not enough overlap in the images',...
'to obtain a solution.',...
' ',...
'Please check that your header information is OK.',...
'The Check Reg utility will show you the initial',...
'alignment between the images, which must be',...
'within about 4cm and about 15 degrees in order',...
'for SPM to find the optimal solution.'};
spm('alert*',str,mfilename,sqrt(-1));
error('insufficient image overlap')
%_______________________________________________________________________
%_______________________________________________________________________
function piccies(VF,VG,M,scal)
% This is for debugging purposes.
% It shows the linear combination of template images, the affine
% transformed source image, the residual image and a histogram of the
% residuals.
%_______________________________________________________________________
figure(2);
Mt = spm_matrix([0 0 (VG(1).dim(3)+1)/2]);
M = (M*VF(1).mat)\VG(1).mat;
t = zeros(VG(1).dim(1:2));
for i=1:length(VG);
t = t + spm_slice_vol(VG(i), Mt,VG(1).dim(1:2),1)*scal(i);
end;
u = spm_slice_vol(VF(1),M*Mt,VG(1).dim(1:2),1);
subplot(2,2,1);imagesc(t');axis image xy off
subplot(2,2,2);imagesc(u');axis image xy off
subplot(2,2,3);imagesc(u'-t');axis image xy off
%subplot(2,2,4);hist(b,50); % Entropy of residuals may be a nice cost function?
drawnow;
return;
%_______________________________________________________________________
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_locate_channels.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_eeg_locate_channels.m
| 2,870 |
utf_8
|
5c2b41cee32e14bd2f6b0d7565ddd0fb
|
function [Cel, Cind, x, y] = spm_eeg_locate_channels(D, n, interpolate_bad)
% Locate channels and generate mask for converting M/EEG data into images
% FORMAT [Cel, Cind, x, y] = spm_eeg_locate_channels(D, n, interpolate_bad)
%
% D - M/EEG object
% n - number of voxels in each direction
% interpolate_bad - flag (1/0), whether bad channels should be interpolated
% or masked out
%
% Cel - coordinates of good channels in new coordinate system
% Cind - the indices of these channels in the total channel
% vector
% x, y - x and y coordinates which support data
%
%__________________________________________________________________________
%
% Locates channels and generates mask for converting M/EEG data to NIfTI
% format ('analysis at sensor level'). If flag interpolate_bad is set to 1,
% the returned x,y-coordinates will include bad sensor position. If
% interpolate_bad is 0, these locations are masked out if the sensor are
% located at the edge of the setup (where the data cannot be well
% interpolated).
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Stefan Kiebel
% $Id: spm_eeg_locate_channels.m 2830 2009-03-05 17:27:34Z guillaume $
% put into n x n grid
%--------------------------------------------------------------------------
[x, y] = meshgrid(1:n, 1:n);
if interpolate_bad
% keep bad electrode positions in
%----------------------------------------------------------------------
Cel = scale_coor(D.coor2D(D.meegchannels), n);
else
% bad electrodes are masked out if located at the edge of the setup
%----------------------------------------------------------------------
Cel = scale_coor(D.coor2D(setdiff(D.meegchannels, D.badchannels)), n);
end
ch = convhull(Cel(:, 1), Cel(:, 2));
Ic = find(inpolygon(x, y, Cel(ch, 1), Cel(ch, 2)));
Cel = scale_coor(D.coor2D(setdiff(D.meegchannels, D.badchannels)), n);
Cind = setdiff(D.meegchannels, D.badchannels);
x = x(Ic); y = y(Ic);
%==========================================================================
% scale_coor
%==========================================================================
function Cel = scale_coor(Cel, n)
% check limits and stretch, if possible
dx = max(Cel(1,:)) - min(Cel(1,:));
dy = max(Cel(2,:)) - min(Cel(2,:));
if dx > 1 || dy > 1
error('Coordinates not between 0 and 1');
end
scale = (1 - 10^(-6))/max(dx, dy);
Cel(1,:) = n*scale*(Cel(1,:) - min(Cel(1,:)) + eps) + 0.5;
Cel(2,:) = n*scale*(Cel(2,:) - min(Cel(2,:)) + eps) + 0.5;
% shift to middle
dx = n+0.5 -n*eps - max(Cel(1,:));
dy = n+0.5 -n*eps - max(Cel(2,:));
Cel(1,:) = Cel(1,:) + dx/2;
Cel(2,:) = Cel(2,:) + dy/2;
% 2D coordinates in voxel-space (incl. badchannels)
Cel = round(Cel)';
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_filter.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_eeg_filter.m
| 6,617 |
utf_8
|
38ceb423092384f9bf967a6534b6484e
|
function D = spm_eeg_filter(S)
% Filter M/EEG data
% FORMAT D = spm_eeg_filter(S)
%
% S - input structure (optional)
% (optional) fields of S:
% S.D - MEEG object or filename of M/EEG mat-file
% S.filter - struct with the following fields:
% type - optional filter type, can be
% 'but' Butterworth IIR filter (default)
% 'fir' FIR filter using Matlab fir1 function
% order - filter order (default - 5 for Butterworth)
% band - filterband [low|high|bandpass|stop]
% PHz - cutoff frequency [Hz]
% dir - optional filter direction, can be
% 'onepass' forward filter only
% 'onepass-reverse' reverse filter only, i.e. backward in time
% 'twopass' zero-phase forward and reverse filter
%
% D - MEEG object (also written to disk)
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Stefan Kiebel
% $Id: spm_eeg_filter.m 4127 2010-11-19 18:05:18Z christophe $
SVNrev = '$Rev: 4127 $';
%-Startup
%--------------------------------------------------------------------------
spm('FnBanner', mfilename, SVNrev);
spm('FigName','M/EEG filter'); spm('Pointer', 'Watch');
if nargin == 0
S = [];
end
%-Ensure backward compatibility
%--------------------------------------------------------------------------
S = spm_eeg_compatibility(S, mfilename);
%-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
%--------------------------------------------------------------------------
if ~isfield(S, 'filter')
S.filter = [];
end
if ~isfield(S.filter, 'band')
S.filter.band = cell2mat(...
spm_input('filterband', '+1', 'm',...
'lowpass|highpass|bandpass|stopband',...
{'low','high','bandpass','stop'}));
end
if ~isfield(S.filter, 'type')
S.filter.type = 'butterworth';
end
if ~isfield(S.filter, 'order')
if strcmp(S.filter.type, 'butterworth')
S.filter.order = 5;
else
S.filter.order = [];
end
end
if ~isfield(S.filter, 'dir')
S.filter.dir = 'twopass';
end
if ~isfield(S.filter, 'PHz')
switch lower(S.filter.band)
case {'low','high'}
str = 'Cutoff [Hz]';
YPos = -1;
while 1
if YPos == -1
YPos = '+1';
end
[PHz, YPos] = spm_input(str, YPos, 'r');
if PHz > 0 && PHz < D.fsample/2, break, end
str = 'Cutoff must be > 0 & < half sample rate';
end
case {'bandpass','stop'}
str = 'band [Hz]';
YPos = -1;
while 1
if YPos == -1
YPos = '+1';
end
[PHz, YPos] = spm_input(str, YPos, 'r', [], 2);
if PHz(1) > 0 && PHz(1) < D.fsample/2 && PHz(1) < PHz(2), break, end
str = 'Cutoff 1 must be > 0 & < half sample rate and Cutoff 1 must be < Cutoff 2';
end
otherwise
error('unknown filter band.')
end
S.filter.PHz = PHz;
end
%-
%--------------------------------------------------------------------------
% generate new meeg object with new filenames
Dnew = clone(D, ['f' fnamedat(D)], [D.nchannels D.nsamples D.ntrials]);
% determine channels for filtering
Fchannels = unique([D.meegchannels, D.eogchannels]);
Fs = D.fsample;
if strcmp(D.type, 'continuous')
% continuous data
spm_progress_bar('Init', nchannels(D), 'Channels filtered'); drawnow;
if nchannels(D) > 100, Ibar = floor(linspace(1, nchannels(D),100));
else Ibar = [1:nchannels(D)]; end
% work on blocks of channels
% determine blocksize
% 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 filter blocks of channels
chncnt=1;
for blk=1:blknum
% load old meeg object blockwise into workspace
blkchan=chncnt:(min(nchannels(D), chncnt+blksz-1));
if isempty(blkchan), break, end
Dtemp=D(blkchan,:,1);
chncnt=chncnt+blksz;
%loop through channels
for j = 1:numel(blkchan)
if ismember(blkchan(j), Fchannels)
Dtemp(j, :) = spm_eeg_preproc_filter(S.filter, Dtemp(j,:), Fs);
end
if ismember(j, Ibar), spm_progress_bar('Set', blkchan(j)); end
end
% write Dtemp to Dnew
Dnew(blkchan,:,1)=Dtemp;
clear Dtemp;
end;
else
% single trial or epoched
spm_progress_bar('Init', D.ntrials, 'Trials filtered'); drawnow;
if D.ntrials > 100, Ibar = floor(linspace(1, D.ntrials,100));
else Ibar = [1:D.ntrials]; end
for i = 1:D.ntrials
d = squeeze(D(:, :, i));
for j = 1:nchannels(D)
if ismember(j, Fchannels)
d(j,:) = spm_eeg_preproc_filter(S.filter, double(d(j,:)), Fs);
end
end
Dnew(:, 1:Dnew.nsamples, i) = d;
if ismember(i, Ibar), spm_progress_bar('Set', i); end
end
disp('Baseline correction is no longer done automatically by spm_eeg_filter. Use spm_eeg_bc if necessary.');
end
spm_progress_bar('Clear');
%-Save new evoked M/EEG dataset
%--------------------------------------------------------------------------
D = Dnew;
D = D.history(mfilename, S);
save(D);
%-Cleanup
%--------------------------------------------------------------------------
spm('FigName','M/EEG filter: done'); spm('Pointer', 'Arrow');
%==========================================================================
function dat = spm_eeg_preproc_filter(filter, dat, Fs)
Fp = filter.PHz;
if isequal(filter.type, 'fir')
type = 'fir';
else
type = 'but';
end
N = filter.order;
dir = filter.dir;
switch filter.band
case 'low'
dat = ft_preproc_lowpassfilter(dat,Fs,Fp,N,type,dir);
case 'high'
dat = ft_preproc_highpassfilter(dat,Fs,Fp,N,type,dir);
case 'bandpass'
dat = ft_preproc_bandpassfilter(dat, Fs, Fp, N, type, dir);
case 'stop'
dat = ft_preproc_bandstopfilter(dat,Fs,Fp,N,type,dir);
end
|
github
|
philippboehmsturm/antx-master
|
savexml.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/savexml.m
| 5,240 |
utf_8
|
575501e05a68903f8f5a2db4cb6a18e9
|
function savexml(filename, varargin)
%SAVEXML Save workspace variables to disk in XML.
% SAVEXML FILENAME saves all workspace variables to the XML-file
% named FILENAME.xml. The data may be retrieved with LOADXML. if
% FILENAME has no extension, .xml is assumed.
%
% SAVE, by itself, creates the XML-file named 'matlab.xml'. It is
% an error if 'matlab.xml' is not writable.
%
% SAVE FILENAME X saves only X.
% SAVE FILENAME X Y Z saves X, Y, and Z. The wildcard '*' can be
% used to save only those variables that match a pattern.
%
% SAVE ... -APPEND adds the variables to an existing file.
%
% Use the functional form of SAVE, such as SAVE(filename','var1','var2'),
% when the filename or variable names are stored in strings.
%
% See also SAVE, MAT2XML, XMLTREE.
% Copyright 2003 Guillaume Flandin.
% $Revision: 4393 $ $Date: 2003/07/10 13:50 $
% $Id: savexml.m 4393 2011-07-18 14:52:32Z guillaume $
if nargin == 0
filename = 'matlab.xml';
fprintf('\nSaving to: %s\n\n',filename);
else
if ~ischar(filename)
error('[SAVEXML] Argument must contain a string.');
end
[pathstr,name,ext] = fileparts(filename);
if isempty(ext)
filename = [filename '.xml'];
end
end
if nargin <= 1, varargin = {'*'}; end
if nargout > 0
error('[SAVEXML] Too many output arguments.');
end
if strcmpi(varargin{end},'-append')
if length(varargin) > 1
varargin = varargin(1:end-1);
else
varargin = {'*'};
end
if exist(filename,'file')
% TODO % No need to parse the whole tree ? detect duplicate variables ?
t = xmltree(filename);
else
error(sprintf(...
'[SAVEXML] Unable to write file %s: file does not exist.',filename));
end
else
t = xmltree('<matfile/>');
end
for i=1:length(varargin)
v = evalin('caller',['whos(''' varargin{i} ''')']);
if isempty(v)
error(['[SAVEXML] Variable ''' varargin{i} ''' not found.']);
end
for j=1:length(v)
[t, uid] = add(t,root(t),'element',v(j).name);
t = attributes(t,'add',uid,'type',v(j).class);
t = attributes(t,'add',uid,'size',xml_num2str(v(j).size));
t = xml_var2xml(t,evalin('caller',v(j).name),uid);
end
end
save(t,filename);
%=======================================================================
function t = xml_var2xml(t,v,uid)
switch class(v)
case {'double','single','logical'}
if ~issparse(v)
t = add(t,uid,'chardata',xml_num2str(v));
else % logical
[i,j,s] = find(v);
[t, uid2] = add(t,uid,'element','row');
t = attributes(t,'add',uid2,'size',xml_num2str(size(i)));
t = add(t,uid2,'chardata',xml_num2str(i));
[t, uid2] = add(t,uid,'element','col');
t = attributes(t,'add',uid2,'size',xml_num2str(size(j)));
t = add(t,uid2,'chardata',xml_num2str(j));
[t, uid2] = add(t,uid,'element','val');
t = attributes(t,'add',uid2,'size',xml_num2str(size(s)));
t = add(t,uid2,'chardata',xml_num2str(s));
end
case 'struct'
names = fieldnames(v);
for j=1:prod(size(v))
for i=1:length(names)
[t, uid2] = add(t,uid,'element',names{i});
t = attributes(t,'add',uid2,'index',num2str(j));
t = attributes(t,'add',uid2,'type',...
class(getfield(v(j),names{i})));
t = attributes(t,'add',uid2,'size', ...
xml_num2str(size(getfield(v(j),names{i}))));
t = xml_var2xml(t,getfield(v(j),names{i}),uid2);
end
end
case 'cell'
for i=1:prod(size(v))
[t, uid2] = add(t,uid,'element','cell');
% TODO % special handling of cellstr ?
t = attributes(t,'add',uid2,'index',num2str(i));
t = attributes(t,'add',uid2,'type',class(v{i}));
t = attributes(t,'add',uid2,'size',xml_num2str(size(v{i})));
t = xml_var2xml(t,v{i},uid2);
end
case 'char'
% TODO % char values should be in CData
if size(v,1) > 1
t = add(t,uid,'chardata',v'); % row-wise order
else
t = add(t,uid,'chardata',v);
end
case {'int8','uint8','int16','uint16','int32','uint32'}
[t, uid] = add(t,uid,'element',class(v));
% TODO % Handle integer formats (cannot use sprintf or num2str)
otherwise
if ismember('serialize',methods(class(v)))
% TODO % is CData necessary for class output ?
t = add(t,uid,'cdata',serialize(v));
else
warning(sprintf(...
'[SAVEXML] Cannot convert from %s to XML.',class(v)));
end
end
%=======================================================================
function s = xml_num2str(n)
% TODO % use format ?
if isempty(n)
s = '[]';
else
s = ['[' sprintf('%g ',n(1:end-1))];
s = [s num2str(n(end)) ']'];
end
|
github
|
philippboehmsturm/antx-master
|
spm_bilinear.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_bilinear.m
| 3,787 |
utf_8
|
37e6b8a17a436698a9c87c2c7e5235be
|
function [H0,H1,H2] = spm_bilinear(A,B,C,D,x0,N,dt)
% returns global Volterra kernels for a MIMO Bilinear system
% FORMAT [H0,H1,H2] = spm_bilinear(A,B,C,D,x0,N,dt)
% A - (n x n) df(x(0),0)/dx - n states
% B - (n x n x m) d2f(x(0),0)/dxdu - m inputs
% C - (n x m) df(x(0),0)/du - d2f(x(0),0)/dxdu*x(0)
% D - (n x 1) f(x(0).0) - df(x(0),0)/dx*x(0)
% x0 - (n x 1) x(0)
% N - kernel depth {intervals}
% dt - interval {seconds}
%
% Volterra kernels:
%
% H0 - (n) = h0(t) = y(t)
% H1 - (N x n x m) = h1i(t,s1) = dy(t)/dui(t - s1)
% H2 - (N x N x n x m x m) = h2ij(t,s1,s2) = d2y(t)/dui(t - s1)duj(t - s2)
%
% where n = p if modes are specified
%___________________________________________________________________________
% Returns Volterra kernels for bilinear systems of the form
%
% dx/dt = f(x,u) = A*x + B1*x*u1 + ... Bm*x*um + C1u1 + ... Cmum + D
% y(t) = x(t)
%
%---------------------------------------------------------------------------
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Karl Friston
% $Id: spm_bilinear.m 1143 2008-02-07 19:33:33Z spm $
% Volterra kernels for bilinear systems
%===========================================================================
% parameters
%---------------------------------------------------------------------------
n = size(A,1); % state variables
m = size(C,2); % inputs
A = full(A);
B = full(B);
C = full(C);
D = full(D);
% eignvector solution {to reduce M0 to leading diagonal form}
%---------------------------------------------------------------------------
M0 = [0 zeros(1,n); D A];
[U J] = eig(M0);
V = pinv(U);
% Lie operator {M0}
%---------------------------------------------------------------------------
M0 = sparse(J);
X0 = V*[1; x0];
% 0th order kernel
%---------------------------------------------------------------------------
H0 = ex(N*dt*M0)*X0;
% 1st order kernel
%---------------------------------------------------------------------------
if nargout > 1
% Lie operator {M1}
%-------------------------------------------------------------------
for i = 1:m
M1(:,:,i) = V*[0 zeros(1,n); C(:,i) B(:,:,i)]*U;
end
% 1st order kernel
%-------------------------------------------------------------------
H1 = zeros(N,n + 1,m);
for p = 1:m
for i = 1:N
u1 = N - i + 1;
H1(u1,:,p) = ex(u1*dt*M0)*M1(:,:,p)*ex(-u1*dt*M0)*H0;
end
end
end
% 2nd order kernels
%---------------------------------------------------------------------------
if nargout > 2
H2 = zeros(N,N,n + 1,m,m);
for p = 1:m
for q = 1:m
for j = 1:N
u2 = N - j + 1;
u1 = N - [1:j] + 1;
H = ex(u2*dt*M0)*M1(:,:,q)*ex(-u2*dt*M0)*H1(u1,:,p)';
H2(u2,u1,:,q,p) = H';
H2(u1,u2,:,p,q) = H';
end
end
end
end
% project to state space and remove kernels associated with the constant
%---------------------------------------------------------------------------
if nargout > 0
H0 = real(U*H0);
H0 = H0([1:n] + 1);
end
if nargout > 1
for p = 1:m
H1(:,:,p) = real(H1(:,:,p)*U.');
end
H1 = H1(:,[1:n] + 1,:);
end
if nargout > 1
for p = 1:m
for q = 1:m
for j = 1:N
H2(j,:,:,p,q) = real(squeeze(H2(j,:,:,p,q))*U.');
end
end
end
H2 = H2(:,:,[1:n] + 1,:,:);
end
return
% matrix exponential function (for diagonal matrices)
%---------------------------------------------------------------------------
function y = ex(x)
n = length(x);
y = spdiags(exp(diag(x)),0,n,n);
return
|
github
|
philippboehmsturm/antx-master
|
spm_powell.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_powell.m
| 8,945 |
utf_8
|
5c2706664704f8db313454deb4e1b755
|
function [p,f] = spm_powell(p,xi,tolsc,func,varargin)
% Powell optimisation method
% FORMAT [p,f] = spm_powell(p,xi,tolsc,func,varargin)
% p - Starting parameter values
% xi - columns containing directions in which to begin
% searching.
% tolsc - stopping criteria
% - optimisation stops when
% sqrt(sum(((p-p_prev)./tolsc).^2))<1
% func - name of evaluated function
% varargin - remaining arguments to func (after p)
%
% p - final parameter estimates
% f - function value at minimum
%
%_______________________________________________________________________
% Method is based on Powell's optimisation method described in
% Numerical Recipes (Press, Flannery, Teukolsky & Vetterling).
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_powell.m 4156 2011-01-11 19:03:31Z guillaume $
p = p(:);
f = feval(func,p,varargin{:});
for iter=1:512,
if numel(p)>1, fprintf('iteration %d...\n', iter); end;
ibig = numel(p);
pp = p;
fp = f;
del = 0;
for i=1:length(p),
ft = f;
[p,junk,f] = min1d(p,xi(:,i),func,f,tolsc,varargin{:});
if abs(ft-f) > del,
del = abs(ft-f);
ibig = i;
end;
end;
if numel(p)==1 || sqrt(sum(((p(:)-pp(:))./tolsc(:)).^2))<1, return; end;
ft = feval(func,2.0*p-pp,varargin{:});
if ft < f,
[p,xi(:,ibig),f] = min1d(p,p-pp,func,f,tolsc,varargin{:});
end;
end;
warning('Too many optimisation iterations');
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [p,pi,f] = min1d(p,pi,func,f,tolsc,varargin)
% Line search for minimum.
global lnm % used in funeval
lnm = struct('p',p,'pi',pi,'func',func,'args',[]);
lnm.args = varargin;
min1d_plot('Init', 'Line Minimisation','Function','Parameter Value');
min1d_plot('Set', 0, f);
tol = 1/sqrt(sum((pi(:)./tolsc(:)).^2));
t = bracket(f);
[f,pmin] = search(t,tol);
pi = pi*pmin;
p = p + pi;
if length(p)<12,
for i=1:length(p), fprintf('%-8.4g ', p(i)); end;
fprintf('| %.5g\n', f);
else
fprintf('%.5g\n', f);
end
min1d_plot('Clear');
return;
%_______________________________________________________________________
%_______________________________________________________________________
function f = funeval(p)
% Reconstruct parameters and evaluate.
global lnm % defined in min1d
pt = lnm.p+p.*lnm.pi;
f = feval(lnm.func,pt,lnm.args{:});
min1d_plot('Set',p,f);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function t = bracket(f)
% Bracket the minimum (t(2)) between t(1) and t(3)
gold = (1+sqrt(5))/2; % Golden ratio
t(1) = struct('p',0,'f',f);
t(2).p = 1;
t(2).f = funeval(t(2).p);
% if t(2) not better than t(1) then swap
if t(2).f > t(1).f,
t(3) = t(1);
t(1) = t(2);
t(2) = t(3);
end;
t(3).p = t(2).p + gold*(t(2).p-t(1).p);
t(3).f = funeval(t(3).p);
while t(2).f > t(3).f,
% fit a polynomial to t
tmp = cat(1,t.p)-t(2).p;
pol = pinv([ones(3,1) tmp tmp.^2])*cat(1,t.f);
% minimum is when gradient of polynomial is zero
% sign of pol(3) (the 2nd deriv) should be +ve
if pol(3)>0,
% minimum is when gradient of polynomial is zero
d = -pol(2)/(2*pol(3)+eps);
% A very conservative constraint on the displacement
if d > (1+gold)*(t(3).p-t(2).p),
d = (1+gold)*(t(3).p-t(2).p);
end;
u.p = t(2).p+d;
else
% sign of pol(3) (the 2nd deriv) is not +ve
% so extend out by golden ratio instead
u.p = t(3).p+gold*(t(3).p-t(2).p);
end;
% FUNCTION EVALUATION
u.f = funeval(u.p);
if (t(2).p < u.p) == (u.p < t(3).p),
% u is between t(2) and t(3)
if u.f < t(3).f,
% minimum between t(2) and t(3) - done
t(1) = t(2);
t(2) = u;
return;
elseif u.f > t(2).f,
% minimum between t(1) and u - done
t(3) = u;
return;
end;
end;
% Move all 3 points along
t(1) = t(2);
t(2) = t(3);
t(3) = u;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [f,p] = search(t, tol)
% Brent's method for line searching - given that minimum is bracketed
gold1 = 1-(sqrt(5)-1)/2;
% Current and previous displacements
d = Inf;
pd = Inf;
% sort t into best first order
[junk,ind] = sort(cat(1,t.f));
t = t(ind);
brk = [min(cat(1,t.p)) max(cat(1,t.p))];
for iter=1:128,
% check stopping criterion
if abs(t(1).p - 0.5*(brk(1)+brk(2)))+0.5*(brk(2)-brk(1)) <= 2*tol,
p = t(1).p;
f = t(1).f;
return;
end;
% keep last two displacents
ppd = pd;
pd = d;
% fit a polynomial to t
tmp = cat(1,t.p)-t(1).p;
pol = pinv([ones(3,1) tmp tmp.^2])*cat(1,t.f);
% minimum is when gradient of polynomial is zero
d = -pol(2)/(2*pol(3)+eps);
u.p = t(1).p+d;
% check so that displacement is less than the last but two,
% that the displaced point is between the brackets
% and that the solution is a minimum rather than a maximum
eps2 = 2*eps*abs(t(1).p)+eps;
if abs(d) > abs(ppd)/2 || u.p < brk(1)+eps2 || u.p > brk(2)-eps2 || pol(3)<=0,
% if criteria are not met, then golden search into the larger part
if t(1).p >= 0.5*(brk(1)+brk(2)),
d = gold1*(brk(1)-t(1).p);
else
d = gold1*(brk(2)-t(1).p);
end;
u.p = t(1).p+d;
end;
% FUNCTION EVALUATION
u.f = funeval(u.p);
% Insert the new point into the appropriate position and update
% the brackets if necessary
if u.f <= t(1).f,
if u.p >= t(1).p, brk(1)=t(1).p; else brk(2)=t(1).p; end;
t(3) = t(2);
t(2) = t(1);
t(1) = u;
else
if u.p < t(1).p, brk(1)=u.p; else brk(2)=u.p; end;
if u.f <= t(2).f,
t(3) = t(2);
t(2) = u;
elseif u.f <= t(3).f,
t(3) = u;
end;
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function min1d_plot(action,arg1,arg2,arg3,arg4)
% Visual output for line minimisation
persistent min1dplot
%-----------------------------------------------------------------------
if (nargin == 0)
min1d_plot('Init');
else
% initialize
%---------------------------------------------------------------
if strcmpi(action,'init')
if (nargin<4)
arg3 = 'Function';
if (nargin<3)
arg2 = 'Value';
if (nargin<2)
arg1 = 'Line minimisation';
end
end
end
fg = spm_figure('FindWin','Interactive');
if ~isempty(fg)
min1dplot = struct('pointer',get(fg,'Pointer'),'name',get(fg,'Name'),'ax',[]);
min1d_plot('Clear');
set(fg,'Pointer','watch');
% set(fg,'Name',arg1);
min1dplot.ax = axes('Position', [0.15 0.1 0.8 0.75],...
'Box', 'on','Parent',fg);
lab = get(min1dplot.ax,'Xlabel');
set(lab,'string',arg3,'FontSize',10);
lab = get(min1dplot.ax,'Ylabel');
set(lab,'string',arg2,'FontSize',10);
lab = get(min1dplot.ax,'Title');
set(lab,'string',arg1);
line('Xdata',[], 'Ydata',[],...
'LineWidth',2,'Tag','LinMinPlot','Parent',min1dplot.ax,...
'LineStyle','-','Marker','o');
drawnow;
end
% reset
%---------------------------------------------------------------
elseif strcmpi(action,'set')
F = spm_figure('FindWin','Interactive');
br = findobj(F,'Tag','LinMinPlot');
if (~isempty(br))
[xd,indx] = sort([get(br,'Xdata') arg1]);
yd = [get(br,'Ydata') arg2];
yd = yd(indx);
set(br,'Ydata',yd,'Xdata',xd);
drawnow;
end
% clear
%---------------------------------------------------------------
elseif strcmpi(action,'clear')
fg = spm_figure('FindWin','Interactive');
if isstruct(min1dplot),
if ishandle(min1dplot.ax), delete(min1dplot.ax); end
set(fg,'Pointer',min1dplot.pointer);
set(fg,'Name',min1dplot.name);
end
spm_figure('Clear',fg);
drawnow;
end
end
%_______________________________________________________________________
|
github
|
philippboehmsturm/antx-master
|
spm_vol.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_vol.m
| 4,687 |
utf_8
|
2066ba9cc72b0c288e592c2871538689
|
function V = spm_vol(P)
% Get header information for images.
% FORMAT V = spm_vol(P)
% P - a matrix of filenames.
% V - a vector of structures containing image volume information.
% The elements of the structures are:
% V.fname - the filename of the image.
% V.dim - the x, y and z dimensions of the volume
% V.dt - A 1x2 array. First element is datatype (see spm_type).
% The second is 1 or 0 depending on the endian-ness.
% V.mat - a 4x4 affine transformation matrix mapping from
% voxel coordinates to real world coordinates.
% V.pinfo - plane info for each plane of the volume.
% V.pinfo(1,:) - scale for each plane
% V.pinfo(2,:) - offset for each plane
% The true voxel intensities of the jth image are given
% by: val*V.pinfo(1,j) + V.pinfo(2,j)
% V.pinfo(3,:) - offset into image (in bytes).
% If the size of pinfo is 3x1, then the volume is assumed
% to be contiguous and each plane has the same scalefactor
% and offset.
%__________________________________________________________________________
%
% The fields listed above are essential for the mex routines, but other
% fields can also be incorporated into the structure.
%
% The images are not memory mapped at this step, but are mapped when
% the mex routines using the volume information are called.
%
% Note that spm_vol can also be applied to the filename(s) of 4-dim
% volumes. In that case, the elements of V will point to a series of 3-dim
% images.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_vol.m 4045 2010-08-26 15:10:46Z guillaume $
if ~nargin
V = struct('fname', {},...
'dim', {},...
'dt', {},...
'pinfo', {},...
'mat', {},...
'n', {},...
'descrip', {},...
'private', {});
return;
end
% If is already a vol structure then just return
if isstruct(P), V = P; return; end
V = subfunc2(P);
%==========================================================================
function V = subfunc2(P)
if iscell(P)
V = cell(size(P));
for j=1:numel(P)
if iscell(P{j})
V{j} = subfunc2(P{j});
else
V{j} = subfunc1(P{j});
end
end
else
V = subfunc1(P);
end
%==========================================================================
function V = subfunc1(P)
if isempty(P), V = []; return; end
counter = 0;
for i=1:size(P,1)
v = subfunc(P(i,:));
[V(counter+1:counter+size(v, 2),1).fname] = deal('');
[V(counter+1:counter+size(v, 2),1).dim] = deal([0 0 0 0]);
[V(counter+1:counter+size(v, 2),1).mat] = deal(eye(4));
[V(counter+1:counter+size(v, 2),1).pinfo] = deal([1 0 0]');
[V(counter+1:counter+size(v, 2),1).dt] = deal([0 0]);
if isempty(v)
hread_error_message(P(i,:));
error(['Can''t get volume information for ''' P(i,:) '''']);
end
f = fieldnames(v);
for j=1:size(f,1)
eval(['[V(counter+1:counter+size(v,2),1).' f{j} '] = deal(v.' f{j} ');']);
end
counter = counter + size(v,2);
end
%==========================================================================
function V = subfunc(p)
[pth,nam,ext,n1] = spm_fileparts(deblank(p));
p = fullfile(pth,[nam ext]);
n = str2num(n1);
if ~spm_existfile(p)
error('File "%s" does not exist.', p);
end
switch ext
case {'.nii','.NII'}
% Do nothing
case {'.img','.IMG'}
if ~spm_existfile(fullfile(pth,[nam '.hdr'])) && ...
~spm_existfile(fullfile(pth,[nam '.HDR']))
error('File "%s" does not exist.', fullfile(pth,[nam '.hdr']));
end
case {'.hdr','.HDR'}
ext = '.img';
p = fullfile(pth,[nam ext]);
if ~spm_existfile(p)
error('File "%s" does not exist.', p);
end
otherwise
error('File "%s" is not of a recognised type.', p);
end
V = spm_vol_nifti(p,n);
if isempty(n) && length(V.private.dat.dim) > 3
V0(1) = V;
for i = 2:V.private.dat.dim(4)
V0(i) = spm_vol_nifti(p, i);
end
V = V0;
end
if ~isempty(V), return; end
return;
%==========================================================================
function hread_error_message(q)
str = {...
'Error reading information on:',...
[' ',spm_str_manip(q,'k40d')],...
' ',...
'Please check that it is in the correct format.'};
spm('alert*',str,mfilename,sqrt(-1));
return;
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_epochs.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_eeg_epochs.m
| 7,801 |
utf_8
|
4fabb15c82422268deb9dca5b1a0ea6b
|
function D = spm_eeg_epochs(S)
% Epoching continuous M/EEG data
% FORMAT D = spm_eeg_epochs(S)
%
% S - input structure (optional)
% (optional) fields of S:
% S.D - MEEG object or filename of M/EEG mat-file with
% continuous data
% S.bc - baseline-correct the data (1 - yes, 0 - no).
%
% Either (to use a ready-made trial definition):
% S.epochinfo.trl - Nx2 or Nx3 matrix (N - number of trials)
% [start end offset]
% S.epochinfo.conditionlabels - one label or cell array of N labels
% S.epochinfo.padding - 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) [in ms]
%
% Or (to define trials using (spm_eeg_definetrial)):
% S.pretrig - pre-trigger time [in ms]
% S.posttrig - post-trigger time [in ms]
% S.trialdef - structure array for trial definition with fields
% S.trialdef.conditionlabel - string label for the condition
% S.trialdef.eventtype - string
% S.trialdef.eventvalue - string, numeric or empty
%
% S.reviewtrials - review individual trials after selection
% S.save - save trial definition
%
% Output:
% D - MEEG object (also written on disk)
%__________________________________________________________________________
%
% spm_eeg_epochs extracts single trials from continuous EEG/MEG data. The
% length of an epoch is determined by the samples before and after stimulus
% presentation. One can limit the extracted trials to specific trial types.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Stefan Kiebel
% $Id: spm_eeg_epochs.m 4430 2011-08-12 18:47:17Z vladimir $
SVNrev = '$Rev: 4430 $';
%-Startup
%--------------------------------------------------------------------------
spm('FnBanner', mfilename, SVNrev);
spm('FigName','M/EEG epoching'); spm('Pointer','Watch');
%-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);
S.D = fullfile(D.path, D.fname);
%-Check that the input file contains continuous data
%--------------------------------------------------------------------------
if ~strncmpi(D.type, 'cont', 4)
error('The file must contain continuous data.');
end
if ~isfield(S, 'bc')
S.bc = 1;
% S.bc = spm_input('Subtract baseline?','+1','yes|no',[1 0], 1);
end
%-First case: deftrials (default for GUI call)
%--------------------------------------------------------------------------
if isfield(S, 'trialdef') || nargin == 0
if isfield(S, 'pretrig')
S_definetrial.pretrig = S.pretrig;
end
if isfield(S, 'posttrig')
S_definetrial.posttrig = S.posttrig;
end
if isfield(S, 'trialdef')
S_definetrial.trialdef = S.trialdef;
end
if isfield(S, 'reviewtrials')
S_definetrial.reviewtrials = S.reviewtrials;
end
if isfield(S, 'save')
S_definetrial.save = S.save;
end
S_definetrial.D = S.D;
S_definetrial.event = D.events;
S_definetrial.fsample = D.fsample;
S_definetrial.timeonset = D.timeonset;
S_definetrial.bc = S.bc;
[epochinfo.trl, epochinfo.conditionlabels, S] = spm_eeg_definetrial(S_definetrial);
%-Second case: epochinfo (trlfile and trl)
%--------------------------------------------------------------------------
else
try
epochinfo.trl = S.epochinfo.trl;
epochinfo.conditionlabels = S.epochinfo.conditionlabels;
catch
try
epochinfo.trlfile = S.epochinfo.trlfile;
catch
epochinfo.trlfile = spm_select(1, 'mat', 'Select a trial definition file');
end
try
epochinfo.trl = getfield(load(S.epochinfo.trlfile, 'trl'), 'trl');
epochinfo.conditionlabels = getfield(load(epochinfo.trlfile, 'conditionlabels'), 'conditionlabels');
catch
error('Trouble reading trl file.');
end
end
end
trl = epochinfo.trl;
conditionlabels = epochinfo.conditionlabels;
if numel(conditionlabels) == 1
conditionlabels = repmat(conditionlabels, 1, size(trl, 1));
end
try
epochinfo.padding = S.epochinfo.padding;
catch
epochinfo.padding = 0;
% for history
S.epochinfo.padding = epochinfo.padding;
end
% checks on input
if size(trl, 2) >= 3
timeOnset = unique(trl(:, 3))./D.fsample;
trl = trl(:, 1:2);
else
timeOnset = 0;
end
if length(timeOnset) > 1
error('All trials should have identical baseline');
end
nsampl = unique(round(diff(trl, [], 2)))+1;
if length(nsampl) > 1 || nsampl<1
error('All trials should have identical and positive lengths');
end
inbounds = (trl(:,1)>=1 & trl(:, 2)<=D.nsamples);
rejected = find(~inbounds);
rejected = rejected(:)';
if ~isempty(rejected)
trl = trl(inbounds, :);
conditionlabels = conditionlabels(inbounds);
warning([D.fname ': Events ' num2str(rejected) ' not extracted - out of bounds']);
end
ntrial = size(trl, 1);
%-Generate new MEEG object with new filenames
%--------------------------------------------------------------------------
Dnew = clone(D, ['e' fnamedat(D)], [D.nchannels nsampl, ntrial]);
%-Epoch data
%--------------------------------------------------------------------------
spm_progress_bar('Init', ntrial, 'Events read');
if ntrial > 100, Ibar = floor(linspace(1, ntrial, 100));
else Ibar = [1:ntrial]; end
for i = 1:ntrial
d = D(:, trl(i, 1):trl(i, 2), 1);
Dnew(:, :, i) = d;
Dnew = events(Dnew, i, select_events(D.events, ...
[trl(i, 1)/D.fsample-epochinfo.padding trl(i, 2)/D.fsample+epochinfo.padding]));
if ismember(i, Ibar), spm_progress_bar('Set', i); end
end
Dnew = conditions(Dnew, [], conditionlabels);
% The conditions will later be sorted in the original order they were defined.
if isfield(S, 'trialdef')
Dnew = condlist(Dnew, {S.trialdef(:).conditionlabel});
end
Dnew = trialonset(Dnew, [], trl(:, 1)./D.fsample+D.trialonset);
Dnew = timeonset(Dnew, timeOnset);
Dnew = type(Dnew, 'single');
%-Perform baseline correction if there are negative time points
%--------------------------------------------------------------------------
if S.bc
if time(Dnew, 1) < 0
S1 = [];
S1.D = Dnew;
S1.time = [time(Dnew, 1, 'ms') 0];
S1.save = false;
S1.updatehistory = false;
Dnew = spm_eeg_bc(S1);
else
warning('There was no baseline specified. The data is not baseline-corrected');
end
end
%-Save new evoked M/EEG dataset
%--------------------------------------------------------------------------
D = Dnew;
% Remove some redundant stuff potentially put in by spm_eeg_definetrial
if isfield(S, 'event'), S = rmfield(S, 'event'); end
D = D.history(mfilename, S);
save(D);
%-Cleanup
%--------------------------------------------------------------------------
spm_progress_bar('Clear');
spm('FigName','M/EEG epoching: done'); spm('Pointer','Arrow');
%==========================================================================
function event = select_events(event, timeseg)
% Utility function to select events according to time segment
if ~isempty(event)
[time ind] = sort([event(:).time]);
selectind = ind(time >= timeseg(1) & time <= timeseg(2));
event = event(selectind);
end
|
github
|
philippboehmsturm/antx-master
|
spm_jobman.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_jobman.m
| 23,512 |
utf_8
|
7a06348ae2c25b462641347366bddd8e
|
function varargout = spm_jobman(varargin)
% Main interface for SPM Batch System
% This function provides a compatibility layer between SPM and matlabbatch.
% It translates spm_jobman callbacks into matlabbatch callbacks and allows
% to edit and run SPM5 style batch jobs.
%
% FORMAT spm_jobman('initcfg')
% Initialise jobs configuration and set MATLAB path accordingly.
%
% FORMAT spm_jobman('run',job[,input1,...inputN])
% FORMAT output_list = spm_jobman('run',job[,input1,...inputN])
% FORMAT [output_list hjob] = spm_jobman('run',job[,input1,...inputN])
% Run specified job
% job - filename of a job (.m, .mat or .xml), or
% cell array of filenames, or
% 'jobs'/'matlabbatch' variable, or
% cell array of 'jobs'/'matlabbatch' variables.
% input1,... - optional list of input arguments. These are filled into
% open inputs ('X->' marked in the GUI) before a job is run.
% output_list - cell array containing the output arguments from each
% module in the job. The format and contents of these
% outputs is defined in the configuration of each module
% (.prog and .vout callbacks).
% hjob - harvested job after it has been filled and run. Note that
% this job has no dependencies any more. If one loads this
% job back to the batch system and changes some of the
% inputs, changed outputs will not be passed on.
%
% FORMAT job_id = spm_jobman
% job_id = spm_jobman('interactive')
% job_id = spm_jobman('interactive',job)
% job_id = spm_jobman('interactive',job,node)
% job_id = spm_jobman('interactive','',node)
% Run the user interface in interactive mode.
% node - indicate which part of the configuration is to be used.
% For example, it could be 'spm.spatial.coreg.estimate'.
% job_id - can be used to manipulate this job in cfg_util. Note that
% changes to the job in cfg_util will not show up in cfg_ui
% unless 'Update View' is called.
%__________________________________________________________________________
%
% Programmers help:
%
% FORMAT output_list = spm_jobman('serial')
% output_list = spm_jobman('serial',job[,'', input1,...inputN])
% output_list = spm_jobman('serial',job ,node[,input1,...inputN])
% output_list = spm_jobman('serial','' ,node[,input1,...inputN])
% Run the user interface in serial mode. If job is not empty, then node
% is silently ignored. Inputs can be a list of arguments. These are passed
% on to the open inputs of the specified job/node. Each input should be
% suitable to be assigned to item.val{1}. For cfg_repeat/cfg_choice items,
% input should be a cell list of indices input{1}...input{k} into
% item.value. See cfg_util('filljob',...) for details.
%
% FORMAT jobs = spm_jobman('spm5tospm8',jobs)
% Take a cell list of SPM5 job structures and returns SPM8 compatible versions.
%
% FORMAT job = spm_jobman('spm5tospm8bulk',jobfiles)
% Take a cell string with SPM5 job filenames and saves them in SPM8
% compatible format. The new job files will be MATLAB .m files. Their
% filenames will be derived from the input filenames. To make sure they are
% valid MATLAB script names they will be processed with
% genvarname(filename) and have a '_spm8' string appended to their
% filename.
%
% FORMAT spm_jobman('help',node)
% spm_jobman('help',node,width)
% Create a cell array containing help information. This is justified
% to be 'width' characters wide. e.g.
% h = spm_jobman('help','spm.spatial.coreg.estimate');
% for i=1:numel(h), fprintf('%s\n',h{i}); end
%
% FORMAT [tag, job] = spm_jobman('harvest', job_id|cfg_item|cfg_struct)
% Take the job with id job_id in cfg_util and extract what is
% needed to save it as a batch job (for experts only). If the argument is a
% cfg_item or cfg_struct tree, it will be harvested outside cfg_util.
% tag - tag of the root node of the current job/cfg_item tree
% job - harvested data from the current job/cfg_item tree
%
% FORMAT spm_jobman('pulldown')
% Create a pulldown 'TASKS' menu in the Graphics window.
%__________________________________________________________________________
%
% not implemented: FORMAT spm_jobman('jobhelp')
% Create a cell array containing help information specific for a certain
% job. Help is only printed for items where job specific help is
% present. This can be used together with spm_jobman('help') to create a
% job specific manual.
%
% not implemented: FORMAT spm_jobman('chmod')
% Change the modality for the TASKS pulldown.
%
% not implemented: FORMAT spm_jobman('defaults')
% Run the interactive defaults editor.
%
% not implemented: FORMAT output_list = spm_jobman('run_nogui',job)
% Run a job without X11 (as long as there is no graphics output from the
% job itself). The matlabbatch system does not need graphics output to run
% a job.
%__________________________________________________________________________
%
% This code is based on earlier versions by John Ashburner, Philippe
% Ciuciu and Guillaume Flandin.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Copyright (C) 2008 Freiburg Brain Imaging
% Volkmar Glauche
% $Id: spm_jobman.m 4242 2011-03-11 15:12:04Z guillaume $
persistent isInitCfg;
if isempty(isInitCfg) && ~(nargin == 1 && strcmpi(varargin{1},'initcfg'))
warning('spm:spm_jobman:NotInitialised',...
'Run spm_jobman(''initcfg''); beforehand');
spm_jobman('initcfg');
end
isInitCfg = true;
if ~nargin
h = cfg_ui;
if nargout > 0, varargout = {h}; end
return;
end
cmd = lower(varargin{1});
if strcmp(cmd,'run_nogui')
warning('spm:spm_jobman:NotImplemented', ...
'Callback ''%s'' not implemented.', cmd);
cmd = 'run';
end
if any(strcmp(cmd, {'serial','interactive','run'}))
if nargin > 1
% sort out job/node arguments for interactive, serial, run cmds
if nargin>=2 && ~isempty(varargin{2})
% do not consider node if job is given
if ischar(varargin{2}) || iscellstr(varargin{2})
jobs = load_jobs(varargin{2});
elseif iscell(varargin{2})
if iscell(varargin{2}{1})
% assume varargin{2} is a cell of jobs
jobs = varargin{2};
else
% assume varargin{2} is a single job
jobs{1} = varargin{2};
end
end
mljob = canonicalise_job(jobs);
elseif any(strcmp(cmd, {'interactive','serial'})) && nargin>=3 && isempty(varargin{2})
% Node spec only allowed for 'interactive', 'serial'
arg3 = regexprep(varargin{3},'^spmjobs\.','spm.');
mod_cfg_id = cfg_util('tag2mod_cfg_id',arg3);
else
error('spm:spm_jobman:WrongUI', ...
'Don''t know how to handle this ''%s'' call.', lower(varargin{1}));
end
end
end
switch cmd
case {'initcfg'}
if ~isdeployed
addpath(fullfile(spm('Dir'),'matlabbatch'));
addpath(fullfile(spm('Dir'),'config'));
end
cfg_get_defaults('cfg_util.genscript_run', @genscript_run);
cfg_util('initcfg'); % This must be the first call to cfg_util
if ~spm('cmdline')
f = cfg_ui('Visible','off'); % Create invisible batch ui
f0 = findobj(f, 'Tag','MenuFile'); % Add entries to file menu
f2 = uimenu(f0,'Label','Load SPM5 job', 'Callback',@load_job, ...
'HandleVisibility','off', 'tag','jobs', ...
'Separator','on');
f3 = uimenu(f0,'Label','Bulk Convert SPM5 job(s)', ...
'Callback',@conv_jobs, ...
'HandleVisibility','off', 'tag','jobs');
end
case {'interactive'}
if exist('mljob', 'var')
cjob = cfg_util('initjob', mljob);
elseif exist('mod_cfg_id', 'var')
if isempty(mod_cfg_id)
arg3 = regexprep(varargin{3},'^spmjobs\.','spm.');
warning('spm:spm_jobman:NodeNotFound', ...
['Can not find executable node ''%s'' - running '...
'matlabbatch without default node.'], arg3);
cjob = cfg_util('initjob');
else
cjob = cfg_util('initjob');
mod_job_id = cfg_util('addtojob', cjob, mod_cfg_id);
cfg_util('harvest', cjob, mod_job_id);
end
else
cjob = cfg_util('initjob');
end
cfg_ui('local_showjob', findobj(0,'tag','cfg_ui'), cjob);
if nargout > 0
varargout{1} = cjob;
end
case {'serial'}
if exist('mljob', 'var')
cjob = cfg_util('initjob', mljob);
else
cjob = cfg_util('initjob');
if nargin > 2
arg3 = regexprep(varargin{3},'^spmjobs\.','spm.');
[mod_cfg_id, item_mod_id] = cfg_util('tag2cfg_id', lower(arg3));
cfg_util('addtojob', cjob, mod_cfg_id);
end
end
sts = fill_run_job(cjob, varargin{4:end});
if sts
if nargout > 0
varargout{1} = cfg_util('getalloutputs', cjob);
end
if nargout > 1
varargout{2} = cfg_util('harvestrun', cjob);
end
end
cfg_util('deljob', cjob);
case {'run'}
cjob = cfg_util('initjob', mljob);
sts = fill_run_job(cjob, varargin{3:end});
if sts
if nargout > 0
varargout{1} = cfg_util('getalloutputs', cjob);
end
if nargout > 1
varargout{2} = cfg_util('harvestrun', cjob);
end
end
cfg_util('deljob', cjob);
case {'spm5tospm8'}
varargout{1} = canonicalise_job(varargin{2});
case {'spm5tospm8bulk'}
conv_jobs(varargin{2});
case {'harvest'}
if nargin == 1
error('spm:spm_jobman:CantHarvest', ...
['Can not harvest job without job_id. Please use ' ...
'spm_jobman(''harvest'', job_id).']);
elseif cfg_util('isjob_id', varargin{2})
[tag job] = cfg_util('harvest', varargin{2});
elseif isa(varargin{2}, 'cfg_item')
[tag job] = harvest(varargin{2}, varargin{2}, false, false);
elseif isstruct(varargin{2})
% try to convert into class before harvesting
c = cfg_struct2cfg(varargin{2});
[tag job] = harvest(c,c,false,false);
else
error('spm:spm_jobman:CantHarvestThis', ...
'Can not harvest this argument.');
end
varargout{1} = tag;
varargout{2} = job;
case {'help'}
if (nargin < 2) || isempty(varargin{2})
node = 'spm';
else
node = regexprep(varargin{2},'^spmjobs\.','spm.');
end
if nargin < 3
width = 60;
else
width = varargin{3};
end
varargout{1} = cfg_util('showdocwidth', width, node);
case {'pulldown'}
pulldown;
case {'defaults'}
warning('spm:spm_jobman:NotImplemented', ...
'Callback ''%s'' not implemented.', varargin{1});
case {'chmod'}
warning('spm:spm_jobman:NotImplemented', ...
'Callback ''%s'' not implemented.', varargin{1});
case {'jobhelp'}
warning('spm:spm_jobman:NotImplemented', ...
'Callback ''%s'' not implemented.', varargin{1});
otherwise
error(['"' varargin{1} '" - unknown option']);
end
%==========================================================================
% function [mljob, comp] = canonicalise_job(job)
%==========================================================================
function [mljob, comp] = canonicalise_job(job)
% job: a cell list of job data structures.
% Check whether job is a SPM5 or matlabbatch job. In the first case, all
% items in job{:} should have a fieldname of either 'temporal', 'spatial',
% 'stats', 'tools' or 'util'. If this is the case, then job will be
% assigned to mljob{1}.spm, which is the tag of the SPM root
% configuration item.
comp = true(size(job));
mljob = cell(size(job));
for cj = 1:numel(job)
for k = 1:numel(job{cj})
comp(cj) = comp(cj) && any(strcmp(fieldnames(job{cj}{k}), ...
{'temporal', 'spatial', 'stats', 'tools', 'util'}));
if ~comp(cj)
break;
end
end
if comp(cj)
tmp = convert_jobs(job{cj});
for i=1:numel(tmp),
mljob{cj}{i}.spm = tmp{i};
end
else
mljob{cj} = job{cj};
end
end
%==========================================================================
% function conv_jobs(varargin)
%==========================================================================
function conv_jobs(varargin)
% Select a list of jobs, canonicalise each of it and save as a .m file
% using gencode.
spm('Pointer','Watch');
if nargin == 0 || ~iscellstr(varargin{1})
[fname sts] = spm_select([1 Inf], 'batch', 'Select job file(s)');
fname = cellstr(fname);
if ~sts, return; end
else
fname = varargin{1};
end
joblist = load_jobs(fname);
for k = 1:numel(fname)
if ~isempty(joblist{k})
[p n] = spm_fileparts(fname{k});
% Save new job as genvarname(*_spm8).m
newfname = fullfile(p, sprintf('%s.m', ...
genvarname(sprintf('%s_spm8', n))));
fprintf('SPM5 job: %s\nSPM8 job: %s\n', fname{k}, newfname);
cjob = cfg_util('initjob', canonicalise_job(joblist(k)));
cfg_util('savejob', cjob, newfname);
cfg_util('deljob', cjob);
end
end
spm('Pointer','Arrow');
%==========================================================================
% function load_job(varargin)
%==========================================================================
function load_job(varargin)
% Select a single job file, canonicalise it and display it in GUI
[fname sts] = spm_select([1 Inf], 'batch', 'Select job file');
if ~sts, return; end
spm('Pointer','Watch');
joblist = load_jobs(fname);
if ~isempty(joblist{1})
spm_jobman('interactive',joblist{1});
end
spm('Pointer','Arrow');
%==========================================================================
% function newjobs = load_jobs(job)
%==========================================================================
function newjobs = load_jobs(job)
% Load a list of possible job files, return a cell list of jobs. Jobs can
% be either SPM5 (i.e. containing a 'jobs' variable) or SPM8/matlabbatch
% jobs. If a job file failed to load, an empty cell is returned in the
% list.
if ischar(job)
filenames = cellstr(job);
else
filenames = job;
end
newjobs = {};
for cf = 1:numel(filenames)
[p,nam,ext] = fileparts(filenames{cf});
switch ext
case '.xml'
spm('Pointer','Watch');
try
loadxml(filenames{cf},'jobs');
catch
try
loadxml(filenames{cf},'matlabbatch');
catch
warning('spm:spm_jobman:LoadFailed','LoadXML failed: ''%s''',filenames{cf});
end
end
spm('Pointer','Arrow');
case '.mat'
try
S=load(filenames{cf});
if isfield(S,'matlabbatch')
matlabbatch = S.matlabbatch;
elseif isfield(S,'jobs')
jobs = S.jobs;
else
warning('spm:spm_jobman:JobNotFound','No SPM5/SPM8 job found in ''%s''', filenames{cf});
end
catch
warning('spm:spm_jobman:LoadFailed','Load failed: ''%s''',filenames{cf});
end
case '.m'
try
fid = fopen(filenames{cf},'rt');
str = fread(fid,'*char');
fclose(fid);
eval(str);
catch
warning('spm:spm_jobman:LoadFailed','Load failed: ''%s''',filenames{cf});
end
if ~(exist('jobs','var') || exist('matlabbatch','var'))
warning('spm:spm_jobman:JobNotFound','No SPM5/SPM8 job found in ''%s''', filenames{cf});
end
otherwise
warning('Unknown extension: ''%s''', filenames{cf});
end
if exist('jobs','var')
newjobs = [newjobs(:); {jobs}];
clear jobs;
elseif exist('matlabbatch','var')
newjobs = [newjobs(:); {matlabbatch}];
clear matlabbatch;
end
end
%==========================================================================
% function njobs = convert_jobs(jobs)
%==========================================================================
function njobs = convert_jobs(jobs)
decel = struct('spatial',struct('realign',[],'coreg',[],'normalise',[]),...
'temporal',[],...
'stats',[],...
'meeg',[],...
'util',[],...
'tools',struct('dartel',[]));
njobs = {};
for i0 = 1:numel(jobs)
tmp0 = fieldnames(jobs{i0});
tmp0 = tmp0{1};
if any(strcmp(tmp0,fieldnames(decel)))
for i1=1:numel(jobs{i0}.(tmp0))
tmp1 = fieldnames(jobs{i0}.(tmp0){i1});
tmp1 = tmp1{1};
if ~isempty(decel.(tmp0))
if any(strcmp(tmp1,fieldnames(decel.(tmp0)))),
for i2=1:numel(jobs{i0}.(tmp0){i1}.(tmp1)),
njobs{end+1} = struct(tmp0,struct(tmp1,jobs{i0}.(tmp0){i1}.(tmp1){i2}));
end
else
njobs{end+1} = struct(tmp0,jobs{i0}.(tmp0){i1});
end
else
njobs{end+1} = struct(tmp0,jobs{i0}.(tmp0){i1});
end
end
else
njobs{end+1} = jobs{i0};
end
end
%==========================================================================
% function pulldown
%==========================================================================
function pulldown
fg = spm_figure('findwin','Graphics');
if isempty(fg), return; end;
delete(findall(fg,'tag','jobs'));
f0 = uimenu(fg,'Label','TASKS', ...
'HandleVisibility','off', 'tag','jobs');
f1 = uimenu(f0,'Label','BATCH', 'Callback',@cfg_ui, ...
'HandleVisibility','off', 'tag','jobs');
f4 = uimenu(f0,'Label','SPM (interactive)', ...
'HandleVisibility','off', 'tag','jobs', 'Separator','on');
cfg_ui('local_setmenu', f4, cfg_util('tag2cfg_id', 'spm'), ...
@local_init_interactive, false);
f5 = uimenu(f0,'Label','SPM (serial)', ...
'HandleVisibility','off', 'tag','jobs');
cfg_ui('local_setmenu', f5, cfg_util('tag2cfg_id', 'spm'), ...
@local_init_serial, false);
%==========================================================================
% function local_init_interactive(varargin)
%==========================================================================
function local_init_interactive(varargin)
cjob = cfg_util('initjob');
mod_cfg_id = get(gcbo,'userdata');
cfg_util('addtojob', cjob, mod_cfg_id);
cfg_ui('local_showjob', findobj(0,'tag','cfg_ui'), cjob);
%==========================================================================
% function local_init_serial(varargin)
%==========================================================================
function local_init_serial(varargin)
mod_cfg_id = get(gcbo,'userdata');
cjob = cfg_util('initjob');
cfg_util('addtojob', cjob, mod_cfg_id);
sts = cfg_util('filljobui', cjob, @serial_ui);
if sts
cfg_util('run', cjob);
end
cfg_util('deljob', cjob);
%==========================================================================
% function sts = fill_run_job(cjob, varargin)
%==========================================================================
function sts = fill_run_job(cjob, varargin)
sts = cfg_util('filljobui', cjob, @serial_ui, varargin{:});
if sts
try
cfg_util('run', cjob);
catch
le = lasterror;
try
errfile = fullfile(pwd, sprintf('spm_error_%s.mat', datestr(now, 'yyyy-mm-dd_HH:MM:SS.FFF')));
[u1 ojob] = cfg_util('harvest', cjob);
[u1 rjob] = cfg_util('harvestrun', cjob);
outputs = cfg_util('getalloutputs', cjob);
diarystr = cfg_util('getdiary', cjob);
save(errfile, 'ojob', 'rjob', 'outputs', 'diarystr');
le.message = sprintf('%s\nError information has been saved to file:\n\n%s', le.message, errfile);
end
le.stack = struct('file','', 'name','SPM Job', 'line',0);
rethrow(le);
end
end
%==========================================================================
% function [val sts] = serial_ui(item)
%==========================================================================
function [val sts] = serial_ui(item)
% wrapper function to translate cfg_util('filljobui'... input requests into
% spm_input/cfg_select calls.
sts = true;
switch class(item)
case 'cfg_choice'
labels = cell(size(item.values));
values = cell(size(item.values));
for k = 1:numel(item.values)
labels{k} = item.values{k}.name;
values{k} = k;
end
val = spm_input(item.name, 1, 'm', labels, values);
case 'cfg_menu'
val = spm_input(item.name, 1, 'm', item.labels, item.values);
val = val{1};
case 'cfg_repeat'
labels = cell(size(item.values));
values = cell(size(item.values));
for k = 1:numel(item.values)
labels{k} = item.values{k}.name;
values{k} = k;
end
% enter at least item.num(1) values
for k = 1:item.num(1)
val(k) = spm_input(sprintf('%s(%d)', item.name, k), 1, 'm', ...
labels, values);
end
% enter more (up to varargin{3}(2) values
labels = {labels{:} 'Done'};
% values is a cell list of natural numbers, use -1 for Done
values = {values{:} -1};
while numel(val) < item.num(2)
val1 = spm_input(sprintf('%s(%d)', item.name, numel(val)+1), 1, ...
'm', labels, values);
if val1{1} == -1
break;
else
val(end+1) = val1;
end
end
case 'cfg_entry'
val = spm_input(item.name, 1, item.strtype, '', item.num, ...
item.extras);
case 'cfg_files'
[t,sts] = cfg_getfile(item.num, item.filter, item.name, '', ...
item.dir, item.ufilter);
if sts
val = cellstr(t);
else
val = {};
error('File selector was closed.');
end
end
%==========================================================================
% function [code cont] = genscript_run
%==========================================================================
function [code cont] = genscript_run
% Return code snippet to initialise SPM defaults and run a job generated by
% cfg_util('genscript',...) through spm_jobman.
modality = spm('CheckModality');
code{1} = sprintf('spm(''defaults'', ''%s'');', modality);
code{2} = 'spm_jobman(''run'', jobs, inputs{:});';
cont = false;
|
github
|
philippboehmsturm/antx-master
|
spm_bms_partition.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_bms_partition.m
| 4,648 |
utf_8
|
0b0d4cfa175b9620fe86629a8490391c
|
function spm_bms_partition(BMS)
% Compute model partitioning for BMS
% FORMAT spm_bms_partition(BMS)
%
% Input:
% BMS structure (BMS.mat)
%
% Output:
% PPM (images) for each of the subsets defined
% xppm_subsetn.img (RFX) and ppm_subsetn.img (FFX)
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Maria Joao Rosa
% $Id: spm_bms_partition.m 4310 2011-04-18 16:07:35Z guillaume $
% Contrast vector
% -------------------------------------------------------------------------
spm_input('Specify contrast vector. Example: [1 1 2 2 3 3]',1,'d');
contrast = spm_input('Contrast vector',2,'e',[]);
% Inference method to plot
% -------------------------------------------------------------------------
method = spm_input('Inference method',3,'b','FFX|RFX',['FFX';'RFX']);
nb_subsets = length(unique(contrast));
max_cont = max(contrast);
nb_models = length(contrast);
switch method
case 'FFX'
str_method = 'ffx';
str_output = 'ppm';
case 'RFX'
str_method = 'rfx';
str_output = 'xppm';
otherwise
error('Unknown inference method.');
end
% Check if ffx exists
% -------------------------------------------------------------------------
if ~isfield(BMS.map,str_method)
msgbox(sprintf('No %s analysis in current BMS.mat.',method));
return
end
% Check number of subsets and nb of models
% -------------------------------------------------------------------------
bms_fields = eval(sprintf('BMS.map.%s.ppm',str_method));
nmodels = size(bms_fields,2);
if nb_models ~= nmodels || nb_subsets == 1 || max_cont ~= nb_subsets
msgbox('Invalid contrast vector!')
return
end
% Get data for each subset
% -------------------------------------------------------------------------
data = cell(1,nb_subsets);
for i = 1:nmodels,
num = contrast(i);
data{num} = [data{num};bms_fields{i}];
end
% Create new images by summing old the ppms
% -------------------------------------------------------------------------
pth = fileparts(BMS.fname);
data_vol = cell(nb_subsets,1);
ftmp = cell(nb_subsets,1);
for j = 1:nb_subsets,
data_vol{j} = spm_vol(char(data{j}));
n_models_sub = size(data{j},1);
ftmp{j} = 'i1';
for jj = 1:n_models_sub-1
ftmp{j} = [ftmp{j},sprintf(' + i%d',jj+1)];
end
fname = fullfile(pth,sprintf('subset%d_%s.img',j,str_output));
save_fn{j} = fname;
Vo = calc_im(j,data_vol,fname,ftmp);
end
% Save new BMS structure
% -------------------------------------------------------------------------
bms_struct = eval(sprintf('BMS.map.%s',str_method));
bms_struct.subsets = save_fn;
switch method
case 'FFX'
BMS.map.ffx = bms_struct;
case 'RFX'
BMS.map.rfx = bms_struct;
end
file_name = BMS.fname;
BMS.xSPM = [];
save(file_name,'BMS')
% Return to results
%==========================================================================
spm_input('Done',1,'d');
return;
%==========================================================================
% out = calc_im(j,data_vol,fname,ftmp)
%==========================================================================
% Function to sum the data (taken from spm_imcalc)
%--------------------------------------------------------------------------
function out = calc_im(j,data_vol,fname,ftmp)
Vi_tmp = data_vol{j};
Vi = Vi_tmp(1);
Vo(j) = struct(...
'fname', fname,...
'dim', Vi.dim,...
'dt', [spm_type('float32') spm_platform('bigend')],...
'mat', Vi.mat,...
'descrip', 'spm - algebra');
hold = 1; mask = 0; dmtx = 0;
Vi = data_vol{j};
n = numel(Vi);
Y = zeros(Vo(j).dim(1:3));
f = ftmp{j};
for p = 1:Vo(j).dim(3),
B = spm_matrix([0 0 -p 0 0 0 1 1 1]);
if dmtx, X=zeros(n,prod(Vo(j).dim(1:2))); end
for i = 1:n
M = inv(B*inv(Vo(j).mat)*Vi(i).mat);
d = spm_slice_vol(Vi(i),M,Vo(j).dim(1:2),[hold,NaN]);
if (mask<0), d(isnan(d))=0; end;
if (mask>0) && ~spm_type(Vi(i).dt(1),'nanrep'), d(d==0)=NaN; end
if dmtx, X(i,:) = d(:)'; else eval(['i',num2str(i),'=d;']); end
end
try
eval(['Yp = ' f ';']);
catch
error(['Can''t evaluate "',f,'".']);
end
if prod(Vo(j).dim(1:2)) ~= numel(Yp),
error(['"',f,'" produced incompatible image.']); end
if (mask<0), Yp(isnan(Yp))=0; end
Y(:,:,p) = reshape(Yp,Vo(j).dim(1:2));
end
temp = Vo(j);
temp = spm_write_vol(temp,Y);
out(j) = temp;
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_inv_vbecd_disp.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_eeg_inv_vbecd_disp.m
| 23,018 |
UNKNOWN
|
5277a06e987a0014165d867f7c51bb1b
|
function spm_eeg_inv_vbecd_disp(action,varargin)
% Display the dipoles as obtained from VB-ECD
%
% FORMAT spm_eeg_inv_vbecd_disp('Init',D)
% Display the latest VB-ECD solution saved in the .inv{} field of the
% data structure D.
%
% FORMAT spm_eeg_inv_vbecd_disp('Init',D, ind)
% Display the ind^th .inv{} cell element, if it is actually a VB-ECD
% solution.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Christophe Phillips
% $Id: spm_eeg_inv_vbecd_disp.m 3951 2010-06-28 15:09:36Z gareth $
% Note:
% unfortunately I cannot see how to ensure that when zooming in the image
% the dipole location stays in place...
global st
Fig = spm_figure('GetWin','Graphics');
colors = {'y','b','g','r','c','m'}; % 6 possible colors
marker = {'o','x','+','*','s','d','v','p','h'}; % 9 possible markers
Ncolors = length(colors);
Nmarker = length(marker);
if nargin == 0, action = 'Init'; end;
switch lower(action),
%==========================================================================
case 'init'
%==========================================================================
% FORMAT spm_eeg_inv_vbecd_disp('init',D,ind)
% Initialise the variables with GUI
%--------------------------------------------------------------------------
if nargin<2
D = spm_eeg_load;
else
D = varargin{1};
end
if nargin<3
% find the latest inverse produced with vbecd
Ninv = length(D.inv);
lind = [];
for ii=1:Ninv
if isfield(D.inv{ii},'method') && ...
strcmp(D.inv{ii}.method,'vbecd')
lind = [lind ii];
end
end
ind = max(lind);
if ~ind,
spm('alert*','No VB-ECD solution found with this data file!',...
'VB-ECD display')
return
end
else
ind = varargin{3};
end
% Stash dipole(s) information in sdip structure
sdip = D.inv{ind}.inverse;
% if the exit flag is not in the structure, assume everything went ok.
if ~isfield(sdip,'exitflag')
sdip.exitflag = ones(1,sdip.n_seeds);
end
try
error('crap');
Pimg = spm_vol(D.inv{ind}.mesh.sMRI);
catch
Pimg = spm_vol(fullfile(spm('dir'), 'canonical', 'single_subj_T1.nii'));
end
spm_orthviews('Reset');
spm_orthviews('Image', Pimg, [0.0 0.45 1 0.55]);
spm_orthviews('MaxBB');
spm_orthviews('AddContext')
st.callback = 'spm_image(''shopos'');';
% remove clicking in image
for ii=1:3,
set(st.vols{1}.ax{ii}.ax,'ButtonDownFcn',';');
end
WS = spm('WinScale');
% Build GUI
%==========================================================================
% Location:
%--------------------------------------------------------------------------
uicontrol(Fig,'Style','Frame','Position',[60 25 200 325].*WS, ...
'DeleteFcn','spm_image(''reset'');');
uicontrol(Fig,'Style','Frame','Position',[70 250 180 90].*WS);
uicontrol(Fig,'Style','Text', 'Position',[75 320 170 016].*WS, ...
'String','Current Position');
uicontrol(Fig,'Style','Text', 'Position',[75 295 35 020].*WS,'String','mm:');
uicontrol(Fig,'Style','Text', 'Position',[75 275 35 020].*WS,'String','vx:');
uicontrol(Fig,'Style','Text', 'Position',[75 255 75 020].*WS,'String','Img Intens.:');
st.mp = uicontrol(Fig,'Style','Text', 'Position',[110 295 135 020].*WS,'String','');
st.vp = uicontrol(Fig,'Style','Text', 'Position',[110 275 135 020].*WS,'String','');
st.in = uicontrol(Fig,'Style','Text', 'Position',[150 255 85 020].*WS,'String','');
c = 'if get(gco,''Value'')==1, spm_orthviews(''Xhairs'',''off''), else, spm_orthviews(''Xhairs'',''on''); end;';
uicontrol(Fig,'Style','togglebutton','Position',[95 220 125 20].*WS,...
'String','Hide Crosshairs','Callback',c,'ToolTipString','show/hide crosshairs');
% Dipoles/seeds selection:
%--------------------------------------------------------------------------
uicontrol(Fig,'Style','Frame','Position',[300 25 180 325].*WS);
sdip.hdl.hcl = uicontrol(Fig,'Style','pushbutton','Position',[310 320 100 20].*WS, ...
'String','Clear all','CallBack','spm_eeg_inv_vbecd_disp(''ClearAll'')');
sdip.hdl.hseed=zeros(sdip.n_seeds,1);
for ii=1:sdip.n_seeds
if sdip.exitflag(ii)==1
sdip.hdl.hseed(ii) = uicontrol(Fig,'Style','togglebutton','String',num2str(ii),...
'Position',[310+rem(ii-1,8)*20 295-fix((ii-1)/8)*20 20 20].*WS,...
'CallBack','spm_eeg_inv_vbecd_disp(''ChgSeed'')');
else
sdip.hdl.hseed(ii) = uicontrol(Fig,'Style','Text','String',num2str(ii), ...
'Position',[310+rem(ii-1,8)*20 293-fix((ii-1)/8)*20 20 20].*WS) ;
end
end
uicontrol(Fig,'Style','text','String','Select dipole # :', ...
'Position',[310 255-fix((sdip.n_seeds-1)/8)*20 110 20].*WS);
txt_box = cell(sdip.n_dip,1);
for ii=1:sdip.n_dip, txt_box{ii} = num2str(ii); end
txt_box{sdip.n_dip+1} = 'all';
sdip.hdl.hdip = uicontrol(Fig,'Style','popup','String',txt_box, ...
'Position',[420 258-fix((sdip.n_seeds-1)/8)*20 40 20].*WS, ...
'Callback','spm_eeg_inv_vbecd_disp(''ChgDip'')');
% Dipoles orientation and strength:
%--------------------------------------------------------------------------
uicontrol(Fig,'Style','Frame','Position',[70 120 180 90].*WS);
uicontrol(Fig,'Style','Text', 'Position',[75 190 170 016].*WS, ...
'String','Dipole orientation & strength');
uicontrol(Fig,'Style','Text', 'Position',[75 165 65 020].*WS, ...
'String','x-y-z or.:');
uicontrol(Fig,'Style','Text', 'Position',[75 145 75 020].*WS, ...
'String','theta-phi or.:');
uicontrol(Fig,'Style','Text', 'Position',[75 125 75 020].*WS, ...
'String','Dip. intens.:');
sdip.hdl.hor1 = uicontrol(Fig,'Style','Text', 'Position', ...
[140 165 105 020].*WS,'String','a');
sdip.hdl.hor2 = uicontrol(Fig,'Style','Text', 'Position', ...
[150 145 85 020].*WS,'String','b');
sdip.hdl.int = uicontrol(Fig,'Style','Text', 'Position', ...
[150 125 85 020].*WS,'String','c');
st.vols{1}.sdip = sdip;
% First plot = all the seeds that converged !
l_conv = find(sdip.exitflag==1);
if isempty(l_conv)
error('No seed converged towards a stable solution, nothing to be displayed !')
else
spm_eeg_inv_vbecd_disp('DrawDip',l_conv,1)
set(sdip.hdl.hseed(l_conv),'Value',1); % toggle all buttons
end
%==========================================================================
case 'drawdip'
%==========================================================================
% FORMAT spm_eeg_inv_vbecd_disp('DrawDip',i_seed,i_dip,sdip)
% e.g. spm_eeg_inv_vbecd_disp('DrawDip',1,1,sdip)
% e.g. spm_eeg_inv_vbecd_disp('DrawDip',[1:5],1,sdip)
%--------------------------------------------------------------------------
if nargin < 2
i_seed = 1;
else
i_seed = varargin{1};
end
if nargin<3
i_dip = 1;
else
i_dip = varargin{2};
end
if nargin<4
if isfield(st.vols{1},'sdip')
sdip = st.vols{1}.sdip;
else
error('I can''t find sdip structure');
end
else
sdip = varargin{3};
st.vols{1}.sdip = sdip;
end
if any(i_seed>sdip.n_seeds) || i_dip>(sdip.n_dip+1)
error('Wrong i_seed or i_dip index in spm_eeg_inv_vbecd_disp');
end
% Note if i_dip==(sdip.n_dip+1) all dipoles are displayed simultaneously,
% The 3D cut will then be at the mean location of all sources !!!
if i_dip == (sdip.n_dip+1)
i_dip = 1:sdip.n_dip;
end
% if seed indexes passed is wrong (no convergence) remove the wrong ones
i_seed(sdip.exitflag(i_seed)~=1) = [];
if isempty(i_seed)
error('You passed the wrong seed indexes...')
end
if size(i_seed,2)==1, i_seed=i_seed'; end
% Display business
%--------------------------------------------------------------------------
loc_mm = sdip.mniloc{i_seed(1)}(:,i_dip);
if length(i_seed)>1
% unit = ones(1,sdip.n_dip);
for ii = i_seed(2:end)
loc_mm = loc_mm + sdip.mniloc{ii}(:,i_dip);
end
loc_mm = loc_mm/length(i_seed);
end
if length(i_dip)>1
loc_mm = mean(loc_mm,2);
end
% Place the underlying image at right cuts
spm_orthviews('Reposition',loc_mm);
if length(i_dip)>1
tabl_seed_dip = [kron(ones(length(i_dip),1),i_seed') ...
kron(i_dip',ones(length(i_seed),1))];
else
tabl_seed_dip = [i_seed' ones(length(i_seed),1)*i_dip];
end
% Scaling, according to all dipoles in the selected seed sets.
% The time displayed is the one corresponding to the maximum EEG power !
Mn_j = -1;
l3 = -2:0;
for ii = 1:length(i_seed)
for jj = 1:sdip.n_dip
Mn_j = max([Mn_j sqrt(sum(sdip.jmni{ii}(jj*3+l3,sdip.Mtb).^2))]);
end
end
st.vols{1}.sdip.tabl_seed_dip = tabl_seed_dip;
% Display all dipoles, the 1st one + the ones close enough.
% Run through the 6 colors and 9 markers to differentiate the dipoles.
% NOTA: 2 dipoles coming from the same set will have same colour/marker
ind = 1 ;
dip_h = zeros(9,size(tabl_seed_dip,1),1);
% each dipole displayed has 9 handles:
% 3 per view (2*3): for the line, for the circle & for the error
js_m = zeros(3,1);
% Deal with case of multiple i_seed and i_dip displayed.
% make sure dipole from same i_seed have same colour but different marker.
pi_dip = find(diff(tabl_seed_dip(:,2)));
if isempty(pi_dip)
% i.e. only one dip displayed per seed, use old fashion
for ii=1:size(tabl_seed_dip,1)
if ii>1
if tabl_seed_dip(ii,1)~=tabl_seed_dip(ii-1,1)
ind = ind+1;
end
end
ic = mod(ind-1,Ncolors)+1;
im = fix(ind/Ncolors)+1;
loc_pl = sdip.mniloc{tabl_seed_dip(ii,1)}(:,tabl_seed_dip(ii,2));
js = sdip.jmni{tabl_seed_dip(ii,1)}(tabl_seed_dip(ii,2)*3+l3,sdip.Mtb);
vloc = sdip.cov_loc{tabl_seed_dip(ii,1)}(tabl_seed_dip(ii,2)*3+l3,tabl_seed_dip(ii,2)*3+l3);
dip_h(:,ii) = add1dip(loc_pl,js/Mn_j*20,vloc, ...
marker{im},colors{ic},st.vols{1}.ax,Fig,st.bb);
js_m = js_m+js;
end
else
for ii=1:pi_dip(1)
if ii>1
if tabl_seed_dip(ii,1)~=tabl_seed_dip(ii-1,1)
ind = ind+1;
end
end
ic = mod(ind-1,Ncolors)+1;
for jj=1:sdip.n_dip
im = mod(jj-1,Nmarker)+1;
loc_pl = sdip.mniloc{tabl_seed_dip(ii,1)}(:,jj);
js = sdip.jmni{tabl_seed_dip(ii,1)}(jj*3+l3,sdip.Mtb);
vloc = sdip.cov_loc{tabl_seed_dip(ii,1)}(jj*3+l3,jj*3+l3);
js_m = js_m+js;
dip_h(:,ii+(jj-1)*pi_dip(1)) = ...
add1dip(loc_pl,js/Mn_j*20,vloc, ...
marker{im},colors{ic},st.vols{1}.ax,Fig,st.bb);
end
end
end
st.vols{1}.sdip.ax = dip_h;
% Display dipoles orientation and strength
js_m = js_m/size(tabl_seed_dip,1);
[th,phi,Ijs_m] = cart2sph(js_m(1),js_m(2),js_m(3));
Njs_m = round(js_m'/Ijs_m*100)/100;
Angle = round([th phi]*1800/pi)/10;
set(sdip.hdl.hor1,'String',[num2str(Njs_m(1)),' ',num2str(Njs_m(2)), ...
' ',num2str(Njs_m(3))]);
set(sdip.hdl.hor2,'String',[num2str(Angle(1)),'� ',num2str(Angle(2)),'�']);
set(sdip.hdl.int,'String',Ijs_m);
% Change the colour of toggle button of dipoles actually displayed
for ii=tabl_seed_dip(:,1)
set(sdip.hdl.hseed(ii),'BackgroundColor',[.7 1 .7]);
end
%==========================================================================
case 'clearall'
%==========================================================================
% Clears all dipoles, and reset the toggle buttons
%--------------------------------------------------------------------------
if isfield(st.vols{1},'sdip')
sdip = st.vols{1}.sdip;
else
error('I can''t find sdip structure');
end
disp('Clears all dipoles')
spm_eeg_inv_vbecd_disp('ClearDip');
for ii=1:st.vols{1}.sdip.n_seeds
if sdip.exitflag(ii)==1
set(st.vols{1}.sdip.hdl.hseed(ii),'Value',0);
end
end
set(st.vols{1}.sdip.hdl.hdip,'Value',1);
%==========================================================================
case 'chgseed'
%==========================================================================
% Changes the seeds displayed
%--------------------------------------------------------------------------
% disp('Change seed')
sdip = st.vols{1}.sdip;
if isfield(sdip,'tabl_seed_dip')
prev_seeds = p_seed(sdip.tabl_seed_dip);
else
prev_seeds = [];
end
l_seed = zeros(sdip.n_seeds,1);
for ii=1:sdip.n_seeds
if sdip.exitflag(ii)==1
l_seed(ii) = get(sdip.hdl.hseed(ii),'Value');
end
end
l_seed = find(l_seed);
% Modify the list of seeds displayed
if isempty(l_seed)
% Nothing left displayed
i_seed=[];
elseif isempty(prev_seeds)
% Just one dipole added, nothing before
i_seed=l_seed;
elseif length(prev_seeds)>length(l_seed)
% One seed removed
i_seed = prev_seeds;
for ii=1:length(l_seed)
p = find(prev_seeds==l_seed(ii));
if ~isempty(p)
prev_seeds(p) = [];
end % prev_seeds is left with the index of the one removed
end
i_seed(i_seed==prev_seeds) = [];
% Remove the dipole & change the button colour
spm_eeg_inv_vbecd_disp('ClearDip',prev_seeds);
set(sdip.hdl.hseed(prev_seeds),'BackgroundColor',[.7 .7 .7]);
else
% One dipole added
i_seed = prev_seeds;
for ii=1:length(prev_seeds)
p = find(prev_seeds(ii)==l_seed);
if ~isempty(p)
l_seed(p) = [];
end % l_seed is left with the index of the one added
end
i_seed = [i_seed ; l_seed];
end
i_dip = get(sdip.hdl.hdip,'Value');
spm_eeg_inv_vbecd_disp('ClearDip');
if ~isempty(i_seed)
spm_eeg_inv_vbecd_disp('DrawDip',i_seed,i_dip);
end
%==========================================================================
case 'chgdip'
%==========================================================================
% Changes the dipole index for the first seed displayed
%--------------------------------------------------------------------------
disp('Change dipole')
sdip = st.vols{1}.sdip;
i_dip = get(sdip.hdl.hdip,'Value');
if isfield(sdip,'tabl_seed_dip')
i_seed = p_seed(sdip.tabl_seed_dip);
else
i_seed = [];
end
if ~isempty(i_seed)
spm_eeg_inv_vbecd_disp('ClearDip')
spm_eeg_inv_vbecd_disp('DrawDip',i_seed,i_dip);
end
%==========================================================================
case 'cleardip'
%==========================================================================
% FORMAT spm_eeg_inv_vbecd_disp('ClearDip',seed_i)
% e.g. spm_eeg_inv_vbecd_disp('ClearDip')
% clears all displayed dipoles
% e.g. spm_eeg_inv_vbecd_disp('ClearDip',1)
% clears the first dipole displayed
%--------------------------------------------------------------------------
if nargin>2
seed_i = varargin{1};
else
seed_i = 0;
end
if isfield(st.vols{1},'sdip')
sdip = st.vols{1}.sdip;
else
return; % I don't do anything, as I can't find sdip strucure
end
if isfield(sdip,'ax')
Nax = size(sdip.ax,2);
else
return; % I don't do anything, as I can't find axes info
end
if seed_i==0 % removes everything
for ii=1:Nax
for jj=1:9
delete(sdip.ax(jj,ii));
end
end
for ii=sdip.tabl_seed_dip(:,1)
set(sdip.hdl.hseed(ii),'BackgroundColor',[.7 .7 .7]);
end
sdip = rmfield(sdip,'tabl_seed_dip');
sdip = rmfield(sdip,'ax');
elseif seed_i<=Nax % remove one seed only
l_seed = find(sdip.tabl_seed_dip(:,1)==seed_i);
for ii=l_seed
for jj=1:9
delete(sdip.ax(jj,ii));
end
end
sdip.ax(:,l_seed) = [];
sdip.tabl_seed_dip(l_seed,:) = [];
else
error('Trying to clear unspecified dipole');
end
st.vols{1}.sdip = sdip;
%==========================================================================
case 'redrawdip'
%==========================================================================
% spm_eeg_inv_vbecd_disp('RedrawDip')
% redraw everything, useful when zooming into image
%--------------------------------------------------------------------------
% spm_eeg_inv_vbecd_disp('ClearDip')
% spm_eeg_inv_vbecd_disp('ChgDip')
% disp('Change dipole')
sdip = st.vols{1}.sdip;
i_dip = get(sdip.hdl.hdip,'Value');
if isfield(sdip,'tabl_seed_dip')
i_seed = p_seed(sdip.tabl_seed_dip);
else
i_seed = [];
end
if ~isempty(i_seed)
spm_eeg_inv_vbecd_disp('ClearDip')
spm_eeg_inv_vbecd_disp('DrawDip',i_seed,i_dip);
end
%==========================================================================
otherwise
%==========================================================================
warning('Unknown action string');
end
% warning(sw);
return
%==========================================================================
% dh = add1dip(loc,js,vloc,mark,col,ax,Fig,bb)
%==========================================================================
function dh = add1dip(loc,js,vloc,mark,col,ax,Fig,bb)
% Plots the dipoles on the 3 views, with an error ellipse for location
% Then returns the handle to the plots
global st
is = inv(st.Space);
loc = is(1:3,1:3)*loc(:) + is(1:3,4);
% taking into account the zooming/scaling only for the location
% NOT for the dipole's amplitude.
% Amplitude plotting is quite arbitrary anyway and up to some scaling
% defined for better viewing...
loc(1,:) = loc(1,:) - bb(1,1)+1;
loc(2,:) = loc(2,:) - bb(1,2)+1;
loc(3,:) = loc(3,:) - bb(1,3)+1;
% +1 added to be like John's orthview code
% prepare error ellipse
vloc = is(1:3,1:3)*vloc*is(1:3,1:3);
[V,E] = eig(vloc);
VE = V*diag(sqrt(diag(E))); % use std
% VE = V*E; % or use variance ???
dh = zeros(9,1);
figure(Fig)
% Transverse slice, # 1
%----------------------
set(Fig,'CurrentAxes',ax{1}.ax)
set(ax{1}.ax,'NextPlot','add')
dh(1) = plot(loc(1),loc(2),[mark,col],'LineWidth',1);
dh(2) = plot(loc(1)+[0 js(1)],loc(2)+[0 js(2)],col,'LineWidth',2);
% add error ellipse
[uu,ss,vv] = svd(VE([1 2],:));
[phi] = cart2pol(uu(1,1),uu(2,1));
e = diag(ss);
t = (-1:.02:1)*pi;
x = e(1)*cos(t)*cos(phi)-e(2)*sin(t)*sin(phi)+loc(1);
y = e(2)*sin(t)*cos(phi)+e(1)*cos(t)*sin(phi)+loc(2);
dh(3) = plot(x,y,[':',col],'LineWidth',.5);
set(ax{1}.ax,'NextPlot','replace')
% Coronal slice, # 2
%----------------------
set(Fig,'CurrentAxes',ax{2}.ax)
set(ax{2}.ax,'NextPlot','add')
dh(4) = plot(loc(1),loc(3),[mark,col],'LineWidth',1);
dh(5) = plot(loc(1)+[0 js(1)],loc(3)+[0 js(3)],col,'LineWidth',2);
% add error ellipse
[uu,ss,vv] = svd(VE([1 3],:));
[phi] = cart2pol(uu(1,1),uu(2,1));
e = diag(ss);
t = (-1:.02:1)*pi;
x = e(1)*cos(t)*cos(phi)-e(2)*sin(t)*sin(phi)+loc(1);
y = e(2)*sin(t)*cos(phi)+e(1)*cos(t)*sin(phi)+loc(3);
dh(6) = plot(x,y,[':',col],'LineWidth',.5);
set(ax{2}.ax,'NextPlot','replace')
% Sagital slice, # 3
%----------------------
set(Fig,'CurrentAxes',ax{3}.ax)
set(ax{3}.ax,'NextPlot','add')
% dh(5) = plot(dim(2)-loc(2),loc(3),[mark,col],'LineWidth',2);
% dh(6) = plot(dim(2)-loc(2)+[0 -js(2)],loc(3)+[0 js(3)],col,'LineWidth',2);
dh(7) = plot(bb(2,2)-bb(1,2)-loc(2),loc(3),[mark,col],'LineWidth',1);
dh(8) = plot(bb(2,2)-bb(1,2)-loc(2)+[0 -js(2)],loc(3)+[0 js(3)],col,'LineWidth',2);
% add error ellipse
[uu,ss,vv] = svd(VE([2 3],:));
[phi] = cart2pol(uu(1,1),uu(2,1));
e = diag(ss);
t = (-1:.02:1)*pi;
x = -(e(1)*cos(t)*cos(phi)-e(2)*sin(t)*sin(phi))+bb(2,2)-bb(1,2)-loc(2);
y = e(2)*sin(t)*cos(phi)+e(1)*cos(t)*sin(phi)+loc(3);
dh(9) = plot(x,y,[':',col],'LineWidth',.5);
set(ax{3}.ax,'NextPlot','replace')
return
%==========================================================================
% pr_seed = p_seed(tabl_seed_dip)
%==========================================================================
function pr_seed = p_seed(tabl_seed_dip)
% Gets the list of seeds used in the previous display
ls = sort(tabl_seed_dip(:,1));
if length(ls)==1
pr_seed = ls;
else
pr_seed = ls([find(diff(ls)) ; length(ls)]);
end
%
% OLD STUFF
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Use it with arguments or not:
% - spm_eeg_inv_vbecd_disp('Init')
% The routine asks for the dipoles file and image to display
% - spm_eeg_inv_vbecd_disp('Init',sdip)
% The routine will use the avg152T1 canonical image
% - spm_eeg_inv_vbecd_disp('Init',sdip,P)
% The routines dispays the dipoles on image P.
%
% If multiple seeds have been used, you can select the seeds to display
% by pressing their index.
% Given that the sources could have different locations, the slices
% displayed will be the 3D view at the *average* or *mean* locations of
% selected sources.
% If more than 1 dipole was fitted at a time, then selection of source 1
% to N is possible through the pull-down selector.
%
% The location of the source/cut is displayed in mm and voxel, as well as
% the underlying image intensity at that location.
% The cross hair position can be hidden by clicking on its button.
%
% Nota_1: If the cross hair is manually moved by clicking in the image or
% changing its coordinates, the dipole displayed will NOT be at
% the right displayed location. That's something that needs to be improved...
%
% Nota_2: Some seeds may have not converged within the limits fixed,
% these dipoles are not displayed...
%
% Fields needed in sdip structure to plot on an image:
% + n_seeds: nr of seeds set used, i.e. nr of solutions calculated
% + n_dip: nr of fitted dipoles on the EEG time series
% + loc: location of fitted dipoles, cell{1,n_seeds}(3 x n_dip)
% remember that loc is fixed over the time window.
% + j: sources amplitude over the time window,
% cell{1,n_seeds}(3*n_dip x Ntimebins)
% + Mtb: index of maximum power in EEG time series used
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% % First point to consider
% loc_mm = sdip.loc{i_seed(1)}(:,i_dip);
%
% % PLace the underlying image at right cuts
% spm_orthviews('Reposition',loc_mm);
% % spm_orthviews('Reposition',loc_vx);
% % spm_orthviews('Xhairs','off')
%
% % if i_seed = set, Are there other dipoles close enough ?
% tabl_seed_dip=[i_seed(1) i_dip]; % table summarising which set & dip to use.
% if length(i_seed)>1
% unit = ones(1,sdip.n_dip);
% for ii = i_seed(2:end)'
% d2 = sqrt(sum((sdip.loc{ii}-loc_mm*unit).^2));
% l_cl = find(d2<=lim_cl);
% if ~isempty(l_cl)
% for jj=l_cl
% tabl_seed_dip = [tabl_seed_dip ; [ii jj]];
% end
% end
% end
% end
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% get(sdip.hdl.hseed(1),'Value')
% for ii=1:sdip.n_seeds, delete(hseed(ii)); end
% h1 = uicontrol(Fig,'Style','togglebutton','Position',[600 25 10 10].*WS)
% h2 = uicontrol(Fig,'Style','togglebutton','Position',[620 100 20 20].*WS,'String','1')
% h2 = uicontrol(Fig,'Style','checkbox','Position',[600 100 10 10].*WS)
% h3 = uicontrol(Fig,'Style','radiobutton','Position',[600 150 20 20].*WS)
% h4 = uicontrol(Fig,'Style','radiobutton','Position',[700 150 20 20].*WS)
% delete(h2),delete(h3),delete(h4),
% delete(hdip)
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_definetrial.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_eeg_definetrial.m
| 11,429 |
utf_8
|
56a6ae7de86bca4e155843aa0d2f736f
|
function [trl, conditionlabels, S] = spm_eeg_definetrial(S)
% Definition of trials based on events
% FORMAT[trl, conditionlabels, S] = spm_eeg_definetrial(S)
% S - input structure (optional)
% (optional) fields of S:
% S.event - event struct (optional)
% S.fsample - sampling rate
% S.dataset - raw dataset (events and fsample can be read from there if absent)
% S.inputformat - data type (optional) to force the use of specific data reader
% S.timeonset - time of the first sample in the data [default: 0]
% S.pretrig - pre-trigger time in ms
% S.posttrig - post-trigger time in ms
% S.trialdef - structure array for trial definition with fields (optional)
% S.trialdef.conditionlabel - string label for the condition
% S.trialdef.eventtype - string
% S.trialdef.eventvalue - string, numeric or empty
% S.reviewtrials - review individual trials after selection (yes/no: 1/0)
% S.save - save trial definition (yes/no: 1/0)
% OUTPUT:
% trl - Nx3 matrix [start end offset]
% conditionlabels - Nx1 cell array of strings, label for each trial
% S - modified configuration structure (for history)
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Vladimir Litvak, Robert Oostenveld
% $Id: spm_eeg_definetrial.m 4756 2012-05-28 15:59:42Z vladimir $
SVNrev = '$Rev: 4756 $';
%-Startup
%--------------------------------------------------------------------------
spm('sFnBanner', mfilename, SVNrev);
spm('FigName','M/EEG trial definition');
%-Get input parameters
%--------------------------------------------------------------------------
try
S.inputformat;
catch
S.inputformat = [];
end
if ~isfield(S, 'event') || ~isfield(S, 'fsample')
if ~isfield(S, 'dataset')
S.dataset = spm_select(1, '\.*', 'Select M/EEG data file');
end
hdr = ft_read_header(S.dataset, 'fallback', 'biosig', 'headerformat', S.inputformat);
S.fsample = hdr.Fs;
event = ft_read_event(S.dataset, 'detectflank', 'both', 'eventformat', S.inputformat);
if ~isempty(strmatch('UPPT001', hdr.label))
% This is s somewhat ugly fix to the specific problem with event
% coding in FIL CTF. It can also be useful for other CTF systems where the
% pulses in the event channel go downwards.
fil_ctf_events = ft_read_event(S.dataset, 'detectflank', 'down', 'type', 'UPPT001', 'trigshift', -1, 'eventformat', S.inputformat);
if ~isempty(fil_ctf_events)
[fil_ctf_events(:).type] = deal('FIL_UPPT001_down');
event = cat(1, event(:), fil_ctf_events(:));
end
end
if ~isempty(strmatch('UPPT002', hdr.label))
% This is s somewhat ugly fix to the specific problem with event
% coding in FIL CTF. It can also be useful for other CTF systems where the
% pulses in the event channel go downwards.
fil_ctf_events = ft_read_event(S.dataset, 'detectflank', 'down', 'type', 'UPPT002', 'trigshift', -1, 'eventformat', S.inputformat);
if ~isempty(fil_ctf_events)
[fil_ctf_events(:).type] = deal('FIL_UPPT002_down');
event = cat(1, event(:), fil_ctf_events(:));
end
end
% This is another FIL-specific fix that will hopefully not affect other sites
if isfield(hdr, 'orig') && isfield(hdr.orig, 'VERSION') && isequal(uint8(hdr.orig.VERSION),uint8([255 'BIOSEMI']))
ind = strcmp('STATUS', {event(:).type});
val = [event(ind).value];
if any(val>255)
bytes = dec2bin(val);
bytes = bytes(:, end-7:end);
bytes = flipdim(bytes, 2);
val = num2cell(bin2dec(bytes));
[event(ind).value] = deal(val{:});
end
end
else
event = S.event;
end
if ~isfield(S, 'timeonset')
S.timeonset = 0;
end
if ~isfield(event, 'time')
for i = 1:numel(event)
if S.timeonset == 0
event(i).time = event(i).sample./S.fsample;
else
event(i).time = (event(i).sample - 1)./S.fsample + S.timeonset;
end
end
end
if ~isfield(event, 'sample')
for i = 1:numel(event)
if S.timeonset == 0
event(i).sample = event(i).time*S.fsample;
else
event(i).sample = (event(i).time-S.timeonset)*S.fsample+1;
end
event(i).sample = round(event(i).sample);
end
end
if isempty(event)
error('No event information was found in the input');
end
if ~isfield(S, 'pretrig')
S.pretrig = spm_input('Start of trial in PST [ms]', '+1', 'r', '', 1);
end
if ~isfield(S, 'posttrig')
S.posttrig = spm_input('End of trial in PST [ms]', '+1', 'r', '', 1);
end
if ~isfield(S, 'trialdef')
S.trialdef = [];
ncond = spm_input('How many conditions?', '+1', 'n', '1');
for i = 1:ncond
OK = 0;
pos = '+1';
while ~OK
conditionlabel = spm_input(['Label of condition ' num2str(i)], pos, 's');
selected = select_event_ui(event);
if isempty(conditionlabel) || isempty(selected)
pos = '-1';
else
for j = 1:size(selected, 1)
S.trialdef = [S.trialdef ...
struct('conditionlabel', conditionlabel, ...
'eventtype', selected{j, 1}, ...
'eventvalue', selected{j, 2})];
OK=1;
end
end
end
end
end
for i = 1:length(S.trialdef)
if ~isfield(S.trialdef(i),'trlshift')
trlshift(i) = 0;
else
trlshift(i) = round(S.trialdef(i).trlshift * S.fsample/1000); % assume passed as ms
end
end
%-Build trl based on selected events
%--------------------------------------------------------------------------
trl = [];
conditionlabels = {};
for i=1:numel(S.trialdef)
if ischar(S.trialdef(i).eventvalue)
% convert single string into cell-array, otherwise the intersection does not work as intended
S.trialdef(i).eventvalue = {S.trialdef(i).eventvalue};
end
sel = [];
% select all events of the specified type and with the specified value
for j=find(strcmp(S.trialdef(i).eventtype, {event.type}))
if isempty(S.trialdef(i).eventvalue)
sel = [sel j];
elseif ~isempty(intersect(event(j).value, S.trialdef(i).eventvalue))
sel = [sel j];
end
end
for j=1:length(sel)
% override the offset of the event
trloff = round(0.001*S.pretrig*S.fsample);
% also shift the begin sample with the specified amount
if ismember(event(sel(j)).type, {'trial', 'average'})
% In case of trial events treat the 0 time point as time of the
% event rather than the beginning of the trial
trlbeg = event(sel(j)).sample - event(sel(j)).offset + trloff;
else
trlbeg = event(sel(j)).sample + trloff;
end
trldur = round(0.001*(-S.pretrig+S.posttrig)*S.fsample);
trlend = trlbeg + trldur;
% Added by Rik in case wish to shift triggers (e.g, due to a delay
% between trigger and visual/auditory stimulus reaching subject).
trlbeg = trlbeg + trlshift(i);
trlend = trlend + trlshift(i);
% add the beginsample, endsample and offset of this trial to the list
trl = [trl; trlbeg trlend trloff];
conditionlabels{end+1} = S.trialdef(i).conditionlabel;
end
end
%-Sort the trl in right temporal order
%--------------------------------------------------------------------------
[junk, sortind] = sort(trl(:,1));
trl = trl(sortind, :);
conditionlabels = conditionlabels(sortind);
%-Review selected trials
%--------------------------------------------------------------------------
if ~isfield(S, 'reviewtrials')
S.reviewtrials = spm_input('Review individual trials?','+1','yes|no',[1 0], 0);
end
if S.reviewtrials
eventstrings=cell(size(trl,1),1);
for i=1:size(trl,1)
eventstrings{i}=[num2str(i) ' Label: ' conditionlabels{i} ' Time (sec): ' num2str((trl(i, 1)- trl(i, 3))./S.fsample)];
end
selected = find(trl(:,1)>0);
[indx OK] = listdlg('ListString', eventstrings, 'SelectionMode', 'multiple', 'InitialValue', ...
selected, 'Name', 'Select events', 'ListSize', [300 300]);
if OK
trl=trl(indx, :);
conditionlabels = conditionlabels(indx);
end
end
%-Create trial definition file
%--------------------------------------------------------------------------
if ~isfield(S, 'save')
S.save = spm_input('Save trial definition?','+1','yes|no',[1 0], 0);
end
if S.save
[trlfilename, trlpathname] = uiputfile( ...
{'*.mat', 'MATLAB File (*.mat)'}, 'Save trial definition as');
save(fullfile(trlpathname, trlfilename), 'trl', 'conditionlabels');
end
%-Cleanup
%--------------------------------------------------------------------------
spm('FigName','M/EEG trial definition: done');
%==========================================================================
% select_event_ui
%==========================================================================
function selected = select_event_ui(event)
% Allow the user to select an event using GUI
selected={};
if isempty(event)
fprintf('no events were found\n');
return
end
eventtype = unique({event.type});
Neventtype = length(eventtype);
% Two lists are built in parallel
settings={}; % The list of actual values to be used later
strsettings={}; % The list of strings to show in the GUI
for i=1:Neventtype
sel = find(strcmp(eventtype{i}, {event.type}));
numind = find(...
cellfun('isclass', {event(sel).value}, 'double') & ...
~cellfun('isempty', {event(sel).value}));
charind = find(cellfun('isclass', {event(sel).value}, 'char'));
emptyind = find(cellfun('isempty', {event(sel).value}));
if ~isempty(numind)
numvalue = unique([event(sel(numind)).value]);
for j=1:length(numvalue)
ninstances = sum([event(sel(numind)).value] == numvalue(j));
strsettings=[strsettings; {['Type: ' eventtype{i} ' ; Value: ' num2str(numvalue(j)) ...
' ; ' num2str(ninstances) ' instances']}];
settings=[settings; [eventtype(i), {numvalue(j)}]];
end
end
if ~isempty(charind)
charvalue = unique({event(sel(charind)).value});
if ~iscell(charvalue)
charvalue = {charvalue};
end
for j=1:length(charvalue)
ninstances = length(strmatch(charvalue{j}, {event(sel(charind)).value}, 'exact'));
strsettings=[strsettings; {['Type: ' eventtype{i} ' ; Value: ' charvalue{j}...
' ; ' num2str(ninstances) ' instances']}];
settings=[settings; [eventtype(i), charvalue(j)]];
end
end
if ~isempty(emptyind)
strsettings=[strsettings; {['Type: ' eventtype{i} ' ; Value: ; ' ...
num2str(length(emptyind)) ' instances']}];
settings=[settings; [eventtype(i), {[]}]];
end
end
[selection ok]= listdlg('ListString',strsettings, 'SelectionMode', 'multiple', 'Name', 'Select event', 'ListSize', [400 300]);
if ok
selected=settings(selection, :);
else
selected={};
end
|
github
|
philippboehmsturm/antx-master
|
spm_mvb_cvk2.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_mvb_cvk2.m
| 5,093 |
utf_8
|
751f7db1cea711d16bdb424252c3e636
|
function [p,pc,R2] = spm_mvb_cvk2(MVB,k)
% k-fold cross validation of a multivariate Bayesian model
% FORMAT [p_value,percent,R2] = spm_mvb_cvk(MVB,k)
%
% MVB - Multivariate Bayes structure
% k - k-fold cross-validation ('0' implies a leave-one-out scheme)
%
% p - p-value: under a null GLM
% percent: proportion correct (median threshold)
% R2 - coefficient of determination
%
% spm_mvb_cvk performs a k-fold cross-validation by trying to predict
% the target variable using training and test partitions on orthogonal
% mixtures of data (from null space of confounds).
% This version uses the optimised covariance model from spm_mvb.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Karl Friston
% $Id: spm_mvb_cvk2.m 3806 2010-04-06 14:42:32Z ged $
%-partition order
%--------------------------------------------------------------------------
try
k;
catch
str = 'k-fold cross-validation';
k = spm_input(str,'!+1','b',{'2','4','8','loo'},[2 4 8 0]);
end
%-Get figure handles and set title
%--------------------------------------------------------------------------
Fmvb = spm_figure('GetWin','MVB');
spm_clf(Fmvb);
% get MVB results
%==========================================================================
try
MVB;
catch
mvb = spm_select(1,'mat','please select models',[],pwd,'MVB_*');
MVB = load(mvb(1,:));
MVB = MVB.MVB;
end
% whiten target and predictor (X) variables (Y) (i.e., remove correlations)
%--------------------------------------------------------------------------
X = MVB.X;
X0 = MVB.X0;
V = MVB.V;
% residual forming matrix
%--------------------------------------------------------------------------
Ns = length(X);
R = speye(Ns) - X0*pinv(X0);
% leave-one-out
%--------------------------------------------------------------------------
if ~k
k = Ns;
end
pX = zeros(Ns,1);
qX = zeros(Ns,1);
qE = zeros(size(MVB.Y,2),k);
% k-fold cross-validation
%==========================================================================
for i = 1:k
[px qx qe] = mvb_cv(MVB,i,k);
pX = pX + px;
qX = qX + qx;
qE(:,i) = qe;
end
% parametric inference
%==========================================================================
% test correlation
%--------------------------------------------------------------------------
[T df] = spm_ancova(X,V,qX,1);
p = 1 - spm_Tcdf(T,df(2));
% percent correct (after projection)
%--------------------------------------------------------------------------
pX = R*X;
qX = R*qX;
T = sign(pX - median(pX)) == sign(qX - median(qX));
pc = 100*sum(T)/length(T);
R2 = corrcoef(pX,qX);
R2 = 100*(R2(1,2)^2);
% assign in base memory
%--------------------------------------------------------------------------
MVB.p_value = p;
MVB.percent = pc;
MVB.R2 = R2;
MVB.cvk = struct('qX',qX,'qE',qE);
% save results
%--------------------------------------------------------------------------
save(MVB.name,'MVB')
assignin('base','MVB',MVB)
% display and plot validation
%--------------------------------------------------------------------------
spm_mvb_cvk_display(MVB)
return
%==========================================================================
function [X,qX,qE] = mvb_cv(MVB,n,k)
%==========================================================================
% MVB - multivariate structure
% n - subset
% k - partition
% Unpack MVB and create test subspace
%--------------------------------------------------------------------------
V = MVB.V;
U = MVB.M.U;
X = MVB.X;
Y = MVB.Y;
X0 = MVB.X0;
h = MVB.M.h;
Cp = MVB.M.Cp;
% Specify indices of training and test data
%--------------------------------------------------------------------------
Ns = length(X);
ns = floor(Ns/k);
test = [1:ns] + (n - 1)*ns;
tran = [1:Ns];
tran(test) = [];
test = full(sparse(test,test,1,Ns,Ns));
tran = full(sparse(tran,tran,1,Ns,Ns));
% Training - add test space to confounds
%==========================================================================
R = speye(Ns) - [X0 test]*pinv([X0 test]);
R = spm_svd(R);
L = R'*Y*U;
% get error covariance
%--------------------------------------------------------------------------
Ce = sparse(Ns,Ns);
if isstruct(V)
for i = 1:length(V)
Ce = Ce + h(i)*V{i};
end
else
Ce = V*h(1);
end
Ce = R'*Ce*R;
% MAP estimates of pattern weights from training data
%----------------------------------------------------------------------
MAP = Cp*L'*inv(Ce + L*Cp*L');
qE = MAP*R'*X;
% Test - add training space to confounds and get predicted X
%==========================================================================
R = speye(Ns) - [X0 tran]*pinv([X0 tran]);
X = R*X; % test data
qE = U*qE; % weights
qX = R*Y*qE; % prediction
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_displayECD.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_eeg_displayECD.m
| 8,250 |
utf_8
|
471c105bf4bbbec394478ff1a280b571
|
function [out] = spm_eeg_displayECD(Pos,Orient,Var,Names,options)
% Plot dipole positions onto the SPM canonical mesh
% FORMAT [out] = spm_eeg_displayDipoles(Pos,Orient,Var,Names,options)
%
% IN (admissible choices):
% - Pos: a 3xndip matrix containing the positions of the dipoles in
% the canonical frame of reference
% - Orient: the same with dipole orientations
% - Var: the same with position variance
% - Names: the same with dipole names
% - options: an optional structure containing
% .hfig: the handle of the display figure
% .tag: the tag to be associated with the created UI objects
% .add: binary variable ({0}, 1: just add dipole in the figure .hfig)
%
% OUT:
% - out: a structure containing the handles of the object in the figure
% (including the mesh, the dipoles, the transparency slider, etc...)
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Jean Daunizeau
% $Id: spm_eeg_displayECD.m 4054 2010-08-27 19:27:09Z karl $
% checks and defaults
%--------------------------------------------------------------------------
hfig = [];
ParentAxes = [];
query = [];
handles = [];
tag = '';
try, options; catch, options = []; end
try, hfig = options.hfig; end
try, tag = options.tag; end
try, ParentAxes = options.ParentAxes; end
try, query = options.query; end
try, handles = options.handles; end
try
figure(hfig);
catch
hfig = spm_figure('GetWin','Graphics');
spm_figure('Clear',hfig);
ParentAxes = axes('parent',hfig);
end
try
markersize = options.markersize;
catch
markersize = 20;
end
try
meshsurf = options.meshsurf;
catch
meshsurf = fullfile(spm('Dir'),'canonical','cortex_5124.surf.gii');
end
if isscalar(Var), Var = Pos*0 + Var^2; end
try, Pos{1}; catch, Pos = {Pos}; end
try, Orient{1}; catch, Orient = {Orient};end
try, Var{1}; catch, Var = {Var}; end
ndip = size(Pos{1},2);
if ~exist('Names','var') || isempty(Names)
for i=1:ndip
Names{i} = num2str(i);
end
end
col = ['b','g','r','c','m','y','k','w'];
tmp = ceil(ndip./numel(col));
col = repmat(col,1,tmp);
pa = get(ParentAxes,'position');
if ndip > 0
if isempty(query)
opt.hfig = hfig;
opt.ParentAxes = ParentAxes;
opt.visible = 'off';
pos2 = [pa(1),pa(2)+0.25*pa(4),0.03,0.5*pa(4)];
out = spm_eeg_render(meshsurf,opt);
handles.mesh = out.handles.p;
handles.BUTTONS.transp = out.handles.transp;
handles.hfig = out.handles.fi;
handles.ParentAxes = out.handles.ParentAxes;
set(handles.mesh,...
'facealpha',0.1,...
'visible','on')
set(handles.BUTTONS.transp,...
'value',0.1,...
'position',pos2,...
'visible','on')
end
set(ParentAxes,'nextplot','add')
for j=1:length(Pos)
for i =1:ndip
try
set(handles.hp(j,i),...
'xdata',Pos{j}(1,i),...
'ydata',Pos{j}(2,i),...
'zdata',Pos{j}(3,i));
catch
handles.hp(j,i) = plot3(handles.ParentAxes,...
Pos{j}(1,i),Pos{j}(2,i),Pos{j}(3,i),...
[col(i),'.'],...
'markerSize',markersize,...
'visible','off');
end
try
no = sqrt(sum(Orient{j}(:,i).^2));
if no > 0
Oi = 1e1.*Orient{j}(:,i)./no;
else
Oi = 1e-5*ones(3,1);
end
try
set(handles.hq(j,i),...
'xdata',Pos{j}(1,i),...
'ydata',Pos{j}(2,i),...
'zdata',Pos{j}(3,i),...
'udata',Oi(1),...
'vdata',Oi(2),...
'wdata',Oi(3))
catch
handles.hq(j,i) = quiver3(handles.ParentAxes,...
Pos{j}(1,i),Pos{j}(2,i),Pos{j}(3,i),...
Oi(1),Oi(2),Oi(3),col(i),...
'lineWidth',2,'visible','off');
end
if isequal(query,'add')
set(handles.hq(j,i),...
'LineStyle','--',...
'lineWidth',1)
end
end
[x,y,z]= ellipsoid(Pos{j}(1,i),Pos{j}(2,i),Pos{j}(3,i),...
1.*sqrt(Var{j}(1,i)),1.*sqrt(Var{j}(2,i)),1.*sqrt(Var{j}(1,i)),20);
try
set(handles.hs(j,i),...
'xdata',x,...
'ydata',y,...
'zdata',z);
catch
handles.hs(j,i) = surf(handles.ParentAxes,...
x,y,z,...
'edgecolor','none',...
'facecolor',col(i),...
'facealpha',0.2,...
'visible','off');
end
try
set(handles.ht(j,i),...
'position',Pos{j}(:,i));
catch
handles.ht(j,i) = text(...
Pos{j}(1,i),Pos{j}(2,i),Pos{j}(3,i),...
Names{i},...
'Parent',handles.ParentAxes,...
'visible','off');
end
end
end
if length(Pos) > 1
try, set(handles.hp(end,:),'visible','on'); end
try, set(handles.hq(end,:),'visible','on'); end
try, set(handles.hs(end,:),'visible','on'); end
try, set(handles.ht(end,:),'visible','on'); end
handles.uic(1) = uicontrol(handles.fi,...
'units','normalized',...
'position',[0.45,0.5,0.2,0.03],...
'style','radio','string','Show priors',...
'callback',@doChange1,...
'BackgroundColor',[1 1 1],...
'tooltipstring','Display prior locations',...
'userdata',handles,'value',0,...
'BusyAction','cancel',...
'Interruptible','off',...
'tag','plotEEG');
handles.uic(2) = uicontrol(handles.fi,...
'units','normalized',...
'position',[0.45,0.53,0.2,0.03],...
'style','radio','string','Show posteriors',...
'callback',@doChange2,...
'BackgroundColor',[1 1 1],...
'tooltipstring','Display posterior locations',...
'userdata',handles,'value',1,...
'BusyAction','cancel',...
'Interruptible','off',...
'tag','plotEEG');
else
try, set(handles.hp(1,:),'visible','on'); end
try, set(handles.hq(1,:),'visible','on'); end
try, set(handles.hs(1,:),'visible','on'); end
try, set(handles.ht(1,:),'visible','on'); end
end
end
try
clear out
out.handles = handles;
catch
out = [];
end
%==========================================================================
function doChange1(i1,i2)
val = get(i1,'value');
handles = get(i1,'userdata');
if ~val
try, set(handles.hp(1,:),'visible','off'); end
try, set(handles.hq(1,:),'visible','off'); end
try, set(handles.hs(1,:),'visible','off'); end
try, set(handles.ht(1,:),'visible','off'); end
else
try, set(handles.hp(1,:),'visible','on'); end
try, set(handles.hq(1,:),'visible','on'); end
try, set(handles.hs(1,:),'visible','on'); end
try, set(handles.ht(1,:),'visible','on'); end
end
%==========================================================================
function doChange2(i1,i2)
val = get(i1,'value');
handles = get(i1,'userdata');
if ~val
try, set(handles.hp(2,:),'visible','off'); end
try, set(handles.hq(2,:),'visible','off'); end
try, set(handles.hs(2,:),'visible','off'); end
try, set(handles.ht(2,:),'visible','off'); end
else
try, set(handles.hp(2,:),'visible','on'); end
try, set(handles.hq(2,:),'visible','on'); end
try, set(handles.hs(2,:),'visible','on'); end
try, set(handles.ht(2,:),'visible','on'); end
end
|
github
|
philippboehmsturm/antx-master
|
spm_uw_apply.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_uw_apply.m
| 14,676 |
utf_8
|
79e215c42faaa2e17fc6bae5cea47179
|
function varargout = spm_uw_apply(ds,flags)
% Reslices images volume by volume
% FORMAT spm_uw_apply(ds,[flags])
% or
% FORMAT P = spm_uw_apply(ds,[flags])
%
%
% ds - a structure created by spm_uw_estimate.m containing the fields:
% ds can also be an array of structures, each struct corresponding
% to one sesssion (it hardly makes sense to try and pool fields across
% sessions since there will have been a reshimming). In that case each
% session is unwarped separately, unwarped into the distortion space of
% the average (default) position of that series, and with the first
% scan on the series defining the pahse encode direction. After that each
% scan is transformed into the space of the first scan of the first series.
% Naturally, there is still only one actual resampling (interpolation).
% It will be assumed that the same unwarping parameters have been used
% for all sessions (anything else would be truly daft).
%
% .P - Images used when estimating deformation field and/or
% its derivative w.r.t. modelled factors. Note that this
% struct-array may contain .mat fields that differ from
% those you would observe with spm_vol(P(1).fname). This
% is because spm_uw_estimate has an option to re-estimate
% the movement parameters. The re-estimated parameters are
% not written to disc (in the form of .mat files), but rather
% stored in the P array in the ds struct.
%
% .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: [8 8 *]
% .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'.
% .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.
%
% flags - a structure containing various options. The fields are:
%
% mask - mask output images (1 for yes, 0 for no)
% To avoid artifactual movement-related variance the realigned
% set of images can be internally masked, within the set (i.e.
% if any image has a zero value at a voxel than all images have
% zero values at that voxel). Zero values occur when regions
% 'outside' the image are moved 'inside' the image during
% realignment.
%
% mean - write mean image
% The average of all the realigned scans is written to
% mean*.img.
%
% interp - the interpolation method (see e.g. spm_bsplins.m).
%
% which - Values of 0 or 1 are allowed.
% 0 - don't create any resliced images.
% Useful if you only want a mean resliced image.
% 1 - reslice all the images.
%
% udc - Values 1 or 2 are allowed
% 1 - Do only unwarping (not correcting
% for changing sampling density).
% 2 - Do both unwarping and Jacobian correction.
%
%
% prefix - Filename prefix for resliced image files. Defaults to 'u'.
%
% The spatially realigned images are written to the orginal
% subdirectory with the same filename but prefixed with an 'u'.
% They are all aligned with the first.
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Jesper Andersson
% $Id: spm_uw_apply.m 4152 2011-01-11 14:13:35Z volkmar $
tiny = 5e-2;
def_flags = spm_get_defaults('realign.write');
def_flags.udc = 1;
def_flags.prefix = 'u';
defnames = fieldnames(def_flags);
if nargin < 1 || isempty(ds)
ds = load(spm_select(1,'.*uw\.mat$','Select Unwarp result file'),'ds');
ds = ds.ds;
end
%
% Default to using Jacobian modulation for the reslicing if it was
% used during the estimation phase.
%
if ds(1).jm ~= 0
def_flags.udc = 2;
end
%
% Replace defaults with user supplied values for all fields
% defined by user.
%
if nargin < 2 || isempty(flags)
flags = def_flags;
end
for i=1:length(defnames)
if ~isfield(flags,defnames{i})
flags.(defnames{i}) = def_flags.(defnames{i});
end
end
if numel(flags.which) == 2
flags.mean = flags.which(2);
flags.which = flags.which(1);
end
ntot = 0;
for i=1:length(ds)
ntot = ntot + length(ds(i).P);
end
hold = [repmat(flags.interp,1,3) flags.wrap];
linfun = inline('fprintf(''%-60s%s'', x,repmat(sprintf(''\b''),1,60))');
%
% Create empty sfield for all structs.
%
[ds.sfield] = deal([]);
%
% Make space for output P-structs if required
%
if nargout > 0
oP = cell(length(ds),1);
end
%
% First, create mask if so required.
%
if flags.mask || flags.mean,
linfun('Computing mask..');
spm_progress_bar('Init',ntot,'Computing available voxels',...
'volumes completed');
[x,y,z] = ndgrid(1:ds(1).P(1).dim(1),1:ds(1).P(1).dim(2),1:ds(1).P(1).dim(3));
xyz = [x(:) y(:) z(:) ones(prod(ds(1).P(1).dim(1:3)),1)]; clear x y z;
if flags.mean
Count = zeros(prod(ds(1).P(1).dim(1:3)),1);
Integral = zeros(prod(ds(1).P(1).dim(1:3)),1);
end
% if flags.mask
msk = zeros(prod(ds(1).P(1).dim(1:3)),1);
% end
tv = 1;
for s=1:length(ds)
def_array = zeros(prod(ds(s).P(1).dim(1:3)),size(ds(s).beta,2));
Bx = spm_dctmtx(ds(s).P(1).dim(1),ds(s).order(1));
By = spm_dctmtx(ds(s).P(1).dim(2),ds(s).order(2));
Bz = spm_dctmtx(ds(s).P(1).dim(3),ds(s).order(3));
if isfield(ds(s),'sfP') && ~isempty(ds(s).sfP)
T = ds(s).sfP.mat\ds(1).P(1).mat;
txyz = xyz * T';
c = spm_bsplinc(ds(s).sfP,ds(s).hold);
ds(s).sfield = spm_bsplins(c,txyz(:,1),txyz(:,2),txyz(:,3),ds(s).hold);
ds(s).sfield = ds(s).sfield(:);
clear c txyz;
end
for i=1:size(ds(s).beta,2)
def_array(:,i) = spm_get_def(Bx,By,Bz,ds(s).beta(:,i));
end
sess_msk = zeros(prod(ds(1).P(1).dim(1:3)),1);
for i = 1:numel(ds(s).P)
T = inv(ds(s).P(i).mat) * ds(1).P(1).mat;
txyz = xyz * T';
txyz(:,2) = txyz(:,2) + spm_get_image_def(ds(s).P(i),ds(s),def_array);
tmp = false(size(txyz,1),1);
if ~flags.wrap(1), tmp = tmp | txyz(:,1) < (1-tiny) | txyz(:,1) > (ds(s).P(i).dim(1)+tiny); end
if ~flags.wrap(2), tmp = tmp | txyz(:,2) < (1-tiny) | txyz(:,2) > (ds(s).P(i).dim(2)+tiny); end
if ~flags.wrap(3), tmp = tmp | txyz(:,3) < (1-tiny) | txyz(:,3) > (ds(s).P(i).dim(3)+tiny); end
sess_msk = sess_msk + real(tmp);
spm_progress_bar('Set',tv);
tv = tv+1;
end
msk = msk + sess_msk;
if flags.mean, Count = Count + repmat(length(ds(s).P),prod(ds(s).P(1).dim(1:3)),1) - sess_msk; end % Changed 23/3-05
%
% Include static field in estmation of mask.
%
if isfield(ds(s),'sfP') && ~isempty(ds(s).sfP)
T = inv(ds(s).sfP.mat) * ds(1).P(1).mat;
txyz = xyz * T';
tmp = false(size(txyz,1),1);
if ~flags.wrap(1), tmp = tmp | txyz(:,1) < (1-tiny) | txyz(:,1) > (ds(s).sfP.dim(1)+tiny); end
if ~flags.wrap(2), tmp = tmp | txyz(:,2) < (1-tiny) | txyz(:,2) > (ds(s).sfP.dim(2)+tiny); end
if ~flags.wrap(3), tmp = tmp | txyz(:,3) < (1-tiny) | txyz(:,3) > (ds(s).sfP.dim(3)+tiny); end
msk = msk + real(tmp);
end
if isfield(ds(s),'sfield') && ~isempty(ds(s).sfield)
ds(s).sfield = [];
end
end
if flags.mask, msk = find(msk ~= 0); end
end
linfun('Reslicing images..');
spm_progress_bar('Init',ntot,'Reslicing','volumes completed');
jP = ds(1).P(1);
jP = rmfield(jP,{'fname','descrip','n','private'});
jP.dim = jP.dim(1:3);
jP.dt = [spm_type('float64'), spm_platform('bigend')];
jP.pinfo = [1 0]';
tv = 1;
for s=1:length(ds)
def_array = zeros(prod(ds(s).P(1).dim(1:3)),size(ds(s).beta,2));
Bx = spm_dctmtx(ds(s).P(1).dim(1),ds(s).order(1));
By = spm_dctmtx(ds(s).P(1).dim(2),ds(s).order(2));
Bz = spm_dctmtx(ds(s).P(1).dim(3),ds(s).order(3));
if isfield(ds(s),'sfP') && ~isempty(ds(s).sfP)
T = ds(s).sfP.mat\ds(1).P(1).mat;
txyz = xyz * T';
c = spm_bsplinc(ds(s).sfP,ds(s).hold);
ds(s).sfield = spm_bsplins(c,txyz(:,1),txyz(:,2),txyz(:,3),ds(s).hold);
ds(s).sfield = ds(s).sfield(:);
clear c txyz;
end
for i=1:size(ds(s).beta,2)
def_array(:,i) = spm_get_def(Bx,By,Bz,ds(s).beta(:,i));
end
if flags.udc > 1
ddef_array = zeros(prod(ds(s).P(1).dim(1:3)),size(ds(s).beta,2));
dBy = spm_dctmtx(ds(s).P(1).dim(2),ds(s).order(2),'diff');
for i=1:size(ds(s).beta,2)
ddef_array(:,i) = spm_get_def(Bx,dBy,Bz,ds(s).beta(:,i));
end
end
for i = 1:length(ds(s).P)
linfun(['Reslicing volume ' num2str(tv) '..']);
%
% Read undeformed image.
%
T = inv(ds(s).P(i).mat) * ds(1).P(1).mat;
txyz = xyz * T';
if flags.udc > 1
[def,jac] = spm_get_image_def(ds(s).P(i),ds(s),def_array,ddef_array);
else
def = spm_get_image_def(ds(s).P(i),ds(s),def_array);
end
txyz(:,2) = txyz(:,2) + def;
if flags.udc > 1
jP.dat = reshape(jac,ds(s).P(i).dim(1:3));
jtxyz = xyz * T';
c = spm_bsplinc(jP.dat,hold);
jac = spm_bsplins(c,jtxyz(:,1),jtxyz(:,2),jtxyz(:,3),hold);
end
c = spm_bsplinc(ds(s).P(i),hold);
ima = spm_bsplins(c,txyz(:,1),txyz(:,2),txyz(:,3),hold);
if flags.udc > 1
ima = ima .* jac;
end
%
% Write it if so required.
%
if flags.which
PO = ds(s).P(i);
PO.fname = prepend(PO.fname,flags.prefix);
PO.mat = ds(1).P(1).mat;
PO.descrip = 'spm - undeformed';
ivol = ima;
if flags.mask
ivol(msk) = NaN;
end
ivol = reshape(ivol,PO.dim(1:3));
PO = spm_create_vol(PO);
for ii=1:PO.dim(3),
PO = spm_write_plane(PO,ivol(:,:,ii),ii);
end;
if nargout > 0
oP{s}(i) = PO;
end
end
%
% Build up mean image if so required.
%
if flags.mean
Integral = Integral + nan2zero(ima);
end
spm_progress_bar('Set',tv);
tv = tv+1;
end
if isfield(ds(s),'sfield') && ~isempty(ds(s).sfield)
ds(s).sfield = [];
end
end
if flags.mean
% Write integral image (16 bit signed)
%-----------------------------------------------------------
sw = warning('off','MATLAB:divideByZero');
Integral = Integral./Count;
warning(sw);
PO = ds(1).P(1);
[pth,nm,xt,vr] = spm_fileparts(deblank(ds(1).P(1).fname));
PO.fname = fullfile(pth,['mean' flags.prefix nm xt vr]);
PO.pinfo = [max(max(max(Integral)))/32767 0 0]';
PO.descrip = 'spm - mean undeformed image';
PO.dt = [4 spm_platform('bigend')];
ivol = reshape(Integral,PO.dim);
spm_write_vol(PO,ivol);
end
linfun(' ');
spm_figure('Clear','Interactive');
if nargout > 0
varargout{1} = oP;
end
return;
%_______________________________________________________________________
function PO = prepend(PI,pre)
[pth,nm,xt,vr] = spm_fileparts(deblank(PI));
PO = fullfile(pth,[pre nm xt vr]);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function vo = nan2zero(vi)
vo = vi;
vo(~isfinite(vo)) = 0;
return;
%_______________________________________________________________________
|
github
|
philippboehmsturm/antx-master
|
fdmar_plot.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/fdmar_plot.m
| 1,420 |
utf_8
|
f58baff924f45e85e7434436c7d8bf48
|
%need:
%obj.X --> data
%obj.res --> residuals from glm
%obj.resgaus --> gaussian distrubuted res
%obj.stimu --> stimu of the experiment
%obj.resar --> residuals of the ar fit
%obj.arspek --> theoretical spektrum build by parameter vector A
function fdmar_plot(obj,figname)
scrsz = get(0,'ScreenSize');
h=figure('Name','ar fit of the glm residuals','Position',[1 1 scrsz(3)/2 scrsz(4)/2]);
%plot data and residuals
subplot(3,2,1);
plot(obj.X,'b')
hold on
plot(obj.res,'r')
plot(obj.stimu,'g')
hold off
title('RAW-data')
legend('RAW-data','GLM-residuals','Location','Best')
%plot qqplot of resgaus
subplot(3,2,2);
plot(sort(obj.res),sort(randn(1,length(obj.res))),'*')
title('qq-Plot glm-residuals')
%plot residual, estimated residual and residuals of the ar fit
subplot(3,2,3);
plot(obj.resar(1:401),'r')
hold on
plot(obj.resest(1:401),'g')
plot(obj.resgaus(obj.order+1:obj.order+401),'b')
hold off
xlim([0,401])
legend('ResAR','ResEst','ResGLM', 'Location','Best')
%plot periodogramm of the residuals of the ar fit
subplot(3,2,4);
periodogram(obj.resar)
ylim([-100,100])
title('residuals arfit')
%plot periodogramm of the gaussian glm residuals
subplot(3,2,5);
periodogram(obj.resgaus)
ylim([-100,100])
title('spectrum glm+gaus residuals')
%plot theoretical ar spectrum
subplot(3,2,6);
semilogy(obj.arspek)
title('theoretical spectrum of est. ar-parameter')
xlim([0,1001])
if nargin > 1
saveas(h,figname);
end
end
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_prep_ui.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_eeg_prep_ui.m
| 29,442 |
utf_8
|
80bb3efbe6195079a20c2e95d5a38104
|
function spm_eeg_prep_ui(callback)
% User interface for spm_eeg_prep function performing several tasks
% for preparation of converted MEEG data for further analysis
% FORMAT spm_eeg_prep_ui(callback)
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Vladimir Litvak
% $Id: spm_eeg_prep_ui.m 3833 2010-04-22 14:49:48Z vladimir $
spm('Pointer','Watch');
if ~nargin, callback = 'CreateMenu'; end
eval(callback);
spm('Pointer','Arrow');
%==========================================================================
% function CreateMenu
%==========================================================================
function CreateMenu
SVNrev = '$Rev: 3833 $';
spm('FnBanner', 'spm_eeg_prep_ui', SVNrev);
Finter = spm('FnUIsetup', 'M/EEG prepare', 0);
%-Draw top level menu
% ====== File ===================================
FileMenu = uimenu(Finter,'Label','File',...
'Tag','EEGprepUI',...
'HandleVisibility','on');
FileOpenMenu = uimenu(FileMenu, ...
'Label','Open',...
'Separator','off',...
'Tag','EEGprepUI',...
'HandleVisibility', 'on',...
'Accelerator','O',...
'Callback', 'spm_eeg_prep_ui(''FileOpenCB'')');
FileSaveMenu = uimenu(FileMenu, ...
'Label','Save',...
'Separator','off',...
'Tag','EEGprepUI',...
'Enable','off',...
'HandleVisibility', 'on',...
'Accelerator','S',...
'Callback', 'spm_eeg_prep_ui(''FileSaveCB'')');
FileExitMenu = uimenu(FileMenu, ...
'Label','Quit',...
'Separator','on',...
'Tag','EEGprepUI',...
'HandleVisibility', 'on',...
'Accelerator','Q',...
'Callback', 'spm_eeg_prep_ui(''FileExitCB'')');
% ====== Channel types ===============================
ChanTypeMenu = uimenu(Finter,'Label','Channel types',...
'Tag','EEGprepUI',...
'Enable', 'off', ...
'HandleVisibility','on');
chanTypes = {'EEG', 'EOG', 'ECG', 'EMG', 'LFP', 'Other'};
for i = 1:length(chanTypes)
CTypesMenu(i) = uimenu(ChanTypeMenu, 'Label', chanTypes{i},...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on',...
'Callback', 'spm_eeg_prep_ui(''ChanTypeCB'')');
end
CTypesRef2MEGMenu = uimenu(ChanTypeMenu, 'Label', 'MEGREF=>MEG',...
'Tag','EEGprepUI',...
'Enable', 'off', ...
'HandleVisibility','on',...
'Separator', 'on',...
'Callback', 'spm_eeg_prep_ui(''MEGChanTypeCB'')');
CTypesDefaultMenu = uimenu(ChanTypeMenu, 'Label', 'Default',...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on',...
'Separator', 'on',...
'Callback', 'spm_eeg_prep_ui(''ChanTypeDefaultCB'')');
CTypesReviewMenu = uimenu(ChanTypeMenu, 'Label', 'Review',...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on',...
'Callback', 'spm_eeg_prep_ui(''ChanTypeCB'')');
% ====== Sensors ===================================
Coor3DMenu = uimenu(Finter,'Label','Sensors',...
'Tag','EEGprepUI',...
'Enable', 'off', ...
'HandleVisibility','on');
LoadEEGSensMenu = uimenu(Coor3DMenu, 'Label', 'Load EEG sensors',...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on');
LoadEEGSensTemplateMenu = uimenu(LoadEEGSensMenu, 'Label', 'Assign default',...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on',...
'Callback', 'spm_eeg_prep_ui(''LoadEEGSensTemplateCB'')');
LoadEEGSensMatMenu = uimenu(LoadEEGSensMenu, 'Label', 'From *.mat file',...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on',...
'Callback', 'spm_eeg_prep_ui(''LoadEEGSensCB'')');
LoadEEGSensOtherMenu = uimenu(LoadEEGSensMenu, 'Label', 'Convert locations file',...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on',...
'Callback', 'spm_eeg_prep_ui(''LoadEEGSensCB'')');
HeadshapeMenu = uimenu(Coor3DMenu, 'Label', 'Load MEG Fiducials/Headshape',...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on',...
'Callback', 'spm_eeg_prep_ui(''HeadshapeCB'')');
CoregisterMenu = uimenu(Coor3DMenu, 'Label', 'Coregister',...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on',...
'Separator', 'on', ...
'Callback', 'spm_eeg_prep_ui(''CoregisterCB'')');
% ====== 2D projection ===================================
Coor2DMenu = uimenu(Finter, 'Label','2D projection',...
'Tag','EEGprepUI',...
'Enable', 'off', ...
'HandleVisibility','on');
EditMEGMenu = uimenu(Coor2DMenu, 'Label', 'Edit existing MEG',...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on',...
'Callback', 'spm_eeg_prep_ui(''EditExistingCoor2DCB'')');
EditEEGMenu = uimenu(Coor2DMenu, 'Label', 'Edit existing EEG',...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on',...
'Callback', 'spm_eeg_prep_ui(''EditExistingCoor2DCB'')');
LoadTemplateMenu = uimenu(Coor2DMenu, 'Label', 'Load template',...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on',...
'Separator', 'on', ...
'Callback', 'spm_eeg_prep_ui(''LoadTemplateCB'')');
SaveTemplateMenu = uimenu(Coor2DMenu, 'Label', 'Save template',...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on',...
'Callback', 'spm_eeg_prep_ui(''SaveTemplateCB'')');
Project3DEEGMenu = uimenu(Coor2DMenu, 'Label', 'Project 3D (EEG)',...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on',...
'Separator', 'on', ...
'Callback', 'spm_eeg_prep_ui(''Project3DCB'')');
Project3DMEGMenu = uimenu(Coor2DMenu, 'Label', 'Project 3D (MEG)',...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on',...
'Callback', 'spm_eeg_prep_ui(''Project3DCB'')');
AddCoor2DMenu = uimenu(Coor2DMenu, 'Label', 'Add sensor',...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on',...
'Separator', 'on', ...
'Callback', 'spm_eeg_prep_ui(''AddCoor2DCB'')');
DeleteCoor2DMenu = uimenu(Coor2DMenu, 'Label', 'Delete sensor',...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on',...
'Callback', 'spm_eeg_prep_ui(''DeleteCoor2DCB'')');
UndoMoveCoor2DMenu = uimenu(Coor2DMenu, 'Label', 'Undo move',...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on',...
'Callback', 'spm_eeg_prep_ui(''UndoMoveCoor2DCB'')');
ApplyCoor2DMenu = uimenu(Coor2DMenu, 'Label', 'Apply',...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on',...
'Separator', 'on', ...
'Callback', 'spm_eeg_prep_ui(''ApplyCoor2DCB'')');
Clear2DMenu = uimenu(Coor2DMenu, 'Label', 'Clear',...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on',...
'Callback', 'spm_eeg_prep_ui(''Clear2DCB'')');
%==========================================================================
% function FileOpenCB
%==========================================================================
function FileOpenCB
D = spm_eeg_load;
setD(D);
update_menu;
%==========================================================================
% function FileSaveCB
%==========================================================================
function FileSaveCB
D = getD;
if ~isempty(D)
D.save;
end
update_menu;
%==========================================================================
% function FileExitCB
%==========================================================================
function FileExitCB
spm_figure('Clear','Interactive');
spm('FigName','M/EEG prepare: done');
%==========================================================================
% function ChanTypeCB
%==========================================================================
function ChanTypeCB
type = get(gcbo, 'Label');
D = getD;
if ~isempty(D)
chanlist ={};
for i = 1:D.nchannels
if strncmp(D.chantype(i), 'MEG', 3) || strncmp(D.chantype(i), 'REF', 3)
chanlist{i} = [num2str(i) ' Label: ' D.chanlabels(i) ' Type: ' D.chantype(i) , ' (nonmodifiable)'];
else
chanlist{i} = [num2str(i) ' Label: ' D.chanlabels(i) ' Type: ' D.chantype(i)];
end
chanlist{i} = [chanlist{i}{:}];
end
if strcmpi(type, 'review')
listdlg('ListString', chanlist, 'SelectionMode', 'single', 'Name', 'Review channels', 'ListSize', [400 300]);
return
else
[selection ok]= listdlg('ListString', chanlist, 'SelectionMode', 'multiple',...
'InitialValue', strmatch(type, D.chantype) ,'Name', ['Set type to ' type], 'ListSize', [400 300]);
selection(strmatch('MEG', chantype(D, selection))) = [];
if ok && ~isempty(selection)
S.task = 'settype';
S.D = D;
S.ind = selection;
S.type = type;
D = spm_eeg_prep(S);
setD(D);
end
end
end
update_menu;
%==========================================================================
% function MEGChanTypeCB
%==========================================================================
function MEGChanTypeCB
S = [];
S.D = getD;
S.task = 'settype';
switch get(gcbo, 'Label')
case 'MEGREF=>MEG'
dictionary = {
'REFMAG', 'MEGMAG';
'REFGRAD', 'MEGGRAD';
};
ind = spm_match_str(S.D.chantype, dictionary(:,1));
grad = S.D.sensors('meg');
if ~isempty(grad)
% Under some montages only subset of the reference sensors are
% in the grad
[junk, sel] = intersect(S.D.chanlabels(ind), grad.label);
ind = ind(sel);
end
S.ind = ind;
[sel1, sel2] = spm_match_str(S.D.chantype(S.ind), dictionary(:, 1));
S.type = dictionary(sel2, 2);
D = spm_eeg_prep(S);
end
setD(D);
update_menu;
%==========================================================================
% function ChanTypeDefaultCB
%==========================================================================
function ChanTypeDefaultCB
S.D = getD;
S.task = 'defaulttype';
D = spm_eeg_prep(S);
setD(D);
update_menu;
%==========================================================================
% function LoadEEGSensTemplateCB
%==========================================================================
function LoadEEGSensTemplateCB
S.D = getD;
S.task = 'defaulteegsens';
if strcmp(S.D.modality(1, 0), 'Multimodal')
fid = fiducials(S.D);
if ~isempty(fid)
lblfid = fid.fid.label;
S.regfid = match_fiducials({'nas'; 'lpa'; 'rpa'}, lblfid);
S.regfid(:, 2) = {'spmnas'; 'spmlpa'; 'spmrpa'};
else
warndlg(strvcat('Could not match EEG fiducials for multimodal dataset.', ...
' EEG coregistration might fail.'));
end
end
D = spm_eeg_prep(S);
setD(D);
update_menu;
%==========================================================================
% function LoadEEGSensCB
%==========================================================================
function LoadEEGSensCB
D = getD;
switch get(gcbo, 'Label')
case 'From *.mat file'
[S.sensfile, sts] = spm_select(1,'mat','Select EEG sensors file');
if ~sts, return, end
S.source = 'mat';
[S.headshapefile, sts] = spm_select(1,'mat','Select EEG fiducials file');
if ~sts, return, end
S.fidlabel = spm_input('Fiducial labels:', '+1', 's', 'nas lpa rpa');
case 'Convert locations file'
[S.sensfile, sts] = spm_select(1, '.*', 'Select locations file');
if ~sts, return, end
S.source = 'locfile';
end
if strcmp(D.modality(1, 0), 'Multimodal')
if ~isempty(D.fiducials)
S.regfid = {};
if strcmp(S.source, 'mat')
fidlabel = S.fidlabel;
lblshape = {};
fidnum = 0;
while ~all(isspace(fidlabel))
fidnum = fidnum+1;
[lblshape{fidnum} fidlabel] = strtok(fidlabel);
end
if (fidnum < 3)
error('At least 3 labeled fiducials are necessary');
end
else
shape = ft_read_headshape(S.sensfile);
lblshape = shape.fid.label;
end
fid = fiducials(D);
lblfid = fid.fid.label;
S.regfid = match_fiducials(lblshape, lblfid);
else
warndlg(strvcat('Could not match EEG fiducials for multimodal dataset.', ...
' EEG coregistration might fail.'));
end
end
S.D = D;
S.task = 'loadeegsens';
D = spm_eeg_prep(S);
% ====== This is for the future ==================================
% sens = D.sensors('EEG');
% label = D.chanlabels(strmatch('EEG',D.chantype));
%
% [sel1, sel2] = spm_match_str(label, sens.label);
%
% montage = [];
% montage.labelorg = sens.label;
% montage.labelnew = label;
% montage.tra = sparse(zeros(numel(label), numel(sens.label)));
% montage.tra(sub2ind(size(montage.tra), sel1, sel2)) = 1;
%
% montage = spm_eeg_montage_ui(montage);
%
% S = [];
% S.D = D;
% S.task = 'sens2chan';
% S.montage = montage;
%
% D = spm_eeg_prep(S);
setD(D);
update_menu;
%==========================================================================
% function HeadshapeCB
%==========================================================================
function HeadshapeCB
S = [];
S.D = getD;
S.task = 'headshape';
[S.headshapefile, sts] = spm_select(1, '.*', 'Select fiducials/headshape file');
if ~sts, return, end
S.source = 'convert';
shape = ft_read_headshape(S.headshapefile);
lblshape = shape.fid.label;
fid = fiducials(S.D);
if ~isempty(fid)
lblfid = fid.fid.label;
S.regfid = match_fiducials(lblshape, lblfid);
end
D = spm_eeg_prep(S);
setD(D);
update_menu;
%==========================================================================
% function CoregisterCB
%==========================================================================
function CoregisterCB
S = [];
S.D = getD;
S.task = 'coregister';
D = spm_eeg_prep(S);
% Bring the menu back
spm_eeg_prep_ui;
setD(D);
update_menu;
%==========================================================================
% function EditExistingCoor2DCB
%==========================================================================
function EditExistingCoor2DCB
D = getD;
switch get(gcbo, 'Label')
case 'Edit existing MEG'
xy = D.coor2D('MEG');
label = D.chanlabels(strmatch('MEG', D.chantype));
case 'Edit existing EEG'
xy = D.coor2D('EEG');
label = D.chanlabels(strmatch('EEG', D.chantype, 'exact'));
end
plot_sensors2D(xy, label);
update_menu;
%==========================================================================
% function LoadTemplateCB
%==========================================================================
function LoadTemplateCB
[sensorfile, sts] = spm_select(1, 'mat', 'Select sensor template file', ...
[], fullfile(spm('dir'), 'EEGtemplates'));
if ~sts, return, end
template = load(sensorfile);
if isfield(template, 'Cnames') && isfield(template, 'Cpos')
plot_sensors2D(template.Cpos, template.Cnames);
end
update_menu;
%==========================================================================
% function SaveTemplateCB
%==========================================================================
function SaveTemplateCB
handles=getHandles;
Cnames = handles.label;
Cpos = handles.xy;
Rxy = 1.5;
Nchannels = length(Cnames);
[filename, pathname] = uiputfile('*.mat', 'Save channel template as');
save(fullfile(pathname, filename), 'Cnames', 'Cpos', 'Rxy', 'Nchannels');
%==========================================================================
% function Project3DCB
%==========================================================================
function Project3DCB
D = getD;
switch get(gcbo, 'Label')
case 'Project 3D (EEG)'
modality = 'EEG';
case 'Project 3D (MEG)'
modality = 'MEG';
end
if ~isfield(D, 'val')
D.val = 1;
end
if isfield(D, 'inv') && isfield(D.inv{D.val}, 'datareg')
datareg = D.inv{D.val}.datareg;
ind = strmatch(modality, {datareg(:).modality}, 'exact');
sens = datareg(ind).sensors;
else
sens = D.sensors(modality);
end
[xy, label] = spm_eeg_project3D(sens, modality);
plot_sensors2D(xy, label);
update_menu;
%==========================================================================
% function AddCoor2DCB
%==========================================================================
function AddCoor2DCB
newlabel = spm_input('Label?', '+1', 's');
if isempty(newlabel)
return;
end
coord = spm_input('Coordinates [x y]', '+1', 'r', '0.5 0.5', 2);
handles = getHandles;
if ~isfield(handles, 'xy')
handles.xy = [];
end
if ~isfield(handles, 'xy')
handles.xy = [];
end
if ~isfield(handles, 'label')
handles.label = {};
end
plot_sensors2D([handles.xy coord(:)], ...
[handles.label newlabel]);
update_menu;
%==========================================================================
% function ApplyCoor2DCB
%==========================================================================
function ApplyCoor2DCB
handles = getHandles;
D = getD;
S = [];
S.task = 'setcoor2d';
S.D = D;
S.xy = handles.xy;
S.label = handles.label;
D = spm_eeg_prep(S);
setD(D);
update_menu;
%==========================================================================
% function update_menu
%==========================================================================
function update_menu
Finter = spm_figure('GetWin','Interactive');
set(findobj(Finter,'Tag','EEGprepUI', 'Label', 'File'), 'Enable', 'on');
IsEEG = 'off';
IsMEG = 'off';
IsNeuromag = 'off';
HasSensors = 'off';
HasSensorsEEG = 'off';
HasSensorsMEG = 'off';
HasChannelsMEGREF = 'off';
HasFiducials = 'off';
HasDefaultLocs = 'off';
HasHistory = 'off';
if isa(get(Finter, 'UserData'), 'meeg')
Dloaded = 'on';
D = getD;
if ~isempty(strmatch('EEG', D.chantype, 'exact'))
IsEEG = 'on';
end
if ~isempty(strmatch('MEG', D.chantype));
IsMEG = 'on';
end
if ft_senstype(D.chanlabels, 'neuromag') &&...
isfield(D, 'origchantypes')
IsNeuromag = 'on';
end
if ~isempty(strmatch('REF', D.chantype));
HasChannelsMEGREF = 'on';
end
if ~isempty(D.sensors('EEG')) || ~isempty(D.sensors('MEG'))
HasSensors = 'on';
end
if ~isempty(D.sensors('EEG'))
HasSensorsEEG = 'on';
end
if ~isempty(D.sensors('MEG'))
HasSensorsMEG = 'on';
end
if ~isempty(D.fiducials)
HasFiducials = 'on';
end
template_sfp = dir(fullfile(spm('dir'), 'EEGtemplates', '*.sfp'));
template_sfp = {template_sfp.name};
ind = strmatch([ft_senstype(D.chanlabels) '.sfp'], template_sfp, 'exact');
if ~isempty(ind)
HasDefaultLocs = 'on';
end
if ~isempty(D.history)
HasHistory = 'on';
end
else
Dloaded = 'off';
end
handles = getHandles;
IsTemplate = 'off';
IsSelected = 'off';
IsMoved = 'off';
if ~isempty(handles)
if isfield(handles, 'xy') && size(handles.xy, 1)>0
IsTemplate = 'on';
end
if isfield(handles, 'labelSelected') && ~isempty(handles.labelSelected)
IsSelected = 'on';
end
if isfield(handles, 'lastMoved')
isMoved = 'on';
end
end
set(findobj(Finter,'Tag','EEGprepUI', 'Label', 'Save'), 'Enable', 'on');
set(findobj(Finter,'Tag','EEGprepUI', 'Label', 'Channel types'), 'Enable', Dloaded);
set(findobj(Finter,'Tag','EEGprepUI', 'Label', 'Sensors'), 'Enable', Dloaded);
set(findobj(Finter,'Tag','EEGprepUI', 'Label', '2D projection'), 'Enable', Dloaded);
set(findobj(Finter,'Tag','EEGprepUI', 'Label', 'MEGREF=>MEG'), 'Enable', HasChannelsMEGREF);
set(findobj(Finter,'Tag','EEGprepUI', 'Label', 'Assign default'), 'Enable', HasDefaultLocs);
set(findobj(Finter,'Tag','EEGprepUI', 'Label', 'Load EEG sensors'), 'Enable', IsEEG);
set(findobj(Finter,'Tag','EEGprepUI', 'Label', 'Load MEG Fiducials/Headshape'), 'Enable', HasSensorsMEG);
set(findobj(Finter,'Tag','EEGprepUI', 'Label', 'Headshape'), 'Enable', HasSensorsMEG);
set(findobj(Finter,'Tag','EEGprepUI', 'Label', 'Coregister'), 'Enable', HasSensors);
set(findobj(Finter,'Tag','EEGprepUI', 'Label', 'Edit existing EEG'), 'Enable', IsEEG);
set(findobj(Finter,'Tag','EEGprepUI', 'Label', 'Edit existing MEG'), 'Enable', IsMEG);
set(findobj(Finter,'Tag','EEGprepUI', 'Label', 'Project 3D (EEG)'), 'Enable', HasSensorsEEG);
set(findobj(Finter,'Tag','EEGprepUI', 'Label', 'Project 3D (MEG)'), 'Enable', HasSensorsMEG);
set(findobj(Finter,'Tag','EEGprepUI', 'Label', 'Delete sensor'), 'Enable', IsSelected);
set(findobj(Finter,'Tag','EEGprepUI', 'Label', 'Undo move'), 'Enable', IsMoved);
set(findobj(Finter,'Tag','EEGprepUI', 'Label', 'Apply'), 'Enable', IsTemplate);
set(findobj(Finter,'Tag','EEGprepUI', 'Label', 'Clear'), 'Enable', IsTemplate);
delete(setdiff(findobj(Finter), [Finter; findobj(Finter,'Tag','EEGprepUI')]));
if strcmp(Dloaded, 'on') && isfield(D,'PSD') && D.PSD == 1
try
hc = get(Finter,'children');
hc = findobj(hc,'flat','type','uimenu');
hc = findobj(hc,'flat','label','File');
delete(hc)
end
uicontrol(Finter,...
'style','pushbutton','string','OK',...
'callback','spm_eeg_review_callbacks(''get'',''prep'')',...
'tooltipstring','Send changes to ''SPM Graphics'' window',...
'BusyAction','cancel',...
'Interruptible','off',...
'Tag','EEGprepUI');
end
figure(Finter);
%==========================================================================
% function getD
%==========================================================================
function D = getD
Finter = spm_figure('GetWin','Interactive');
D = get(Finter, 'UserData');
if ~isa(D, 'meeg')
D = [];
end
%==========================================================================
% function setD
%==========================================================================
function setD(D)
Finter = spm_figure('GetWin','Interactive');
set(Finter, 'UserData', D);
%==========================================================================
% function getHandles
%==========================================================================
function handles = getHandles
Fgraph = spm_figure('GetWin','Graphics');
handles = get(Fgraph, 'UserData');
%==========================================================================
% function setHandles
%==========================================================================
function setHandles(handles)
Fgraph = spm_figure('GetWin','Graphics');
set(Fgraph, 'UserData', handles);
%==========================================================================
% function plot_sensors2D
%==========================================================================
function plot_sensors2D(xy, label)
Fgraph = spm_figure('GetWin','Graphics');
spm_clf(Fgraph);
handles = [];
if ~isempty(xy)
if size(xy, 1) ~= 2
xy = xy';
end
xy(xy < 0.05) = 0.05;
xy(xy > 0.95) = 0.95;
handles.h_lbl=text(xy(1,:), xy(2, :),strvcat(label),...
'FontSize', 9,...
'Color','r',...
'FontWeight','bold');
set(handles.h_lbl, 'ButtonDownFcn', 'spm_eeg_prep_ui(''LabelClickCB'')');
hold on
handles.h_el =[];
for i=1:size(xy, 2)
handles.h_el(i) = plot(xy(1,i), xy(2,i), 'or');
end
set(handles.h_el,'MarkerFaceColor','r','MarkerSize', 2,'MarkerEdgeColor','k');
handles.TemplateFrame = ...
plot([0.05 0.05 0.95 0.95 0.05], [0.05 0.95 0.95 0.05 0.05], 'k-');
axis off;
end
handles.xy = xy;
handles.label = label(:)';
setHandles(handles);
update_menu;
%==========================================================================
% function DeleteCoor2DCB
%==========================================================================
function DeleteCoor2DCB
handles = getHandles;
graph = spm_figure('GetWin','Graphics');
if isfield(handles, 'labelSelected') && ~isempty(handles.labelSelected)
set(graph, 'WindowButtonDownFcn', '');
label=get(handles.labelSelected, 'String');
ind=strmatch(label, handles.label, 'exact');
delete([handles.labelSelected handles.pointSelected]);
handles.xy(:, ind)=[];
handles.label(ind) = [];
plot_sensors2D(handles.xy, handles.label)
end
%==========================================================================
% function UndoMoveCoor2DCB
%==========================================================================
function UndoMoveCoor2DCB
handles = getHandles;
if isfield(handles, 'lastMoved')
label = get(handles.lastMoved(end).label, 'String');
ind = strmatch(label, handles.label, 'exact');
handles.xy(:, ind) = handles.lastMoved(end).coords(:);
set(handles.lastMoved(end).point, 'XData', handles.lastMoved(end).coords(1));
set(handles.lastMoved(end).point, 'YData', handles.lastMoved(end).coords(2));
set(handles.lastMoved(end).label, 'Position', handles.lastMoved(end).coords);
if length(handles.lastMoved)>1
handles.lastMoved = handles.lastMoved(1:(end-1));
else
handles = rmfield(handles, 'lastMoved');
end
setHandles(handles);
update_menu;
end
%==========================================================================
% function LabelClickCB
%==========================================================================
function LabelClickCB
handles=getHandles;
Fgraph = spm_figure('GetWin','Graphics');
if isfield(handles, 'labelSelected') && ~isempty(handles.labelSelected)
if handles.labelSelected == gcbo
set(handles.labelSelected, 'Color', 'r');
set(handles.pointSelected,'MarkerFaceColor', 'r');
set(Fgraph, 'WindowButtonDownFcn', '');
else
handles.pointSelected=[];
handles.labelSelected=[];
end
else
set(Fgraph, 'WindowButtonDownFcn', 'spm_eeg_prep_ui(''LabelMoveCB'')');
coords = get(gcbo, 'Position');
handles.labelSelected=gcbo;
handles.pointSelected=findobj(gca, 'Type', 'line',...
'XData', coords(1), 'YData', coords(2));
set(handles.labelSelected, 'Color', 'g');
set(handles.pointSelected,'MarkerFaceColor', 'g');
end
setHandles(handles);
update_menu;
%==========================================================================
% function LabelMoveCB
%==========================================================================
function LabelMoveCB
handles = getHandles;
Fgraph = spm_figure('GetWin','Graphics');
coords=mean(get(gca, 'CurrentPoint'));
coords(coords < 0.05) = 0.05;
coords(coords > 0.95) = 0.95;
set(handles.pointSelected, 'XData', coords(1));
set(handles.pointSelected, 'YData', coords(2));
set(handles.labelSelected, 'Position', coords);
set(handles.labelSelected, 'Color', 'r');
set(handles.pointSelected,'MarkerFaceColor','r','MarkerSize',2,'MarkerEdgeColor','k');
set(Fgraph, 'WindowButtonDownFcn', '');
set(Fgraph, 'WindowButtonMotionFcn', 'spm_eeg_prep_ui(''CancelMoveCB'')');
labelind=strmatch(get(handles.labelSelected, 'String'), handles.label);
if isfield(handles, 'lastMoved')
handles.lastMoved(end+1).point = handles.pointSelected;
handles.lastMoved(end).label = handles.labelSelected;
handles.lastMoved(end).coords = handles.xy(:, labelind);
else
handles.lastMoved.point = handles.pointSelected;
handles.lastMoved.label = handles.labelSelected;
handles.lastMoved.coords = handles.xy(:, labelind);
end
handles.xy(:, labelind) = coords(1:2)';
setHandles(handles);
update_menu;
%==========================================================================
% function CancelMoveCB
%==========================================================================
function CancelMoveCB
Fgraph = spm_figure('GetWin','Graphics');
handles = getHandles;
handles.pointSelected=[];
handles.labelSelected=[];
set(Fgraph, 'WindowButtonMotionFcn', '');
setHandles(handles);
update_menu;
%==========================================================================
% function Clear2DCB
%==========================================================================
function Clear2DCB
plot_sensors2D([], {});
update_menu;
%==========================================================================
% function match_fiducials
%==========================================================================
function regfid = match_fiducials(lblshape, lblfid)
if numel(intersect(upper(lblshape), upper(lblfid))) < 3
if numel(lblshape)<3 || numel(lblfid)<3
warndlg('3 fiducials are required');
return;
else
regfid = {};
for i = 1:length(lblfid)
[selection ok]= listdlg('ListString',lblshape, 'SelectionMode', 'single',...
'InitialValue', strmatch(upper(lblfid{i}), upper(lblshape)), ...
'Name', ['Select matching fiducial for ' lblfid{i}], 'ListSize', [400 300]);
if ~ok
continue
end
regfid = [regfid; [lblfid(i) lblshape(selection)]];
end
if size(regfid, 1) < 3
warndlg('3 fiducials are required to load headshape');
return;
end
end
else
[sel1, sel2] = spm_match_str(upper(lblfid), upper(lblshape));
lblfid = lblfid(sel1);
lblshape = lblshape(sel2);
regfid = [lblfid(:) lblshape(:)];
end
|
github
|
philippboehmsturm/antx-master
|
spm_read_netcdf.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_read_netcdf.m
| 4,350 |
utf_8
|
1cd1b0f7f4b4349d963028c168cd4f2d
|
function cdf = spm_read_netcdf(fname)
% Read the header information from a NetCDF file into a data structure.
% FORMAT cdf = spm_read_netcdf(fname)
% fname - name of NetCDF file
% cdf - data structure
%
% See: http://www.unidata.ucar.edu/packages/netcdf/
% _________________________________________________________________________
% Copyright (C) 1999-2011 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_read_netcdf.m 4182 2011-02-01 12:29:09Z guillaume $
dsiz = [1 1 2 4 4 8];
fp=fopen(fname,'r','ieee-be');
if fp==-1
cdf = [];
return;
end
% Return null if not a CDF file.
%--------------------------------------------------------------------------
mgc = fread(fp,4,'uchar')';
if ~all(['CDF' 1] == mgc)
cdf = [];
fclose(fp);
if all(mgc==[137,72,68,70])
fprintf(['"%s" appears to be based around HDF.\n',...
'This is a newer version of MINC that SPM can not yet read.\n'],...
fname);
end
return;
end
% I've no idea what this is for
numrecs = fread(fp,1,'uint32');
cdf = struct('numrecs', numrecs,...
'dim_array', [], ...
'gatt_array', [], ...
'var_array', []);
dt = fread(fp,1,'uint32');
if dt == 10
% Dimensions
nelem = fread(fp,1,'uint32');
for j=1:nelem
str = readname(fp);
dim_length = fread(fp,1,'uint32');
cdf.dim_array(j).name = str;
cdf.dim_array(j).dim_length = dim_length;
end
dt = fread(fp,1,'uint32');
end
while ~dt, dt = fread(fp,1,'uint32'); end
if dt == 12
% Attributes
nelem = fread(fp,1,'uint32');
for j=1:nelem
str = readname(fp);
nc_type = fread(fp,1,'uint32');
nnelem = fread(fp,1,'uint32');
val = fread(fp,nnelem,dtypestr(nc_type));
if nc_type == 2, val = deblank([val' ' ']); end
padding= fread(fp,...
ceil(nnelem*dsiz(nc_type)/4)*4-nnelem*dsiz(nc_type),'uchar');
cdf.gatt_array(j).name = str;
cdf.gatt_array(j).nc_type = nc_type;
cdf.gatt_array(j).val = val;
end
dt = fread(fp,1,'uint32');
end
while ~dt, dt = fread(fp,1,'uint32'); end
if dt == 11
% Variables
nelem = fread(fp,1,'uint32');
for j=1:nelem
str = readname(fp);
nnelem = fread(fp,1,'uint32');
val = fread(fp,nnelem,'uint32');
cdf.var_array(j).name = str;
cdf.var_array(j).dimid = val+1;
cdf.var_array(j).nc_type = 0;
cdf.var_array(j).vsize = 0;
cdf.var_array(j).begin = 0;
dt0 = fread(fp,1,'uint32');
if dt0 == 12
nelem0 = fread(fp,1,'uint32');
for jj=1:nelem0
str = readname(fp);
nc_type= fread(fp,1,'uint32');
nnelem = fread(fp,1,'uint32');
val = fread(fp,nnelem,dtypestr(nc_type));
if nc_type == 2, val = deblank([val' ' ']); end
padding= fread(fp,...
ceil(nnelem*dsiz(nc_type)/4)*4-nnelem*dsiz(nc_type),'uchar');
cdf.var_array(j).vatt_array(jj).name = str;
cdf.var_array(j).vatt_array(jj).nc_type = nc_type;
cdf.var_array(j).vatt_array(jj).val = val;
end
dt0 = fread(fp,1,'uint32');
end
cdf.var_array(j).nc_type = dt0;
cdf.var_array(j).vsize = fread(fp,1,'uint32');
cdf.var_array(j).begin = fread(fp,1,'uint32');
end
dt = fread(fp,1,'uint32');
end
fclose(fp);
%==========================================================================
% function str = dtypestr(i)
%==========================================================================
function str = dtypestr(i)
% Returns a string appropriate for reading or writing the CDF data-type.
types = char('uint8','uint8','int16','int32','float32','float64');
str = deblank(types(i,:));
%==========================================================================
% function name = readname(fp)
%==========================================================================
function name = readname(fp)
% Extracts a name from a CDF file pointed to at the right location by fp.
stlen = fread(fp,1,'uint32');
name = deblank([fread(fp,stlen,'uchar')' ' ']);
padding = fread(fp,ceil(stlen/4)*4-stlen,'uchar');
|
github
|
philippboehmsturm/antx-master
|
spm_figure.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_figure.m
| 38,735 |
utf_8
|
ec6276bcd9442a37949e30e810130c25
|
function varargout=spm_figure(varargin)
% Setup and callback functions for Graphics window
% FORMAT varargout=spm_figure(varargin)
%
% spm_figure provides utility routines for using the SPM Graphics
% interface. Most used syntaxes are listed here, see the embedded callback
% reference in the main body of this function, below the help text.
%
% FORMAT F = spm_figure('Create',Tag,Name,Visible)
% FORMAT F = spm_figure('FindWin',Tag)
% FORMAT F = spm_figure('GetWin',Tag)
% FORMAT spm_figure('Clear',F,Tags)
% FORMAT spm_figure('Close',F)
% FORMAT spm_figure('Print',F)
% FORMAT spm_figure('WaterMark',F,str,Tag,Angle,Perm)
%
% FORMAT spm_figure('NewPage',hPage)
% FORMAT spm_figure('TurnPage',move,F)
% FORMAT spm_figure('DeletePageControls',F)
% FORMAT n = spm_figure('#page')
% FORMAT n = spm_figure('CurrentPage')
%__________________________________________________________________________
%
% spm_figure creates and manages the 'Graphics' window. This window and
% these facilities may be used independently of SPM, and any number of
% Graphics windows my be used within the same MATLAB session. (Though
% only one SPM 'Graphics' 'Tag'ed window is permitted).
%
% The Graphics window is provided with a menu bar at the top that
% facilitates editing and printing of the current graphic display.
% (This menu is also provided as a figure background "ContextMenu" -
% right-clicking on the figure background should bring up the menu).
%
% "Print": Graphics windows with multi-page axes are printed page by page.
%
% "Clear": Clears the Graphics window. If in SPM usage (figure 'Tag'ed as
% 'Graphics') then all SPM windows are cleared and reset.
%
% "Colours":
% * gray, hot, pink, jet: Sets the colormap to selected item.
% * gray-hot, etc: Creates a 'split' colormap {128 x 3 matrix}.
% The lower half is a gray scale and the upper half is selected
% colormap This colormap is used for viewing 'rendered' SPMs on a
% PET, MRI or other background images.
% Colormap effects:
% * Invert: Inverts (flips) the current color map.
% * Brighten and Darken: Brighten and Darken the current colourmap
% using the MATLAB BRIGHTEN command, with beta's of +0.2 and -0.2
% respectively.
%
% For SPM usage, the figure should be 'Tag'ed as 'Graphics'.
%
% See also: spm_print, spm_clf
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Andrew Holmes
% $Id: spm_figure.m 4405 2011-07-22 12:54:59Z guillaume $
%==========================================================================
% - FORMAT specifications for embedded CallBack functions
%==========================================================================
%
% FORMAT F = spm_figure
% [ShortCut] Defaults to Action 'Create'
%
% FORMAT F = spm_figure(F) - numeric F
% [ShortCut] Defaults to spm_figure('CreateBar',F)
%
% FORMAT F = spm_figure('Create',Tag,Name,Visible)
% Create a full length WhiteBg figure 'Tag'ed Tag (if specified),
% with a ToolBar and background context menu.
% Equivalent to spm_figure('CreateWin','Tag') and spm_figure('CreateBar')
% Tag - 'Tag' string for figure.
% Name - Name for window
% Visible - 'on' or 'off'
% F - Figure used
%
% FORMAT F = spm_figure('FindWin',F)
% Finds window with 'Tag' or figure numnber F - returns empty F if not found
% F - (Input) Figure to use [Optional] - 'Tag' string or figure number.
% - Defaults to 'Graphics'
% F - (Output) Figure number (if found) or empty (if not).
%
% FORMAT F = spm_figure('GetWin',Tag)
% Like spm_figure('FindWin',Tag), except that if no such 'Tag'ged figure
% is found and 'Tag' is recognized, one is created. Further, the "got"
% window is made current.
% Tag - Figure 'Tag' to get, defaults to 'Graphics'
% F - Figure number (if found/created) or empty (if not).
%
% FORMAT spm_figure('Clear',F,Tags)
% Clears figure, leaving ToolBar (& other objects with invisible handles)
% Optional third argument specifies 'Tag's of objects to delete.
% If figure F is 'Tag'ged 'Interactive' (SPM usage), then the window
% name and pointer are reset.
% F - 'Tag' string or figure number of figure to clear, defaults to gcf
% Tags - 'Tag's (string matrix or cell array of strings) of objects to delete
% *regardless* of 'HandleVisibility'. Only these objects are deleted.
% '!all' denotes all objects
%
% FORMAT spm_figure('Close',F)
% Closes figures (deletion without confirmation)
% Also closes the docking container if empty.
% F - 'Tag' string or figure number of figure to clear, defaults to gcf
%
% FORMAT spm_figure('Print',F)
% F - [Optional] Figure to print. ('Tag' or figure number)
% Defaults to figure 'Tag'ed as 'Graphics'.
% If none found, uses CurrentFigure if avaliable.
% If objects 'Tag'ed 'NextPage' and 'PrevPage' are found, then the
% pages are shown and printed in order. In breif, pages are held as
% seperate axes, with ony one 'Visible' at any one time. The handles of
% the "page" axes are stored in the 'UserData' of the 'NextPage'
% object, while the 'PrevPage' object holds the current page number.
% See spm_help('!Disp') for details on setting up paging axes.
%
% FORMAT [hNextPage, hPrevPage, hPageNo] = spm_figure('NewPage',hPage)
% SPM pagination function: Makes objects with handles hPage paginated
% Creates pagination buttons if necessary.
% hPage - Handles of objects to stick to this page
% hNextPage, hPrevPage, hPageNo - Handles of pagination controls
%
% FORMAT spm_figure('TurnPage',move,F)
% SPM pagination function: Turn to specified page
%
% FORMAT spm_figure('DeletePageControls',F)
% SPM pagination function: Deletes page controls
% F - [Optional] Figure in which to attempt to turn the page
% Defaults to 'Graphics' 'Tag'ged window
%
% FORMAT n = spm_figure('#page')
% Returns the current number of pages.
%
% FORMAT n = spm_figure('CurrentPage');
% Return the current page number.
%
% FORMAT spm_figure('WaterMark',F,str,Tag,Angle,Perm)
% Adds watermark to figure windows.
% F - Figure for watermark. Defaults to gcf
% str - Watermark string. Defaults (missing or empty) to SPM
% Tag - Tag for watermark axes. Defaults to ''
% Angle - Angle for watermark. Defaults to -45
% Perm - If specified, then watermark is permanent (HandleVisibility 'off')
%
% FORMAT F = spm_figure('CreateWin',Tag,Name,Visible)
% Creates a full length WhiteBg figure 'Tag'ged Tag (if specified).
% F - Figure created
% Tag - Tag for window
% Name - Name for window
% Visible - 'on' or 'off'
%
% FORMAT spm_figure('CreateBar',F)
% Creates toolbar in figure F (defaults to gcf). F can be a 'Tag'
%
% FORMAT spm_figure('ColorMap')
% Callback for "ColorMap" menu
%
% FORMAT spm_figure('FontSize')
% Callback for "FontSize" menu
%__________________________________________________________________________
%-Condition arguments
%--------------------------------------------------------------------------
if ~nargin, Action = 'Create'; else Action = varargin{1}; end
%==========================================================================
switch lower(Action), case 'create'
%==========================================================================
% F = spm_figure('Create',Tag,Name,Visible)
if nargin<4, Visible='on'; else Visible=varargin{4}; end
if nargin<3, Name=''; else Name=varargin{3}; end
if nargin<2, Tag=''; else Tag=varargin{2}; end
F = spm_figure('CreateWin',Tag,Name,Visible);
spm_figure('CreateBar',F);
spm_figure('FigContextMenu',F);
varargout = {F};
%==========================================================================
case 'findwin'
%==========================================================================
% F=spm_figure('FindWin',F)
% F=spm_figure('FindWin',Tag)
%-Find window: Find window with FigureNumber# / 'Tag' attribute
%-Returns empty if window cannot be found - deletes multiple tagged figs.
if nargin<2, F='Graphics'; else F=varargin{2}; end
if isempty(F)
% Leave F empty
elseif ischar(F)
% Finds Graphics window with 'Tag' string - delete multiples
Tag = F;
F = findall(allchild(0),'Flat','Tag',Tag);
if length(F) > 1
% Multiple Graphics windows - close all but most recent
close(F(2:end))
F = F(1);
end
else
% F is supposed to be a figure number - check it
if ~any(F==allchild(0)), F=[]; end
end
varargout = {F};
%==========================================================================
case 'getwin'
%==========================================================================
% F=spm_figure('GetWin',Tag)
%-Like spm_figure('FindWin',Tag), except that if no such 'Tag'ged figure
% is found and 'Tag' is recognized, one is created.
if nargin<2, Tag='Graphics'; else Tag=varargin{2}; end
F = spm_figure('FindWin',Tag);
if isempty(F)
if ischar(Tag)
switch Tag
case 'Graphics'
F = spm_figure('Create','Graphics','Graphics');
case 'DEM'
F = spm_figure('Create','DEM','Dynamic Expectation Maximisation');
case 'DFP'
F = spm_figure('Create','DFP','Variational filtering');
case 'FMIN'
F = spm_figure('Create','FMIN','Function minimisation');
case 'MFM'
F = spm_figure('Create','MFM','Mean-field and neural mass models');
case 'MVB'
F = spm_figure('Create','MVB','Multivariate Bayes');
case 'SI'
F = spm_figure('Create','SI','System Identification');
case 'PPI'
F = spm_figure('Create','PPI','Physio/Psycho-Physiologic Interaction');
case 'Interactive'
F = spm('CreateIntWin');
otherwise
F = spm_figure('Create',Tag,Tag);
end
end
else
set(0,'CurrentFigure',F);
figure(F);
end
varargout = {F};
%==========================================================================
case 'parentfig'
%==========================================================================
% F=spm_figure('ParentFig',h)
warning('spm_figure(''ParentFig'',h) is deprecated. Use ANCESTOR instead.');
if nargin<2, error('No object specified'), else h=varargin{2}; end
F = ancestor(h,'figure');
varargout = {F};
%==========================================================================
case 'clear'
%==========================================================================
% spm_figure('Clear',F,Tags)
%-Sort out arguments
if nargin<3, Tags=[]; else Tags=varargin{3}; end
if nargin<2, F=get(0,'CurrentFigure'); else F=varargin{2}; end
F = spm_figure('FindWin',F);
if isempty(F), return, end
%-Clear figure
isdocked = strcmp(get(F,'WindowStyle'),'docked');
if isempty(Tags)
%-Clear figure of objects with 'HandleVisibility' 'on'
pos = get(F,'Position');
delete(findall(allchild(F),'flat','HandleVisibility','on'));
drawnow
if ~isdocked, set(F,'Position',pos); end
%-Reset figures callback functions
zoom(F,'off');
rotate3d(F,'off');
set(F,'KeyPressFcn','',...
'WindowButtonDownFcn','',...
'WindowButtonMotionFcn','',...
'WindowButtonUpFcn','')
%-If this is the 'Interactive' window, reset name & UserData
if strcmp(get(F,'Tag'),'Interactive')
set(F,'Name','','UserData',[]), end
else
%-Clear specified objects from figure
if ischar(Tags); Tags=cellstr(Tags); end
if any(strcmp(Tags(:),'!all'))
delete(allchild(F))
else
for tag = Tags(:)'
delete(findall(allchild(F),'flat','Tag',tag{:}));
end
end
end
set(F,'Pointer','Arrow')
%if ~isdocked && ~spm('CmdLine'), movegui(F); end
%==========================================================================
case 'close'
%==========================================================================
% spm_figure('Close',F)
%-Sort out arguments
if nargin < 2, F = gcf; else F = varargin{2}; end
F = spm_figure('FindWin',F);
if isempty(F), return, end
%-Detect if SPM windows are in docked mode
hMenu = spm_figure('FindWin','Menu');
isdocked = strcmp(get(hMenu,'WindowStyle'),'docked');
%-Close figures (and deleted without confirmation)
delete(F);
%-If in docked mode and closing SPM, close the container as well
if isdocked && ismember(hMenu,F)
try
desktop = com.mathworks.mde.desk.MLDesktop.getInstance;
group = ['Statistical Parametric Mapping (' spm('Ver') ')'];
hContainer = desktop.getGroupContainer(group);
hContainer.getTopLevelAncestor.hide;
end
end
%==========================================================================
case 'print'
%==========================================================================
% spm_figure('Print',F,fname)
%-Arguments & defaults
if nargin<3, fname=''; else fname=varargin{3};end
if nargin<2, F='Graphics'; else F=varargin{2}; end
%-Find window to print, default to gcf if specified figure not found
% Return if no figures
if ~isempty(F), F = spm_figure('FindWin',F); end
if isempty(F), F = get(0,'CurrentFigure'); end
if isempty(F), return, end
%-Note current figure, & switch to figure to print
cF = get(0,'CurrentFigure');
set(0,'CurrentFigure',F)
%-See if window has paging controls
hNextPage = findall(F,'Tag','NextPage');
hPrevPage = findall(F,'Tag','PrevPage');
hPageNo = findall(F,'Tag','PageNo');
iPaged = ~isempty(hNextPage);
%-Temporarily change all units to normalized prior to printing
H = findall(allchild(F),'flat','Type','axes');
if ~isempty(H)
un = cellstr(get(H,'Units'));
set(H,'Units','normalized');
end
%-Print
if ~iPaged
spm_print(fname,F);
else
hPg = get(hNextPage,'UserData');
Cpage = get(hPageNo, 'UserData');
nPages = size(hPg,1);
set([hNextPage,hPrevPage,hPageNo],'Visible','off');
if Cpage~=1
set(hPg{Cpage,1},'Visible','off');
end
for p = 1:nPages
set(hPg{p,1},'Visible','on');
spm_print(fname,F);
set(hPg{p,1},'Visible','off');
end
set(hPg{Cpage,1},'Visible','on');
set([hNextPage,hPrevPage,hPageNo],'Visible','on');
end
if ~isempty(H), set(H,{'Units'},un); end
set(0,'CurrentFigure',cF);
%==========================================================================
case 'printto'
%==========================================================================
%spm_figure('PrintTo',F)
%-Arguments & defaults
if nargin<2, F='Graphics'; else F=varargin{2}; end
%-Find window to print, default to gcf if specified figure not found
% Return if no figures
F=spm_figure('FindWin',F);
if isempty(F), F = get(0,'CurrentFigure'); end
if isempty(F), return, end
[fn, pn, fi] = uiputfile({'*.ps','PostScript file (*.ps)'},'Print to File');
if isequal(fn,0) || isequal(pn,0), return, end
psname = fullfile(pn, fn);
spm_figure('Print',F,psname);
%==========================================================================
case 'newpage'
%==========================================================================
% [hNextPage, hPrevPage, hPageNo] = spm_figure('NewPage',h)
if nargin<2 || isempty(varargin{2}), error('No handles to paginate')
else h=varargin{2}(:)'; end
%-Work out which figure we're in
F = ancestor(h(1),'figure');
hNextPage = findall(F,'Tag','NextPage');
hPrevPage = findall(F,'Tag','PrevPage');
hPageNo = findall(F,'Tag','PageNo');
%-Create pagination widgets if required
%--------------------------------------------------------------------------
if isempty(hNextPage)
WS = spm('WinScale');
FS = spm('FontSizes');
SatFig = findall(0,'Tag','Satellite');
if ~isempty(SatFig)
SatFigPos = get(SatFig,'Position');
hNextPagePos = [SatFigPos(3)-25 15 15 15];
hPrevPagePos = [SatFigPos(3)-40 15 15 15];
hPageNo = [SatFigPos(3)-40 5 30 10];
else
hNextPagePos = [580 022 015 015].*WS;
hPrevPagePos = [565 022 015 015].*WS;
hPageNo = [550 005 060 015].*WS;
end
hNextPage = uicontrol(F,'Style','Pushbutton',...
'HandleVisibility','on',...
'String','>','FontSize',FS(10),...
'ToolTipString','next page',...
'Callback','spm_figure(''TurnPage'',''+1'',gcbf)',...
'Position',hNextPagePos,...
'ForegroundColor',[0 0 0],...
'Tag','NextPage','UserData',[]);
hPrevPage = uicontrol(F,'Style','Pushbutton',...
'HandleVisibility','on',...
'String','<','FontSize',FS(10),...
'ToolTipString','previous page',...
'Callback','spm_figure(''TurnPage'',''-1'',gcbf)',...
'Position',hPrevPagePos,...
'Visible','on',...
'Enable','off',...
'Tag','PrevPage');
hPageNo = uicontrol(F,'Style','Text',...
'HandleVisibility','on',...
'String','1',...
'FontSize',FS(6),...
'HorizontalAlignment','center',...
'BackgroundColor','w',...
'Position',hPageNo,...
'Visible','on',...
'UserData',1,...
'Tag','PageNo','UserData',1);
end
%-Add handles for this page to UserData of hNextPage
%-Make handles for this page invisible if PageNo>1
%--------------------------------------------------------------------------
mVis = strcmp('on',get(h,'Visible'));
mHit = strcmp('on',get(h,'HitTest'));
hPg = get(hNextPage,'UserData');
if isempty(hPg)
hPg = {h(mVis), h(~mVis), h(mHit), h(~mHit)};
else
hPg = [hPg; {h(mVis), h(~mVis), h(mHit), h(~mHit)}];
set(h(mVis),'Visible','off');
set(h(mHit),'HitTest','off');
end
set(hNextPage,'UserData',hPg)
%-Return handles to pagination controls if requested
if nargout>0, varargout = {[hNextPage, hPrevPage, hPageNo]}; end
%==========================================================================
case 'turnpage'
%==========================================================================
% spm_figure('TurnPage',move,F)
if nargin<3, F='Graphics'; else F=varargin{3}; end
if nargin<2, move=1; else move=varargin{2}; end
F = spm_figure('FindWin',F);
if isempty(F), error('No Graphics window'), end
hNextPage = findall(F,'Tag','NextPage');
hPrevPage = findall(F,'Tag','PrevPage');
hPageNo = findall(F,'Tag','PageNo');
if isempty(hNextPage), return, end
hPg = get(hNextPage,'UserData');
Cpage = get(hPageNo, 'UserData');
nPages = size(hPg,1);
%-Sort out new page number
if ischar(move), Npage = Cpage+eval(move); else Npage = move; end
Npage = max(min(Npage,nPages),1);
%-Make current page invisible, new page visible, set page number string
set(hPg{Cpage,1},'Visible','off');
set(hPg{Cpage,3},'HitTest','off');
set(hPg{Npage,1},'Visible','on');
set(hPg{Npage,3},'HitTest','on');
set(hPageNo,'UserData',Npage,'String',sprintf('%d / %d',Npage,nPages))
for k = 1:length(hPg{Npage,1})
if strcmp(get(hPg{Npage,1}(k),'Type'),'axes')
axes(hPg{Npage,1}(k));
end
end
%-Disable appropriate page turning control if on first/last page
if Npage==1, set(hPrevPage,'Enable','off')
else set(hPrevPage,'Enable','on'), end
if Npage==nPages, set(hNextPage,'Enable','off')
else set(hNextPage,'Enable','on'), end
%==========================================================================
case 'deletepagecontrols'
%==========================================================================
% spm_figure('DeletePageControls',F)
if nargin<2, F='Graphics'; else F=varargin{2}; end
F = spm_figure('FindWin',F);
if isempty(F), error('No Graphics window'), end
hNextPage = findall(F,'Tag','NextPage');
hPrevPage = findall(F,'Tag','PrevPage');
hPageNo = findall(F,'Tag','PageNo');
delete([hNextPage hPrevPage hPageNo])
%==========================================================================
case '#page'
%==========================================================================
% n = spm_figure('#Page',F)
if nargin<2, F='Graphics'; else F=varargin{2}; end
F = spm_figure('FindWin',F);
if isempty(F), error('No Graphics window'), end
hNextPage = findall(F,'Tag','NextPage');
if isempty(hNextPage)
n = 1;
else
n = size(get(hNextPage,'UserData'),1)+1;
end
varargout = {n};
%==========================================================================
case 'currentpage'
%==========================================================================
% n = spm_figure('CurrentPage', F)
if nargin<2, F='Graphics'; else F=varargin{2}; end
F = spm_figure('FindWin',F);
if isempty(F), error('No Graphics window'), end
hPageNo = findall(F,'Tag','PageNo');
Cpage = get(hPageNo, 'UserData');
varargout = {Cpage};
%==========================================================================
case 'watermark'
%==========================================================================
% spm_figure('WaterMark',F,str,Tag,Angle,Perm)
if nargin<6, HVis='on'; else HVis='off'; end
if nargin<5, Angle=-45; else Angle=varargin{5}; end
if nargin<4 || isempty(varargin{4}), Tag = 'WaterMark'; else Tag=varargin{4}; end
if nargin<3 || isempty(varargin{3}), str = 'SPM'; else str=varargin{3}; end
if nargin<2, if any(allchild(0)), F=gcf; else F=''; end
else F=varargin{2}; end
F = spm_figure('FindWin',F);
if isempty(F), return, end
%-Specify watermark color from background colour
Colour = get(F,'Color');
%-Only mess with grayscale backgrounds
if ~all(Colour==Colour(1)), return, end
%-Work out colour - lighter unless grey value > 0.9
Colour = Colour+(2*(Colour(1)<0.9)-1)*0.02;
cF = get(0,'CurrentFigure');
set(0,'CurrentFigure',F)
Units=get(F,'Units');
set(F,'Units','normalized');
h = axes('Position',[0.45,0.5,0.1,0.1],...
'Units','normalized',...
'Visible','off',...
'Tag',Tag);
set(F,'Units',Units)
text(0.5,0.5,str,...
'FontSize',spm('FontSize',80),...
'FontWeight','Bold',...
'FontName',spm_platform('Font','times'),...
'Rotation',Angle,...
'HorizontalAlignment','Center',...
'VerticalAlignment','middle',... %'EraseMode','normal',...
'Color',Colour,...
'ButtonDownFcn',[...
'if strcmp(get(gcbf,''SelectionType''),''open''),',...
'delete(get(gcbo,''Parent'')),',...
'end'])
set(h,'HandleVisibility',HVis)
set(0,'CurrentFigure',cF)
%==========================================================================
case 'createwin'
%==========================================================================
% F=spm_figure('CreateWin',Tag,Name,Visible)
if nargin<4 || isempty(varargin{4}), Visible='on'; else Visible=varargin{4}; end
if nargin<3, Name=''; else Name = varargin{3}; end
if nargin<2, Tag=''; else Tag = varargin{2}; end
FS = spm('FontSizes'); %-Scaled font sizes
PF = spm_platform('fonts'); %-Font names (for this platform)
Rect = spm('WinSize','Graphics'); %-Graphics window rectangle
S0 = spm('WinSize','0',1); %-Screen size (of the current monitor)
F = figure(...
'Tag',Tag,...
'Position',[S0(1) S0(2) 0 0] + Rect,...
'Resize','off',...
'Color','w',...
'ColorMap',gray(64),...
'DefaultTextColor','k',...
'DefaultTextInterpreter','none',...
'DefaultTextFontName',PF.helvetica,...
'DefaultTextFontSize',FS(10),...
'DefaultAxesColor','w',...
'DefaultAxesXColor','k',...
'DefaultAxesYColor','k',...
'DefaultAxesZColor','k',...
'DefaultAxesFontName',PF.helvetica,...
'DefaultPatchFaceColor','k',...
'DefaultPatchEdgeColor','k',...
'DefaultSurfaceEdgeColor','k',...
'DefaultLineColor','k',...
'DefaultUicontrolFontName',PF.helvetica,...
'DefaultUicontrolFontSize',FS(10),...
'DefaultUicontrolInterruptible','on',...
'PaperType','A4',...
'PaperUnits','normalized',...
'PaperPosition',[.0726 .0644 .854 .870],...
'InvertHardcopy','off',...
'Renderer',spm_get_defaults('renderer'),...
'Visible','off',...
'Toolbar','none');
if ~isempty(Name)
set(F,'Name',sprintf('%s%s: %s',spm('ver'),...
spm('getUser',' (%s)'),Name),'NumberTitle','off')
end
set(F,'Visible',Visible)
varargout = {F};
isdocked = strcmp(get(spm_figure('FindWin','Menu'),'WindowStyle'),'docked');
if isdocked
try
desktop = com.mathworks.mde.desk.MLDesktop.getInstance;
group = ['Statistical Parametric Mapping (' spm('Ver') ')'];
set(getJFrame(F),'GroupName',group);
set(F,'WindowStyle','docked');
end
end
%==========================================================================
case 'createbar'
%==========================================================================
% spm_figure('CreateBar',F)
if nargin<2, if any(allchild(0)), F=gcf; else F=''; end
else F=varargin{2}; end
F = spm_figure('FindWin',F);
if isempty(F), return, end
%-Help Menu
t0 = findall(allchild(F),'Flat','Label','&Help');
delete(allchild(t0)); set(t0,'Callback','');
if isempty(t0), t0 = uimenu( F,'Label','&Help'); end;
pos = get(t0,'Position');
uimenu(t0,'Label','SPM Help','CallBack','spm_help');
uimenu(t0,'Label','SPM Manual (PDF)',...
'CallBack','try,open(fullfile(spm(''dir''),''man'',''manual.pdf''));end');
t1=uimenu(t0,'Label','SPM &Web Resources');
uimenu(t1,'Label','SPM Web &Site',...
'CallBack','web(''http://www.fil.ion.ucl.ac.uk/spm/'');');
uimenu(t1,'Label','SPM &WikiBook',...
'CallBack','web(''http://en.wikibooks.org/wiki/SPM'');');
uimenu(t1,'Separator','on','Label','SPM &Extensions',...
'CallBack','web(''http://www.fil.ion.ucl.ac.uk/spm/ext/'');');
%-Check Menu
if ~isdeployed
uimenu(t0,'Separator','on','Label','SPM Check Installation',...
'CallBack','spm_check_installation(''full'')');
uimenu(t0,'Label','SPM Check for Updates',...
'CallBack','spm(''alert"'',evalc(''spm_update''),''SPM Update'');');
end
%- About Menu
uimenu(t0,'Separator','on','Label',['&About ' spm('Ver')],...
'CallBack',@spm_about);
uimenu(t0,'Label','&About MATLAB',...
'CallBack','helpmenufcn(gcbf,''HelpAbout'')');
%-Figure Menu
t0=uimenu(F, 'Position',pos, 'Label','&SPM Figure', 'HandleVisibility','off', 'Callback',@myisresults);
%-Show All Figures
uimenu(t0, 'Label','Show All &Windows', 'HandleVisibility','off',...
'CallBack','spm(''Show'');');
%-Dock SPM Figures
uimenu(t0, 'Label','&Dock SPM Windows', 'HandleVisibility','off',...
'CallBack',@mydockspm);
%-Print Menu
t1=uimenu(t0, 'Label','&Save Figure', 'HandleVisibility','off','Separator','on');
uimenu(t1, 'Label','&Default File', 'HandleVisibility','off', ...
'CallBack','spm_figure(''Print'',gcf)');
uimenu(t1, 'Label','&Specify File...', 'HandleVisibility','off', ...
'CallBack','spm_figure(''PrintTo'',spm_figure(''FindWin'',''Graphics''))');
%-Copy Figure
if ispc
uimenu(t0, 'Label','Co&py Figure', 'HandleVisibility','off',...
'CallBack','editmenufcn(gcbf,''EditCopyFigure'')');
end
%-Clear Menu
uimenu(t0, 'Label','&Clear Figure', 'HandleVisibility','off', ...
'CallBack','spm_figure(''Clear'',gcbf)');
%-Close non-SPM figures
uimenu(t0, 'Label','C&lose non-SPM Figures', 'HandleVisibility','off', ...
'CallBack',@myclosefig);
%-Colour Menu
t1=uimenu(t0, 'Label','C&olours', 'HandleVisibility','off','Separator','on');
t2=uimenu(t1, 'Label','Colormap');
uimenu(t2, 'Label','Gray', 'CallBack','spm_figure(''ColorMap'',''gray'')');
uimenu(t2, 'Label','Hot', 'CallBack','spm_figure(''ColorMap'',''hot'')');
uimenu(t2, 'Label','Pink', 'CallBack','spm_figure(''ColorMap'',''pink'')');
uimenu(t2, 'Label','Jet', 'CallBack','spm_figure(''ColorMap'',''jet'')');
uimenu(t2, 'Label','Gray-Hot', 'CallBack','spm_figure(''ColorMap'',''gray-hot'')');
uimenu(t2, 'Label','Gray-Cool', 'CallBack','spm_figure(''ColorMap'',''gray-cool'')');
uimenu(t2, 'Label','Gray-Pink', 'CallBack','spm_figure(''ColorMap'',''gray-pink'')');
uimenu(t2, 'Label','Gray-Jet', 'CallBack','spm_figure(''ColorMap'',''gray-jet'')');
t2=uimenu(t1, 'Label','Effects');
uimenu(t2, 'Label','Invert', 'CallBack','spm_figure(''ColorMap'',''invert'')');
uimenu(t2, 'Label','Brighten', 'CallBack','spm_figure(''ColorMap'',''brighten'')');
uimenu(t2, 'Label','Darken', 'CallBack','spm_figure(''ColorMap'',''darken'')');
%-Font Size Menu
t1=uimenu(t0, 'Label','&Font Size', 'HandleVisibility','off');
uimenu(t1, 'Label','&Increase', 'CallBack','spm_figure(''FontSize'',1)', 'Accelerator', '=');
uimenu(t1, 'Label','&Decrease', 'CallBack','spm_figure(''FontSize'',-1)', 'Accelerator', '-');
%-Satellite Table
uimenu(t0, 'Label','&Results Table', 'HandleVisibility','off', ...
'Separator','on', 'Callback',@mysatfig);
% Tasks Menu
%try, spm_jobman('pulldown'); end
%==========================================================================
case 'figcontextmenu'
%==========================================================================
% h = spm_figure('FigContextMenu',F)
if nargin<2
F = get(0,'CurrentFigure');
if isempty(F), error('no figure'), end
else
F = spm_figure('FindWin',varargin{2});
if isempty(F), error('no such figure'), end
end
h = uicontextmenu('Parent',F,'HandleVisibility','CallBack');
copy_menu(F,h);
set(F,'UIContextMenu',h)
varargout = {h};
%==========================================================================
case 'colormap'
%==========================================================================
% spm_figure('ColorMap',ColAction)
if nargin<2, ColAction='gray'; else ColAction=varargin{2}; end
switch lower(ColAction), case 'gray'
colormap(gray(64))
case 'hot'
colormap(hot(64))
case 'pink'
colormap(pink(64))
case 'jet'
colormap(jet(64))
case 'gray-hot'
tmp = hot(64 + 16); tmp = tmp((1:64) + 16,:);
colormap([gray(64); tmp]);
case 'gray-cool'
cool = [zeros(10,1) zeros(10,1) linspace(0.5,1,10)';
zeros(31,1) linspace(0,1,31)' ones(31,1);
linspace(0,1,23)' ones(23,1) ones(23,1) ];
colormap([gray(64); cool]);
case 'gray-pink'
tmp = pink(64 + 16); tmp = tmp((1:64) + 16,:);
colormap([gray(64); tmp]);
case 'gray-jet'
colormap([gray(64); jet(64)]);
case 'invert'
colormap(flipud(colormap));
case 'brighten'
colormap(brighten(colormap, 0.2));
case 'darken'
colormap(brighten(colormap, -0.2));
otherwise
error('Illegal ColAction specification');
end
%==========================================================================
case 'fontsize'
%==========================================================================
% spm_figure('FontSize',sz)
if nargin<2, sz=0; else sz=varargin{2}; end
h = [get(0,'CurrentFigure') spm_figure('FindWin','Satellite')];
h = [findall(h,'type','text'); findall(h,'type','uicontrol')];
fs = get(h,'fontsize');
if ~isempty(fs)
set(h,{'fontsize'},cellfun(@(x) max(x+sz,eps),fs,'UniformOutput',false));
end
%==========================================================================
otherwise
%==========================================================================
warning(['Illegal Action string: ',Action])
end
return;
%==========================================================================
function myisresults(obj,evt)
%==========================================================================
hr = findall(obj,'Label','&Results Table');
try
evalin('base','xSPM;');
set(hr,'Enable','on');
catch
set(hr,'Enable','off');
end
SatWindow = spm_figure('FindWin','Satellite');
if ~isempty(SatWindow)
set(hr,'Checked','on');
else
set(hr,'Checked','off');
end
%==========================================================================
function mysatfig(obj,evt)
%==========================================================================
SatWindow = spm_figure('FindWin','Satellite');
if ~isempty(SatWindow)
figure(SatWindow)
else
FS = spm('FontSizes'); %-Scaled font sizes
PF = spm_platform('fonts'); %-Font names
WS = spm('WinSize','0','raw'); %-Screen size (of current monitor)
Rect = [WS(1)+5 WS(4)*.40 WS(3)*.49 WS(4)*.57];
figure(...
'Tag','Satellite',...
'Position',Rect,...
'Resize','off',...
'MenuBar','none',...
'Name','SPM: Satellite Results Table',...
'Numbertitle','off',...
'Color','w',...
'ColorMap',gray(64),...
'DefaultTextColor','k',...
'DefaultTextInterpreter','none',...
'DefaultTextFontName',PF.helvetica,...
'DefaultTextFontSize',FS(10),...
'DefaultAxesColor','w',...
'DefaultAxesXColor','k',...
'DefaultAxesYColor','k',...
'DefaultAxesZColor','k',...
'DefaultAxesFontName',PF.helvetica,...
'DefaultPatchFaceColor','k',...
'DefaultPatchEdgeColor','k',...
'DefaultSurfaceEdgeColor','k',...
'DefaultLineColor','k',...
'DefaultUicontrolFontName',PF.helvetica,...
'DefaultUicontrolFontSize',FS(10),...
'DefaultUicontrolInterruptible','on',...
'PaperType','A4',...
'PaperUnits','normalized',...
'PaperPosition',[.0726 .0644 .854 .870],...
'InvertHardcopy','off',...
'Renderer',spm_get_defaults('renderer'),...
'Visible','on');
end
%==========================================================================
function mydockspm(obj,evt)
%==========================================================================
% Largely inspired by setFigDockGroup from Yair Altman
% http://www.mathworks.com/matlabcentral/fileexchange/16650
hMenu = spm_figure('FindWin','Menu');
hInt = spm_figure('FindWin','Interactive');
hGra = spm_figure('FindWin','Graphics');
h = [hMenu hInt hGra];
group = ['Statistical Parametric Mapping (' spm('Ver') ')'];
try
desktop = com.mathworks.mde.desk.MLDesktop.getInstance;
if ~ismember(group,cell(desktop.getGroupTitles))
desktop.addGroup(group);
end
for i=1:length(h)
set(getJFrame(h(i)),'GroupName',group);
end
hContainer = desktop.getGroupContainer(group);
set(hContainer,'userdata',group);
end
set(h,'WindowStyle','docked');
try, pause(0.5), desktop.setGroupDocked(group,false); end
%==========================================================================
function myclosefig(obj,evt)
%==========================================================================
hMenu = spm_figure('FindWin','Menu');
hInt = spm_figure('FindWin','Interactive');
hGra = spm_figure('FindWin','Graphics');
h = setdiff(findobj(get(0,'children'),'flat','visible','on'), ...
[hMenu hInt hGra gcf]);
close(h,'force');
%==========================================================================
function copy_menu(F,G)
%==========================================================================
handles = findall(allchild(F),'Flat','Type','uimenu','Visible','on');
if isempty(handles), return; end;
for F1=handles(:)'
if ~ismember(get(F1,'Label'),{'&Window' '&Desktop'})
G1 = uimenu(G,'Label',get(F1,'Label'),...
'CallBack',get(F1,'CallBack'),...
'Position',get(F1,'Position'),...
'Separator',get(F1,'Separator'));
copy_menu(F1,G1);
end
end
%==========================================================================
function jframe = getJFrame(h)
%==========================================================================
warning('off','MATLAB:HandleGraphics:ObsoletedProperty:JavaFrame');
hhFig = handle(h);
jframe = [];
maxTries = 16;
while maxTries > 0
try
jframe = get(hhFig,'javaframe');
if ~isempty(jframe)
break;
else
maxTries = maxTries - 1;
drawnow; pause(0.1);
end
catch
maxTries = maxTries - 1;
drawnow; pause(0.1);
end
end
if isempty(jframe)
error('Cannot retrieve the java frame from handle.');
end
%==========================================================================
function spm_about(obj,evt)
%==========================================================================
[v,r] = spm('Ver');
h = figure('MenuBar','none',...
'NumberTitle','off',...
'Name',['About ' v],...
'Resize','off',...
'Toolbar','none',...
'Tag','AboutSPM',...
'WindowStyle','Modal',...
'Color',[0 0 0],...
'Visible','off',...
'DoubleBuffer','on');
pos = get(h,'Position');
pos([3 4]) = [300 400];
set(h,'Position',pos);
set(h,'Visible','on');
a = axes('Parent',h, 'Units','pixels', 'Position',[50 201 200 200],...
'Visible','off');
IMG = imread(fullfile(spm('Dir'),'man','images','spm8.png'));
image(IMG,'Parent',a); set(a,'Visible','off');
a = axes('Parent',h,'Units','pixels','Position',[0 0 300 400],...
'Visible','off','Tag','textcont');
text(0.5,0.45,'Statistical Parametric Mapping','Parent',a,...
'HorizontalAlignment','center','Color',[1 1 1],'FontWeight','Bold');
text(0.5,0.40,[v ' (v' r ')'],'Parent',a,'HorizontalAlignment','center',...
'Color',[1 1 1]);
text(0.5,0.30,'Wellcome Trust Centre for Neuroimaging','Parent',a,...
'HorizontalAlignment','center','Color',[1 1 1],'FontWeight','Bold');
text(0.5,0.25,['Copyright (C) 1991,1994-' datestr(now,'yyyy')],...
'Parent',a,'HorizontalAlignment','center','Color',[1 1 1]);
text(0.5,0.20,'http://www.fil.ion.ucl.ac.uk/spm/','Parent',a,...
'HorizontalAlignment','center','Color',[1 1 1],...
'ButtonDownFcn','web(''http://www.fil.ion.ucl.ac.uk/spm/'');');
uicontrol('Style','pushbutton','String','Credits','Position',[40 25 60 25],...
'Callback',@myscroll,'BusyAction','Cancel');
uicontrol('Style','pushbutton','String','OK','Position',[200 25 60 25],...
'Callback','close(gcf)','BusyAction','Cancel');
%==========================================================================
function myscroll(obj,evt)
%==========================================================================
ax = findobj(gcf,'Tag','textcont');
cla(ax);
[current, previous] = spm_authors;
authors = {['*' spm('Ver') '*'] current{:} '' ...
'*Previous versions*' previous{:} '' ...
'*Thanks to the SPM community*'};
x = 0.2;
h = [];
for i=1:numel(authors)
h(i) = text(0.5,x,authors{i},'Parent',ax,...
'HorizontalAlignment','center','Color',col(x));
if any(authors{i} == '*')
set(h(i),'String',strrep(authors{i},'*',''),'FontWeight','Bold');
end
x = x - 0.05;
end
pause(0.5);
try
for j=1:fix((0.5-(0.2-numel(authors)*0.05))/0.01)
for i=1:numel(h)
p = get(h(i),'Position');
p2 = p(2)+0.01;
set(h(i),'Position',[p(1) p2 p(3)],'Color',col(p2));
if p2 > 0.5, set(h(i),'Visible','off'); end
end
pause(0.1)
end
end
%==========================================================================
function c = col(x)
%==========================================================================
if x < 0.4 && x > 0.3
c = [1 1 1];
elseif x <= 0.3
c = [1 1 1] - 6*abs(0.3-x);
else
c = [1 1 1] - 6*abs(0.4-x);
end
c(c<0) = 0; c(c>1) = 1;
|
github
|
philippboehmsturm/antx-master
|
spm_P_RF.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_P_RF.m
| 6,258 |
utf_8
|
12cabbf3a8ca0c5e43a3fd4025db3e69
|
function [P,p,Ec,Ek] = spm_P_RF(c,k,Z,df,STAT,R,n)
% Returns the [un]corrected P value using unifed EC theory
% FORMAT [P p Ec Ek] = spm_P_RF(c,k,z,df,STAT,R,n)
%
% c - cluster number
% k - extent {RESELS}
% z - height {minimum over n values}
% df - [df{interest} df{error}]
% STAT - Statistical field
% 'Z' - Gaussian field
% 'T' - T - field
% 'X' - Chi squared field
% 'F' - F - field
% R - RESEL Count {defining search volume}
% n - number of component SPMs in conjunction
%
% P - corrected P value - P(C >= c | K >= k}
% p - uncorrected P value
% Ec - expected number of clusters (maxima)
% Ek - expected number of resels per cluster
%
%__________________________________________________________________________
%
% spm_P_RF returns the probability of c or more clusters with more than
% k resels in volume process of R RESELS thresholded at u. All p values
% can be considered special cases:
%
% spm_P_RF(1,0,z,df,STAT,1,n) = uncorrected p value
% spm_P_RF(1,0,z,df,STAT,R,n) = corrected p value {based on height z)
% spm_P_RF(1,k,u,df,STAT,R,n) = corrected p value {based on extent k at u)
% spm_P_RF(c,k,u,df,STAT,R,n) = corrected p value {based on number c at k and u)
% spm_P_RF(c,0,u,df,STAT,R,n) = omnibus p value {based on number c at u)
%
% If n > 1 a conjunction probility over the n values of the statistic
% is returned
%__________________________________________________________________________
%
% References:
%
% [1] Hasofer AM (1978) Upcrossings of random fields
% Suppl Adv Appl Prob 10:14-21
% [2] Friston KJ et al (1994) Assessing the Significance of Focal Activations
% Using Their Spatial Extent
% Human Brain Mapping 1:210-220
% [3] Worsley KJ et al (1996) A Unified Statistical Approach for Determining
% Significant Signals in Images of Cerebral Activation
% Human Brain Mapping 4:58-73
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Karl Friston
% $Id: spm_P_RF.m 4225 2011-03-02 15:53:05Z guillaume $
% get expectations
%==========================================================================
% get EC densities
%--------------------------------------------------------------------------
D = find(R,1,'last');
R = R(1:D);
G = sqrt(pi)./gamma(([1:D])/2);
EC = spm_ECdensity(STAT,Z,df);
EC = max(EC(1:D),eps);
% corrected p value
%--------------------------------------------------------------------------
P = triu(toeplitz(EC'.*G))^n;
P = P(1,:);
EM = (R./G).*P; % <maxima> over D dimensions
Ec = sum(EM); % <maxima>
EN = P(1)*R(D); % <resels>
Ek = EN/EM(D); % Ek = EN/EM(D);
% get P{n > k}
%==========================================================================
% assume a Gaussian form for P{n > k} ~ exp(-beta*k^(2/D))
% Appropriate for SPM{Z} and high d.f. SPM{T}
%--------------------------------------------------------------------------
D = D - 1;
if ~k || ~D
p = 1;
elseif STAT == 'Z'
beta = (gamma(D/2 + 1)/Ek)^(2/D);
p = exp(-beta*(k^(2/D)));
elseif STAT == 'T'
beta = (gamma(D/2 + 1)/Ek)^(2/D);
p = exp(-beta*(k^(2/D)));
elseif STAT == 'X'
beta = (gamma(D/2 + 1)/Ek)^(2/D);
p = exp(-beta*(k^(2/D)));
elseif STAT == 'F'
beta = (gamma(D/2 + 1)/Ek)^(2/D);
p = exp(-beta*(k^(2/D)));
end
% Poisson clumping heuristic {for multiple clusters}
%==========================================================================
P = 1 - spm_Pcdf(c - 1,(Ec + eps)*p);
% set P and p = [] for non-implemented cases
%++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
if k > 0 && (STAT == 'X' || STAT == 'F')
P = []; p = [];
end
%++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
%==========================================================================
% spm_ECdensity
%==========================================================================
function [EC] = spm_ECdensity(STAT,t,df)
% Returns the EC density
%__________________________________________________________________________
%
% Reference : Worsley KJ et al 1996, Hum Brain Mapp. 4:58-73
%
%--------------------------------------------------------------------------
% EC densities (EC}
%--------------------------------------------------------------------------
t = t(:)';
if STAT == 'Z'
% Gaussian Field
%----------------------------------------------------------------------
a = 4*log(2);
b = exp(-t.^2/2);
EC(1,:) = 1 - spm_Ncdf(t);
EC(2,:) = a^(1/2)/(2*pi)*b;
EC(3,:) = a/((2*pi)^(3/2))*b.*t;
EC(4,:) = a^(3/2)/((2*pi)^2)*b.*(t.^2 - 1);
elseif STAT == 'T'
% T - Field
%----------------------------------------------------------------------
v = df(2);
a = 4*log(2);
b = exp(gammaln((v+1)/2) - gammaln(v/2));
c = (1+t.^2/v).^((1-v)/2);
EC(1,:) = 1 - spm_Tcdf(t,v);
EC(2,:) = a^(1/2)/(2*pi)*c;
EC(3,:) = a/((2*pi)^(3/2))*c.*t/((v/2)^(1/2))*b;
EC(4,:) = a^(3/2)/((2*pi)^2)*c.*((v-1)*(t.^2)/v - 1);
elseif STAT == 'X'
% X - Field
%----------------------------------------------------------------------
v = df(2);
a = (4*log(2))/(2*pi);
b = t.^(1/2*(v - 1)).*exp(-t/2-gammaln(v/2))/2^((v-2)/2);
EC(1,:) = 1 - spm_Xcdf(t,v);
EC(2,:) = a^(1/2)*b;
EC(3,:) = a*b.*(t-(v-1));
EC(4,:) = a^(3/2)*b.*(t.^2-(2*v-1)*t+(v-1)*(v-2));
elseif STAT == 'F'
% F Field
%----------------------------------------------------------------------
k = df(1);
v = df(2);
a = (4*log(2))/(2*pi);
b = gammaln(v/2) + gammaln(k/2);
EC(1,:) = 1 - spm_Fcdf(t,df);
EC(2,:) = a^(1/2)*exp(gammaln((v+k-1)/2)-b)*2^(1/2)...
*(k*t/v).^(1/2*(k-1)).*(1+k*t/v).^(-1/2*(v+k-2));
EC(3,:) = a*exp(gammaln((v+k-2)/2)-b)*(k*t/v).^(1/2*(k-2))...
.*(1+k*t/v).^(-1/2*(v+k-2)).*((v-1)*k*t/v-(k-1));
EC(4,:) = a^(3/2)*exp(gammaln((v+k-3)/2)-b)...
*2^(-1/2)*(k*t/v).^(1/2*(k-3)).*(1+k*t/v).^(-1/2*(v+k-2))...
.*((v-1)*(v-2)*(k*t/v).^2-(2*v*k-v-k-1)*(k*t/v)+(k-1)*(k-2));
end
|
github
|
philippboehmsturm/antx-master
|
spm_dicom_headers.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_dicom_headers.m
| 20,594 |
utf_8
|
1383d5701aed00742ecf464bb28923b6
|
function hdr = spm_dicom_headers(P, essentials)
% Read header information from DICOM files
% FORMAT hdr = spm_dicom_headers(P [,essentials])
% P - array of filenames
% essentials - if true, then only save the essential parts of the header
% hdr - cell array of headers, one element for each file.
%
% Contents of headers are approximately explained in:
% http://medical.nema.org/dicom/2001.html
%
% This code will not work for all cases of DICOM data, as DICOM is an
% extremely complicated "standard".
%
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_dicom_headers.m 4334 2011-05-31 16:39:53Z john $
if nargin<2, essentials = false; end
dict = readdict;
j = 0;
hdr = {};
if size(P,1)>1, spm_progress_bar('Init',size(P,1),'Reading DICOM headers','Files complete'); end;
for i=1:size(P,1),
tmp = readdicomfile(P(i,:),dict);
if ~isempty(tmp),
if essentials, tmp = spm_dicom_essentials(tmp); end
j = j + 1;
hdr{j} = tmp;
end;
if size(P,1)>1, spm_progress_bar('Set',i); end;
end;
if size(P,1)>1, spm_progress_bar('Clear'); end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function ret = readdicomfile(P,dict)
ret = [];
P = deblank(P);
fp = fopen(P,'r','ieee-le');
if fp==-1, warning(['Cant open "' P '".']); return; end;
fseek(fp,128,'bof');
dcm = char(fread(fp,4,'uint8')');
if ~strcmp(dcm,'DICM'),
% Try truncated DICOM file fomat
fseek(fp,0,'bof');
tag.group = fread(fp,1,'ushort');
tag.element = fread(fp,1,'ushort');
if isempty(tag.group) || isempty(tag.element),
fclose(fp);
warning('Truncated file "%s"',P);
return;
end;
%t = dict.tags(tag.group+1,tag.element+1);
if isempty(find(dict.group==tag.group & dict.element==tag.element,1)) && ~(tag.group==8 && tag.element==0),
% entry not found in DICOM dict and not from a GE Twin+excite
% that starts with with an 8/0 tag that I can't find any
% documentation for.
fclose(fp);
warning(['"' P '" is not a DICOM file.']);
return;
else
fseek(fp,0,'bof');
end;
end;
try
ret = read_dicom(fp, 'il',dict);
ret.Filename = fopen(fp);
catch
fprintf('Trouble reading DICOM file %s, skipping.\n', fopen(fp));
l = lasterror;
disp(l.message);
end
fclose(fp);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [ret,len] = read_dicom(fp, flg, dict,lim)
if nargin<4, lim=Inf; end;
%if lim==2^32-1, lim=Inf; end;
len = 0;
ret = [];
tag = read_tag(fp,flg,dict);
while ~isempty(tag) && ~(tag.group==65534 && tag.element==57357), % && tag.length==0),
%fprintf('%.4x/%.4x %d\n', tag.group, tag.element, tag.length);
if tag.length>0,
switch tag.name,
case {'GroupLength'},
% Ignore it
fseek(fp,tag.length,'cof');
case {'PixelData'},
ret.StartOfPixelData = ftell(fp);
ret.SizeOfPixelData = tag.length;
ret.VROfPixelData = tag.vr;
fseek(fp,tag.length,'cof');
case {'CSAData'}, % raw data
ret.StartOfCSAData = ftell(fp);
ret.SizeOfCSAData = tag.length;
fseek(fp,tag.length,'cof');
case {'CSAImageHeaderInfo', 'CSASeriesHeaderInfo','Private_0029_1110','Private_0029_1120','Private_0029_1210','Private_0029_1220'},
dat = decode_csa(fp,tag.length);
ret.(tag.name) = dat;
case {'TransferSyntaxUID'},
dat = char(fread(fp,tag.length,'uint8')');
dat = deblank(dat);
ret.(tag.name) = dat;
switch dat,
case {'1.2.840.10008.1.2'}, % Implicit VR Little Endian
flg = 'il';
case {'1.2.840.10008.1.2.1'}, % Explicit VR Little Endian
flg = 'el';
case {'1.2.840.10008.1.2.1.99'}, % Deflated Explicit VR Little Endian
warning(['Cant read Deflated Explicit VR Little Endian file "' fopen(fp) '".']);
flg = 'dl';
return;
case {'1.2.840.10008.1.2.2'}, % Explicit VR Big Endian
%warning(['Cant read Explicit VR Big Endian file "' fopen(fp) '".']);
flg = 'eb'; % Unused
case {'1.2.840.10008.1.2.4.50','1.2.840.10008.1.2.4.51','1.2.840.10008.1.2.4.70',...
'1.2.840.10008.1.2.4.80','1.2.840.10008.1.2.4.90','1.2.840.10008.1.2.4.91'}, % JPEG Explicit VR
flg = 'el';
%warning(['Cant read JPEG Encoded file "' fopen(fp) '".']);
otherwise,
flg = 'el';
warning(['Unknown Transfer Syntax UID for "' fopen(fp) '".']);
return;
end;
otherwise,
switch tag.vr,
case {'UN'},
% Unknown - read as char
dat = fread(fp,tag.length,'uint8')';
case {'AE', 'AS', 'CS', 'DA', 'DS', 'DT', 'IS', 'LO', 'LT',...
'PN', 'SH', 'ST', 'TM', 'UI', 'UT'},
% Character strings
dat = char(fread(fp,tag.length,'uint8')');
switch tag.vr,
case {'UI','ST'},
dat = deblank(dat);
case {'DS'},
try
dat = textscan(dat,'%f','delimiter','\\')';
dat = dat{1};
catch
dat = textscan(dat,'%f','delimiter','/')';
dat = dat{1};
end
case {'IS'},
dat = textscan(dat,'%d','delimiter','\\')';
dat = double(dat{1});
case {'DA'},
dat = strrep(dat,'.',' ');
dat = textscan(dat,'%4d%2d%2d');
[y,m,d] = deal(dat{:});
dat = datenum(double(y),double(m),double(d));
case {'TM'},
if any(dat==':'),
dat = textscan(dat,'%d:%d:%f');
[h,m,s] = deal(dat{:});
h = double(h);
m = double(m);
else
dat = textscan(dat,'%2d%2d%f');
[h,m,s] = deal(dat{:});
h = double(h);
m = double(m);
end
if isempty(h), h = 0; end;
if isempty(m), m = 0; end;
if isempty(s), s = 0; end;
dat = s+60*(m+60*h);
case {'LO'},
dat = uscore_subst(dat);
otherwise,
end;
case {'OB'},
% dont know if this should be signed or unsigned
dat = fread(fp,tag.length,'uint8')';
case {'US', 'AT', 'OW'},
dat = fread(fp,tag.length/2,'uint16')';
case {'SS'},
dat = fread(fp,tag.length/2,'int16')';
case {'UL'},
dat = fread(fp,tag.length/4,'uint32')';
case {'SL'},
dat = fread(fp,tag.length/4,'int32')';
case {'FL'},
dat = fread(fp,tag.length/4,'float')';
case {'FD'},
dat = fread(fp,tag.length/8,'double')';
case {'SQ'},
[dat,len1] = read_sq(fp, flg,dict,tag.length);
tag.length = len1;
otherwise,
dat = '';
if tag.length
fseek(fp,tag.length,'cof');
warning(['Unknown VR [' num2str(tag.vr+0) '] in "'...
fopen(fp) '" (offset=' num2str(ftell(fp)) ').']);
end
end;
if ~isempty(tag.name),
ret.(tag.name) = dat;
end;
end;
end;
len = len + tag.le + tag.length;
if len>=lim, return; end;
tag = read_tag(fp,flg,dict);
end;
if ~isempty(tag),
len = len + tag.le;
% I can't find this bit in the DICOM standard, but it seems to
% be needed for Philips Integra
if tag.group==65534 && tag.element==57357 && tag.length~=0,
fseek(fp,-4,'cof');
len = len-4;
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [ret,len] = read_sq(fp, flg, dict,lim)
ret = {};
n = 0;
len = 0;
while len<lim,
tag.group = fread(fp,1,'ushort');
tag.element = fread(fp,1,'ushort');
tag.length = fread(fp,1,'uint');
if isempty(tag.length), return; end;
%if tag.length == 2^32-1, % FFFFFFFF
%tag.length = Inf;
%end;
if tag.length==13, tag.length=10; end;
len = len + 8;
if (tag.group == 65534) && (tag.element == 57344), % FFFE/E000
[Item,len1] = read_dicom(fp, flg, dict, tag.length);
len = len + len1;
if ~isempty(Item)
n = n + 1;
ret{n} = Item;
else
end
elseif (tag.group == 65279) && (tag.element == 224), % FEFF/00E0
% Byte-swapped
[fname,perm,fmt] = fopen(fp);
flg1 = flg;
if flg(2)=='b',
flg1(2) = 'l';
else
flg1(2) = 'b';
end;
[Item,len1] = read_dicom(fp, flg1, dict, tag.length);
len = len + len1;
n = n + 1;
ret{n} = Item;
pos = ftell(fp);
fclose(fp);
fp = fopen(fname,perm,fmt);
fseek(fp,pos,'bof');
elseif (tag.group == 65534) && (tag.element == 57565), % FFFE/E0DD
break;
elseif (tag.group == 65279) && (tag.element == 56800), % FEFF/DDE0
% Byte-swapped
break;
else
warning([num2str(tag.group) '/' num2str(tag.element) ' unexpected.']);
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function tag = read_tag(fp,flg,dict)
tag.group = fread(fp,1,'ushort');
tag.element = fread(fp,1,'ushort');
if isempty(tag.element), tag=[]; return; end;
if tag.group == 2, flg = 'el'; end;
%t = dict.tags(tag.group+1,tag.element+1);
t = find(dict.group==tag.group & dict.element==tag.element);
if t>0,
tag.name = dict.values(t).name;
tag.vr = dict.values(t).vr{1};
else
% Set tag.name = '' in order to restrict the fields to those
% in the dictionary. With a reduced dictionary, this could
% speed things up considerably.
% tag.name = '';
tag.name = sprintf('Private_%.4x_%.4x',tag.group,tag.element);
tag.vr = 'UN';
end;
if flg(2) == 'b',
[fname,perm,fmt] = fopen(fp);
if strcmp(fmt,'ieee-le') || strcmp(fmt,'ieee-le.l64'),
pos = ftell(fp);
fclose(fp);
fp = fopen(fname,perm,'ieee-be');
fseek(fp,pos,'bof');
end;
end;
if flg(1) =='e',
tag.vr = char(fread(fp,2,'uint8')');
tag.le = 6;
switch tag.vr,
case {'OB','OW','SQ','UN','UT'}
if ~strcmp(tag.vr,'UN') || tag.group~=65534,
fseek(fp,2,0);
end;
tag.length = double(fread(fp,1,'uint'));
tag.le = tag.le + 6;
case {'AE','AS','AT','CS','DA','DS','DT','FD','FL','IS','LO','LT','PN','SH','SL','SS','ST','TM','UI','UL','US'},
tag.length = double(fread(fp,1,'ushort'));
tag.le = tag.le + 2;
case char([0 0])
if (tag.group == 65534) && (tag.element == 57357)
% at least on GE, ItemDeliminationItem does not have a
% VR, but 4 bytes zeroes as length
tag.vr = 'UN';
tag.le = 8;
tag.length = 0;
tmp = fread(fp,1,'ushort');
elseif (tag.group == 65534) && (tag.element == 57565)
% SequenceDelimitationItem - NOT ENTIRELY HAPPY WITH THIS
double(fread(fp,1,'uint'));
tag.vr = 'UN';
tag.length = 0;
tag.le = tag.le + 6;
else
warning('Don''t know how to handle VR of ''\0\0''');
end;
otherwise,
fseek(fp,2,0);
tag.length = double(fread(fp,1,'uint'));
tag.le = tag.le + 6;
end;
else
tag.le = 8;
tag.length = double(fread(fp,1,'uint'));
end;
if isempty(tag.vr) || isempty(tag.length),
tag = [];
return;
end;
if rem(tag.length,2),
if tag.length==4294967295,
tag.length = Inf;
return;
elseif tag.length==13,
% disp(['Whichever manufacturer created "' fopen(fp) '" is taking the p***!']);
% For some bizarre reason, known only to themselves, they confuse lengths of
% 13 with lengths of 10.
tag.length = 10;
else
warning(['Unknown odd numbered Value Length (' sprintf('%x',tag.length) ') in "' fopen(fp) '".']);
tag = [];
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function dict = readdict(P)
if nargin<1, P = 'spm_dicom_dict.mat'; end;
try
dict = load(P);
catch
fprintf('\nUnable to load the file "%s".\n', P);
rethrow(lasterror);
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function dict = readdict_txt
fid = fopen('spm_dicom_dict.txt','rt');
file = textscan(fid,'%s','delimiter','\n','whitespace',''); file = file{1};
fclose(fid);
clear values
i = 0;
for i0=1:length(file),
words = textscan(file{i0},'%s','delimiter','\t'); words = words{1};
if length(words)>=5 && ~strcmp(words{1}(3:4),'xx'),
grp = sscanf(words{1},'%x');
ele = sscanf(words{2},'%x');
if ~isempty(grp) && ~isempty(ele),
i = i + 1;
group(i) = grp;
element(i) = ele;
vr = {};
for j=1:length(words{4})/2,
vr{j} = words{4}(2*(j-1)+1:2*(j-1)+2);
end;
name = words{3};
msk = ~(name>='a' & name<='z') & ~(name>='A' & name<='Z') &...
~(name>='0' & name<='9') & ~(name=='_');
name(msk) = '';
values(i) = struct('name',name,'vr',{vr},'vm',words{5});
end;
end;
end;
tags = sparse(group+1,element+1,1:length(group));
dict = struct('values',values,'tags',tags);
dict = desparsify(dict);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function dict = desparsify(dict)
[group,element] = find(dict.tags);
offs = zeros(size(group));
for k=1:length(group),
offs(k) = dict.tags(group(k),element(k));
end;
dict.group(offs) = group-1;
dict.element(offs) = element-1;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function t = decode_csa(fp,lim)
% Decode shadow information (0029,1010) and (0029,1020)
[fname,perm,fmt] = fopen(fp);
pos = ftell(fp);
if strcmp(fmt,'ieee-be') || strcmp(fmt,'ieee-be.l64'),
fclose(fp);
fp = fopen(fname,perm,'ieee-le');
fseek(fp,pos,'bof');
end;
c = fread(fp,4,'uint8');
fseek(fp,pos,'bof');
if all(c'==[83 86 49 48]), % "SV10"
t = decode_csa2(fp,lim);
else
t = decode_csa1(fp,lim);
end;
if strcmp(fmt,'ieee-be') || strcmp(fmt,'ieee-be.l64'),
fclose(fp);
fp = fopen(fname,perm,fmt);
end;
fseek(fp,pos+lim,'bof');
return;
%_______________________________________________________________________
%_______________________________________________________________________
function t = decode_csa1(fp,lim)
n = fread(fp,1,'uint32');
if isempty(n) || n>1024 || n <= 0,
fseek(fp,lim-4,'cof');
t = struct('name','JUNK: Don''t know how to read this damned file format');
return;
end;
unused = fread(fp,1,'uint32')'; % Unused "M" or 77 for some reason
tot = 2*4;
for i=1:n,
t(i).name = fread(fp,64,'uint8')';
msk = find(~t(i).name)-1;
if ~isempty(msk),
t(i).name = char(t(i).name(1:msk(1)));
else
t(i).name = char(t(i).name);
end;
t(i).vm = fread(fp,1,'int32')';
t(i).vr = fread(fp,4,'uint8')';
t(i).vr = char(t(i).vr(1:3));
t(i).syngodt = fread(fp,1,'int32')';
t(i).nitems = fread(fp,1,'int32')';
t(i).xx = fread(fp,1,'int32')'; % 77 or 205
tot = tot + 64+4+4+4+4+4;
for j=1:t(i).nitems
% This bit is just wierd
t(i).item(j).xx = fread(fp,4,'int32')'; % [x x 77 x]
len = t(i).item(j).xx(1)-t(1).nitems;
if len<0 || len+tot+4*4>lim,
t(i).item(j).val = '';
tot = tot + 4*4;
break;
end;
t(i).item(j).val = char(fread(fp,len,'uint8')');
fread(fp,4-rem(len,4),'uint8');
tot = tot + 4*4+len+(4-rem(len,4));
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function t = decode_csa2(fp,lim)
unused1 = fread(fp,4,'uint8'); % Unused
unused2 = fread(fp,4,'uint8'); % Unused
n = fread(fp,1,'uint32');
opos = ftell(fp);
if isempty(n) || n>1024 || n < 0,
fseek(fp,lim-4,'cof');
t = struct('name','Don''t know how to read this damned file format');
return;
end;
unused = fread(fp,1,'uint32')'; % Unused "M" or 77 for some reason
pos = 16;
for i=1:n,
t(i).name = fread(fp,64,'uint8')';
pos = pos + 64;
msk = find(~t(i).name)-1;
if ~isempty(msk),
t(i).name = char(t(i).name(1:msk(1)));
else
t(i).name = char(t(i).name);
end;
t(i).vm = fread(fp,1,'int32')';
t(i).vr = fread(fp,4,'uint8')';
t(i).vr = char(t(i).vr(1:3));
t(i).syngodt = fread(fp,1,'int32')';
t(i).nitems = fread(fp,1,'int32')';
t(i).xx = fread(fp,1,'int32')'; % 77 or 205
pos = pos + 20;
for j=1:t(i).nitems
t(i).item(j).xx = fread(fp,4,'int32')'; % [x x 77 x]
pos = pos + 16;
len = t(i).item(j).xx(2);
if len>lim-pos,
len = lim-pos;
t(i).item(j).val = char(fread(fp,len,'uint8')');
fread(fp,rem(4-rem(len,4),4),'uint8');
warning('Problem reading Siemens CSA field');
return;
end
t(i).item(j).val = char(fread(fp,len,'uint8')');
fread(fp,rem(4-rem(len,4),4),'uint8');
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function str_out = uscore_subst(str_in)
str_out = str_in;
pos = strfind(str_in,'+AF8-');
if ~isempty(pos),
str_out(pos) = '_';
str_out(repmat(pos,4,1)+repmat((1:4)',1,numel(pos))) = [];
end
return;
%_______________________________________________________________________
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_inv_mesh_spherify.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_eeg_inv_mesh_spherify.m
| 5,338 |
utf_8
|
95d0130b96a9bec003e301440cfd4caa
|
function [pnt, tri] = spm_eeg_inv_mesh_spherify(pnt, tri, varargin)
% Takes a cortical mesh and scales it so that it fits into a
% unit sphere.
%
% This function determines the points of the original mesh that support a
% convex hull and determines the radius of those points. Subsequently the
% radius of the support points is interpolated onto all vertices of the
% original mesh, and the vertices of the original mesh are scaled by
% dividing them by this interpolated radius.
%
% Use as
% [pnt, tri] = mesh_spherify(pnt, tri, ...)
%
% Optional arguments should come as key-value pairs and may include
% shift = 'no', mean', 'range'
% smooth = number (default = 20)
% Copyright (C) 2008, Robert Oostenveld
%
% $Log: mesh_spherify.m,v $
% Revision 1.1 2008/12/18 16:14:08 roboos
% new implementation
%
% $Id: spm_eeg_inv_mesh_spherify.m 2696 2009-02-05 20:29:48Z guillaume $
global fb
if isempty(fb)
fb = false;
end
shift = keyval('shift', varargin);
smooth = keyval('smooth', varargin);
% set the concentration factor
if ~isempty(smooth)
k = smooth;
else
k = 100;
end
% the following code is for debugging
if fb
figure
[sphere_pnt, sphere_tri] = icosahedron162;
y = vonmisesfischer(5, [0 0 1], sphere_pnt);
triplot(sphere_pnt, sphere_tri, y);
end
npnt = size(pnt, 1);
ntri = size(tri, 1);
switch shift
case 'mean'
pnt(:,1) = pnt(:,1) - mean(pnt(:,1));
pnt(:,2) = pnt(:,2) - mean(pnt(:,2));
pnt(:,3) = pnt(:,3) - mean(pnt(:,3));
case 'range'
minx = min(pnt(:,1));
miny = min(pnt(:,2));
minz = min(pnt(:,3));
maxx = max(pnt(:,1));
maxy = max(pnt(:,2));
maxz = max(pnt(:,3));
pnt(:,1) = pnt(:,1) - mean([minx maxx]);
pnt(:,2) = pnt(:,2) - mean([miny maxy]);
pnt(:,3) = pnt(:,3) - mean([minz maxz]);
otherwise
% do nothing
end
% determine the convex hull, especially to determine the support points
tric = convhulln(pnt);
sel = unique(tric(:));
% create a triangulation for only the support points
support_pnt = pnt(sel,:);
support_tri = convhulln(support_pnt);
if fb
figure
triplot(support_pnt, support_tri, [], 'faces_skin');
triplot(pnt, tri, [], 'faces_skin');
alpha 0.5
end
% determine the radius and thereby scaling factor for the support points
support_scale = zeros(length(sel),1);
for i=1:length(sel)
support_scale(i) = norm(support_pnt(i,:));
end
% interpolate the scaling factor for the support points to all points
scale = zeros(npnt,1);
for i=1:npnt
u = pnt(i,:);
y = vonmisesfischer(k, u, support_pnt);
y = y ./ sum(y);
scale(i) = y' * support_scale;
end
% apply the interpolated scaling to all points
pnt(:,1) = pnt(:,1) ./ scale;
pnt(:,2) = pnt(:,2) ./ scale;
pnt(:,3) = pnt(:,3) ./ scale;
% downscale the points further to make sure that nothing sticks out
n = zeros(npnt,1);
for i = 1:npnt
n(i) = norm(pnt(i, :));
end
mscale = (1-eps) / max(n);
pnt = mscale * pnt;
if fb
figure
[sphere_pnt, sphere_tri] = icosahedron162;
triplot(sphere_pnt, sphere_tri, [], 'faces_skin');
triplot(pnt, tri, [], 'faces_skin');
alpha 0.5
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% VONMISESFISCHER probability distribution
%
% Use as
% y = vonmisesfischer(k, u, x)
% where
% k = concentration parameter
% u = mean direction
% x = direction of the points on the sphere
%
% The von Mises?Fisher distribution is a probability distribution on the
% (p?1) dimensional sphere in Rp. If p=2 the distribution reduces to the
% von Mises distribution on the circle. The distribution belongs to the
% field of directional statistics.
%
% This implementation is based on
% http://en.wikipedia.org/wiki/Von_Mises-Fisher_distribution
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function y = vonmisesfischer(k, u, x)
% the data describes N points in P-dimensional space
[n, p] = size(x);
% ensure that the direction vectors are unit length
u = u ./ norm(u);
for i=1:n
x(i,:) = x(i,:) ./ norm(x(i,:));
end
% FIXME this normalisation is wrong
% but it is not yet needed, so the problem is acceptable for now
% Cpk = (k^((p/2)-1)) ./ ( (2*pi)^(p/2) * besseli(p/2-1, k));
Cpk = 1;
y = exp(k * u * x') ./ Cpk;
y = y(:);
function [val] = keyval(key, varargin);
% KEYVAL returns the value that corresponds to the requested key in a
% key-value pair list of variable input arguments
%
% Use as
% [val] = keyval(key, varargin)
%
% See also VARARGIN
% Copyright (C) 2005-2007, Robert Oostenveld
%
% $Log: keyval.m,v $
% Revision 1.1 2008/11/13 09:55:36 roboos
% moved from fieldtrip/private, fileio or from roboos/misc to new location at fieldtrip/public
%
% Revision 1.2 2007/07/18 12:43:53 roboos
% test for an even number of optional input arguments
%
% Revision 1.1 2005/11/04 10:24:46 roboos
% new implementation
%
if length(varargin)==1 && iscell(varargin{1})
varargin = varargin{1};
end
if mod(length(varargin),2)
error('optional input arguments should come in key-value pairs, i.e. there should be an even number');
end
keys = varargin(1:2:end);
vals = varargin(2:2:end);
hit = find(strcmp(key, keys));
if length(hit)==0
% the requested key was not found
val = [];
elseif length(hit)==1
% the requested key was found
val = vals{hit};
else
error('multiple input arguments with the same name');
end
|
github
|
philippboehmsturm/antx-master
|
spm_image.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_image.m
| 20,716 |
utf_8
|
6a45267c81435eab6cb3c47db120f88d
|
function spm_image(action,varargin)
% Image and header display
% FORMAT spm_image
%__________________________________________________________________________
%
% spm_image is an interactive facility that allows orthogonal sections
% from an image volume to be displayed. Clicking the cursor on either
% of the three images moves the point around which the orthogonal
% sections are viewed. The co-ordinates of the cursor are shown both
% in voxel co-ordinates and millimeters within some fixed framework.
% The intensity at that point in the image (sampled using the current
% interpolation scheme) is also given. The position of the crosshairs
% can also be moved by specifying the co-ordinates in millimeters to
% which they should be moved. Clicking on the horizontal bar above
% these boxes will move the cursor back to the origin (analogous to
% setting the crosshair position (in mm) to [0 0 0]).
%
% The images can be re-oriented by entering appropriate translations,
% rotations and zooms into the panel on the left. The transformations
% can then be saved by hitting the "Reorient images..." button. The
% transformations that were applied to the image are saved to the header
% information of the selected images. The transformations are considered
% to be relative to any existing transformations that may be stored.
% Note that the order that the transformations are applied in is the
% same as in spm_matrix.m.
%
% The ``Reset...'' button next to it is for setting the orientation of
% images back to transverse. It retains the current voxel sizes,
% but sets the origin of the images to be the centre of the volumes
% and all rotations back to zero.
%
% The right panel shows miscellaneous information about the image.
% This includes:
% Dimensions - the x, y and z dimensions of the image.
% Datatype - the computer representation of each voxel.
% Intensity - scalefactors and possibly a DC offset.
% Miscellaneous other information about the image.
% Vox size - the distance (in mm) between the centres of
% neighbouring voxels.
% Origin - the voxel at the origin of the co-ordinate system
% Dir Cos - Direction cosines. This is a widely used
% representation of the orientation of an image.
%
% There are also a few options for different resampling modes, zooms
% etc. You can also flip between voxel space or world space. If you
% are re-orienting the images, make sure that world space is specified.
% Blobs (from activation studies) can be superimposed on the images and
% the intensity windowing can also be changed.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_image.m 625 2011-02-24 15:59:50Z vglauche $
global st
if ~nargin, action = 'Init'; end
if ~any(strcmpi(action,{'init','reset'})) && ...
(isempty(st) || ~isfield(st,'vols') || isempty(st.vols{1}))
spm_image('Reset');
warning('Lost all the image information');
return;
end
switch lower(action)
case {'init','display'}
% Display image
%----------------------------------------------------------------------
if isempty(varargin)
[P, sts] = spm_select(1,'image','Select image');
if ~sts, return; end
else
P = varargin{1};
end
if ischar(P), P = spm_vol(P); end
P = P(1);
init_display(P);
case 'repos'
% The widgets for translation rotation or zooms have been modified
%----------------------------------------------------------------------
trz = varargin{1};
try, st.B(trz) = eval(get(gco,'String')); end
set(gco,'String',st.B(trz));
st.vols{1}.premul = spm_matrix(st.B);
% spm_orthviews('MaxBB');
spm_image('Zoom');
spm_image('Update');
case 'shopos'
% The position of the crosshairs has been moved
%----------------------------------------------------------------------
if isfield(st,'mp')
fg = spm_figure('Findwin','Graphics');
if any(findobj(fg) == st.mp)
set(st.mp,'String',sprintf('%.1f %.1f %.1f',spm_orthviews('Pos')));
pos = spm_orthviews('Pos',1);
set(st.vp,'String',sprintf('%.1f %.1f %.1f',pos));
set(st.in,'String',sprintf('%g',spm_sample_vol(st.vols{1},pos(1),pos(2),pos(3),st.hld)));
else
st.Callback = ';';
st = rmfield(st,{'mp','vp','in'});
end
else
st.Callback = ';';
end
case 'setposmm'
% Move the crosshairs to the specified position {mm}
%----------------------------------------------------------------------
if isfield(st,'mp')
fg = spm_figure('Findwin','Graphics');
if any(findobj(fg) == st.mp)
pos = sscanf(get(st.mp,'String'), '%g %g %g');
if length(pos)~=3
pos = spm_orthviews('Pos');
end
spm_orthviews('Reposition',pos);
end
end
case 'setposvx'
% Move the crosshairs to the specified position {vx}
%----------------------------------------------------------------------
if isfield(st,'mp')
fg = spm_figure('Findwin','Graphics');
if any(findobj(fg) == st.vp)
pos = sscanf(get(st.vp,'String'), '%g %g %g');
if length(pos)~=3
pos = spm_orthviews('pos',1);
end
tmp = st.vols{1}.premul*st.vols{1}.mat;
pos = tmp(1:3,:)*[pos ; 1];
spm_orthviews('Reposition',pos);
end
end
case 'addblobs'
% Add blobs to the image - in full colour
%----------------------------------------------------------------------
spm_figure('Clear','Interactive');
nblobs = spm_input('Number of sets of blobs',1,'1|2|3|4|5|6',[1 2 3 4 5 6],1);
for i=1:nblobs
[SPM,xSPM] = spm_getSPM;
c = spm_input('Colour','+1','m','Red blobs|Yellow blobs|Green blobs|Cyan blobs|Blue blobs|Magenta blobs',[1 2 3 4 5 6],1);
colours = [1 0 0;1 1 0;0 1 0;0 1 1;0 0 1;1 0 1];
spm_orthviews('AddColouredBlobs',1,xSPM.XYZ,xSPM.Z,xSPM.M,colours(c,:));
set(st.blobber,'String','Remove Blobs','Callback','spm_image(''RemoveBlobs'');');
end
spm_orthviews('Redraw');
case {'removeblobs','rmblobs'}
% Remove all blobs from the images
%----------------------------------------------------------------------
spm_orthviews('RemoveBlobs',1);
set(st.blobber,'String','Add Blobs','Callback','spm_image(''AddBlobs'');');
spm_orthviews('Redraw');
case 'window'
% Window
%----------------------------------------------------------------------
op = get(st.win,'Value');
if op == 1
spm_orthviews('Window',1); % automatic
else
spm_orthviews('Window',1,spm_input('Range','+1','e','',2));
end
case 'reorient'
% Reorient images
%----------------------------------------------------------------------
mat = spm_matrix(st.B);
if det(mat)<=0
spm('alert!','This will flip the images',mfilename,0,1);
end
[P, sts] = spm_select([1 Inf], 'image','Images to reorient');
if ~sts, return; else P = cellstr(P); end
Mats = zeros(4,4,numel(P));
spm_progress_bar('Init',numel(P),'Reading current orientations',...
'Images Complete');
for i=1:numel(P)
Mats(:,:,i) = spm_get_space(P{i});
spm_progress_bar('Set',i);
end
spm_progress_bar('Init',numel(P),'Reorienting images',...
'Images Complete');
for i=1:numel(P)
spm_get_space(P{i},mat*Mats(:,:,i));
spm_progress_bar('Set',i);
end
spm_progress_bar('Clear');
tmp = spm_get_space([st.vols{1}.fname ',' num2str(st.vols{1}.n)]);
if sum((tmp(:)-st.vols{1}.mat(:)).^2) > 1e-8
spm_image('Init',st.vols{1}.fname);
end
case 'resetorient'
% Reset orientation of images
%----------------------------------------------------------------------
[P,sts] = spm_select([1 Inf], 'image','Images to reset orientation of');
if ~sts, return; else P = cellstr(P); end
spm_progress_bar('Init',numel(P),'Resetting orientations',...
'Images Complete');
for i=1:numel(P)
V = spm_vol(P{i});
M = V.mat;
vox = sqrt(sum(M(1:3,1:3).^2));
if det(M(1:3,1:3))<0, vox(1) = -vox(1); end
orig = (V.dim(1:3)+1)/2;
off = -vox.*orig;
M = [vox(1) 0 0 off(1)
0 vox(2) 0 off(2)
0 0 vox(3) off(3)
0 0 0 1];
spm_get_space(P{i},M);
spm_progress_bar('Set',i);
end
spm_progress_bar('Clear');
tmp = spm_get_space([st.vols{1}.fname ',' num2str(st.vols{1}.n)]);
if sum((tmp(:)-st.vols{1}.mat(:)).^2) > 1e-8
spm_image('Init',st.vols{1}.fname);
end
case 'update'
% Modify the positional information in the right hand panel
%----------------------------------------------------------------------
mat = st.vols{1}.premul*st.vols{1}.mat;
Z = spm_imatrix(mat);
Z = Z(7:9);
set(st.posinf.z,'String', sprintf('%.3g x %.3g x %.3g', Z));
O = mat\[0 0 0 1]'; O=O(1:3)';
set(st.posinf.o, 'String', sprintf('%.3g %.3g %.3g', O));
R = spm_imatrix(mat);
R = spm_matrix([0 0 0 R(4:6)]);
R = R(1:3,1:3);
tmp2 = sprintf('%+5.3f %+5.3f %+5.3f', R(1,1:3)); tmp2(tmp2=='+') = ' ';
set(st.posinf.m1, 'String', tmp2);
tmp2 = sprintf('%+5.3f %+5.3f %+5.3f', R(2,1:3)); tmp2(tmp2=='+') = ' ';
set(st.posinf.m2, 'String', tmp2);
tmp2 = sprintf('%+5.3f %+5.3f %+5.3f', R(3,1:3)); tmp2(tmp2=='+') = ' ';
set(st.posinf.m3, 'String', tmp2);
tmp = [[R zeros(3,1)] ; 0 0 0 1]*diag([Z 1])*spm_matrix(-O) - mat;
if sum(tmp(:).^2)>1e-5
set(st.posinf.w, 'String', 'Warning: shears involved');
else
set(st.posinf.w, 'String', '');
end
case 'zoom'
% Zoom in
%----------------------------------------------------------------------
[zl rl] = spm_orthviews('ZoomMenu');
% Values are listed in reverse order
cz = numel(zl)-get(st.zoomer,'Value')+1;
spm_orthviews('Zoom',zl(cz),rl(cz));
case 'reset'
% Reset
%----------------------------------------------------------------------
spm_orthviews('Reset');
spm_figure('Clear','Graphics');
end
%==========================================================================
function init_display(P)
global st
fg = spm_figure('GetWin','Graphics');
spm_image('Reset');
spm_orthviews('Image', P, [0.0 0.45 1 0.55]);
if isempty(st.vols{1}), return; end
spm_orthviews('MaxBB');
spm_orthviews('Addcontext',1);
st.callback = 'spm_image(''shopos'');';
st.B = [0 0 0 0 0 0 1 1 1 0 0 0];
% Widgets for re-orienting images.
%--------------------------------------------------------------------------
WS = spm('WinScale');
uicontrol(fg,'Style','Frame','Position',[60 25 200 325].*WS,'DeleteFcn','spm_image(''reset'');');
uicontrol(fg,'Style','Text', 'Position',[75 220 100 016].*WS,'String','right {mm}');
uicontrol(fg,'Style','Text', 'Position',[75 200 100 016].*WS,'String','forward {mm}');
uicontrol(fg,'Style','Text', 'Position',[75 180 100 016].*WS,'String','up {mm}');
uicontrol(fg,'Style','Text', 'Position',[75 160 100 016].*WS,'String','pitch {rad}');
uicontrol(fg,'Style','Text', 'Position',[75 140 100 016].*WS,'String','roll {rad}');
uicontrol(fg,'Style','Text', 'Position',[75 120 100 016].*WS,'String','yaw {rad}');
uicontrol(fg,'Style','Text', 'Position',[75 100 100 016].*WS,'String','resize {x}');
uicontrol(fg,'Style','Text', 'Position',[75 80 100 016].*WS,'String','resize {y}');
uicontrol(fg,'Style','Text', 'Position',[75 60 100 016].*WS,'String','resize {z}');
uicontrol(fg,'Style','edit','Callback','spm_image(''repos'',1)','Position',[175 220 065 020].*WS,'String','0','ToolTipString','translate');
uicontrol(fg,'Style','edit','Callback','spm_image(''repos'',2)','Position',[175 200 065 020].*WS,'String','0','ToolTipString','translate');
uicontrol(fg,'Style','edit','Callback','spm_image(''repos'',3)','Position',[175 180 065 020].*WS,'String','0','ToolTipString','translate');
uicontrol(fg,'Style','edit','Callback','spm_image(''repos'',4)','Position',[175 160 065 020].*WS,'String','0','ToolTipString','rotate');
uicontrol(fg,'Style','edit','Callback','spm_image(''repos'',5)','Position',[175 140 065 020].*WS,'String','0','ToolTipString','rotate');
uicontrol(fg,'Style','edit','Callback','spm_image(''repos'',6)','Position',[175 120 065 020].*WS,'String','0','ToolTipString','rotate');
uicontrol(fg,'Style','edit','Callback','spm_image(''repos'',7)','Position',[175 100 065 020].*WS,'String','1','ToolTipString','zoom');
uicontrol(fg,'Style','edit','Callback','spm_image(''repos'',8)','Position',[175 80 065 020].*WS,'String','1','ToolTipString','zoom');
uicontrol(fg,'Style','edit','Callback','spm_image(''repos'',9)','Position',[175 60 065 020].*WS,'String','1','ToolTipString','zoom');
uicontrol(fg,'Style','Pushbutton','String','Reorient images...','Callback','spm_image(''reorient'')',...
'Position',[70 35 125 020].*WS,'ToolTipString','modify position information of selected images');
uicontrol(fg,'Style','Pushbutton','String','Reset...','Callback','spm_image(''resetorient'')',...
'Position',[195 35 55 020].*WS,'ToolTipString','reset orientations of selected images');
% Crosshair position
%--------------------------------------------------------------------------
uicontrol(fg,'Style','Frame','Position',[70 250 180 90].*WS);
uicontrol(fg,'Style','Text', 'Position',[75 320 170 016].*WS,'String','Crosshair Position');
uicontrol(fg,'Style','PushButton', 'Position',[75 316 170 006].*WS,...
'Callback','spm_orthviews(''Reposition'',[0 0 0]);','ToolTipString','move crosshairs to origin');
% uicontrol(fg,'Style','PushButton', 'Position',[75 315 170 020].*WS,'String','Crosshair Position',...
% 'Callback','spm_orthviews(''Reposition'',[0 0 0]);','ToolTipString','move crosshairs to origin');
uicontrol(fg,'Style','Text', 'Position',[75 295 35 020].*WS,'String','mm:');
uicontrol(fg,'Style','Text', 'Position',[75 275 35 020].*WS,'String','vx:');
uicontrol(fg,'Style','Text', 'Position',[75 255 65 020].*WS,'String','Intensity:');
st.mp = uicontrol(fg,'Style','edit', 'Position',[110 295 135 020].*WS,'String','','Callback','spm_image(''setposmm'')','ToolTipString','move crosshairs to mm coordinates');
st.vp = uicontrol(fg,'Style','edit', 'Position',[110 275 135 020].*WS,'String','','Callback','spm_image(''setposvx'')','ToolTipString','move crosshairs to voxel coordinates');
st.in = uicontrol(fg,'Style','Text', 'Position',[140 255 85 020].*WS,'String','');
% General information
%--------------------------------------------------------------------------
uicontrol(fg,'Style','Frame','Position',[305 25 280 325].*WS);
uicontrol(fg,'Style','Text','Position' ,[310 330 50 016].*WS,...
'HorizontalAlignment','right', 'String', 'File:');
uicontrol(fg,'Style','Text','Position' ,[360 330 210 016].*WS,...
'HorizontalAlignment','left', 'String', spm_str_manip(st.vols{1}.fname,'k25'),'FontWeight','bold');
uicontrol(fg,'Style','Text','Position' ,[310 310 100 016].*WS,...
'HorizontalAlignment','right', 'String', 'Dimensions:');
uicontrol(fg,'Style','Text','Position' ,[410 310 160 016].*WS,...
'HorizontalAlignment','left', 'String', sprintf('%d x %d x %d', st.vols{1}.dim(1:3)),'FontWeight','bold');
uicontrol(fg,'Style','Text','Position' ,[310 290 100 016].*WS,...
'HorizontalAlignment','right', 'String', 'Datatype:');
uicontrol(fg,'Style','Text','Position' ,[410 290 160 016].*WS,...
'HorizontalAlignment','left', 'String', spm_type(st.vols{1}.dt(1)),'FontWeight','bold');
uicontrol(fg,'Style','Text','Position' ,[310 270 100 016].*WS,...
'HorizontalAlignment','right', 'String', 'Intensity:');
str = 'varied';
if size(st.vols{1}.pinfo,2) == 1
if st.vols{1}.pinfo(2)
str = sprintf('Y = %g X + %g', st.vols{1}.pinfo(1:2)');
else
str = sprintf('Y = %g X', st.vols{1}.pinfo(1)');
end
end
uicontrol(fg,'Style','Text','Position' ,[410 270 160 016].*WS,...
'HorizontalAlignment','left', 'String', str,'FontWeight','bold');
if isfield(st.vols{1}, 'descrip')
uicontrol(fg,'Style','Text','Position' ,[310 250 260 016].*WS,...
'HorizontalAlignment','center', 'String', st.vols{1}.descrip,'FontWeight','bold');
end
% Positional information
%--------------------------------------------------------------------------
mat = st.vols{1}.premul*st.vols{1}.mat;
Z = spm_imatrix(mat);
Z = Z(7:9);
uicontrol(fg,'Style','Text','Position' ,[310 210 100 016].*WS,...
'HorizontalAlignment','right', 'String', 'Vox size:');
st.posinf = struct('z',uicontrol(fg,'Style','Text','Position' ,[410 210 160 016].*WS,...
'HorizontalAlignment','left', 'String', sprintf('%.3g x %.3g x %.3g', Z),'FontWeight','bold'));
O = mat\[0 0 0 1]'; O=O(1:3)';
uicontrol(fg,'Style','Text','Position' ,[310 190 100 016].*WS,...
'HorizontalAlignment','right', 'String', 'Origin:');
st.posinf.o = uicontrol(fg,'Style','Text','Position' ,[410 190 160 016].*WS,...
'HorizontalAlignment','left', 'String', sprintf('%.3g %.3g %.3g', O),'FontWeight','bold');
R = spm_imatrix(mat);
R = spm_matrix([0 0 0 R(4:6)]);
R = R(1:3,1:3);
uicontrol(fg,'Style','Text','Position' ,[310 170 100 016].*WS,...
'HorizontalAlignment','right', 'String', 'Dir Cos:');
tmp2 = sprintf('%+5.3f %+5.3f %+5.3f', R(1,1:3)); tmp2(tmp2=='+') = ' ';
st.posinf.m1 = uicontrol(fg,'Style','Text','Position' ,[410 170 160 016].*WS,...
'HorizontalAlignment','left', 'String', tmp2,'FontWeight','bold');
tmp2 = sprintf('%+5.3f %+5.3f %+5.3f', R(2,1:3)); tmp2(tmp2=='+') = ' ';
st.posinf.m2 = uicontrol(fg,'Style','Text','Position' ,[410 150 160 016].*WS,...
'HorizontalAlignment','left', 'String', tmp2,'FontWeight','bold');
tmp2 = sprintf('%+5.3f %+5.3f %+5.3f', R(3,1:3)); tmp2(tmp2=='+') = ' ';
st.posinf.m3 = uicontrol(fg,'Style','Text','Position' ,[410 130 160 016].*WS,...
'HorizontalAlignment','left', 'String', tmp2,'FontWeight','bold');
tmp = [[R zeros(3,1)] ; 0 0 0 1]*diag([Z 1])*spm_matrix(-O) - mat;
st.posinf.w = uicontrol(fg,'Style','Text','Position' ,[310 110 260 016].*WS,...
'HorizontalAlignment','center', 'String', '','FontWeight','bold');
if sum(tmp(:).^2)>1e-8
set(st.posinf.w, 'String', 'Warning: shears involved');
end
% Assorted other buttons
%--------------------------------------------------------------------------
uicontrol(fg,'Style','Frame','Position',[310 30 270 70].*WS);
zl = spm_orthviews('ZoomMenu');
czlabel = cell(size(zl));
% List zoom steps in reverse order
zl = zl(end:-1:1);
for cz = 1:numel(zl)
if isinf(zl(cz))
czlabel{cz} = 'Full Volume';
elseif isnan(zl(cz))
czlabel{cz} = 'BBox (Y > ...)';
elseif zl(cz) == 0
czlabel{cz} = 'BBox (nonzero)';
else
czlabel{cz} = sprintf('%dx%dx%dmm', 2*zl(cz), 2*zl(cz), 2*zl(cz));
end
end
st.zoomer = uicontrol(fg,'Style','popupmenu' ,'Position',[315 75 125 20].*WS,...
'String',czlabel,...
'Callback','spm_image(''zoom'')','ToolTipString','zoom in by different amounts');
c = 'if get(gco,''Value'')==1, spm_orthviews(''Space''), else, spm_orthviews(''Space'', 1);end;spm_image(''zoom'')';
uicontrol(fg,'Style','popupmenu' ,'Position',[315 55 125 20].*WS,...
'String',char('World Space','Voxel Space'),...
'Callback',c,'ToolTipString','display in aquired/world orientation');
c = 'if get(gco,''Value'')==1, spm_orthviews(''Xhairs'',''off''), else, spm_orthviews(''Xhairs'',''on''); end;';
uicontrol(fg,'Style','togglebutton','Position',[450 75 125 20].*WS,...
'String','Hide Crosshairs','Callback',c,'ToolTipString','show/hide crosshairs');
uicontrol(fg,'Style','popupmenu' ,'Position',[450 55 125 20].*WS,...
'String',char('NN interp','bilin interp','sinc interp'),...
'Callback','tmp_ = [0 1 -4];spm_orthviews(''Interp'',tmp_(get(gco,''Value'')))',...
'Value',2,'ToolTipString','interpolation method for displaying images');
st.win = uicontrol(fg,'Style','popupmenu','Position',[315 35 125 20].*WS,...
'String',char('Auto Window','Manual Window'),'Callback','spm_image(''window'');','ToolTipString','range of voxel intensities displayed');
% uicontrol(fg,'Style','pushbutton','Position',[315 35 125 20].*WS,...
% 'String','Window','Callback','spm_image(''window'');','ToolTipString','range of voxel intensities % displayed');
st.blobber = uicontrol(fg,'Style','pushbutton','Position',[450 35 125 20].*WS,...
'String','Add Blobs','Callback','spm_image(''addblobs'');','ToolTipString','superimpose activations');
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_montage_ui.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_eeg_montage_ui.m
| 7,209 |
utf_8
|
81b00840683562c05ad7e333633cbfb5
|
function montage = spm_eeg_montage_ui(montage)
% GUI for EEG montage (rereference EEG data to new reference channel(s))
% FORMAT montage = spm_eeg_montage_ui(montage)
%
% montage - structure with fields:
% tra - MxN matrix
% labelnew - Mx1 cell-array - new labels
% labelorg - Nx1 cell-array - original labels
%
% Output is empty if the GUI is closed.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Jean Daunizeau
% $Id: spm_eeg_montage_ui.m 3674 2010-01-12 18:25:05Z jean $
error(nargchk(1,1,nargin));
% Create the figure
%--------------------------------------------------------------------------
fig = figure;
S0 = spm('WinSize','0',1);
pos = get(fig,'position');
pos2 = [40 70 pos(3)-60 pos(4)-100];
pos = [S0(1) S0(2) 0 0] + [pos(1) pos(2) 1.8*pos(3) pos(4)];
set(gcf,...
'menubar', 'none',...
'position', pos,...
'numbertitle', 'off',...
'name', 'Montage edition');
addButtons(fig);
% Display the uitable component
%--------------------------------------------------------------------------
table = cat(2,montage.labelnew(:),num2cell(montage.tra));
colnames = cat(2,'channel labels',montage.labelorg(:)');
pause(1e-1) % This is weird, but fixes java troubles.
[ht,hc] = spm_uitable(table,colnames);
set(ht,'position',pos2, 'units','normalized');
% Display the matrix representation of the montage
%--------------------------------------------------------------------------
ax = axes('position',[0.6 0.18 0.4 0.77]);
hi = imagesc(montage.tra,'parent',ax);
axis('image');
colormap('bone');
zoom(fig,'on');
% Store info in figure's userdata and wait for user interaction
%--------------------------------------------------------------------------
ud.hi = hi;
ud.ht = ht;
ud.montage = montage;
set(fig,'userdata',ud);
uiwait(fig);
% Get the montage from the GUI
%--------------------------------------------------------------------------
try
ud = get(fig,'userdata');
montage = ud.montage;
close(fig);
catch % GUI was closed without 'OK' button
montage = [];
end
%==========================================================================
function doAddRow(obj,evd,h)
%==========================================================================
% 'add row' button subfunction
ud = get(h,'userdata');
[M,newLabels] = getM(ud.ht);
M = [M;zeros(1,size(M,2))];
newLabels = cat(1,newLabels(:),num2str(size(M,1)));
set(ud.ht,'units','pixels');
pos = get(ud.ht,'Position');
delete(ud.ht);
table = cat(2,newLabels,num2cell(M));
colnames = cat(2,'channel labels',ud.montage.labelorg(:)');
pause(1) % This is weird, but fixes java troubles.
ht = spm_uitable(table,colnames);
set(ht,'position',pos,...
'units','normalized');
ud.ht = ht;
set(h,'userdata',ud);
doCheck(obj,evd,h);
%==========================================================================
function doLoad(obj,evd,h)
%==========================================================================
% 'load' button subfunction
[t,sts] = spm_select(1,'mat','Load montage file');
if sts
montage = load(t);
if ismember('montage', fieldnames(montage))
montage = montage.montage;
ud = get(h,'userdata');
set(ud.ht,'units','pixels');
pos = get(ud.ht,'Position');
delete(ud.ht);
table = cat(2,montage.labelnew(:),num2cell(montage.tra));
colnames = cat(2,'channel labels',montage.labelorg(:)');
pause(1) % This is weird, but fixes java troubles.
ht = spm_uitable(table,colnames);
set(ht,'position',pos,...
'units','normalized');
ud.ht = ht;
ud.montage = montage;
set(h,'userdata',ud);
pause(1)
doCheck(obj,evd,h);
else
spm('alert!','File did not contain any montage!','Montage edition');
end
end
%==========================================================================
function doSave(obj,evd,h)
%==========================================================================
% 'save as' button subfunction
doCheck(obj,evd,h);
ud = get(h,'userdata');
[M,newLabels] = getM(ud.ht);
% delete row if empty:
ind = ~any(M,2);
M(ind,:) = [];
newLabels(ind) = [];
montage.tra = M;
montage.labelorg = ud.montage.labelorg;
montage.labelnew = newLabels;
uisave('montage','SPMeeg_montage.mat');
%==========================================================================
function doOK(obj,evd,h)
%==========================================================================
% 'OK' button subfunction
doCheck(obj,evd,h);
ud = get(h,'userdata');
[M, newLabels] = getM(ud.ht);
% delete row if empty:
ind = ~any(M,2);
M(ind,:) = [];
newLabels(ind) = [];
montage.tra = M;
montage.labelorg = ud.montage.labelorg(:);
montage.labelnew = newLabels(:);
ud.montage = montage;
set(h,'userdata',ud);
uiresume(h);
%==========================================================================
function doCheck(obj,evd,h)
%==========================================================================
% Update the montage display
ud = get(h,'userdata');
M = getM(ud.ht);
set(ud.hi,'cdata',M);
set(gca,'xlim',[0.5 size(M,1)]);
set(gca,'ylim',[0.5 size(M,2)]);
axis('image');
drawnow;
%==========================================================================
function [M,newLabels] = getM(ht)
%==========================================================================
% extracting montage from java object
nnew = get(ht,'NumRows');
nold = get(ht,'NumColumns')-1;
M = zeros(nnew,nold);
data = get(ht,'data');
for i =1:nnew
if ~isempty(data(i,1))
newLabels{i} = data(i,1);
else
newLabels{i} = [];
end
for j =1:nold
if ~isempty(data(i,j+1))
if ~ischar(data(i,j+1))
M(i,j) = data(i,j+1);
else
M0 = str2double(data(i,j+1));
if ~isempty(M0)
M(i,j) = M0;
else
M(i,j) = 0;
end
end
else
M(i,j) = 0;
end
end
end
%==========================================================================
function addButtons(h)
%==========================================================================
% adding buttons to the montage GUI
hAdd = uicontrol('style','pushbutton',...
'string','Add row','callback',{@doAddRow,h},...
'position',[60 20 80 20]);
set(hAdd,'units','normalized');
hLoad = uicontrol('style','pushbutton',...
'string','Load file','callback',{@doLoad,h},...
'position',[180 20 80 20]);
set(hLoad,'units','normalized');
hSave = uicontrol('style','pushbutton',...
'string','Save as','callback',{@doSave,h},...
'position',[280 20 80 20]);
set(hSave,'units','normalized');
hOK = uicontrol('style','pushbutton',...
'string',' OK ','callback',{@doOK,h},...
'position',[400 20 80 20]);
set(hOK,'units','normalized');
hCheck = uicontrol('style','pushbutton',...
'string',' Refresh display ','callback',{@doCheck,h},...
'position',[760 20 120 20]);
set(hCheck,'units','normalized');
|
github
|
philippboehmsturm/antx-master
|
spm_interp.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_interp.m
| 1,111 |
utf_8
|
5f0170891b0600c4824810d278725d9f
|
function [x] = spm_interp(x,r)
% 1 or 2-D array interpolation
% FORMAT [x] = spm_interp(x,r)
% x - array
% r - interpolation rate
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Karl Friston
% $Id: spm_interp.m 3733 2010-02-18 17:43:18Z karl $
% interpolate
%---------------------------------------------------------------------------
[n m] = size(x);
if n > 1 && m > 1 % matrix
X = zeros(r*n,m);
for i = 1:m
X(:,i) = interpolate(x(:,i),r);
end
x = zeros(r*n,r*m);
for i = 1:r*n
x(i,:) = interpolate(X(i,:),r)';
end
elseif n == 1 % row vector
x = interpolate(x',r)';
elseif m == 1 % column vector
x = interpolate(x,r);
end
% Interpolate using DCT
% -------------------------------------------------------------------------
function [u] = interpolate(y,r)
if r == 1;
u = y;
else
y = y(:);
n = size(y,1);
Dy = spm_dctmtx(r*n,n);
Du = spm_dctmtx(n,n);
Dy = Dy*sqrt(r);
u = Dy*(Du'*y);
end
|
github
|
philippboehmsturm/antx-master
|
spm_transverse.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_transverse.m
| 15,678 |
utf_8
|
22c28b8cda464e1764eee552402294ab
|
function spm_transverse(varargin)
% Rendering of regional effects [SPM{T/F}] on transverse sections
% FORMAT spm_transverse('set',SPM,hReg)
% FORMAT spm_transverse('setcoords',xyzmm)
% FORMAT spm_transverse('clear')
%
% SPM - structure containing SPM, distribution & filtering details
% about the excursion set (xSPM)
% - required fields are:
% .Z - minimum of n Statistics {filtered on u and k}
% .STAT - distribution {Z, T, X or F}
% .u - height threshold
% .XYZ - location of voxels {voxel coords}
% .iM - mm -> voxels matrix
% .VOX - voxel dimensions {mm}
% .DIM - image dimensions {voxels}
%
% hReg - handle of MIP XYZ registry object (see spm_XYZreg for details)
%
% spm_transverse automatically updates its co-ordinates from the
% registry, but clicking on the slices has no effect on the registry.
% i.e., the updating is one way only.
%
% See also: spm_getSPM
%__________________________________________________________________________
%
% spm_transverse is called by the SPM results section and uses
% variables in SPM and SPM to create three transverse sections though a
% background image. Regional foci from the selected SPM{T/F} are
% rendered on this image.
%
% Although the SPM{.} adopts the neurological convention (left = left)
% the rendered images follow the same convention as the original data.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Karl Friston & John Ashburner
% $Id: spm_transverse.m 3348 2009-09-03 10:32:01Z guillaume $
switch lower(varargin{1})
case 'set'
% draw slices
%----------------------------------------------------------------------
init(varargin{2},varargin{3});
case 'setcoords'
% reposition
%----------------------------------------------------------------------
disp('Reposition');
case 'clear'
% clear
%----------------------------------------------------------------------
clear_global;
end
return;
%==========================================================================
% function init(SPM,hReg)
%==========================================================================
function init(SPM,hReg)
%-Get figure handles
%--------------------------------------------------------------------------
Fgraph = spm_figure('GetWin','Graphics');
%-Get the image on which to render
%--------------------------------------------------------------------------
spms = spm_select(1,'image','Select image for rendering on');
spm('Pointer','Watch');
%-Delete previous axis and their pagination controls (if any)
%--------------------------------------------------------------------------
spm_results_ui('Clear',Fgraph);
global transv
transv = struct('blob',[],'V',spm_vol(spms),'h',[],'hReg',hReg,'fig',Fgraph);
transv.blob = struct('xyz', round(SPM.XYZ), 't',SPM.Z, 'dim',SPM.DIM(1:3),...
'iM',SPM.iM,...
'vox', sqrt(sum(SPM.M(1:3,1:3).^2)), 'u', SPM.u);
%-Get current location and convert to pixel co-ordinates
%--------------------------------------------------------------------------
xyzmm = spm_XYZreg('GetCoords',transv.hReg);
xyz = round(transv.blob.iM(1:3,:)*[xyzmm; 1]);
try
units = SPM.units;
catch
units = {'mm' 'mm' 'mm'};
end
%-Extract data from SPM [at one plane separation] and get background slices
%--------------------------------------------------------------------------
dim = ceil(transv.blob.dim(1:3)'.*transv.blob.vox);
A = transv.blob.iM*transv.V.mat;
hld = 0;
zoomM = inv(spm_matrix([0 0 -1 0 0 0 transv.blob.vox([1 2]) 1]));
zoomM1 = spm_matrix([0 0 0 0 0 0 transv.blob.vox([1 2]) 1]);
Q = find(abs(transv.blob.xyz(3,:) - xyz(3)) < 0.5);
T2 = full(sparse(transv.blob.xyz(1,Q),transv.blob.xyz(2,Q),transv.blob.t(Q),transv.blob.dim(1),transv.blob.dim(2)));
T2 = spm_slice_vol(T2,zoomM,dim([1 2]),[hld NaN]);
Q = find(T2==0) ; T2(Q) = NaN;
D = zoomM1*[1 0 0 0;0 1 0 0;0 0 1 -xyz(3);0 0 0 1]*A;
D2 = spm_slice_vol(transv.V,inv(D),dim([1 2]),1);
maxD = max([max(D2(:)) eps]);
minD = min([min(D2(:)) eps]);
if transv.blob.dim(3) > 1
Q = find(abs(transv.blob.xyz(3,:) - xyz(3)+1) < 0.5);
T1 = full(sparse(transv.blob.xyz(1,Q),...
transv.blob.xyz(2,Q),transv.blob.t(Q),transv.blob.dim(1),transv.blob.dim(2)));
T1 = spm_slice_vol(T1,zoomM,dim([1 2]),[hld NaN]);
Q = find(T1==0) ; T1(Q) = NaN;
D = zoomM1*[1 0 0 0;0 1 0 0;0 0 1 -xyz(3)+1;0 0 0 1]*A;
D1 = spm_slice_vol(transv.V,inv(D),dim([1 2]),1);
maxD = max([maxD ; D1(:)]);
minD = min([minD ; D1(:)]);
Q = find(abs(transv.blob.xyz(3,:) - xyz(3)-1) < 0.5);
T3 = full(sparse(transv.blob.xyz(1,Q),...
transv.blob.xyz(2,Q),transv.blob.t(Q),transv.blob.dim(1),transv.blob.dim(2)));
T3 = spm_slice_vol(T3,zoomM,dim([1 2]),[hld NaN]);
Q = find(T3==0) ; T3(Q) = NaN;
D = zoomM1*[1 0 0 0;0 1 0 0;0 0 1 -xyz(3)-1;0 0 0 1]*A;
D3 = spm_slice_vol(transv.V,inv(D),dim([1 2]),1);
maxD = max([maxD ; D3(:)]);
minD = min([minD ; D3(:)]);
end
mx = max([max(T2(:)) eps]);
mn = min([min(T2(:)) 0]);
D2 = (D2-minD)/(maxD-minD);
if transv.blob.dim(3) > 1,
D1 = (D1-minD)/(maxD-minD);
D3 = (D3-minD)/(maxD-minD);
mx = max([mx ; T1(:) ; T3(:) ; eps]);
mn = min([mn ; T1(:) ; T3(:) ; 0]);
end;
%-Configure {128 level} colormap
%--------------------------------------------------------------------------
cmap = get(Fgraph,'Colormap');
if size(cmap,1) ~= 128
figure(Fgraph)
spm_figure('Colormap','gray-hot')
cmap = get(Fgraph,'Colormap');
end
D = length(cmap)/2;
Q = find(T2(:) > transv.blob.u); T2 = (T2(Q)-mn)/(mx-mn); D2(Q) = 1+1.51/D + T2; T2 = D*D2;
if transv.blob.dim(3) > 1
Q = find(T1(:) > transv.blob.u); T1 = (T1(Q)-mn)/(mx-mn); D1(Q) = 1+1.51/D + T1; T1 = D*D1;
Q = find(T3(:) > transv.blob.u); T3 = (T3(Q)-mn)/(mx-mn); D3(Q) = 1+1.51/D + T3; T3 = D*D3;
end
set(Fgraph,'Units','pixels')
siz = get(Fgraph,'Position');
siz = siz(3:4);
P = xyz.*transv.blob.vox';
%-Render activation foci on background images
%--------------------------------------------------------------------------
if transv.blob.dim(3) > 1
zm = min([(siz(1) - 120)/(dim(1)*3),(siz(2)/2 - 60)/dim(2)]);
xo = (siz(1)-(dim(1)*zm*3)-120)/2;
yo = (siz(2)/2 - dim(2)*zm - 60)/2;
transv.h(1) = axes('Units','pixels','Parent',Fgraph,'Position',[20+xo 20+yo dim(1)*zm dim(2)*zm]);
transv.h(2) = image(rot90(spm_grid(T1)),'Parent',transv.h(1));
axis image; axis off;
tmp = SPM.iM\[xyz(1:2)' (xyz(3)-1) 1]';
ax=transv.h(1);tpoint=get(ax,'title');
str=sprintf('z = %0.0f%s',tmp(3),units{3});
set(tpoint,'string',str);
transv.h(3) = line([1 1]*P(1),[0 dim(2)],'Color','w','Parent',transv.h(1));
transv.h(4) = line([0 dim(1)],[1 1]*(dim(2)-P(2)+1),'Color','w','Parent',transv.h(1));
transv.h(5) = axes('Units','pixels','Parent',Fgraph,'Position',[40+dim(1)*zm+xo 20+yo dim(1)*zm dim(2)*zm]);
transv.h(6) = image(rot90(spm_grid(T2)),'Parent',transv.h(5));
axis image; axis off;
tmp = SPM.iM\[xyz(1:2)' xyz(3) 1]';
ax=transv.h(5);tpoint=get(ax,'title');
str=sprintf('z = %0.0f%s',tmp(3),units{3});
set(tpoint,'string',str);
transv.h(7) = line([1 1]*P(1),[0 dim(2)],'Color','w','Parent',transv.h(5));
transv.h(8) = line([0 dim(1)],[1 1]*(dim(2)-P(2)+1),'Color','w','Parent',transv.h(5));
transv.h(9) = axes('Units','pixels','Parent',Fgraph,'Position',[60+dim(1)*zm*2+xo 20+yo dim(1)*zm dim(2)*zm]);
transv.h(10) = image(rot90(spm_grid(T3)),'Parent',transv.h(9));
axis image; axis off;
tmp = SPM.iM\[xyz(1:2)' (xyz(3)+1) 1]';
ax=transv.h(9);tpoint=get(ax,'title');
str=sprintf('z = %0.0f%s',tmp(3),units{3});
set(tpoint,'string',str);
transv.h(11) = line([1 1]*P(1),[0 dim(2)],'Color','w','Parent',transv.h(9));
transv.h(12) = line([0 dim(1)],[1 1]*(dim(2)-P(2)+1),'Color','w','Parent',transv.h(9));
% colorbar
%----------------------------------------------------------------------
q = [80+dim(1)*zm*3+xo 20+yo 20 dim(2)*zm];
if SPM.STAT=='P'
str='Effect size';
else
str=[SPM.STAT ' value'];
end
transv.h(13) = axes('Units','pixels','Parent',Fgraph,'Position',q,'Visible','off');
transv.h(14) = image([0 mx/32],[mn mx],(1:D)' + D,'Parent',transv.h(13));
ax=transv.h(13);
tpoint=get(ax,'title');
set(tpoint,'string',str);
set(tpoint,'FontSize',9);
%title(ax,str,'FontSize',9);
set(ax,'XTickLabel',[]);
axis(ax,'xy');
else
zm = min([(siz(1) - 80)/dim(1),(siz(2)/2 - 60)/dim(2)]);
xo = (siz(1)-(dim(1)*zm)-80)/2;
yo = (siz(2)/2 - dim(2)*zm - 60)/2;
transv.h(1) = axes('Units','pixels','Parent',Fgraph,'Position',[20+xo 20+yo dim(1)*zm dim(2)*zm]);
transv.h(2) = image(rot90(spm_grid(T2)),'Parent',transv.h(1));
axis image; axis off;
title(sprintf('z = %0.0f%s',xyzmm(3),units{3}));
transv.h(3) = line([1 1]*P(1),[0 dim(2)],'Color','w','Parent',transv.h(1));
transv.h(4) = line([0 dim(1)],[1 1]*(dim(2)-P(2)+1),'Color','w','Parent',transv.h(1));
% colorbar
%----------------------------------------------------------------------
q = [40+dim(1)*zm+xo 20+yo 20 dim(2)*zm];
transv.h(5) = axes('Units','pixels','Parent',Fgraph,'Position',q,'Visible','off');
transv.h(6) = image([0 mx/32],[mn mx],(1:D)' + D,'Parent',transv.h(5));
if SPM.STAT=='P'
str='Effect size';
else
str=[SPM.STAT ' value'];
end
title(str,'FontSize',9);
set(gca,'XTickLabel',[]);
axis xy;
end
spm_XYZreg('Add2Reg',transv.hReg,transv.h(1), 'spm_transverse');
for h=transv.h,
set(h,'DeleteFcn',@clear_global);
end
%-Reset pointer
%--------------------------------------------------------------------------
spm('Pointer','Arrow')
return;
%==========================================================================
% function reposition(xyzmm)
%==========================================================================
function reposition(xyzmm)
global transv
if ~isstruct(transv), return; end;
spm('Pointer','Watch');
%-Get current location and convert to pixel co-ordinates
%--------------------------------------------------------------------------
% xyzmm = spm_XYZreg('GetCoords',transv.hReg)
xyz = round(transv.blob.iM(1:3,:)*[xyzmm; 1]);
% extract data from SPM [at one plane separation]
% and get background slices
%--------------------------------------------------------------------------
dim = ceil(transv.blob.dim(1:3)'.*transv.blob.vox);
A = transv.blob.iM*transv.V.mat;
hld = 0;
zoomM = inv(spm_matrix([0 0 -1 0 0 0 transv.blob.vox([1 2]) 1]));
zoomM1 = spm_matrix([0 0 0 0 0 0 transv.blob.vox([1 2]) 1]);
Q = find(abs(transv.blob.xyz(3,:) - xyz(3)) < 0.5);
T2 = full(sparse(transv.blob.xyz(1,Q),transv.blob.xyz(2,Q),transv.blob.t(Q),transv.blob.dim(1),transv.blob.dim(2)));
T2 = spm_slice_vol(T2,zoomM,dim([1 2]),[hld NaN]);
Q = find(T2==0) ; T2(Q) = NaN;
D = zoomM1*[1 0 0 0;0 1 0 0;0 0 1 -xyz(3);0 0 0 1]*A;
D2 = spm_slice_vol(transv.V,inv(D),dim([1 2]),1);
maxD = max([max(D2(:)) eps]);
minD = min([min(D2(:)) 0]);
if transv.blob.dim(3) > 1
Q = find(abs(transv.blob.xyz(3,:) - xyz(3)+1) < 0.5);
T1 = full(sparse(transv.blob.xyz(1,Q),...
transv.blob.xyz(2,Q),transv.blob.t(Q),transv.blob.dim(1),transv.blob.dim(2)));
T1 = spm_slice_vol(T1,zoomM,dim([1 2]),[hld NaN]);
Q = find(T1==0) ; T1(Q) = NaN;
D = zoomM1*[1 0 0 0;0 1 0 0;0 0 1 -xyz(3)+1;0 0 0 1]*A;
D1 = spm_slice_vol(transv.V,inv(D),dim([1 2]),1);
maxD = max([maxD ; D1(:)]);
minD = min([minD ; D1(:)]);
Q = find(abs(transv.blob.xyz(3,:) - xyz(3)-1) < 0.5);
T3 = full(sparse(transv.blob.xyz(1,Q),...
transv.blob.xyz(2,Q),transv.blob.t(Q),transv.blob.dim(1),transv.blob.dim(2)));
T3 = spm_slice_vol(T3,zoomM,dim([1 2]),[hld NaN]);
Q = find(T3==0) ; T3(Q) = NaN;
D = zoomM1*[1 0 0 0;0 1 0 0;0 0 1 -xyz(3)-1;0 0 0 1]*A;
D3 = spm_slice_vol(transv.V,inv(D),dim([1 2]),1);
maxD = max([maxD ; D3(:)]);
minD = min([minD ; D3(:)]);
end
mx = max([max(T2(:)) eps]);
mn = min([min(T2(:)) 0]);
D2 = (D2-minD)/(maxD-minD);
if transv.blob.dim(3) > 1,
D1 = (D1-minD)/(maxD-minD);
D3 = (D3-minD)/(maxD-minD);
mx = max([mx ; T1(:) ; T3(:) ; eps]);
mn = min([mn ; T1(:) ; T3(:) ; 0]);
end;
%-Configure {128 level} colormap
%--------------------------------------------------------------------------
cmap = get(transv.fig,'Colormap');
if size(cmap,1) ~= 128
figure(transv.fig)
spm_figure('Colormap','gray-hot')
cmap = get(transv.fig,'Colormap');
end
D = length(cmap)/2;
Q = find(T2(:) > transv.blob.u); T2 = (T2(Q)-mn)/(mx-mn); D2(Q) = 1+1.51/D + T2; T2 = D*D2;
if transv.blob.dim(3) > 1
Q = find(T1(:) > transv.blob.u); T1 = (T1(Q)-mn)/(mx-mn); D1(Q) = 1+1.51/D + T1; T1 = D*D1;
Q = find(T3(:) > transv.blob.u); T3 = (T3(Q)-mn)/(mx-mn); D3(Q) = 1+1.51/D + T3; T3 = D*D3;
end
P = xyz.*transv.blob.vox';
%-Render activation foci on background images
%--------------------------------------------------------------------------
if transv.blob.dim(3) > 1
set(transv.h(2),'Cdata',rot90(spm_grid(T1)));
tmp = transv.blob.iM\[xyz(1:2)' (xyz(3)-1) 1]';
set(get(transv.h(1),'Title'),'String',sprintf('z = %0.0fmm',tmp(3)));
set(transv.h(3),'Xdata',[1 1]*P(1),'Ydata',[0 dim(2)]);
set(transv.h(4),'Xdata',[0 dim(1)],'Ydata',[1 1]*(dim(2)-P(2)+1));
set(transv.h(6),'Cdata',rot90(spm_grid(T2)));
set(get(transv.h(5),'Title'),'String',sprintf('z = %0.0fmm',xyzmm(3)));
set(transv.h(7),'Xdata',[1 1]*P(1),'Ydata',[0 dim(2)]);
set(transv.h(8),'Xdata',[0 dim(1)],'Ydata',[1 1]*(dim(2)-P(2)+1));
set(transv.h(10),'Cdata',rot90(spm_grid(T3)));
tmp = transv.blob.iM\[xyz(1:2)' (xyz(3)+1) 1]';
set(get(transv.h(9),'Title'),'String',sprintf('z = %0.0fmm',tmp(3)));
set(transv.h(11),'Xdata',[1 1]*P(1),'Ydata',[0 dim(2)]);
set(transv.h(12),'Xdata',[0 dim(1)],'Ydata',[1 1]*(dim(2)-P(2)+1));
% colorbar
%----------------------------------------------------------------------
set(transv.h(14), 'Ydata',[mn mx], 'Cdata',(1:D)' + D);
set(transv.h(13),'XTickLabel',[],'Ylim',[mn mx]);
else
set(transv.h(2),'Cdata',rot90(spm_grid(T2)));
set(get(transv.h(1),'Title'),'String',sprintf('z = %0.0fmm',xyzmm(3)));
set(transv.h(3),'Xdata',[1 1]*P(1),'Ydata',[0 dim(2)]);
set(transv.h(4),'Xdata',[0 dim(1)],'Ydata',[1 1]*(dim(2)-P(2)+1));
% colorbar
%----------------------------------------------------------------------
set(transv.h(6), 'Ydata',[0 d], 'Cdata',(1:D)' + D);
set(transv.h(5),'XTickLabel',[],'Ylim',[0 d]);
end
%-Reset pointer
%--------------------------------------------------------------------------
spm('Pointer','Arrow')
return;
%==========================================================================
% function clear_global(varargin)
%==========================================================================
function clear_global(varargin)
global transv
if isstruct(transv),
for h = transv.h,
if ishandle(h), set(h,'DeleteFcn',''); end;
end
for h = transv.h,
if ishandle(h), delete(h); end;
end
transv = [];
clear global transv;
end
return;
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_prep.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_eeg_prep.m
| 17,544 |
utf_8
|
b98c008aeb790380204751207d3eafec
|
function D = spm_eeg_prep(S)
% Prepare converted M/EEG data for further analysis
% FORMAT D = spm_eeg_prep(S)
% S - configuration structure (optional)
% (optional) fields of S:
% S.D - MEEG object or filename of M/EEG mat-file
% S.task - action string. One of 'settype', 'defaulttype',
% 'loadtemplate','setcoor2d', 'project3d', 'loadeegsens',
% 'defaulteegsens', 'sens2chan', 'headshape', 'coregister'.
% S.updatehistory - update history information [default: true]
% S.save - save MEEG object [default: false]
%
% D - MEEG object
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Vladimir Litvak
% $Id: spm_eeg_prep.m 3833 2010-04-22 14:49:48Z vladimir $
if ~nargin
spm_eeg_prep_ui;
return;
end
D = spm_eeg_load(S.D);
switch lower(S.task)
%----------------------------------------------------------------------
case 'settype'
%----------------------------------------------------------------------
D = chantype(D, S.ind, S.type);
%----------------------------------------------------------------------
case 'defaulttype'
%----------------------------------------------------------------------
if isfield(S, 'ind')
ind = S.ind;
else
ind = 1:D.nchannels;
end
dictionary = {
'eog', 'EOG';
'eeg', 'EEG';
'ecg', 'ECG';
'lfp', 'LFP';
'emg', 'EMG';
'meg', 'MEG';
'ref', 'REF';
'megmag', 'MEGMAG';
'megplanar', 'MEGPLANAR';
'meggrad', 'MEGGRAD';
'refmag', 'REFMAG';
'refgrad', 'REFGRAD'
};
D = chantype(D, ind, 'Other');
type = ft_chantype(D.chanlabels);
% If there is useful information in the original types it
% overwrites the default assignment
if isfield(D, 'origchantypes')
[sel1, sel2] = spm_match_str(chanlabels(D, ind), D.origchantypes.label);
type(ind(sel1)) = D.origchantypes.type(sel2);
end
spmtype = repmat({'Other'}, 1, length(ind));
[sel1, sel2] = spm_match_str(type(ind), dictionary(:, 1));
spmtype(sel1) = dictionary(sel2, 2);
D = chantype(D, ind, spmtype);
%----------------------------------------------------------------------
case {'loadtemplate', 'setcoor2d', 'project3d'}
%----------------------------------------------------------------------
switch lower(S.task)
case 'loadtemplate'
template = load(S.P); % must contain Cpos, Cnames
xy = template.Cpos;
label = template.Cnames;
case 'setcoor2d'
xy = S.xy;
label = S.label;
case 'project3d'
if ~isfield(D, 'val')
D.val = 1;
end
if isfield(D, 'inv') && isfield(D.inv{D.val}, 'datareg')
datareg = D.inv{D.val}.datareg;
ind = strmatch(S.modality, {datareg(:).modality}, 'exact');
sens = datareg(ind).sensors;
else
sens = D.sensors(S.modality);
end
[xy, label] = spm_eeg_project3D(sens, S.modality);
end
[sel1, sel2] = spm_match_str(lower(D.chanlabels), lower(label));
if ~isempty(sel1)
megind = D.meegchannels('MEG');
eegind = D.meegchannels('EEG');
if ~isempty(intersect(megind, sel1)) && ~isempty(setdiff(megind, sel1))
error('2D locations not found for all MEG channels');
end
if ~isempty(intersect(eegind, sel1)) && ~isempty(setdiff(eegind, sel1))
warning(['2D locations not found for all EEG channels, changing type of channels', ...
num2str(setdiff(eegind, sel1)) ' to ''Other''']);
D = chantype(D, setdiff(eegind, sel1), 'Other');
end
if any(any(coor2D(D, sel1) - xy(:, sel2)))
D = coor2D(D, sel1, num2cell(xy(:, sel2)));
end
end
%----------------------------------------------------------------------
case 'loadeegsens'
%----------------------------------------------------------------------
switch S.source
case 'mat'
senspos = load(S.sensfile);
name = fieldnames(senspos);
senspos = getfield(senspos,name{1});
label = chanlabels(D, sort(strmatch('EEG', D.chantype, 'exact')));
if size(senspos, 1) ~= length(label)
error('To read sensor positions without labels the numbers of sensors and EEG channels should match.');
end
elec = [];
elec.pnt = senspos;
elec.label = label;
headshape = load(S.headshapefile);
name = fieldnames(headshape);
headshape = getfield(headshape,name{1});
shape = [];
fidnum = 0;
while ~all(isspace(S.fidlabel))
fidnum = fidnum+1;
[shape.fid.label{fidnum} S.fidlabel] = strtok(S.fidlabel);
end
if (fidnum < 3) || (size(headshape, 1) < fidnum)
error('At least 3 labeled fiducials are necessary');
end
shape.fid.pnt = headshape(1:fidnum, :);
if size(headshape, 1) > fidnum
shape.pnt = headshape((fidnum+1):end, :);
else
shape.pnt = [];
end
case 'locfile'
label = chanlabels(D, D.meegchannels('EEG'));
elec = ft_read_sens(S.sensfile);
% Remove headshape points
hspind = strmatch('headshape', elec.label);
elec.pnt(hspind, :) = [];
elec.label(hspind) = [];
% This handles FIL Polhemus case and other possible cases
% when no proper labels are available.
if isempty(intersect(label, elec.label))
ind = str2num(strvcat(elec.label));
if length(ind) == length(label)
elec.label = label(ind);
else
error('To read sensor positions without labels the numbers of sensors and EEG channels should match.');
end
end
shape = ft_read_headshape(S.sensfile);
% In case electrode file is used for fiducials, the
% electrodes can be used as headshape
if ~isfield(shape, 'pnt') || isempty(shape.pnt) && ...
size(shape.fid.pnt, 1) > 3
shape.pnt = shape.fid.pnt;
end
end
elec = ft_convert_units(elec, 'mm');
shape= ft_convert_units(shape, 'mm');
if isequal(D.modality(1, 0), 'Multimodal')
if ~isempty(D.fiducials) && isfield(S, 'regfid') && ~isempty(S.regfid)
M1 = coreg(D.fiducials, shape, S.regfid);
elec = ft_transform_sens(M1, elec);
else
error(['MEG fiducials matched to EEG fiducials are required '...
'to add EEG sensors to a multimodal dataset.']);
end
else
D = fiducials(D, shape);
end
D = sensors(D, 'EEG', elec);
%----------------------------------------------------------------------
case 'defaulteegsens'
%----------------------------------------------------------------------
template_sfp = dir(fullfile(spm('dir'), 'EEGtemplates', '*.sfp'));
template_sfp = {template_sfp.name};
ind = strmatch([ft_senstype(D.chanlabels(D.meegchannels('EEG'))) '.sfp'], template_sfp, 'exact');
if ~isempty(ind)
fid = D.fiducials;
if isequal(D.modality(1, 0), 'Multimodal') && ~isempty(fid)
nzlbl = {'fidnz', 'nz', 'nas', 'nasion', 'spmnas'};
lelbl = {'fidle', 'fidt9', 'lpa', 'lear', 'earl', 'le', 'l', 't9', 'spmlpa'};
relbl = {'fidre', 'fidt10', 'rpa', 'rear', 'earr', 're', 'r', 't10', 'spmrpa'};
[sel1, nzind] = spm_match_str(nzlbl, lower(fid.fid.label));
if ~isempty(nzind)
nzind = nzind(1);
end
[sel1, leind] = spm_match_str(lelbl, lower(fid.fid.label));
if ~isempty(leind)
leind = leind(1);
end
[sel1, reind] = spm_match_str(relbl, lower(fid.fid.label));
if ~isempty(reind)
reind = reind(1);
end
regfid = fid.fid.label([nzind, leind, reind]);
if numel(regfid) < 3
error('Could not automatically understand the MEG fiducial labels. Please use the GUI.');
else
regfid = [regfid(:) {'spmnas'; 'spmlpa'; 'spmrpa'}];
end
S1 = [];
S1.D = D;
S1.task = 'loadeegsens';
S1.source = 'locfile';
S1.regfid = regfid;
S1.sensfile = fullfile(spm('dir'), 'EEGtemplates', template_sfp{ind});
S1.updatehistory = 0;
D = spm_eeg_prep(S1);
else
elec = ft_read_sens(fullfile(spm('dir'), 'EEGtemplates', template_sfp{ind}));
[sel1, sel2] = spm_match_str(lower(D.chanlabels), lower(elec.label));
sens = elec;
sens.pnt = sens.pnt(sel2, :);
% This takes care of possible case mismatch
sens.label = D.chanlabels(sel1);
sens.label = sens.label(:);
D = sensors(D, 'EEG', sens);
% Assumes that the first 3 points in standard location files
% are the 3 fiducials (nas, lpa, rpa)
fid = [];
fid.pnt = elec.pnt;
fid.fid.pnt = elec.pnt(1:3, :);
fid.fid.label = elec.label(1:3);
[xy, label] = spm_eeg_project3D(D.sensors('EEG'), 'EEG');
[sel1, sel2] = spm_match_str(lower(D.chanlabels), lower(label));
if ~isempty(sel1)
eegind = strmatch('EEG', chantype(D), 'exact');
if ~isempty(intersect(eegind, sel1)) && ~isempty(setdiff(eegind, sel1))
warning(['2D locations not found for all EEG channels, changing type of channels ', ...
num2str(setdiff(eegind(:)', sel1(:)')) ' to ''Other''']);
D = chantype(D, setdiff(eegind, sel1), 'Other');
end
if any(any(coor2D(D, sel1) - xy(:, sel2)))
D = coor2D(D, sel1, num2cell(xy(:, sel2)));
end
end
if ~isempty(D.fiducials) && isfield(S, 'regfid') && ~isempty(S.regfid)
M1 = coreg(D.fiducials, fid, S.regfid);
D = sensors(D, 'EEG', ft_transform_sens(M1, D.sensors('EEG')));
else
D = fiducials(D, fid);
end
end
end
%----------------------------------------------------------------------
case 'sens2chan'
%----------------------------------------------------------------------
montage = S.montage;
eeglabel = D.chanlabels(strmatch('EEG',D.chantype));
meglabel = D.chanlabels(strmatch('MEG',D.chantype));
if ~isempty(intersect(eeglabel, montage.labelnew))
sens = sensors(D, 'EEG');
if isempty(sens)
error('The montage cannod be applied - no EEG sensors specified');
end
sens = ft_apply_montage(sens, montage, 'keepunused', 'no');
D = sensors(D, 'EEG', sens);
elseif ~isempty(intersect(meglabel, montage.labelnew))
sens = sensors(D, 'MEG');
if isempty(sens)
error('The montage cannod be applied - no MEG sensors specified');
end
sens = ft_apply_montage(sens, montage, 'keepunused', 'no');
D = sensors(D, 'MEG', sens);
else
error('The montage cannot be applied to the sensors');
end
%----------------------------------------------------------------------
case 'headshape'
%----------------------------------------------------------------------
switch S.source
case 'mat'
headshape = load(S.headshapefile);
name = fieldnames(headshape);
headshape = getfield(headshape,name{1});
shape = [];
fidnum = 0;
while ~all(isspace(S.fidlabel))
fidnum = fidnum+1;
[shape.fid.label{fidnum} S.fidlabel] = strtok(S.fidlabel);
end
if (fidnum < 3) || (size(headshape, 1) < fidnum)
error('At least 3 labeled fiducials are necessary');
end
shape.fid.pnt = headshape(1:fidnum, :);
if size(headshape, 1) > fidnum
shape.pnt = headshape((fidnum+1):end, :);
else
shape.pnt = [];
end
otherwise
shape = ft_read_headshape(S.headshapefile);
% In case electrode file is used for fiducials, the
% electrodes can be used as headshape
if ~isfield(shape, 'pnt') || isempty(shape.pnt) && ...
size(shape.fid.pnt, 1) > 3
shape.pnt = shape.fid.pnt;
end
end
shape = ft_convert_units(shape, 'mm');
fid = D.fiducials;
if ~isempty(fid) && isfield(S, 'regfid') && ~isempty(S.regfid)
M1 = coreg(fid, shape, S.regfid);
shape = ft_transform_headshape(M1, shape);
end
D = fiducials(D, shape);
%----------------------------------------------------------------------
case 'coregister'
%----------------------------------------------------------------------
[ok, D] = check(D, 'sensfid');
if ~ok
error('Coregistration cannot be performed due to missing data');
end
try
val = D.val;
Msize = D.inv{val}.mesh.Msize;
catch
val = 1;
Msize = 1;
end
D = spm_eeg_inv_mesh_ui(D, val, 1, Msize);
D = spm_eeg_inv_datareg_ui(D, val);
%----------------------------------------------------------------------
otherwise
%----------------------------------------------------------------------
fprintf('Unknown task ''%s'' to perform: Nothing done.\n',S.task);
end
% When prep is called from other functions with history, history should be
% disabled
if ~isfield(S, 'updatehistory') || S.updatehistory
Stemp = S;
Stemp.D = fullfile(D.path,D.fname);
Stemp.save = 1;
D = D.history('spm_eeg_prep', Stemp);
end
if isfield(S, 'save') && S.save
save(D);
end
%==========================================================================
% function coreg
%==========================================================================
function M1 = coreg(fid, shape, regfid)
[junk, sel1] = spm_match_str(regfid(:, 1), fid.fid.label);
[junk, sel2] = spm_match_str(regfid(:, 2), shape.fid.label);
S = [];
S.targetfid = fid;
S.targetfid.fid.pnt = S.targetfid.fid.pnt(sel1, :);
S.sourcefid = shape;
S.sourcefid.fid.pnt = S.sourcefid.fid.pnt(sel2, :);
S.sourcefid.fid.label = S.sourcefid.fid.label(sel2);
S.targetfid.fid.label = S.sourcefid.fid.label;
S.template = 1;
S.useheadshape = 0;
M1 = spm_eeg_inv_datareg(S);
|
github
|
philippboehmsturm/antx-master
|
spm_bias_ui.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_bias_ui.m
| 5,624 |
utf_8
|
bf36e864bf3d49ba97e9bc133ecb84c2
|
function spm_bias_ui(P)
% Non-uniformity correct images.
%
% 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.
%
%_______________________________________________________________________
% Ref:
% J Ashburner. 2002. "Another MRI Bias Correction Approach" [abstract].
% Presented at the 8th International Conference on Functional Mapping of
% the Human Brain, June 2-6, 2002, Sendai, Japan. Available on CD-Rom
% in NeuroImage, Vol. 16, No. 2.
%
%_______________________________________________________________________
%
% The Prompts Explained
%_______________________________________________________________________
%
% 'Scans to correct' - self explanatory
%
%_______________________________________________________________________
%
% Defaults Options
%_______________________________________________________________________
%[ things in square brackets indicate corresponding defaults field ]
%
% 'Number of histogram bins?'
% The probability density of the image intensity is represented by a
% histogram. The optimum number of bins depends on the number of voxels
% in the image. More voxels allows a more detailed representation.
% Another factor is any potential aliasing effect due to there being a
% discrete number of different intensities in the image. Fewer bins
% should be used in this case.
% [defaults.bias.nbins]
%
% 'Regularisation?'
% The importance of smoothness for the estimated bias field. Without
% any regularisation, the algorithm will attempt to correct for
% different grey levels arising from different tissue types, rather than
% just correcting bias artifact.
% Bias correction uses a Bayesian framework (again) to model intensity
% inhomogeneities in the image(s). The variance associated with each
% tissue class is assumed to be multiplicative (with the
% inhomogeneities). The low frequency intensity variability is
% modelled by a linear combination of three dimensional DCT basis
% functions (again), using a fast algorithm (again) to generate the
% curvature matrix. The regularization is based upon minimizing the
% integral of square of the fourth derivatives of the modulation field
% (the integral of the squares of the first and second derivs give the
% membrane and bending energies respectively).
% [defaults.bias.reg]
%
% 'Cutoff?'
% Cutoff of DCT bases. Only DCT bases of periods longer than the
% cutoff are used to describe the warps. The number used will
% depend on the cutoff and the field of view of the image.
% [defaults.bias.cutoff]
%
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_bias_ui.m 3756 2010-03-05 18:43:37Z guillaume $
global defaults
if nargin==1 && strcmpi(P,'defaults');
defaults.bias = edit_defaults(defaults.bias);
return;
end;
bias_ui(defaults.bias);
return;
%=======================================================================
%=======================================================================
function bias_ui(flags)
% User interface for nonuniformity correction
spm('FnBanner',mfilename,'$Rev: 3756 $');
[Finter,unused,CmdLine] = spm('FnUIsetup','Flatten');
spm_help('!ContextHelp',mfilename);
PP = spm_select(Inf, 'image', 'Scans to correct');
spm('Pointer','Watch');
for i=1:size(PP,1),
spm('FigName',['Flatten: working on scan ' num2str(i)],Finter,CmdLine);
drawnow;
P = deblank(PP(i,:));
T = spm_bias_estimate(P,flags);
[pth,nm,xt,vr] = spm_fileparts(P);
S = fullfile(pth,['bias_' nm '.mat']);
%S = ['bias_' nm '.mat'];
spm_bias_apply(P,S);
end;
if 0,
fg = spm_figure('FindWin','Interactive');
if ~isempty(fg), spm_figure('Clear',fg); end;
end
spm('FigName','Flatten: done',Finter,CmdLine);
spm('Pointer');
return;
%=======================================================================
%=======================================================================
function flags = edit_defaults(flags)
nb = [32 64 128 256 512 1024 2048];
tmp = find(nb == flags.nbins);
if isempty(tmp), tmp = 6; end;
flags.nbins = spm_input('Number of histogram bins?','+1','m',...
[' 32 bins | 64 bins| 128 bins| 256 bins| 512 bins|1024 bins|2048 bins'],...
nb, tmp);
rg = [0 0.00001 0.0001 0.001 0.01 0.1 1.0 10];
tmp = find(rg == flags.reg);
if isempty(tmp), tmp = 4; end;
flags.reg = spm_input('Regularisation?','+1','m',...
['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)'],...
rg, tmp);
co = [20 25 30 35 40 45 50 60 70 80 90 100];
tmp = find(co == flags.cutoff);
if isempty(tmp), tmp = 4; end;
flags.cutoff = spm_input('Cutoff?','+1','m',...
[' 20mm cutoff| 25mm cutoff| 30mm cutoff| 35mm cutoff| 40mm cutoff|'...
' 45mm cutoff| 50mm cutoff| 60mm cutoff| 70mm cutoff| 80mm cutoff|'...
' 90mm cutoff|100mm cutoff'],...
co, tmp);
return;
%=======================================================================
|
github
|
philippboehmsturm/antx-master
|
fdmar_init.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/fdmar_init.m
| 368 |
utf_8
|
97dc3cc885f39aad9e6912e28093ba94
|
%A -> Parameter Matrix of arfit_coeff()
%X -> filtered data
%res -> residuals of the glm-analysis (first pass of spm_spm)
%stimu -> stiumuli from the experiment
function obj = fdmar_init(A,X,res,stimu)
obj.order = length(A);
obj.coeff = A;
obj.X = X;
obj.res = res;
obj.stimu = stimu;
obj.resgaus=fdmar_gaus(res);
obj=fdmar_resar(obj);
obj=fdmar_arspekth(obj);
end
|
github
|
philippboehmsturm/antx-master
|
spm_mesh_render.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_mesh_render.m
| 26,450 |
utf_8
|
2a52d696ff0df1dbd3e2cf641187b0be
|
function varargout = spm_mesh_render(action,varargin)
% Display a surface mesh & various utilities
% FORMAT H = spm_mesh_render('Disp',M,'PropertyName',propertyvalue)
% M - a GIfTI filename/object or patch structure
% H - structure containing handles of various objects
% Opens a new figure unless a 'parent' Property is provided with an axis
% handle.
%
% FORMAT H = spm_mesh_render(M)
% Shortcut to previous call format.
%
% FORMAT H = spm_mesh_render('ContextMenu',AX)
% AX - axis handle or structure returned by spm_mesh_render('Disp',...)
%
% FORMAT H = spm_mesh_render('Overlay',AX,P)
% AX - axis handle or structure given by spm_mesh_render('Disp',...)
% P - data to be overlayed on mesh (see spm_mesh_project)
%
% FORMAT H = spm_mesh_render('ColourBar',AX,MODE)
% AX - axis handle or structure returned by spm_mesh_render('Disp',...)
% MODE - {['on'],'off'}
%
% FORMAT H = spm_mesh_render('ColourMap',AX,MAP)
% AX - axis handle or structure returned by spm_mesh_render('Disp',...)
% MAP - a colour map matrix
%
% FORMAT MAP = spm_mesh_render('ColourMap',AX)
% Retrieves the current colourmap.
%
% FORMAT spm_mesh_render('Register',AX,hReg)
% AX - axis handle or structure returned by spm_mesh_render('Disp',...)
% hReg - Handle of HandleGraphics object to build registry in.
% See spm_XYZreg for more information.
%__________________________________________________________________________
% Copyright (C) 2010-2011 Wellcome Trust Centre for Neuroimaging
% Guillaume Flandin
% $Id: spm_mesh_render.m 4590 2011-12-14 12:24:24Z guillaume $
%-Input parameters
%--------------------------------------------------------------------------
if ~nargin, action = 'Disp'; end
if ~ischar(action)
varargin = {action varargin{:}};
action = 'Disp';
end
varargout = {[]};
%-Action
%--------------------------------------------------------------------------
switch lower(action)
%-Display
%======================================================================
case 'disp'
if isempty(varargin)
[M, sts] = spm_select(1,'mesh','Select surface mesh file');
if ~sts, return; end
else
M = varargin{1};
end
if ischar(M), M = export(gifti(M),'patch'); end
O = getOptions(varargin{2:end});
%-Figure & Axis
%------------------------------------------------------------------
if isfield(O,'parent')
H.axis = O.parent;
H.figure = ancestor(H.axis,'figure');
else
H.figure = figure('Color',[1 1 1]);
H.axis = axes('Parent',H.figure);
set(H.axis,'Visible','off');
end
renderer = get(H.figure,'Renderer');
set(H.figure,'Renderer','OpenGL');
%-Patch
%------------------------------------------------------------------
P = struct('vertices',M.vertices, 'faces',M.faces);
H.patch = patch(P,...
'FaceColor', [0.6 0.6 0.6],...
'EdgeColor', 'none',...
'FaceLighting', 'phong',...
'SpecularStrength', 0.7,...
'AmbientStrength', 0.1,...
'DiffuseStrength', 0.7,...
'SpecularExponent', 10,...
'Clipping', 'off',...
'DeleteFcn', {@myDeleteFcn, renderer},...
'Visible', 'off',...
'Tag', 'SPMMeshRender',...
'Parent', H.axis);
setappdata(H.patch,'patch',P);
%-Label connected components of the mesh
%------------------------------------------------------------------
C = spm_mesh_label(P);
setappdata(H.patch,'cclabel',C);
%-Compute mesh curvature
%------------------------------------------------------------------
curv = spm_mesh_curvature(P) > 0;
setappdata(H.patch,'curvature',curv);
%-Apply texture to mesh
%------------------------------------------------------------------
updateTexture(H,[]);
%-Set viewpoint, light and manipulation options
%------------------------------------------------------------------
axis(H.axis,'image');
axis(H.axis,'off');
view(H.axis,[-90 0]);
material(H.figure,'dull');
H.light = camlight; set(H.light,'Parent',H.axis);
H.rotate3d = rotate3d(H.axis);
set(H.rotate3d,'Enable','on');
set(H.rotate3d,'ActionPostCallback',{@myPostCallback, H});
%try
% setAllowAxesRotate(H.rotate3d, ...
% setxor(findobj(H.figure,'Type','axes'),H.axis), false);
%end
%-Store handles
%------------------------------------------------------------------
setappdata(H.axis,'handles',H);
set(H.patch,'Visible','on');
%-Add context menu
%------------------------------------------------------------------
spm_mesh_render('ContextMenu',H);
%-Context Menu
%======================================================================
case 'contextmenu'
if isempty(varargin), varargin{1} = gca; end
H = getHandles(varargin{1});
if ~isempty(get(H.patch,'UIContextMenu')), return; end
cmenu = uicontextmenu('Callback',{@myMenuCallback, H});
uimenu(cmenu, 'Label','Inflate', 'Interruptible','off', ...
'Callback',{@myInflate, H});
uimenu(cmenu, 'Label','Overlay...', 'Interruptible','off', ...
'Callback',{@myOverlay, H});
uimenu(cmenu, 'Label','Image Sections...', 'Interruptible','off', ...
'Callback',{@myImageSections, H});
c = uimenu(cmenu, 'Label', 'Connected Components', 'Interruptible','off');
C = getappdata(H.patch,'cclabel');
for i=1:length(unique(C))
uimenu(c, 'Label',sprintf('Component %d',i), 'Checked','on', ...
'Callback',{@myCCLabel, H});
end
uimenu(cmenu, 'Label','Rotate', 'Checked','on', 'Separator','on', ...
'Callback',{@mySwitchRotate, H});
uimenu(cmenu, 'Label','Synchronise Views', 'Visible','off', ...
'Checked','off', 'Tag','SynchroMenu', 'Callback',{@mySynchroniseViews, H});
c = uimenu(cmenu, 'Label','View');
uimenu(c, 'Label','Go to Y-Z view (right)', 'Callback', {@myView, H, [90 0]});
uimenu(c, 'Label','Go to Y-Z view (left)', 'Callback', {@myView, H, [-90 0]});
uimenu(c, 'Label','Go to X-Y view (top)', 'Callback', {@myView, H, [0 90]});
uimenu(c, 'Label','Go to X-Y view (bottom)', 'Callback', {@myView, H, [-180 -90]});
uimenu(c, 'Label','Go to X-Z view (front)', 'Callback', {@myView, H, [-180 0]});
uimenu(c, 'Label','Go to X-Z view (back)', 'Callback', {@myView, H, [0 0]});
uimenu(cmenu, 'Label','Colorbar', 'Callback', {@myColourbar, H});
c = uimenu(cmenu, 'Label','Colormap');
clrmp = {'hot' 'jet' 'gray' 'hsv' 'bone' 'copper' 'pink' 'white' ...
'flag' 'lines' 'colorcube' 'prism' 'cool' 'autumn' ...
'spring' 'winter' 'summer'};
for i=1:numel(clrmp)
uimenu(c, 'Label', clrmp{i}, 'Callback', {@myColourmap, H});
end
c = uimenu(cmenu, 'Label','Transparency');
uimenu(c, 'Label','0%', 'Checked','on', 'Callback', {@myTransparency, H});
uimenu(c, 'Label','20%', 'Checked','off', 'Callback', {@myTransparency, H});
uimenu(c, 'Label','40%', 'Checked','off', 'Callback', {@myTransparency, H});
uimenu(c, 'Label','60%', 'Checked','off', 'Callback', {@myTransparency, H});
uimenu(c, 'Label','80%', 'Checked','off', 'Callback', {@myTransparency, H});
uimenu(cmenu, 'Label','Data Cursor', 'Callback', {@myDataCursor, H});
c = uimenu(cmenu, 'Label','Background Color');
uimenu(c, 'Label','White', 'Callback', {@myBackgroundColor, H, [1 1 1]});
uimenu(c, 'Label','Black', 'Callback', {@myBackgroundColor, H, [0 0 0]});
uimenu(c, 'Label','Custom...', 'Callback', {@myBackgroundColor, H, []});
uimenu(cmenu, 'Label','Save As...', 'Separator', 'on', ...
'Callback', {@mySave, H});
set(H.rotate3d,'enable','off');
try, set(H.rotate3d,'uicontextmenu',cmenu); end
try, set(H.patch, 'uicontextmenu',cmenu); end
set(H.rotate3d,'enable','on');
dcm_obj = datacursormode(H.figure);
set(dcm_obj, 'Enable','off', 'SnapToDataVertex','on', ...
'DisplayStyle','Window', 'Updatefcn',{@myDataCursorUpdate, H});
%-Overlay
%======================================================================
case 'overlay'
if isempty(varargin), varargin{1} = gca; end
H = getHandles(varargin{1});
if nargin < 3, varargin{2} = []; end
updateTexture(H,varargin{2:end});
%-Slices
%======================================================================
case 'slices'
if isempty(varargin), varargin{1} = gca; end
H = getHandles(varargin{1});
if nargin < 3, varargin{2} = []; end
renderSlices(H,varargin{2:end});
%-ColourBar
%======================================================================
case {'colourbar', 'colorbar'}
if isempty(varargin), varargin{1} = gca; end
if length(varargin) == 1, varargin{2} = 'on'; end
H = getHandles(varargin{1});
d = getappdata(H.patch,'data');
col = getappdata(H.patch,'colourmap');
if strcmpi(varargin{2},'off')
if isfield(H,'colourbar') && ishandle(H.colourbar)
delete(H.colourbar);
H = rmfield(H,'colourbar');
setappdata(H.axis,'handles',H);
end
return;
end
if isempty(d) || ~any(d(:)), varargout = {H}; return; end
if isempty(col), col = hot(256); end
if ~isfield(H,'colourbar') || ~ishandle(H.colourbar)
H.colourbar = colorbar('peer',H.axis);
set(H.colourbar,'Tag','');
set(get(H.colourbar,'Children'),'Tag','');
end
c(1:size(col,1),1,1:size(col,2)) = col;
ic = findobj(H.colourbar,'Type','image');
if size(d,1) > 1
set(ic,'CData',c(1:size(d,1),:,:));
set(ic,'YData',[1 size(d,1)]);
set(H.colourbar,'YLim',[1 size(d,1)]);
set(H.colourbar,'YTickLabel',[]);
else
set(ic,'CData',c);
clim = getappdata(H.patch,'clim');
if isempty(clim), clim = [false min(d) max(d)]; end
set(ic,'YData',clim(2:3));
set(H.colourbar,'YLim',clim(2:3));
end
setappdata(H.axis,'handles',H);
%-ColourMap
%======================================================================
case {'colourmap', 'colormap'}
if isempty(varargin), varargin{1} = gca; end
H = getHandles(varargin{1});
if length(varargin) == 1
varargout = { getappdata(H.patch,'colourmap') };
return;
else
setappdata(H.patch,'colourmap',varargin{2});
d = getappdata(H.patch,'data');
updateTexture(H,d);
end
%-CLim
%======================================================================
case 'clim'
if isempty(varargin), varargin{1} = gca; end
H = getHandles(varargin{1});
if length(varargin) == 1
c = getappdata(H.patch,'clim');
if ~isempty(c), c = c(2:3); end
varargout = { c };
return;
else
if isempty(varargin{2}) || any(~isfinite(varargin{2}))
setappdata(H.patch,'clim',[false NaN NaN]);
else
setappdata(H.patch,'clim',[true varargin{2}]);
end
d = getappdata(H.patch,'data');
updateTexture(H,d);
end
%-Register
%======================================================================
case 'register'
if isempty(varargin), varargin{1} = gca; end
H = getHandles(varargin{1});
hReg = varargin{2};
xyz = spm_XYZreg('GetCoords',hReg);
hs = myCrossBar('Create',H,xyz);
set(hs,'UserData',hReg);
spm_XYZreg('Add2Reg',hReg,hs,@myCrossBar);
%-Otherwise...
%======================================================================
otherwise
try
H = spm_mesh_render('Disp',action,varargin{:});
catch
error('Unknown action.');
end
end
varargout = {H};
%==========================================================================
function O = getOptions(varargin)
O = [];
if ~nargin
return;
elseif nargin == 1 && isstruct(varargin{1})
for i=fieldnames(varargin{1})
O.(lower(i{1})) = varargin{1}.(i{1});
end
elseif mod(nargin,2) == 0
for i=1:2:numel(varargin)
O.(lower(varargin{i})) = varargin{i+1};
end
else
error('Invalid list of property/value pairs.');
end
%==========================================================================
function H = getHandles(H)
if ~nargin || isempty(H), H = gca; end
if ishandle(H) && ~isappdata(H,'handles')
a = H; clear H;
H.axis = a;
H.figure = ancestor(H.axis,'figure');
H.patch = findobj(H.axis,'type','patch');
H.light = findobj(H.axis,'type','light');
H.rotate3d = rotate3d(H.figure);
setappdata(H.axis,'handles',H);
elseif ishandle(H)
H = getappdata(H,'handles');
else
H = getappdata(H.axis,'handles');
end
%==========================================================================
function myMenuCallback(obj,evt,H)
H = getHandles(H);
h = findobj(obj,'Label','Rotate');
if strcmpi(get(H.rotate3d,'Enable'),'on')
set(h,'Checked','on');
else
set(h,'Checked','off');
end
if numel(findobj('Tag','SPMMeshRender','Type','Patch')) > 1
h = findobj(obj,'Tag','SynchroMenu');
set(h,'Visible','on');
end
h = findobj(obj,'Label','Colorbar');
d = getappdata(H.patch,'data');
if isempty(d) || ~any(d(:)), set(h,'Enable','off'); else set(h,'Enable','on'); end
if isfield(H,'colourbar')
if ishandle(H.colourbar)
set(h,'Checked','on');
else
H = rmfield(H,'colourbar');
set(h,'Checked','off');
end
else
set(h,'Checked','off');
end
setappdata(H.axis,'handles',H);
%==========================================================================
function myPostCallback(obj,evt,H)
P = findobj('Tag','SPMMeshRender','Type','Patch');
if numel(P) == 1
camlight(H.light);
else
for i=1:numel(P)
H = getappdata(ancestor(P(i),'axes'),'handles');
camlight(H.light);
end
end
%==========================================================================
function varargout = myCrossBar(varargin)
switch lower(varargin{1})
case 'create'
%----------------------------------------------------------------------
% hMe = myCrossBar('Create',H,xyz)
H = varargin{2};
xyz = varargin{3};
hold(H.axis,'on');
hs = plot3(xyz(1),xyz(2),xyz(3),'Marker','+','MarkerSize',40,...
'parent',H.axis,'Color',[1 1 1],'Tag','CrossBar','ButtonDownFcn',{});
varargout = {hs};
case 'setcoords'
%----------------------------------------------------------------------
% [xyz,d] = myCrossBar('SetCoords',xyz,hMe)
hMe = varargin{3};
xyz = varargin{2};
set(hMe,'XData',xyz(1));
set(hMe,'YData',xyz(2));
set(hMe,'ZData',xyz(3));
varargout = {xyz,[]};
otherwise
%----------------------------------------------------------------------
error('Unknown action string')
end
%==========================================================================
function myInflate(obj,evt,H)
spm_mesh_inflate(H.patch,Inf,1);
axis(H.axis,'image');
%==========================================================================
function myCCLabel(obj,evt,H)
C = getappdata(H.patch,'cclabel');
F = get(H.patch,'Faces');
ind = sscanf(get(obj,'Label'),'Component %d');
V = get(H.patch,'FaceVertexAlphaData');
Fa = get(H.patch,'FaceAlpha');
if ~isnumeric(Fa)
if ~isempty(V), Fa = max(V); else Fa = 1; end
if Fa == 0, Fa = 1; end
end
if isempty(V) || numel(V) == 1
Ve = get(H.patch,'Vertices');
if isempty(V) || V == 1
V = Fa * ones(size(Ve,1),1);
else
V = zeros(size(Ve,1),1);
end
end
if strcmpi(get(obj,'Checked'),'on')
V(reshape(F(C==ind,:),[],1)) = 0;
set(obj,'Checked','off');
else
V(reshape(F(C==ind,:),[],1)) = Fa;
set(obj,'Checked','on');
end
set(H.patch, 'FaceVertexAlphaData', V);
if all(V)
set(H.patch, 'FaceAlpha', Fa);
else
set(H.patch, 'FaceAlpha', 'interp');
end
%==========================================================================
function myTransparency(obj,evt,H)
t = 1 - sscanf(get(obj,'Label'),'%d%%') / 100;
set(H.patch,'FaceAlpha',t);
set(get(get(obj,'parent'),'children'),'Checked','off');
set(obj,'Checked','on');
%==========================================================================
function mySwitchRotate(obj,evt,H)
if strcmpi(get(H.rotate3d,'enable'),'on')
set(H.rotate3d,'enable','off');
set(obj,'Checked','off');
else
set(H.rotate3d,'enable','on');
set(obj,'Checked','on');
end
%==========================================================================
function myView(obj,evt,H,varargin)
view(H.axis,varargin{1});
axis(H.axis,'image');
camlight(H.light);
%==========================================================================
function myColourbar(obj,evt,H)
y = {'on','off'}; toggle = @(x) y{1+strcmpi(x,'on')};
spm_mesh_render('Colourbar',H,toggle(get(obj,'Checked')));
%==========================================================================
function myColourmap(obj,evt,H)
spm_mesh_render('Colourmap',H,feval(get(obj,'Label'),256));
%==========================================================================
function mySynchroniseViews(obj,evt,H)
P = findobj('Tag','SPMMeshRender','Type','Patch');
v = get(H.axis,'cameraposition');
for i=1:numel(P)
H = getappdata(ancestor(P(i),'axes'),'handles');
set(H.axis,'cameraposition',v);
axis(H.axis,'image');
camlight(H.light);
end
%==========================================================================
function myDataCursor(obj,evt,H)
dcm_obj = datacursormode(H.figure);
set(dcm_obj, 'Enable','on', 'SnapToDataVertex','on', ...
'DisplayStyle','Window', 'Updatefcn',{@myDataCursorUpdate, H});
%==========================================================================
function txt = myDataCursorUpdate(obj,evt,H)
pos = get(evt,'Position');
txt = {['X: ',num2str(pos(1))],...
['Y: ',num2str(pos(2))],...
['Z: ',num2str(pos(3))]};
i = ismember(get(H.patch,'vertices'),pos,'rows');
txt = {['Node: ' num2str(find(i))] txt{:}};
d = getappdata(H.patch,'data');
if ~isempty(d) && any(d(:))
if any(i), txt = {txt{:} ['T: ',num2str(d(i))]}; end
end
hMe = findobj(H.axis,'Tag','CrossBar');
if ~isempty(hMe)
ws = warning('off');
spm_XYZreg('SetCoords',pos,get(hMe,'UserData'));
warning(ws);
end
%==========================================================================
function myBackgroundColor(obj,evt,H,varargin)
if isempty(varargin{1})
c = uisetcolor(H.figure, ...
'Pick a background color...');
if numel(c) == 1, return; end
else
c = varargin{1};
end
h = findobj(H.figure,'Tag','SPMMeshRenderBackground');
if isempty(h)
set(H.figure,'Color',c);
else
set(h,'Color',c);
end
%==========================================================================
function mySave(obj,evt,H)
[filename, pathname, filterindex] = uiputfile({...
'*.gii' 'GIfTI files (*.gii)'; ...
'*.png' 'PNG files (*.png)';...
'*.dae' 'Collada files (*.dae)';...
'*.idtf' 'IDTF files (*.idtf)'}, 'Save as');
if ~isequal(filename,0) && ~isequal(pathname,0)
[pth,nam,ext] = fileparts(filename);
switch ext
case '.gii'
filterindex = 1;
case '.png'
filterindex = 2;
case '.dae'
filterindex = 3;
case '.idtf'
filterindex = 4;
otherwise
switch filterindex
case 1
filename = [filename '.gii'];
case 2
filename = [filename '.png'];
case 3
filename = [filename '.dae'];
end
end
switch filterindex
case 1
G = gifti(H.patch);
[p,n,e] = fileparts(filename);
[p,n,e] = fileparts(n);
switch lower(e)
case '.func'
save(gifti(getappdata(H.patch,'data')),...
fullfile(pathname, filename));
case '.surf'
save(gifti(struct('vertices',G.vertices,'faces',G.faces)),...
fullfile(pathname, filename));
case '.rgba'
save(gifti(G.cdata),fullfile(pathname, filename));
otherwise
save(G,fullfile(pathname, filename));
end
case 2
u = get(H.axis,'units');
set(H.axis,'units','pixels');
p = get(H.axis,'Position');
r = get(H.figure,'Renderer');
hc = findobj(H.figure,'Tag','SPMMeshRenderBackground');
if isempty(hc)
c = get(H.figure,'Color');
else
c = get(hc,'Color');
end
h = figure('Position',p+[0 0 10 10], ...
'InvertHardcopy','off', ...
'Color',c, ...
'Renderer',r);
copyobj(H.axis,h);
set(H.axis,'units',u);
set(get(h,'children'),'visible','off');
%a = get(h,'children');
%set(a,'Position',get(a,'Position').*[0 0 1 1]+[10 10 0 0]);
if isdeployed
deployprint(h, '-dpng', '-opengl', fullfile(pathname, filename));
else
print(h, '-dpng', '-opengl', fullfile(pathname, filename));
end
close(h);
set(getappdata(obj,'fig'),'renderer',r);
case 3
save(gifti(H.patch),fullfile(pathname, filename),'collada');
case 4
save(gifti(H.patch),fullfile(pathname, filename),'idtf');
end
end
%==========================================================================
function myDeleteFcn(obj,evt,renderer)
try, rotate3d(get(obj,'parent'),'off'); end
set(ancestor(obj,'figure'),'Renderer',renderer);
%==========================================================================
function myOverlay(obj,evt,H)
[P, sts] = spm_select(1,'\.img|\.nii|\.gii|\.mat','Select file to overlay');
if ~sts, return; end
spm_mesh_render('Overlay',H,P);
%==========================================================================
function myImageSections(obj,evt,H)
[P, sts] = spm_select(1,'image','Select image to render');
if ~sts, return; end
renderSlices(H,P);
%==========================================================================
function renderSlices(H,P,pls)
if nargin <3
pls = 0.05:0.2:0.9;
end
N = nifti(P);
d = size(N.dat);
pls = round(pls.*d(3));
hold(H.axis,'on');
for i=1:numel(pls)
[x,y,z] = ndgrid(1:d(1),1:d(2),pls(i));
f = N.dat(:,:,pls(i));
x1 = N.mat(1,1)*x + N.mat(1,2)*y + N.mat(1,3)*z + N.mat(1,4);
y1 = N.mat(2,1)*x + N.mat(2,2)*y + N.mat(2,3)*z + N.mat(2,4);
z1 = N.mat(3,1)*x + N.mat(3,2)*y + N.mat(3,3)*z + N.mat(3,4);
surf(x1,y1,z1, repmat(f,[1 1 3]), 'EdgeColor','none', ...
'Clipping','off', 'Parent',H.axis);
end
hold(H.axis,'off');
axis(H.axis,'image');
%==========================================================================
function C = updateTexture(H,v,col)
%-Get colourmap
%--------------------------------------------------------------------------
if nargin<3, col = getappdata(H.patch,'colourmap'); end
if isempty(col), col = hot(256); end
setappdata(H.patch,'colourmap',col);
%-Get curvature
%--------------------------------------------------------------------------
curv = getappdata(H.patch,'curvature');
if size(curv,2) == 1
curv = 0.5 * repmat(curv,1,3) + 0.3 * repmat(~curv,1,3);
end
%-Project data onto surface mesh
%--------------------------------------------------------------------------
if nargin < 2, v = []; end
if ischar(v)
[p,n,e] = fileparts(v);
if strcmp([n e],'SPM.mat')
swd = pwd;
spm_figure('GetWin','Interactive');
[SPM,v] = spm_getSPM(struct('swd',p));
cd(swd);
else
try, spm_vol(v); catch, v = gifti(v); end;
end
end
if isa(v,'gifti'), v = v.cdata; end
if isempty(v)
v = zeros(size(curv))';
elseif ischar(v) || iscellstr(v) || isstruct(v)
v = spm_mesh_project(H.patch,v);
elseif isnumeric(v) || islogical(v)
if size(v,2) == 1
v = v';
end
else
error('Unknown data type.');
end
v(isinf(v)) = NaN;
setappdata(H.patch,'data',v);
%-Create RGB representation of data according to colourmap
%--------------------------------------------------------------------------
C = zeros(size(v,2),3);
clim = getappdata(H.patch, 'clim');
if isempty(clim), clim = [false NaN NaN]; end
mi = clim(2); ma = clim(3);
if any(v(:))
if size(col,1)>3
if size(v,1) == 1
if ~clim(1), mi = min(v(:)); ma = max(v(:)); end
C = squeeze(ind2rgb(floor(((v(:)-mi)/(ma-mi))*size(col,1)),col));
else
C = v; v = v';
end
else
if ~clim(1), ma = max(v(:)); end
for i=1:size(v,1)
C = C + v(i,:)'/ma * col(i,:);
end
end
else
end
setappdata(H.patch, 'clim', [false mi ma]);
%-Build texture by merging curvature and data
%--------------------------------------------------------------------------
C = repmat(~any(v,1),3,1)' .* curv + repmat(any(v,1),3,1)' .* C;
set(H.patch, 'FaceVertexCData',C, 'FaceColor','interp');
%-Update the colourbar
%--------------------------------------------------------------------------
if isfield(H,'colourbar')
spm_mesh_render('Colourbar',H);
end
|
github
|
philippboehmsturm/antx-master
|
spm_smooth.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_smooth.m
| 3,746 |
utf_8
|
641f9055c7e9c0b87c38737330881a53
|
function spm_smooth(P,Q,s,dtype)
% 3 dimensional convolution of an image
% FORMAT spm_smooth(P,Q,S,dtype)
% P - image to be smoothed (or 3D array)
% Q - filename for smoothed image (or 3D array)
% S - [sx sy sz] Gaussian filter width {FWHM} in mm (or edges)
% dtype - datatype [default: 0 == same datatype as P]
%____________________________________________________________________________
%
% spm_smooth is used to smooth or convolve images in a file (maybe).
%
% The sum of kernel coeficients are set to unity. Boundary
% conditions assume data does not exist outside the image in z (i.e.
% the kernel is truncated in z at the boundaries of the image space). S
% can be a vector of 3 FWHM values that specifiy an anisotropic
% smoothing. If S is a scalar isotropic smoothing is implemented.
%
% If Q is not a string, it is used as the destination of the smoothed
% image. It must already be defined with the same number of elements
% as the image.
%
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner & Tom Nichols
% $Id: spm_smooth.m 4172 2011-01-26 12:13:29Z guillaume $
%-----------------------------------------------------------------------
if numel(s) == 1, s = [s s s]; end
if nargin < 4, dtype = 0; end;
if ischar(P), P = spm_vol(P); end;
if isstruct(P),
for i= 1:numel(P),
smooth1(P(i),Q,s,dtype);
end
else
smooth1(P,Q,s,dtype);
end
%_______________________________________________________________________
%_______________________________________________________________________
function smooth1(P,Q,s,dtype)
if isstruct(P),
VOX = sqrt(sum(P.mat(1:3,1:3).^2));
else
VOX = [1 1 1];
end;
if ischar(Q) && isstruct(P),
[pth,nam,ext,num] = spm_fileparts(Q);
q = fullfile(pth,[nam,ext]);
Q = P;
Q.fname = q;
if ~isempty(num),
Q.n = str2num(num);
end;
if ~isfield(Q,'descrip'), Q.descrip = sprintf('SPM compatible'); end;
Q.descrip = sprintf('%s - conv(%g,%g,%g)',Q.descrip, s);
if dtype~=0, % Need to figure out some rescaling.
Q.dt(1) = dtype;
if ~isfinite(spm_type(Q.dt(1),'maxval')),
Q.pinfo = [1 0 0]'; % float or double, so scalefactor of 1
else
% Need to determine the range of intensities
if isfinite(spm_type(P.dt(1),'maxval')),
% Integer types have a defined maximum value
maxv = spm_type(P.dt(1),'maxval')*P.pinfo(1) + P.pinfo(2);
else
% Need to find the max and min values in original image
mx = -Inf;
mn = Inf;
for pl=1:P.dim(3),
tmp = spm_slice_vol(P,spm_matrix([0 0 pl]),P.dim(1:2),0);
tmp = tmp(isfinite(tmp));
mx = max(max(tmp),mx);
mn = min(min(tmp),mn);
end
maxv = max(mx,-mn);
end
sf = maxv/spm_type(Q.dt(1),'maxval');
Q.pinfo = [sf 0 0]';
end
end
end
% compute parameters for spm_conv_vol
%-----------------------------------------------------------------------
s = s./VOX; % voxel anisotropy
s1 = s/sqrt(8*log(2)); % FWHM -> Gaussian parameter
x = round(6*s1(1)); x = -x:x; x = spm_smoothkern(s(1),x,1); x = x/sum(x);
y = round(6*s1(2)); y = -y:y; y = spm_smoothkern(s(2),y,1); y = y/sum(y);
z = round(6*s1(3)); z = -z:z; z = spm_smoothkern(s(3),z,1); z = z/sum(z);
i = (length(x) - 1)/2;
j = (length(y) - 1)/2;
k = (length(z) - 1)/2;
if isstruct(Q), Q = spm_create_vol(Q); end;
spm_conv_vol(P,Q,x,y,z,-[i,j,k]);
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_inv_imag_api.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_eeg_inv_imag_api.m
| 15,840 |
utf_8
|
169f5a7cb18e2a5ae436135b1c16203c
|
function varargout = spm_eeg_inv_imag_api(varargin)
% API for EEG/MEG source reconstruction interface
% FORMAT:
% FIG = SPM_EEG_INV_IMAG_API launch spm_eeg_inv_imag_api GUI.
% SPM_EEG_INV_IMAG_API('callback_name', ...) invoke the named callback.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Jeremie Mattout
% $Id: spm_eeg_inv_imag_api.m 4260 2011-03-23 13:42:21Z vladimir $
spm('Clear');
% Launch API
%==========================================================================
if nargin < 2
% open figure
%----------------------------------------------------------------------
fig = openfig(mfilename,'reuse');
set(fig,'name',[spm('ver') ': ' get(fig,'name')]);
Rect = spm('WinSize','Menu');
S0 = spm('WinSize','0',1);
set(fig,'units','pixels');
Fdim = get(fig,'position');
set(fig,'position',[S0(1)+Rect(1) S0(2)+Rect(2) Fdim(3) Fdim(4)]);
handles = guihandles(fig);
% Use system color scheme for figure:
%----------------------------------------------------------------------
set(fig,'Color',get(0,'defaultUicontrolBackgroundColor'));
handles.fig = fig;
guidata(fig,handles);
% intialise with D
%----------------------------------------------------------------------
try
D = spm_eeg_inv_check(varargin{1});
set(handles.DataFile,'String',D.fname);
set(handles.Exit,'enable','on')
cd(D.path);
handles.D = D;
Reset(fig, [], handles);
guidata(fig,handles);
end
% INVOKE NAMED SUBFUNCTION OR CALLBACK
%--------------------------------------------------------------------------
elseif ischar(varargin{1})
if nargout
[varargout{1:nargout}] = feval(varargin{:}); % FEVAL switchyard
else
feval(varargin{:}); % FEVAL switchyard
end
else
error('Wrong input format.');
end
% MAIN FUNCTIONS FOR MODEL SEPCIFICATION AND INVERSION
%==========================================================================
% --- Executes on button press in CreateMeshes.
%--------------------------------------------------------------------------
function CreateMeshes_Callback(hObject, eventdata, handles)
handles.D = spm_eeg_inv_mesh_ui(handles.D, handles.D.val, 0);
Reset(hObject, eventdata, handles);
% --- Executes on button press in Reg2tem.
%--------------------------------------------------------------------------
function Reg2tem_Callback(hObject, eventdata, handles)
handles.D = spm_eeg_inv_mesh_ui(handles.D, handles.D.val, 1);
Reset(hObject, eventdata, handles);
% --- Executes on button press in Data Reg.
%--------------------------------------------------------------------------
function DataReg_Callback(hObject, eventdata, handles)
handles.D = spm_eeg_inv_datareg_ui(handles.D);
Reset(hObject, eventdata, handles);
% --- Executes on button press in Forward Model.
%--------------------------------------------------------------------------
function Forward_Callback(hObject, eventdata, handles)
handles.D = spm_eeg_inv_forward_ui(handles.D);
Reset(hObject, eventdata, handles);
% --- Executes on button press in Invert.
%--------------------------------------------------------------------------
function Inverse_Callback(hObject, eventdata, handles)
handles.D = spm_eeg_invert_ui(handles.D);
Reset(hObject, eventdata, handles);
% --- Executes on button press in contrast.
%--------------------------------------------------------------------------
function contrast_Callback(hObject, eventdata, handles)
handles.D = spm_eeg_inv_results_ui(handles.D);
Reset(hObject, eventdata, handles);
% --- Executes on button press in Image.
%--------------------------------------------------------------------------
function Image_Callback(hObject, eventdata,handles)
handles.D.inv{handles.D.val}.contrast.display = 1;
handles.D = spm_eeg_inv_Mesh2Voxels(handles.D);
Reset(hObject, eventdata, handles);
% LOAD AND EXIT
%==========================================================================
% --- Executes on button press in Load.
%--------------------------------------------------------------------------
function Load_Callback(hObject, eventdata, handles)
[S, sts] = spm_select(1, 'mat', 'Select M/EEG mat file');
if ~sts, return; end
D = spm_eeg_load(S);
[ok, D] = check(D, 'sensfid');
if ~ok
if check(D, 'basic')
warndlg(['The requested file is not ready for source reconstruction.'...
'See Matlab window for details.']);
else
warndlg('The meeg file is corrupt or incomplete');
end
return
end
set(handles.DataFile,'String',D.fname);
set(handles.Exit,'enable','on');
cd(D.path);
handles.D = D;
Reset(hObject, eventdata, handles);
% --- Executes on button press in Exit.
%--------------------------------------------------------------------------
function Exit_Callback(hObject, eventdata, handles)
D = handles.D;
D.save;
varargout{1} = handles.D;
assignin('base','D',handles.D)
% FUCNTIONS FOR MANAGING DIFFERENT MODELS
%==========================================================================
% --- Executes on button press in new.
%--------------------------------------------------------------------------
function new_Callback(hObject, eventdata, handles)
D = handles.D;
if ~isfield(D,'inv')
val = 1;
elseif isempty(D.inv)
val = 1;
else
val = length(D.inv) + 1;
D.inv{val} = D.inv{D.val};
end
% set D in handles and update analysis specific buttons
%--------------------------------------------------------------------------
D.val = val;
D = set_CommentDate(D);
handles.D = D;
set(handles.CreateMeshes,'enable','on')
set(handles.Reg2tem,'enable','on')
Reset(hObject, eventdata, handles);
% --- Executes on button press in next.
%--------------------------------------------------------------------------
function next_Callback(hObject, eventdata, handles)
if handles.D.val < length(handles.D.inv)
handles.D.val = handles.D.val + 1;
end
Reset(hObject, eventdata, handles);
% --- Executes on button press in previous.
%--------------------------------------------------------------------------
function previous_Callback(hObject, eventdata, handles)
if handles.D.val > 1
handles.D.val = handles.D.val - 1;
end
Reset(hObject, eventdata, handles);
% --- Executes on button press in clear.
%--------------------------------------------------------------------------
function clear_Callback(hObject, eventdata, handles)
try
inv.comment = handles.D.inv{handles.D.val}.comment;
inv.date = handles.D.inv{handles.D.val}.date;
handles.D.inv{handles.D.val} = inv;
end
Reset(hObject, eventdata, handles);
% --- Executes on button press in delete.
%--------------------------------------------------------------------------
function delete_Callback(hObject, eventdata, handles)
if ~isempty(handles.D.inv)
try
str = handles.D.inv{handles.D.val}.comment;
warndlg({'you are about to delete:',str{1}});
uiwait
end
handles.D.inv(handles.D.val) = [];
handles.D.val = handles.D.val - 1;
end
Reset(hObject, eventdata, handles);
% Auxillary functions
%==========================================================================
function Reset(hObject, eventdata, handles)
% Check to see if a new analysis is required
%--------------------------------------------------------------------------
try
set(handles.DataFile,'String',handles.D.fname);
end
if ~isfield(handles.D,'inv')
new_Callback(hObject, eventdata, handles)
return
end
if isempty(handles.D.inv)
new_Callback(hObject, eventdata, handles)
return
end
try
val = handles.D.val;
handles.D.inv{val};
catch
handles.D.val = 1;
val = 1;
end
% analysis specification buttons
%--------------------------------------------------------------------------
Q = handles.D.inv{val};
% === This is for backward compatibility with SPM8b. Can be removed after
% some time
if isfield(Q, 'mesh') &&...
isfield(Q.mesh, 'tess_ctx') && ~isa(Q.mesh.tess_ctx, 'char')
warning(['This is an old version of SPM8b inversion. ',...
'You can only review and export solutions. ',...
'Clear and invert again to update']);
Q = rmfield(Q, {'mesh', 'datareg', 'forward'});
end
% =========================================================================
set(handles.new, 'enable','on','value',0)
set(handles.clear, 'enable','on','value',0)
set(handles.delete, 'enable','on','value',0)
set(handles.next, 'value',0)
set(handles.previous, 'value',0)
if val < length(handles.D.inv)
set(handles.next, 'enable','on')
end
if val > 1
set(handles.previous,'enable','on')
end
if val == 1
set(handles.previous,'enable','off')
end
if val == length(handles.D.inv)
set(handles.next, 'enable','off')
end
try
str = sprintf('%i: %s',val,Q.comment{1});
catch
try
str = sprintf('%i: %s',val,Q.comment);
catch
str = sprintf('%i',val);
end
end
set(handles.val, 'Value',val,'string',str);
% condition specification
%--------------------------------------------------------------------------
try
handles.D.con = max(handles.D.con,1);
if handles.D.con > length(handles.D.inv{val}.inverse.J);
handles.D.con = 1;
end
catch
try
handles.D.con = length(handles.D.inv{val}.inverse.J);
catch
handles.D.con = 0;
end
end
if handles.D.con
str = sprintf('condition %d',handles.D.con);
set(handles.con,'String',str,'Enable','on','Value',0)
else
set(handles.con,'Enable','off','Value',0)
end
% check anaylsis buttons
%--------------------------------------------------------------------------
set(handles.DataReg, 'enable','off')
set(handles.Forward, 'enable','off')
set(handles.Inverse, 'enable','off')
set(handles.contrast,'enable','off')
set(handles.Image, 'enable','off')
set(handles.CheckReg, 'enable','off','Value',0)
set(handles.CheckMesh, 'enable','off','Value',0)
set(handles.CheckForward, 'enable','off','Value',0)
set(handles.CheckInverse, 'enable','off','Value',0)
set(handles.CheckContrast,'enable','off','Value',0)
set(handles.CheckImage, 'enable','off','Value',0)
set(handles.Movie, 'enable','off','Value',0)
set(handles.Vis3D, 'enable','off','Value',0)
set(handles.Image, 'enable','off','Value',0)
set(handles.CreateMeshes,'enable','on')
set(handles.Reg2tem,'enable','on')
if isfield(Q, 'mesh')
set(handles.DataReg, 'enable','on')
set(handles.CheckMesh,'enable','on')
if isfield(Q,'datareg') && isfield(Q.datareg, 'sensors')
set(handles.Forward, 'enable','on')
set(handles.CheckReg,'enable','on')
if isfield(Q,'forward') && isfield(Q.forward, 'vol')
set(handles.Inverse, 'enable','on')
set(handles.CheckForward,'enable','on')
end
end
end
if isfield(Q,'inverse') && isfield(Q, 'method')
set(handles.CheckInverse,'enable','on')
if isfield(Q.inverse,'J')
set(handles.contrast, 'enable','on')
set(handles.Movie, 'enable','on')
set(handles.Vis3D, 'enable','on')
if isfield(Q,'contrast')
set(handles.CheckContrast,'enable','on')
set(handles.Image, 'enable','on')
if isfield(Q.contrast,'fname')
set(handles.CheckImage,'enable','on')
end
end
end
end
try
if strcmp(handles.D.inv{handles.D.val}.method,'Imaging')
set(handles.CheckInverse,'String','mip');
set(handles.PST,'Enable','on');
else
set(handles.CheckInverse,'String','dip');
set(handles.PST,'Enable','off');
end
end
set(handles.fig,'Pointer','arrow')
assignin('base','D',handles.D)
guidata(hObject,handles);
% Set Comment and Date for new inverse analysis
%--------------------------------------------------------------------------
function S = set_CommentDate(D)
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{D.val}.date = strvcat(date,clck);
D.inv{D.val}.comment = inputdlg('Comment/Label for this analysis:');
S = D;
% CHECKS AND DISPLAYS
%==========================================================================
% --- Executes on button press in CheckMesh.
%--------------------------------------------------------------------------
function CheckMesh_Callback(hObject, eventdata, handles)
spm_eeg_inv_checkmeshes(handles.D);
Reset(hObject, eventdata, handles);
% --- Executes on button press in CheckReg.
%--------------------------------------------------------------------------
function CheckReg_Callback(hObject, eventdata, handles)
% check and display registration
%--------------------------------------------------------------------------
spm_eeg_inv_checkdatareg(handles.D);
Reset(hObject, eventdata, handles);
% --- Executes on button press in CheckForward.
%--------------------------------------------------------------------------
function CheckForward_Callback(hObject, eventdata, handles)
spm_eeg_inv_checkforward(handles.D);
Reset(hObject, eventdata, handles);
% --- Executes on button press in CheckInverse.
%--------------------------------------------------------------------------
function CheckInverse_Callback(hObject, eventdata, handles)
if strcmp(handles.D.inv{handles.D.val}.method,'Imaging')
PST = str2num(get(handles.PST,'String'));
spm_eeg_invert_display(handles.D,PST);
if length(PST) == 3 && get(handles.extract, 'Value')
handles.D = spm_eeg_inv_extract_ui(handles.D, handles.D.val, PST);
end
elseif strcmp(handles.D.inv{handles.D.val}.method, 'vbecd')
spm_eeg_inv_vbecd_disp('init',handles.D);
end
Reset(hObject, eventdata, handles);
% --- Executes on button press in Movie.
%--------------------------------------------------------------------------
function Movie_Callback(hObject, eventdata, handles)
figure(spm_figure('GetWin','Graphics'));
PST(1) = str2num(get(handles.Start,'String'));
PST(2) = str2num(get(handles.Stop ,'String'));
spm_eeg_invert_display(handles.D,PST);
Reset(hObject, eventdata, handles);
% --- Executes on button press in CheckContrast.
%--------------------------------------------------------------------------
function CheckContrast_Callback(hObject, eventdata, handles)
spm_eeg_inv_results_display(handles.D);
Reset(hObject, eventdata, handles);
% --- Executes on button press in Vis3D.
%--------------------------------------------------------------------------
function Vis3D_Callback(hObject, eventdata, handles)
Exit_Callback(hObject, eventdata, handles)
try
spm_eeg_inv_visu3D_api(handles.D);
catch
spm_eeg_review(handles.D,6,handles.D.val);
end
Reset(hObject, eventdata, handles);
% --- Executes on button press in CheckImage.
%--------------------------------------------------------------------------
function CheckImage_Callback(hObject, eventdata, handles)
spm_eeg_inv_image_display(handles.D)
Reset(hObject, eventdata, handles);
% --- Executes on button press in con.
%--------------------------------------------------------------------------
function con_Callback(hObject, eventdata, handles)
try
handles.D.con = handles.D.con + 1;
if handles.D.con > length(handles.D.inverse.J);
handles.D.con = 1;
end
end
Reset(hObject, eventdata, handles);
% --- Executes on button press in help.
%--------------------------------------------------------------------------
function help_Callback(hObject, eventdata, handles)
edit spm_eeg_inv_help
% --- Executes on button press in group.
%--------------------------------------------------------------------------
function group_Callback(hObject, eventdata, handles)
spm_eeg_inv_group;
|
github
|
philippboehmsturm/antx-master
|
spm_smoothto8bit.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_smoothto8bit.m
| 2,427 |
utf_8
|
d81ad311f697d9c9ad9899bd8115c3ce
|
function VO = spm_smoothto8bit(V,fwhm)
% 3 dimensional convolution of an image to 8bit data in memory
% FORMAT VO = spm_smoothto8bit(V,fwhm)
% V - mapped image to be smoothed
% fwhm - FWHM of Guassian filter width in mm
% VO - smoothed volume in a form that can be used by the
% spm_*_vol.mex* functions.
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_smoothto8bit.m 4310 2011-04-18 16:07:35Z guillaume $
if nargin>1 && fwhm>0,
VO = smoothto8bit(V,fwhm);
else
VO = V;
end
return;
%_______________________________________________________________________
%_______________________________________________________________________
function VO = smoothto8bit(V,fwhm)
% 3 dimensional convolution of an image to 8bit data in memory
% FORMAT VO = smoothto8bit(V,fwhm)
% V - mapped image to be smoothed
% fwhm - FWHM of Guassian filter width in mm
% VO - smoothed volume in a form that can be used by the
% spm_*_vol.mex* functions.
%_______________________________________________________________________
vx = sqrt(sum(V.mat(1:3,1:3).^2));
s = (fwhm./vx./sqrt(8*log(2)) + eps).^2;
r = cell(1,3);
for i=1:3,
r{i}.s = ceil(3.5*sqrt(s(i)));
x = -r{i}.s:r{i}.s;
r{i}.k = exp(-0.5 * (x.*x)/s(i))/sqrt(2*pi*s(i));
r{i}.k = r{i}.k/sum(r{i}.k);
end
buff = zeros([V.dim(1:2) r{3}.s*2+1]);
VO = V;
VO.dt = [spm_type('uint8') spm_platform('bigend')];
V0.dat = uint8(0);
V0.dat(VO.dim(1:3)) = uint8(0);
VO.pinfo = [];
for i=1:V.dim(3)+r{3}.s,
if i<=V.dim(3),
img = spm_slice_vol(V,spm_matrix([0 0 i]),V.dim(1:2),0);
msk = find(~isfinite(img));
img(msk) = 0;
buff(:,:,rem(i-1,r{3}.s*2+1)+1) = ...
conv2(conv2(img,r{1}.k,'same'),r{2}.k','same');
else
buff(:,:,rem(i-1,r{3}.s*2+1)+1) = 0;
end
if i>r{3}.s,
kern = zeros(size(r{3}.k'));
kern(rem((i:(i+r{3}.s*2))',r{3}.s*2+1)+1) = r{3}.k';
img = reshape(buff,[prod(V.dim(1:2)) r{3}.s*2+1])*kern;
img = reshape(img,V.dim(1:2));
ii = i-r{3}.s;
mx = max(img(:));
mn = min(img(:));
if mx==mn, mx=mn+eps; end
VO.pinfo(1:2,ii) = [(mx-mn)/255 mn]';
VO.dat(:,:,ii) = uint8(round((img-mn)*(255/(mx-mn))));
end
end
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_review_switchDisplay.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_eeg_review_switchDisplay.m
| 26,701 |
utf_8
|
a75c0568a1bf5e7efc01a71adf3e3e20
|
function [D] = spm_eeg_review_switchDisplay(D)
% Switch between displays in the M/EEG Review facility
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Jean Daunizeau
% $Id: spm_eeg_review_switchDisplay.m 4136 2010-12-09 22:22:28Z guillaume $
try % only if already displayed stuffs
handles = rmfield(D.PSD.handles,'PLOT');
D.PSD.handles = handles;
end
switch D.PSD.VIZU.modality
case 'source'
delete(findobj('tag','plotEEG'));
[D] = visuRecon(D);
case 'info'
[D] = DataInfo(D);
set(D.PSD.handles.hfig,'userdata',D)
otherwise % plot data (EEG/MEG/OTHER)
try
y = D.data.y(:,D.PSD.VIZU.xlim(1):D.PSD.VIZU.xlim(2));
% ! accelerates memory mapping reading
catch
D.PSD.VIZU.xlim = [1,min([5e2,D.Nsamples])];
end
switch D.PSD.VIZU.type
case 1
delete(findobj('tag','plotEEG'))
[D] = standardData(D);
cameratoolbar('resetcamera')
try cameratoolbar('close'); end
case 2
delete(findobj('tag','plotEEG'))
[D] = scalpData(D);
cameratoolbar('resetcamera')
try cameratoolbar('close'); end
end
end
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Standard EEG/MEG data plot
function [D] = standardData(D)
% POS = get(D.PSD.handles.hfig,'position');
switch D.PSD.VIZU.modality
case 'eeg'
I = D.PSD.EEG.I;
scb = 6;
case 'meg'
I = D.PSD.MEG.I;
scb = 6;
case 'megplanar'
I = D.PSD.MEGPLANAR.I;
scb = 6;
case 'other'
I = D.PSD.other.I;
scb = []; % no scalp interpolation button
end
if isempty(I)
uicontrol('style','text',...
'units','normalized','Position',[0.14 0.84 0.7 0.04],...
'string','No channel of this type in the SPM data file !',...
'BackgroundColor',0.95*[1 1 1],...
'tag','plotEEG')
else
if ~strcmp(D.transform.ID,'time')
uicontrol('style','text',...
'units','normalized','Position',[0.14 0.84 0.7 0.04],...
'string','Not for time-frequency data !',...
'BackgroundColor',0.95*[1 1 1],...
'tag','plotEEG')
else
D.PSD.VIZU.type = 1;
% add buttons
object.type = 'buttons';
object.options.multSelect = 0;
object.list = [2;3;4;5;scb];
switch D.PSD.type
case 'continuous'
object.list = [object.list;9];
case 'epoched'
object.list = [object.list;7;11];
if strcmp(D.type,'single')
object.list = [object.list;13];
end
end
D = spm_eeg_review_uis(D,object);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% 'SPM-like' EEG/MEG data plot
function [D] = scalpData(D)
% POS = get(D.PSD.handles.hfig,'position');
switch D.PSD.VIZU.modality
case 'eeg'
I = D.PSD.EEG.I;
case 'meg'
I = D.PSD.MEG.I;
case 'megplanar'
I = D.PSD.MEGPLANAR.I;
case 'other'
I = D.PSD.other.I;
end
if isempty(I)
uicontrol('style','text',...
'units','normalized','Position',[0.14 0.84 0.7 0.04],...
'string','No channel of this type in the SPM data file !',...
'BackgroundColor',0.95*[1 1 1],...
'tag','plotEEG')
else
if strcmp(D.PSD.type,'continuous')
uicontrol('style','text',...
'units','normalized','Position',[0.14 0.84 0.7 0.04],...
'string','Only for epoched data !',...
'BackgroundColor',0.95*[1 1 1],...
'tag','plotEEG')
else
D.PSD.VIZU.type = 2;
% add buttons
object.type = 'buttons';
object.list = [5;7];
if strcmp(D.transform.ID,'time') % only for time data!
object.options.multSelect = 1;
object.list = [object.list;4;6;11];
else
object.options.multSelect = 0;
end
if strcmp(D.type,'single')
object.list = [object.list;13];
end
D = spm_eeg_review_uis(D,object);
% add axes (!!give channels!!)
switch D.PSD.VIZU.modality
case 'eeg'
I = D.PSD.EEG.I;
ylim = D.PSD.EEG.VIZU.ylim;
case 'meg'
I = D.PSD.MEG.I;
ylim = D.PSD.MEG.VIZU.ylim;
case 'megplanar'
I = D.PSD.MEGPLANAR.I;
ylim = D.PSD.MEGPLANAR.VIZU.ylim;
case 'other'
I = D.PSD.other.I;
ylim = D.PSD.other.VIZU.ylim;
end
object.type = 'axes';
object.what = 'scalp';
object.options.channelPlot = I;
object.options.ylim = ylim;
D = spm_eeg_review_uis(D,object);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% RENDERING OF INVERSE SOLUTIONS
function [D] = visuRecon(D)
POS = get(D.PSD.handles.hfig,'position');
if ~~D.PSD.source.VIZU.current
isInv = D.PSD.source.VIZU.isInv;
Ninv = length(isInv);
if D.PSD.source.VIZU.current > Ninv
D.PSD.source.VIZU.current = 1;
end
invN = isInv(D.PSD.source.VIZU.current);
pst = D.PSD.source.VIZU.pst;
F = D.PSD.source.VIZU.F;
ID = D.PSD.source.VIZU.ID;
% create uitabs for inverse solutions
hInv = D.PSD.handles.tabs.hp;
[h] = spm_uitab(hInv,D.PSD.source.VIZU.labels,...
D.PSD.source.VIZU.callbacks,'plotEEG',...
D.PSD.source.VIZU.current);
D.PSD.handles.SubTabs_inv = h;
trN = D.PSD.trials.current(1);
model = D.other.inv{invN}.inverse;
D.PSD.source.VIZU.J = zeros(model.Nd,size(model.T,1));
D.PSD.source.VIZU.J(model.Is,:) = model.J{trN}*model.T';
D.PSD.source.VIZU.miJ = min(min(D.PSD.source.VIZU.J));
D.PSD.source.VIZU.maJ = max(max(D.PSD.source.VIZU.J));
J = D.PSD.source.VIZU.J;
miJ = D.PSD.source.VIZU.miJ;
maJ = D.PSD.source.VIZU.maJ;
time = (model.pst-0).^2;
indTime = find(time==min(time));
gridTime = model.pst(indTime);
% create axes
object.type = 'axes';
object.what = 'source';
object.options.Ninv = Ninv;
object.options.miJ = miJ;
object.options.maJ = maJ;
object.options.pst = pst;
D = spm_eeg_review_uis(D,object);
% plot BMC free energies in appropriate axes
if Ninv>1
if isnan(ID(invN))
xF = find(isnan(ID));
else
xF = find(abs(ID-ID(invN))<eps);
end
if length(xF)>1
D.PSD.handles.hbar = bar(D.PSD.handles.BMCplot,...
xF ,F(xF)-min(F(xF)),...
'barwidth',0.5,...
'FaceColor',0.5*[1 1 1],...
'visible','off',...
'tag','plotEEG');
D.PSD.handles.BMCcurrent = plot(D.PSD.handles.BMCplot,...
find(xF==invN),0,'ro',...
'visible','off',...
'tag','plotEEG');
set(D.PSD.handles.BMCplot,...
'xtick',xF,...
'xticklabel',D.PSD.source.VIZU.labels(xF),...
'xlim',[0,length(xF)+1]);
drawnow
end
end
% Create mesh and related objects
Dmesh = D.other.inv{invN}.mesh;
mesh.vertices = Dmesh.tess_mni.vert;
mesh.faces = Dmesh.tess_mni.face;
options.texture = J(:,indTime);
options.hfig = D.PSD.handles.hfig;
options.ParentAxes = D.PSD.handles.axes;
options.tag = 'plotEEG';
options.visible = 'off';
[out] = spm_eeg_render(mesh,options);
D.PSD.handles.mesh = out.handles.p;
D.PSD.handles.BUTTONS.transp = out.handles.transp;
D.PSD.handles.colorbar = out.handles.hc;
D.PSD.handles.BUTTONS.ct1 = out.handles.s1;
D.PSD.handles.BUTTONS.ct2 = out.handles.s2;
% add spheres if constrained inverse solution
if isfield(model,'dipfit')...
|| ~isequal(model.xyz,zeros(1,3))
try
xyz = model.dipfit.Lpos;
radius = model.dipfit.radius;
catch
xyz = model.xyz';
radius = model.rad(1);
end
Np = size(xyz,2);
[x,y,z] = sphere(20);
axes(D.PSD.handles.axes)
for i=1:Np
fvc = surf2patch(x.*radius+xyz(1,i),...
y.*radius+xyz(2,i),z.*radius+xyz(3,i));
D.PSD.handles.dipSpheres(i) = patch(fvc,...
'parent',D.PSD.handles.axes,...
'facecolor',[1 1 1],...
'edgecolor','none',...
'facealpha',0.5,...
'tag','dipSpheres');
end
axis(D.PSD.handles.axes,'tight');
end
% plot time courses
switch D.PSD.source.VIZU.timeCourses
case 1
Jp(1,:) = min(J,[],1);
Jp(2,:) = max(J,[],1);
D.PSD.source.VIZU.plotTC = plot(D.PSD.handles.axes2,...
model.pst,Jp',...
'color',0.5*[1 1 1],...
'visible','off');
% Add virtual electrode
try
ve = D.PSD.source.VIZU.ve;
catch
[mj ve] = max(max(abs(J),[],2));
D.PSD.source.VIZU.ve =ve;
end
Jve = J(D.PSD.source.VIZU.ve,:);
try
qC = model.qC(ve).*diag(model.qV)';
ci = 1.64*sqrt(qC);
D.PSD.source.VIZU.pve2 = plot(D.PSD.handles.axes2,...
model.pst,Jve +ci,'b:',model.pst,Jve -ci,'b:');
end
D.PSD.source.VIZU.pve = plot(D.PSD.handles.axes2,...
model.pst,Jve,...
'color','b',...
'visible','off');
otherwise
% this is meant to be extended for displaying something
% else than just J (e.g. J^2, etc...)
end
D.PSD.source.VIZU.lineTime = line('parent',D.PSD.handles.axes2,...
'xdata',[gridTime;gridTime],...
'ydata',[miJ;maJ],...
'visible','off');
set(D.PSD.handles.axes2,...
'ylim',[miJ;maJ]);
% create buttons
object.type = 'buttons';
object.list = [7;8;10];
object.options.multSelect = 0;
object.options.pst = pst;
object.options.gridTime = gridTime;
D = spm_eeg_review_uis(D,object);
% create info text
object.type = 'text';
object.what = 'source';
D = spm_eeg_review_uis(D,object);
% set graphical object visible
set(D.PSD.handles.mesh,'visible','on')
set(D.PSD.handles.colorbar,'visible','on')
set(D.PSD.handles.axes2,'visible','on')
set(D.PSD.source.VIZU.lineTime,'visible','on')
set(D.PSD.source.VIZU.plotTC,'visible','on')
set(D.PSD.source.VIZU.pve,'visible','on')
try
set(D.PSD.handles.BMCplot,'visible','on');
set(D.PSD.handles.hbar,'visible','on');
set(D.PSD.handles.BMCcurrent,'visible','on');
set(D.PSD.handles.BMCpanel,'visible','on');
end
set(D.PSD.handles.hfig,'userdata',D)
else
uicontrol('style','text',...
'units','normalized','Position',[0.14 0.84 0.7 0.04],...
'string','There is no (imaging) inverse source reconstruction in this data file !',...
'BackgroundColor',0.95*[1 1 1],...
'tag','plotEEG')
labels{1} = '1';
callbacks{1} = [];
hInv = D.PSD.handles.tabs.hp;
spm_uitab(hInv,labels,callbacks,'plotEEG');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% GET DATA INFO
function [D] = DataInfo(D)
switch D.PSD.VIZU.uitable
case 'off'
% delete graphical objects from other main tabs
delete(findobj('tag','plotEEG'));
% create info text
object.type = 'text';
object.what = 'data';
D = spm_eeg_review_uis(D,object);
% add buttons
object.type = 'buttons';
object.list = [14,15];
D = spm_eeg_review_uis(D,object);
set(D.PSD.handles.BUTTONS.showSensors,...
'position',[0.7 0.9 0.25 0.02]);
set(D.PSD.handles.BUTTONS.saveHistory,...
'string','save history as script',...
'position',[0.7 0.87 0.25 0.02]);
case 'on'
if isempty(D.PSD.VIZU.fromTab) || ~isequal(D.PSD.VIZU.fromTab,'info')
% delete graphical objects from other main tabs
delete(findobj('tag','plotEEG'));
% create info text
object.type = 'text';
object.what = 'data';
D = spm_eeg_review_uis(D,object);
% Create uitabs for channels and trials
try
D.PSD.VIZU.info;
catch
D.PSD.VIZU.info = 4;
end
labels = {'channels','trials','inv','history'};
callbacks = {'spm_eeg_review_callbacks(''visu'',''main'',''info'',1)',...,...
'spm_eeg_review_callbacks(''visu'',''main'',''info'',2)'...
'spm_eeg_review_callbacks(''visu'',''main'',''info'',3)',...
'spm_eeg_review_callbacks(''visu'',''main'',''info'',4)'};
[h] = spm_uitab(D.PSD.handles.tabs.hp,labels,callbacks,'plotEEG',D.PSD.VIZU.info,0.9);
D.PSD.handles.infoTabs = h;
else
% delete info table (if any)
try delete(D.PSD.handles.infoUItable);end
% delete info message (if any)
try delete(D.PSD.handles.message);end
% delete buttons if any
try delete(D.PSD.handles.BUTTONS.OKinfo);end
try delete(D.PSD.handles.BUTTONS.showSensors);end
try delete(D.PSD.handles.BUTTONS.saveHistory);end
end
% add table and buttons
object.type = 'buttons';
object.list = [];
switch D.PSD.VIZU.info
case 1 % channels info
object.list = [object.list;12;14];
nc = length(D.channels);
table = cell(nc,5);
for i=1:nc
table{i,1} = D.channels(i).label;
table{i,2} = D.channels(i).type;
if D.channels(i).bad
table{i,3} = 'yes';
else
table{i,3} = 'no';
end
if ~isempty(D.channels(i).X_plot2D)
table{i,4} = 'yes';
else
table{i,4} = 'no';
end
table{i,5} = D.channels(i).units;
end
colnames = {'label','type','bad','position','units'};
[ht,hc] = spm_uitable(table,colnames);
set(ht,'units','normalized');
set(hc,'position',[0.1 0.05 0.55 0.7],...
'tag','plotEEG');
D.PSD.handles.infoUItable = ht;
D.PSD.handles.infoUItable2 = hc;
D = spm_eeg_review_uis(D,object); % this adds the buttons
case 2 % trials info
object.list = [object.list;12];
ok = 1;
if strcmp(D.type,'continuous')
try
ne = length(D.trials(1).events);
if ne == 0
ok = 0;
end
catch
ne = 0;
ok = 0;
end
if ne > 0
table = cell(ne,3);
for i=1:ne
table{i,1} = D.trials(1).label;
table{i,2} = D.trials(1).events(i).type;
table{i,3} = num2str(D.trials(1).events(i).value);
if ~isempty(D.trials(1).events(i).duration)
table{i,4} = num2str(D.trials(1).events(i).duration);
else
table{i,4} = [];
end
table{i,5} = num2str(D.trials(1).events(i).time);
table{i,6} = 'Undefined';
table{i,7} = num2str(D.trials(1).onset);
end
colnames = {'label','type','value','duration','time','bad','onset'};
[ht,hc] = spm_uitable(table,colnames);
set(ht,'units','normalized');
set(hc,'position',[0.1 0.05 0.74 0.7],...
'tag','plotEEG');
else
POS = get(D.PSD.handles.infoTabs.hp,'position');
D.PSD.handles.message = uicontrol('style','text','units','normalized',...
'Position',[0.14 0.84 0.7 0.04].*repmat(POS(3:4),1,2),...
'string','There is no event in this data file !',...
'BackgroundColor',0.95*[1 1 1],...
'tag','plotEEG');
end
else
nt = length(D.trials);
table = cell(nt,3);
if strcmp(D.type,'single')
for i=1:nt
table{i,1} = D.trials(i).label;
ne = length(D.trials(i).events);
if ne == 0 || ((ne == 1) && isequal(D.trials(i).events(1).type, 'no events'))
table{i,2} = 'no events';
table{i,3} = 'no events';
table{i,4} = 'no events';
table{i,5} = 'no events';
elseif ne >1
table{i,2} = 'multiple events';
table{i,3} = 'multiple events';
table{i,4} = 'multiple events';
table{i,5} = 'multiple events';
else
table{i,2} = D.trials(i).events.type;
table{i,3} = num2str(D.trials(i).events.value);
if ~isempty(D.trials(i).events.duration)
table{i,4} = num2str(D.trials(i).events.duration);
else
table{i,4} = 'Undefined';
end
table{i,5} = num2str(D.trials(i).events.time);
end
if D.trials(i).bad
table{i,6} = 'yes';
else
table{i,6} = 'no';
end
table{i,7} = num2str(D.trials(i).onset);
end
colnames = {'label','type','value','duration','time','bad','onset'};
[ht,hc] = spm_uitable(table,colnames);
set(ht,'units','normalized');
set(hc,'position',[0.1 0.05 0.74 0.7],...
'tag','plotEEG');
else
for i=1:nt
table{i,1} = D.trials(i).label;
table{i,2} = num2str(D.trials(i).repl);
if D.trials(i).bad
table{i,3} = 'yes';
else
table{i,3} = 'no';
end
end
colnames = {'label','nb of repl','bad'};
[ht,hc] = spm_uitable(table,colnames);
set(ht,'units','normalized');
set(hc,'position',[0.1 0.05 0.32 0.7],...
'tag','plotEEG');
end
end
if ok
D.PSD.handles.infoUItable = ht;
D.PSD.handles.infoUItable2 = hc;
D = spm_eeg_review_uis(D,object); % this adds the buttons
end
case 3 % inv info
object.list = [object.list;12];
isInv = D.PSD.source.VIZU.isInv;
% isInv = 1:length(D.other.inv);
if numel(isInv) >= 1 %D.PSD.source.VIZU.current ~= 0
Ninv = length(isInv);
table = cell(Ninv,12);
for i=1:Ninv
try
table{i,1} = [D.other.inv{isInv(i)}.comment{1},' '];
catch
table{i,1} = ' ';
end
table{i,2} = [D.other.inv{isInv(i)}.date(1,:)];
try
table{i,3} = [D.other.inv{isInv(i)}.inverse.modality];
catch
try
table{i,3} = [D.other.inv{isInv(i)}.modality];
catch
table{i,3} = '?';
end
end
table{i,4} = [D.other.inv{isInv(i)}.method];
try
table{i,5} = [num2str(length(D.other.inv{isInv(i)}.inverse.Is))];
catch
try
table{i,5} = [num2str(D.other.inv{isInv(i)}.inverse.n_dip)];
catch
table{i,5} = '?';
end
end
try
table{i,6} = [D.other.inv{isInv(i)}.inverse.type];
catch
table{i,6} = '?';
end
try
table{i,7} = [num2str(floor(D.other.inv{isInv(i)}.inverse.woi(1))),...
' to ',num2str(floor(D.other.inv{isInv(i)}.inverse.woi(2))),' ms'];
catch
table{i,7} = [num2str(floor(D.other.inv{isInv(i)}.inverse.pst(1))),...
' to ',num2str(floor(D.other.inv{isInv(i)}.inverse.pst(end))),' ms'];
end
try
if D.other.inv{isInv(i)}.inverse.Han
han = 'yes';
else
han = 'no';
end
table{i,8} = [han];
catch
table{i,8} = ['?'];
end
try
table{i,9} = [num2str(D.other.inv{isInv(i)}.inverse.lpf),...
' to ',num2str(D.other.inv{isInv(i)}.inverse.hpf), 'Hz'];
catch
table{i,9} = ['?'];
end
try
table{i,10} = [num2str(size(D.other.inv{isInv(i)}.inverse.T,2))];
catch
table{i,10} = '?';
end
try
table{i,11} = [num2str(D.other.inv{isInv(i)}.inverse.R2)];
catch
table{i,11} = '?';
end
table{i,12} = [num2str(sum(D.other.inv{isInv(i)}.inverse.F))];
end
colnames = {'label','date','modality','model','#dipoles','method',...
'pst','hanning','band pass','#modes','%var','log[p(y|m)]'};
[ht,hc] = spm_uitable('set',table,colnames);
set(ht,'units','normalized');
set(hc,'position',[0.1 0.05 0.8 0.7],...
'tag','plotEEG');
D.PSD.handles.infoUItable = ht;
D.PSD.handles.infoUItable2 = hc;
D = spm_eeg_review_uis(D,object); % this adds the buttons
else
POS = get(D.PSD.handles.infoTabs.hp,'position');
D.PSD.handles.message = uicontrol('style','text','units','normalized',...
'Position',[0.14 0.84 0.7 0.04].*repmat(POS(3:4),1,2),...
'string','There is no source reconstruction in this data file !',...
'BackgroundColor',0.95*[1 1 1],...
'tag','plotEEG');
end
case 4 % history info
object.list = [object.list;15];
table = spm_eeg_history(D);
if ~isempty(table)
colnames = {'Process','function called','input file','output file'};
[ht,hc] = spm_uitable(table,colnames);
set(ht,'units','normalized','editable',0);
set(hc,'position',[0.1 0.05 0.8 0.7],...
'tag','plotEEG');
D.PSD.handles.infoUItable = ht;
D.PSD.handles.infoUItable2 = hc;
else
POS = get(D.PSD.handles.infoTabs.hp,'position');
D.PSD.handles.message = uicontrol('style','text','units','normalized',...
'Position',[0.14 0.84 0.7 0.04].*repmat(POS(3:4),1,2),...
'string','The history of this file is not available !',...
'BackgroundColor',0.95*[1 1 1],...
'tag','plotEEG');
end
D = spm_eeg_review_uis(D,object); % this adds the buttons
end
% update data info if action called from 'info' tab...
if ~isempty(D.PSD.VIZU.fromTab) && isequal(D.PSD.VIZU.fromTab,'info')
[str] = spm_eeg_review_callbacks('get','dataInfo');
set(D.PSD.handles.infoText,'string',str)
end
end
|
github
|
philippboehmsturm/antx-master
|
spm_dcm_bma_results.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_dcm_bma_results.m
| 10,252 |
utf_8
|
17ac38a624a58cb94d8b565b24ce5ff4
|
function spm_dcm_bma_results(BMS,method)
% Plot histograms from BMA for selected modulatory and driving input
% FORMAT spm_dcm_bma_results(BMS,mod_in,drive_in,method)
%
% Input:
% BMS - BMS.mat file
% method - inference method (FFX or RFX)
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Maria Joao
% $Id: spm_dcm_bma_results.m 4743 2012-05-17 14:36:33Z will $
if nargin < 1
fname = spm_select(1,'^BMS.mat$','select BMS.mat file');
else
fname = BMS;
end
% load BMS file
%--------------------------------------------------------------------------
load(fname)
% Check BMS/BMA method used
%--------------------------------------------------------------------------
if nargin < 2
ff = fieldnames(BMS.DCM);
Nff = numel(ff);
if Nff==2
method = spm_input('Inference method','+1','b','FFX|RFX',['ffx';'rfx']);
else % pick the one available if only one method
method = char(ff);
end
end
% select method
%--------------------------------------------------------------------------
if isfield(BMS.DCM,method)
switch method
case 'ffx'
if isempty(BMS.DCM.ffx.bma)
error('No BMA analysis for FFX in BMS file!');
else
Nsamp = BMS.DCM.ffx.bma.nsamp;
amat = BMS.DCM.ffx.bma.a;
bmat = BMS.DCM.ffx.bma.b;
cmat = BMS.DCM.ffx.bma.c;
dmat = BMS.DCM.ffx.bma.d;
end
disp('Loading model space...')
load(BMS.DCM.ffx.data)
load(subj(1).sess(1).model(1).fname)
case 'rfx'
if isempty(BMS.DCM.rfx.bma)
error('No BMA analysis for RFX in BMS file!');
else
Nsamp = BMS.DCM.rfx.bma.nsamp;
amat = BMS.DCM.rfx.bma.a;
bmat = BMS.DCM.rfx.bma.b;
cmat = BMS.DCM.rfx.bma.c;
dmat = BMS.DCM.rfx.bma.d;
end
disp('Loading model space...')
load(BMS.DCM.rfx.data)
load(subj(1).sess(1).model(1).fname)
end
else
msgbox(sprintf('No %s analysis in current BMS.mat file!',method))
return
end
% number of regions, mod. inputs and names
%--------------------------------------------------------------------------
n = size(amat,2); % #region
m = size(bmat,3); % #drv/mod inputs
mi = size(cmat,2);
% Look for modulatory inputs
mod_input = [];
for ii=1:m
% look for bits of B not full of zeros
tmp = squeeze(bmat(:,:,ii,:));
if any(tmp(:))
mod_input = [mod_input ii];
end
end
% Look for effective driving inputs
drive_input = [];
for ii=1:m
% look for bits of not full of zeros
tmp = any(cmat(:,ii,:));
if sum(tmp)
drive_input = [drive_input ii];
end
end
% Non linear model ? If so find the driving regions
if ~isempty(dmat)
nonLin = 1;
mod_reg = [];
for ii=1:n
% look for bits of D not full of zeros
tmp = squeeze(dmat(:,:,ii,:));
if any(tmp(:))
mod_reg = [mod_reg ii];
end
end
else
nonLin = 0;
mod_reg = [];
end
if isfield(DCM.Y,'name')
for i=1:n,
region(i).name = DCM.Y.name{i};
end
else
for i=1:n,
str = sprintf('Region %d',i);
region(i).name = spm_input(['Name for ',str],'+1','s');
end
end
bins = Nsamp/100;
% intrinsic connection density
%--------------------------------------------------------------------------
F = spm_figure('GetWin','Graphics');
set(F,'name','BMA: results');
FS = spm('FontSizes');
usd.amat = amat;
usd.bmat = bmat;
usd.cmat = cmat;
usd.dmat = dmat;
usd.region = region;
usd.n = n;
usd.m = m;
usd.ni = mi;
usd.FS = FS;
usd.drive_input = drive_input;
usd.mod_input = mod_input;
if nonLin
usd.mod_reg = mod_reg;
end
usd.bins = bins;
usd.Nsamp = Nsamp;
set(F,'userdata',usd);
clf(F);
labels = {'a: int.'};
callbacks = {@plot_a};
for ii = mod_input
labels{end+1} = ['b: mod. i#',num2str(ii)];
callbacks{end+1} = @plot_b;
end
for ii = drive_input
labels{end+1} = ['c: drv. i#',num2str(ii)];
callbacks{end+1} = @plot_c;
end
if nonLin
for ii = mod_reg
labels{end+1} = ['d: mod. r#',num2str(ii)];
callbacks{end+1} = @plot_d;
end
end
[handles] = spm_uitab(F,labels,callbacks,'BMA_parameters',1);
set(handles.htab,'backgroundcolor',[1 1 1])
set(handles.hh,'backgroundcolor',[1 1 1])
set(handles.hp,'HighlightColor',0.8*[1 1 1])
set(handles.hp,'backgroundcolor',[1 1 1])
feval(@plot_a,F)
%==========================================================================
function plot_a(F)
try
F;
catch
F = get(gco,'parent');
end
hc = intersect(findobj('tag','bma_results'),get(F,'children'));
if ~isempty(hc)
delete(hc)
end
ud = get(F,'userdata');
titlewin = 'BMA: intrinsic connections (a)';
hTitAx = axes('Parent',F,'Position',[0.2,0.04,0.6,0.02],...
'Visible','off','tag','bma_results');
text(0.55,0,titlewin,'Parent',hTitAx,'HorizontalAlignment','center',...
'VerticalAlignment','baseline','FontWeight','Bold','FontSize',ud.FS(12))
for i=1:ud.n,
for j=1:ud.n,
k=(i-1)*ud.n+j;
subplot(ud.n,ud.n,k);
if (i==j)
axis off
else
hist(squeeze(ud.amat(i,j,:)),ud.bins,'r');
amax = max(abs(ud.amat(i,j,:)))*1.05; % enlarge scale by 5%
if amax > 0
xlim([-amax amax])
else % case where parameter is constrained to be 0.
xlim([-10 10])
end
set(gca,'YTickLabel',[]);
set(gca,'FontSize',12);
title(sprintf('%s to %s',ud.region(j).name,ud.region(i).name));
end
end
end
%==========================================================================
function plot_b
hf = get(gco,'parent');
ud = get(hf,'userdata');
hc = intersect(findobj('tag','bma_results'),get(hf,'children'));
if ~isempty(hc)
delete(hc)
end
% spot the bmod input index from the fig name
ht = intersect(findobj('style','pushbutton'),get(hf,'children'));
ht = findobj(ht,'flat','Fontweight','bold');
t_str = get(ht,'string');
b_ind = str2num(t_str(strfind(t_str,'#')+1:end));
i_mod = find(ud.mod_input==b_ind);
titlewin = ['BMA: modulatory connections (b',num2str(b_ind),')'];
hTitAx = axes('Parent',hf,'Position',[0.2,0.04,0.6,0.02],...
'Visible','off','tag','bma_results');
text(0.55,0,titlewin,'Parent',hTitAx,'HorizontalAlignment','center',...
'VerticalAlignment','baseline','FontWeight','Bold','FontSize',ud.FS(12))
for i=1:ud.n,
for j=1:ud.n,
k=(i-1)*ud.n+j;
subplot(ud.n,ud.n,k);
if (i==j)
axis off
else
hist(squeeze(ud.bmat(i,j,ud.mod_input(i_mod),:)),ud.bins,'r');
bmax = max(abs(ud.bmat(i,j,ud.mod_input(i_mod),:)))*1.05; % enlarge scale by 5%
if bmax > 0
xlim([-bmax bmax])
else % case where parameter is constrained to be 0.
xlim([-10 10])
end
set(gca,'YTickLabel',[]);
set(gca,'FontSize',12);
title(sprintf('%s to %s',ud.region(j).name,ud.region(i).name));
end
end
end
%==========================================================================
function plot_c
hf = get(gco,'parent');
ud = get(hf,'userdata');
hc = intersect(findobj('tag','bma_results'),get(hf,'children'));
if ~isempty(hc)
delete(hc)
end
% spot the c_drv input index from the fig name
ht = intersect(findobj('style','pushbutton'),get(hf,'children'));
ht = findobj(ht,'flat','Fontweight','bold');
t_str = get(ht,'string');
c_ind = str2num(t_str(strfind(t_str,'#')+1:end));
i_drv = find(ud.drive_input==c_ind);
titlewin = ['BMA: input connections (c',num2str(c_ind),')'];
hTitAx = axes('Parent',hf,'Position',[0.2,0.04,0.6,0.02],...
'Visible','off','tag','bma_results');
text(0.55,0,titlewin,'Parent',hTitAx,'HorizontalAlignment','center',...
'VerticalAlignment','baseline','FontWeight','Bold','FontSize',ud.FS(12))
for j=1:ud.n,
subplot(1,ud.n,j);
if length(find(ud.cmat(j,ud.drive_input(i_drv),:)==0))==ud.Nsamp
plot([0 0],[0 1],'k');
else
hist(squeeze(ud.cmat(j,ud.drive_input(i_drv),:)),ud.bins,'r');
cmax = max(abs(ud.cmat(j,ud.drive_input(i_drv),:)))*1.05; % enlarge scale by 5%
if cmax > 0
xlim([-cmax cmax])
else % case where parameter is constrained to be 0.
xlim([-10 10])
end
end
set(gca,'YTickLabel',[]);
set(gca,'FontSize',12);
title(sprintf('%s ',ud.region(j).name));
end
%==========================================================================
function plot_d
hf = get(gco,'parent');
ud = get(hf,'userdata');
hc = intersect(findobj('tag','bma_results'),get(hf,'children'));
if ~isempty(hc)
delete(hc)
end
% spot the d_reg input index from the fig name
ht = intersect(findobj('style','pushbutton'),get(hf,'children'));
ht = findobj(ht,'flat','Fontweight','bold');
t_str = get(ht,'string');
d_ind = str2num(t_str(strfind(t_str,'#')+1:end));
i_mreg = find(ud.mod_reg==d_ind);
titlewin = ['BMA: non-linear connections (d',num2str(d_ind),')'];
hTitAx = axes('Parent',hf,'Position',[0.2,0.04,0.6,0.02],...
'Visible','off','tag','bma_results');
text(0.55,0,titlewin,'Parent',hTitAx,'HorizontalAlignment','center',...
'VerticalAlignment','baseline','FontWeight','Bold','FontSize',ud.FS(12))
for i=1:ud.n,
for j=1:ud.n,
k=(i-1)*ud.n+j;
subplot(ud.n,ud.n,k);
if (i==j)
axis off
else
hist(squeeze(ud.dmat(i,j,ud.mod_reg(i_mreg),:)),ud.bins,'r');
dmax = max(abs(ud.dmat(i,j,ud.mod_reg(i_mreg),:)))*1.05; % enlarge scale by 5%
if dmax > 0
xlim([-dmax dmax])
else % case where parameter is constrained to be 0.
xlim([-10 10])
end
set(gca,'YTickLabel',[]);
set(gca,'FontSize',12);
title(sprintf('%s to %s',ud.region(j).name,ud.region(i).name));
end
end
end
|
github
|
philippboehmsturm/antx-master
|
spm_check_filename.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_check_filename.m
| 2,311 |
utf_8
|
b8de0a161ecbb9d70247bbf51873bb0e
|
function V = spm_check_filename(V)
% Checks paths are valid and tries to restore path names
% FORMAT V = spm_check_filename(V)
%
% V - struct array of file handles
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Karl Friston
% $Id: spm_check_filename.m 3934 2010-06-17 14:58:25Z guillaume $
if isdeployed, return; end
% check filenames
%--------------------------------------------------------------------------
for i = 1:length(V)
% see if file exists
%----------------------------------------------------------------------
if ~spm_existfile(V(i).fname)
% try current directory
%------------------------------------------------------------------
[p,n,e] = fileparts(V(i).fname);
fname = which([n,e]);
if ~isempty(fname)
V(i).fname = fname;
else
% try parent directory
%--------------------------------------------------------------
cwd = pwd;
cd('..')
fname = which([n,e]);
if ~isempty(fname)
V(i).fname = fname;
else
% try children of parent
%----------------------------------------------------------
V = spm_which_filename(V);
cd(cwd)
return
end
cd(cwd)
end
end
end
%==========================================================================
function V = spm_which_filename(V)
% get children directories of parent
%--------------------------------------------------------------------------
cwd = pwd;
cd('..')
gwd = genpath(pwd);
addpath(gwd);
% cycle through handles
%--------------------------------------------------------------------------
for i = 1:length(V)
try
% get relative path (directory and filename) and find in children
%------------------------------------------------------------------
j = strfind(V(i).fname,filesep);
fname = which(fname(j(end - 1):end));
if ~isempty(fname)
V(i).fname = fname;
end
end
end
% reset paths
%--------------------------------------------------------------------------
rmpath(gwd);
cd(cwd);
|
github
|
philippboehmsturm/antx-master
|
spm_defs.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_defs.m
| 11,688 |
utf_8
|
217cf06b73a160542c57789ec5490b4f
|
function out = spm_defs(job)
% Various deformation field utilities.
% FORMAT out = spm_defs(job)
% job - a job created via spm_config_defs.m and spm_jobman.m
% out - a struct with fields
% .def - file name of created deformation field
% .warped - file names of warped images
%
% See spm_config_defs.m for more information.
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_defs.m 4194 2011-02-05 18:08:06Z ged $
[Def,mat] = get_comp(job.comp);
[dpath ipath] = get_paths(job);
out.def = save_def(Def,mat,strvcat(job.ofname),dpath);
out.warped = apply_def(Def,mat,strvcat(job.fnames),ipath,job.interp);
%_______________________________________________________________________
%_______________________________________________________________________
function [Def,mat] = get_comp(job)
% Return the composition of a number of deformation fields.
if isempty(job),
error('Empty list of jobs in composition');
end;
[Def,mat] = get_job(job{1});
for i=2:numel(job),
Def1 = Def;
mat1 = mat;
[Def,mat] = get_job(job{i});
M = inv(mat1);
for j=1:size(Def{1},3)
d0 = {double(Def{1}(:,:,j)), double(Def{2}(:,:,j)),double(Def{3}(:,:,j))};
d{1} = M(1,1)*d0{1}+M(1,2)*d0{2}+M(1,3)*d0{3}+M(1,4);
d{2} = M(2,1)*d0{1}+M(2,2)*d0{2}+M(2,3)*d0{3}+M(2,4);
d{3} = M(3,1)*d0{1}+M(3,2)*d0{2}+M(3,3)*d0{3}+M(3,4);
Def{1}(:,:,j) = single(spm_sample_vol(Def1{1},d{:},[1,NaN]));
Def{2}(:,:,j) = single(spm_sample_vol(Def1{2},d{:},[1,NaN]));
Def{3}(:,:,j) = single(spm_sample_vol(Def1{3},d{:},[1,NaN]));
end;
end;
%_______________________________________________________________________
%_______________________________________________________________________
function [Def,mat] = get_job(job)
% Determine what is required, and pass the relevant bit of the
% job out to the appropriate function.
fn = fieldnames(job);
fn = fn{1};
switch fn
case {'comp'}
[Def,mat] = get_comp(job.(fn));
case {'def'}
[Def,mat] = get_def(job.(fn));
case {'dartel'}
[Def,mat] = get_dartel(job.(fn));
case {'sn2def'}
[Def,mat] = get_sn2def(job.(fn));
case {'inv'}
[Def,mat] = get_inv(job.(fn));
case {'id'}
[Def,mat] = get_id(job.(fn));
case {'idbbvox'}
[Def,mat] = get_idbbvox(job.(fn));
otherwise
error('Unrecognised job type');
end;
%_______________________________________________________________________
%_______________________________________________________________________
function [Def,mat] = get_sn2def(job)
% Convert a SPM _sn.mat file into a deformation field, and return it.
vox = job.vox;
bb = job.bb;
sn = load(job.matname{1});
if any(isfinite(bb(:))) || any(isfinite(vox)),
[bb0,vox0] = spm_get_bbox(sn.VG(1), 'old');
if any(~isfinite(vox)), vox = vox0; end;
if any(~isfinite(bb)), bb = bb0; end;
bb = sort(bb);
vox = abs(vox);
% Adjust bounding box slightly - so it rounds to closest voxel.
bb(:,1) = round(bb(:,1)/vox(1))*vox(1);
bb(:,2) = round(bb(:,2)/vox(2))*vox(2);
bb(:,3) = round(bb(:,3)/vox(3))*vox(3);
M = sn.VG(1).mat;
vxg = sqrt(sum(M(1:3,1:3).^2));
ogn = M\[0 0 0 1]';
ogn = ogn(1:3)';
% Convert range into range of voxels within template image
x = (bb(1,1):vox(1):bb(2,1))/vxg(1) + ogn(1);
y = (bb(1,2):vox(2):bb(2,2))/vxg(2) + ogn(2);
z = (bb(1,3):vox(3):bb(2,3))/vxg(3) + ogn(3);
og = -vxg.*ogn;
of = -vox.*(round(-bb(1,:)./vox)+1);
M1 = [vxg(1) 0 0 og(1) ; 0 vxg(2) 0 og(2) ; 0 0 vxg(3) og(3) ; 0 0 0 1];
M2 = [vox(1) 0 0 of(1) ; 0 vox(2) 0 of(2) ; 0 0 vox(3) of(3) ; 0 0 0 1];
mat = sn.VG(1).mat*inv(M1)*M2;
% dim = [length(x) length(y) length(z)];
else
dim = sn.VG(1).dim;
x = 1:dim(1);
y = 1:dim(2);
z = 1:dim(3);
mat = sn.VG(1).mat;
end
[X,Y] = ndgrid(x,y);
st = size(sn.Tr);
if (prod(st) == 0),
affine_only = true;
basX = 0;
basY = 0;
basZ = 0;
else
affine_only = false;
basX = spm_dctmtx(sn.VG(1).dim(1),st(1),x-1);
basY = spm_dctmtx(sn.VG(1).dim(2),st(2),y-1);
basZ = spm_dctmtx(sn.VG(1).dim(3),st(3),z-1);
end,
Def = single(0);
Def(numel(x),numel(y),numel(z)) = 0;
Def = {Def; Def; Def};
for j=1:length(z)
if (~affine_only)
tx = reshape( reshape(sn.Tr(:,:,:,1),st(1)*st(2),st(3)) *basZ(j,:)', st(1), st(2) );
ty = reshape( reshape(sn.Tr(:,:,:,2),st(1)*st(2),st(3)) *basZ(j,:)', st(1), st(2) );
tz = reshape( reshape(sn.Tr(:,:,:,3),st(1)*st(2),st(3)) *basZ(j,:)', st(1), st(2) );
X1 = X + basX*tx*basY';
Y1 = Y + basX*ty*basY';
Z1 = z(j) + basX*tz*basY';
end
Mult = sn.VF.mat*sn.Affine;
if (~affine_only)
X2= Mult(1,1)*X1 + Mult(1,2)*Y1 + Mult(1,3)*Z1 + Mult(1,4);
Y2= Mult(2,1)*X1 + Mult(2,2)*Y1 + Mult(2,3)*Z1 + Mult(2,4);
Z2= Mult(3,1)*X1 + Mult(3,2)*Y1 + Mult(3,3)*Z1 + Mult(3,4);
else
X2= Mult(1,1)*X + Mult(1,2)*Y + (Mult(1,3)*z(j) + Mult(1,4));
Y2= Mult(2,1)*X + Mult(2,2)*Y + (Mult(2,3)*z(j) + Mult(2,4));
Z2= Mult(3,1)*X + Mult(3,2)*Y + (Mult(3,3)*z(j) + Mult(3,4));
end
Def{1}(:,:,j) = single(X2);
Def{2}(:,:,j) = single(Y2);
Def{3}(:,:,j) = single(Z2);
end;
%_______________________________________________________________________
%_______________________________________________________________________
function [Def,mat] = get_def(job)
% Load a deformation field saved as an image
P = [repmat(job{:},3,1), [',1,1';',1,2';',1,3']];
V = spm_vol(P);
Def = cell(3,1);
Def{1} = spm_load_float(V(1));
Def{2} = spm_load_float(V(2));
Def{3} = spm_load_float(V(3));
mat = V(1).mat;
%_______________________________________________________________________
%_______________________________________________________________________
function [Def,mat] = get_dartel(job)
% Integrate a DARTEL flow field
N = nifti(job.flowfield{1});
y = spm_dartel_integrate(N.dat,job.times,job.K);
Def = cell(3,1);
if all(job.times == [0 1]),
M = single(N.mat);
mat = N.mat0;
else
M = single(N.mat0);
mat = N.mat;
end
Def{1} = y(:,:,:,1)*M(1,1) + y(:,:,:,2)*M(1,2) + y(:,:,:,3)*M(1,3) + M(1,4);
Def{2} = y(:,:,:,1)*M(2,1) + y(:,:,:,2)*M(2,2) + y(:,:,:,3)*M(2,3) + M(2,4);
Def{3} = y(:,:,:,1)*M(3,1) + y(:,:,:,2)*M(3,2) + y(:,:,:,3)*M(3,3) + M(3,4);
%_______________________________________________________________________
%_______________________________________________________________________
function [Def,mat] = get_id(job)
% Get an identity transform based on an image volume.
N = nifti(job.space{1});
d = [size(N.dat),1];
d = d(1:3);
mat = N.mat;
Def = cell(3,1);
[y1,y2,y3] = ndgrid(1:d(1),1:d(2),1:d(3));
Def{1} = single(y1*mat(1,1) + y2*mat(1,2) + y3*mat(1,3) + mat(1,4));
Def{2} = single(y1*mat(2,1) + y2*mat(2,2) + y3*mat(2,3) + mat(2,4));
Def{3} = single(y1*mat(3,1) + y2*mat(3,2) + y3*mat(3,3) + mat(3,4));
%_______________________________________________________________________
%_______________________________________________________________________
function [Def,mat] = get_idbbvox(job)
% Get an identity transform based on bounding box and voxel size.
% This will produce a transversal image.
d = floor(diff(job.bb)./job.vox);
d(d == 0) = 1;
mat = diag([-1 1 1 1])*spm_matrix([job.bb(1,:) 0 0 0 job.vox]);
Def = cell(3,1);
[y1,y2,y3] = ndgrid(1:d(1),1:d(2),1:d(3));
Def{1} = single(y1*mat(1,1) + y2*mat(1,2) + y3*mat(1,3) + mat(1,4));
Def{2} = single(y1*mat(2,1) + y2*mat(2,2) + y3*mat(2,3) + mat(2,4));
Def{3} = single(y1*mat(3,1) + y2*mat(3,2) + y3*mat(3,3) + mat(3,4));
%_______________________________________________________________________
%_______________________________________________________________________
function [Def,mat] = get_inv(job)
% Invert a deformation field (derived from a composition of deformations)
VT = spm_vol(job.space{:});
[Def0,mat0] = get_comp(job.comp);
M0 = mat0;
M1 = inv(VT.mat);
M0(4,:) = [0 0 0 1];
M1(4,:) = [0 0 0 1];
[Def{1},Def{2},Def{3}] = spm_invdef(Def0{:},VT.dim(1:3),M1,M0);
mat = VT.mat;
%_______________________________________________________________________
%_______________________________________________________________________
function [dpath,ipath] = get_paths(job)
switch char(fieldnames(job.savedir))
case 'savepwd'
dpath = pwd;
ipath = pwd;
case 'savesrc'
dpath = get_dpath(job);
ipath = '';
case 'savedef'
dpath = get_dpath(job);
ipath = dpath;
case 'saveusr'
dpath = job.savedir.saveusr{1};
ipath = dpath;
end
%_______________________________________________________________________
%_______________________________________________________________________
function dpath = get_dpath(job)
% Determine what is required, and pass the relevant bit of the
% job out to the appropriate function.
fn = fieldnames(job);
fn = fn{1};
switch fn
case {'comp'}
dpath = get_dpath(job.(fn){1});
case {'def'}
dpath = fileparts(job.(fn){1});
case {'dartel'}
dpath = fileparts(job.(fn).flowfield{1});
case {'sn2def'}
dpath = fileparts(job.(fn).matname{1});
case {'inv'}
dpath = fileparts(job.(fn).space{1});
case {'id'}
dpath = fileparts(job.(fn).space{1});
otherwise
error('Unrecognised job type');
end;
%_______________________________________________________________________
%_______________________________________________________________________
function fname = save_def(Def,mat,ofname,odir)
% Save a deformation field as an image
if isempty(ofname), fname = {}; return; end;
fname = {fullfile(odir,['y_' ofname '.nii'])};
dim = [size(Def{1},1) size(Def{1},2) size(Def{1},3) 1 3];
dtype = 'FLOAT32';
off = 0;
scale = 1;
inter = 0;
dat = file_array(fname{1},dim,dtype,off,scale,inter);
N = nifti;
N.dat = dat;
N.mat = mat;
N.mat0 = mat;
N.mat_intent = 'Aligned';
N.mat0_intent = 'Aligned';
N.intent.code = 'VECTOR';
N.intent.name = 'Mapping';
N.descrip = 'Deformation field';
create(N);
N.dat(:,:,:,1,1) = Def{1};
N.dat(:,:,:,1,2) = Def{2};
N.dat(:,:,:,1,3) = Def{3};
return;
%_______________________________________________________________________
%_______________________________________________________________________
function ofnames = apply_def(Def,mat,fnames,odir,intrp)
% Warp an image or series of images according to a deformation field
intrp = [intrp*[1 1 1], 0 0 0];
ofnames = cell(size(fnames,1),1);
for i=1:size(fnames,1),
V = spm_vol(fnames(i,:));
M = inv(V.mat);
[pth,nam,ext,num] = spm_fileparts(deblank(fnames(i,:)));
if isempty(odir)
% use same path as source image
opth = pth;
else
% use prespecified path
opth = odir;
end
ofnames{i} = fullfile(opth,['w',nam,ext]);
Vo = struct('fname',ofnames{i},...
'dim',[size(Def{1},1) size(Def{1},2) size(Def{1},3)],...
'dt',V.dt,...
'pinfo',V.pinfo,...
'mat',mat,...
'n',V.n,...
'descrip',V.descrip);
ofnames{i} = [ofnames{i} num];
C = spm_bsplinc(V,intrp);
Vo = spm_create_vol(Vo);
for j=1:size(Def{1},3)
d0 = {double(Def{1}(:,:,j)), double(Def{2}(:,:,j)),double(Def{3}(:,:,j))};
d{1} = M(1,1)*d0{1}+M(1,2)*d0{2}+M(1,3)*d0{3}+M(1,4);
d{2} = M(2,1)*d0{1}+M(2,2)*d0{2}+M(2,3)*d0{3}+M(2,4);
d{3} = M(3,1)*d0{1}+M(3,2)*d0{2}+M(3,3)*d0{3}+M(3,4);
dat = spm_bsplins(C,d{:},intrp);
Vo = spm_write_plane(Vo,dat,j);
end;
end;
return;
|
github
|
philippboehmsturm/antx-master
|
spm_sp.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_sp.m
| 39,708 |
utf_8
|
180830974ed2715dc2f976a356081a60
|
function varargout = spm_sp(varargin)
% Orthogonal (design) matrix space setting & manipulation
% FORMAT varargout = spm_spc(action,varargin)
%
% This function computes the different projectors related to the row
% and column spaces X. It should be used to avoid redundant computation
% of svd on large X matrix. It is divided into actions that set up the
% space, (Create,Set,...) and actions that compute projections (pinv,
% pinvXpX, pinvXXp, ...) This is motivated by the problem of rounding
% errors that can invalidate some computation and is a tool to work
% with spaces.
%
% The only thing that is not easily computed is the null space of
% the line of X (assuming size(X,1) > size(X,2)).
% To get this space (a basis of it or a projector on it) use spm_sp on X'.
%
% The only restriction on the use of the space structure is when X is
% so big that you can't fit X and its svd in memory at the same time.
% Otherwise, the use of spm_sp will generally speed up computations and
% optimise memory use.
%
% Note that since the design matrix is stored in the space structure,
% there is no need to keep a separate copy of it.
%
% ----------------
%
% The structure is:
% x = struct(...
% 'X', [],... % Mtx
% 'tol', [],... % tolerance
% 'ds', [],... % vectors of singular values
% 'u', [],... % u as in X = u*diag(ds)*v'
% 'v', [],... % v as in X = u*diag(ds)*v'
% 'rk', [],... % rank
% 'oP', [],... % orthogonal projector on X
% 'oPp', [],... % orthogonal projector on X'
% 'ups', [],... % space in which this one is embeded
% 'sus', []); % subspace
%
% The basic required fields are X, tol, ds, u, v, rk.
%
% ======================================================================
%
% FORMAT x = spm_sp('Set',X)
% Set up space structure, storing matrix, singular values, rank & tolerance
% X - a (design) matrix (2D)
% x - the corresponding space structure, with basic fields filled in
% The SVD is an "economy size" svd, using MatLab's svd(X,0)
%
%
% FORMAT r = spm_sp('oP',x[,Y])
% FORMAT r = spm_sp('oPp',x[,Y])
% Return orthogonal projectors, or orthogonal projection of data Y (if passed)
% x - space structure of matrix X
% r - ('oP' usage) ortho. projection matrix projecting into column space of x.X
% - ('oPp' usage) ortho. projection matrix projecting into row space of x.X
% Y - data (optional)
% - If data are specified then the corresponding projection of data is
% returned. This is usually more efficient that computing and applying
% the projection matrix directly.
%
%
% FORMAT pX = spm_sp('pinv',x)
% Returns a pseudo-inverse of X - pinv(X) - computed efficiently
% x - space structure of matrix X
% pX - pseudo-inverse of X
% This is the same as MatLab's pinv - the Moore-Penrose pseudoinverse
% ( Note that because size(pinv(X)) == size(X'), it is not generally )
% ( useful to compute pinv(X)*Data sequentially (as is the case for )
% ( 'res' or 'oP') )
%
%
% FORMAT pXpX = spm_sp('pinvxpx',x)
% Returns a pseudo-inverse of X'X - pinv(X'*X) - computed efficiently
% x - space structure of matrix X
% pXpX - pseudo-inverse of (X'X)
% ( Note that because size(pinv(X'*X)) == [size(X,2) size(X,2)], )
% ( it is not useful to compute pinv(X'X)*Data sequentially unless )
% ( size(X,1) < size(X,2) )
%
%
% FORMAT XpX = spm_sp('xpx',x)
% Returns (X'X) - computed efficiently
% x - space structure of matrix X
% XpX - (X'X)
%
%
% FORMAT pXXp = spm_sp('pinvxxp',x)
% Returns a pseudo-inverse of XX' - pinv(X*X') - computed efficiently
% x - space structure of matrix X
% pXXp - pseudo-inverse of (XX')
%
%
% FORMAT XXp = spm_sp('xxp',x)
% Returns (XX') - computed efficiently
% x - space structure of matrix X
% XXp - (XX')
%
%
% FORMAT b = spm_sp('isinsp',x,c[,tol])
% FORMAT b = spm_sp('isinspp',x,c[,tol])
% Check whether vectors c are in the column/row space of X
% x - space structure of matrix X
% c - vector(s) (Multiple vectors passed as a matrix)
% tol - (optional) tolerance (for rounding error)
% [defaults to tolerance specified in space structure: x.tol]
% b - ('isinsp' usage) true if c is in the column space of X
% - ('isinspp' usage) true if c is in the column space of X
%
% FORMAT b = spm_sp('eachinsp',x,c[,tol])
% FORMAT b = spm_sp('eachinspp',x,c[,tol])
% Same as 'isinsp' and 'isinspp' but returns a logical row vector of
% length size(c,2).
%
% FORMAT N = spm_sp('n',x)
% Simply returns the null space of matrix X (same as matlab NULL)
% (Null space = vectors associated with zero eigenvalues)
% x - space structure of matrix X
% N - null space
%
%
% FORMAT r = spm_sp('nop',x[,Y])
% Orthogonal projector onto null space of X, or projection of data Y (if passed)
% x - space structure of matrix X
% Y - (optional) data
% r - (if no Y passed) orthogonal projection matrix into the null space of X
% - (if Y passed ) orthogonal projection of data into the null space of X
% ( Note that if xp = spm_sp('set',x.X'), we have: )
% ( spm_sp('nop',x) == spm_sp('res',xp) )
% ( or, equivalently: )
% ( spm_sp('nop',x) + spm_sp('oP',xp) == eye(size(xp.X,1)); )
%
%
% FORMAT r = spm_sp('res',x[,Y])
% Returns residual formaing matrix wirit column space of X, or residuals (if Y)
% x - space structure of matrix X
% Y - (optional) data
% r - (if no Y passed) residual forming matrix for design matrix X
% - (if Y passed ) residuals, i.e. residual forming matrix times data
% ( This will be more efficient than
% ( spm_sp('res',x)*Data, when size(X,1) > size(X,2)
% Note that this can also be seen as the orthogonal projector onto the
% null space of x.X' (which is not generally computed in svd, unless
% size(X,1) < size(X,2)).
%
%
% FORMAT oX = spm_sp('ox', x)
% FORMAT oXp = spm_sp('oxp',x)
% Returns an orthonormal basis for X ('ox' usage) or X' ('oxp' usage)
% x - space structure of matrix X
% oX - orthonormal basis for X - same as orth(x.X)
% xOp - *an* orthonormal for X' (but not the same as orth(x.X'))
%
%
% FORMAT b = spm_sp('isspc',x)
% Check a variable is a structure with the right fields for a space structure
% x - candidate variable
% b - true if x is a structure with fieldnames corresponding to spm_sp('create')
%
%
% FORMAT [b,e] = spm_sp('issetspc',x)
% Test whether a variable is a space structure with the basic fields set
% x - candidate variable
% b - true is x is a structure with fieldnames corresponding to
% spm_sp('Create'), which has it's basic fields filled in.
% e - string describing why x fails the issetspc test (if it does)
% This is simply a gateway function combining spm_sp('isspc',x) with
% the internal subfunction sf_isset, which checks that the basic fields
% are not empty. See sf_isset (below).
%
%-----------------------------------------------------------------------
% SUBFUNCTIONS:
%
% FORMAT b = sf_isset(x)
% Checks that the basic fields are non-empty (doesn't check they're right!)
% x - space structure
% b - true if the basic fields are non-empty
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Jean-Baptiste Poline
% $Id: spm_sp.m 1143 2008-02-07 19:33:33Z spm $
if nargin==0
error('Do what? no arguments given...')
else
action = varargin{1};
end
%- check the very basics arguments
switch lower(action),
case {'create','set','issetspc','isspc'}
%- do nothing
otherwise,
if nargin==1, error('No space : can''t do much!'), end
[ok,str] = spm_sp('issetspc',varargin{2});
if ~ok, error(str), else, sX = varargin{2}; end;
end;
switch lower(action),
case 'create' %-Create space structure
%=======================================================================
% x = spm_sp('Create')
varargout = {sf_create};
case 'set' %-Set singular values, space basis, rank & tolerance
%=======================================================================
% x = spm_sp('Set',X)
if nargin==1 error('No design matrix : can''t do much!'),
else X = varargin{2}; end
if isempty(X), varargout = {sf_create}; return, end
%- only sets plain matrices
%- check X has 2 dim only
if max(size(size(X))) > 2, error('Too many dim in the set'), end
if ~isnumeric(X), error('only sets numeric matrices'), end
varargout = {sf_set(X)};
case {'p', 'transp'} %-Transpose space of X
%=======================================================================
switch nargin
case 2
varargout = {sf_transp(sX)};
otherwise
error('too many input argument in spm_sp');
end % switch nargin
case {'op', 'op:'} %-Orthogonal projectors on space of X
%=======================================================================
% r = spm_sp('oP', sX[,Y])
% r = spm_sp('oP:', sX[,Y]) %- set to 0 less than tolerence values
%
% if isempty(Y) returns as if Y not given
%-----------------------------------------------------------------------
switch nargin
case 2
switch lower(action),
case 'op'
varargout = {sf_op(sX)};
case 'op:'
varargout = {sf_tol(sf_op(sX),sX.tol)};
end %- switch lower(action),
case 3
Y = varargin{3};
if isempty(Y), varargout = {spm_sp(action,sX)}; return, end
if size(Y,1) ~= sf_s1(sX), error('Dim dont match'); end;
switch lower(action),
case 'op'
varargout = {sf_op(sX)*Y};
case 'op:'
varargout = {sf_tol(sf_op(sX)*Y,sX.tol)};
end % switch lower(action)
otherwise
error('too many input argument in spm_sp');
end % switch nargin
case {'opp', 'opp:'} %-Orthogonal projectors on space of X'
%=======================================================================
% r = spm_sp('oPp',sX[,Y])
% r = spm_sp('oPp:',sX[,Y]) %- set to 0 less than tolerence values
%
% if isempty(Y) returns as if Y not given
%-----------------------------------------------------------------------
switch nargin
case 2
switch lower(action),
case 'opp'
varargout = {sf_opp(sX)};
case 'opp:'
varargout = {sf_tol(sf_opp(sX),sX.tol)};
end %- switch lower(action),
case 3
Y = varargin{3};
if isempty(Y), varargout = {spm_sp(action,sX)}; return, end
if size(Y,1) ~= sf_s2(sX), error('Dim dont match'); end;
switch lower(action),
case 'opp'
varargout = {sf_opp(sX)*Y};
case 'opp:'
varargout = {sf_tol(sf_opp(sX)*Y,sX.tol)};
end % switch lower(action)
otherwise
error('too many input argument in spm_sp');
end % switch nargin
case {'x-','x-:'} %-Pseudo-inverse of X - pinv(X)
%=======================================================================
% = spm_sp('x-',x)
switch nargin
case 2
switch lower(action),
case {'x-'}
varargout = { sf_pinv(sX) };
case {'x-:'}
varargout = {sf_tol( sf_pinv(sX), sf_t(sX) )};
end
case 3
%- check dimensions of Y
Y = varargin{3};
if isempty(Y), varargout = {spm_sp(action,sX)}; return, end
if size(Y,1) ~= sf_s1(sX), error(['Dim dont match ' action]); end
switch lower(action),
case {'x-'}
varargout = { sf_pinv(sX)*Y };
case {'x-:'}
varargout = {sf_tol( sf_pinv(sX)*Y, sf_t(sX) )};
end
otherwise
error(['too many input argument in spm_sp ' action]);
end % switch nargin
case {'xp-','xp-:','x-p','x-p:'} %- Pseudo-inverse of X'
%=======================================================================
% pX = spm_sp('xp-',x)
switch nargin
case 2
switch lower(action),
case {'xp-','x-p'}
varargout = { sf_pinvxp(sX) };
case {'xp-:','x-p:'}
varargout = {sf_tol( sf_pinvxp(sX), sf_t(sX) )};
end
case 3
%- check dimensions of Y
Y = varargin{3};
if isempty(Y), varargout = {spm_sp(action,sX)}; return, end
if size(Y,1) ~= sf_s2(sX), error(['Dim dont match ' action]); end
switch lower(action),
case {'xp-','x-p'}
varargout = { sf_pinvxp(sX)*Y };
case {'xp-:','x-p:'}
varargout = {sf_tol( sf_pinvxp(sX)*Y, sf_t(sX) )};
end
otherwise
error(['too many input argument in spm_sp ' action]);
end % switch nargin
case {'cukxp-','cukxp-:'} %- Coordinates of pinv(X') in the base of uk
%=======================================================================
% pX = spm_sp('cukxp-',x)
switch nargin
case 2
switch lower(action),
case {'cukxp-'}
varargout = { sf_cukpinvxp(sX) };
case {'cukxp-:'}
varargout = {sf_tol(sf_cukpinvxp(sX),sX.tol)};
end
case 3
%- check dimensions of Y
Y = varargin{3};
if isempty(Y), varargout = {spm_sp(action,sX)}; return, end
if size(Y,1) ~= sf_s2(sX), error(['Dim dont match ' action]); end
switch lower(action),
case {'cukxp-'}
varargout = { sf_cukpinvxp(sX)*Y };
case {'cukxp-:'}
varargout = {sf_tol(sf_cukpinvxp(sX)*Y,sX.tol)};
end
otherwise
error(['too many input argument in spm_sp ' action]);
end % switch nargin
case {'cukx','cukx:'} %- Coordinates of X in the base of uk
%=======================================================================
% pX = spm_sp('cukx',x)
switch nargin
case 2
switch lower(action),
case {'cukx'}
varargout = { sf_cukx(sX) };
case {'cukx:'}
varargout = {sf_tol(sf_cukx(sX),sX.tol)};
end
case 3
%- check dimensions of Y
Y = varargin{3};
if isempty(Y), varargout = {spm_sp(action,sX)}; return, end
if size(Y,1) ~= sf_s2(sX), error(['Dim dont match ' action]); end
switch lower(action),
case {'cukx'}
varargout = { sf_cukx(sX)*Y };
case {'cukx:'}
varargout = {sf_tol(sf_cukx(sX)*Y,sX.tol)};
end
otherwise
error(['too many input argument in spm_sp ' action]);
end % switch nargin
case {'rk'} %- Returns rank
%=======================================================================
varargout = { sf_rk(sX) };
case {'ox', 'oxp'} %-Orthonormal basis sets for X / X'
%=======================================================================
% oX = spm_sp('ox', x)
% oXp = spm_sp('oxp',x)
if sf_rk(sX) > 0
switch lower(action)
case 'ox'
varargout = {sf_uk(sX)};
case 'oxp'
varargout = {sf_vk(sX)};
end
else
switch lower(action)
case 'ox'
varargout = {zeros(sf_s1(sX),1)};
case 'oxp'
varargout = {zeros(sf_s2(sX),1)};
end
end
case {'x', 'xp'} %- X / X' robust to spm_sp changes
%=======================================================================
% X = spm_sp('x', x)
% X' = spm_sp('xp',x)
switch lower(action)
case 'x', varargout = {sX.X};
case 'xp', varargout = {sX.X'};
end
case {'xi', 'xpi'} %- X(:,i) / X'(:,i) robust to spm_sp changes
%=======================================================================
% X = spm_sp('xi', x)
% X' = spm_sp('xpi',x)
i = varargin{3}; % NO CHECKING on i !!! assumes correct
switch lower(action)
case 'xi', varargout = {sX.X(:,i)};
case 'xpi', varargout = {sX.X(i,:)'};
end
case {'uk','uk:'} %- Returns u(:,1:r)
%=======================================================================
% pX = spm_sp('uk',x)
% Notice the difference with 'ox' : 'ox' always returns a basis of the
% proper siwe while this returns empty if rank is null
warning('can''t you use ox ?');
switch nargin
case 2
switch lower(action),
case {'uk'}
varargout = { sf_uk(sX) };
case {'uk:'}
varargout = { sf_tol(sf_uk(sX),sX.tol) };
end
case 3
%- check dimensions of Y
Y = varargin{3};
if isempty(Y), varargout = {spm_sp(action,sX)}; return, end
if size(Y,1) ~= sf_rk(sX), error(['Dim dont match ' action]); end
switch lower(action),
case {'uk'}
varargout = { sf_uk(sX)*Y };
case {'uk:'}
varargout = {sf_tol(sf_uk(sX)*Y,sX.tol)};
end
otherwise
error(['too many input argument in spm_sp ' action]);
end % switch nargin
case {'pinvxpx', 'xpx-', 'pinvxpx:', 'xpx-:',} %- Pseudo-inv of (X'X)
%=======================================================================
% pXpX = spm_sp('pinvxpx',x [,Y])
switch nargin
case 2
switch lower(action),
case {'xpx-','pinvxpx'}
varargout = {sf_pinvxpx(sX)};
case {'xpx-:','pinvxpx:'}
varargout = {sf_tol(sf_pinvxpx(sX),sX.tol)};
end %-
case 3
%- check dimensions of Y
Y = varargin{3};
if isempty(Y), varargout = {spm_sp(action,sX)}; return, end
if size(Y,1) ~= sf_s2(sX), error('Dim dont match'); end;
switch lower(action),
case {'xpx-','pinvxpx'}
varargout = {sf_pinvxpx(sX)*Y};
case {'xpx-:','pinvxpx:'}
varargout = {sf_tol(sf_pinvxpx(sX)*Y,sX.tol)};
end %-
otherwise
error('too many input argument in spm_sp');
end % switch nargin
case {'xpx','xpx:'} %-Computation of (X'*X)
%=======================================================================
% XpX = spm_sp('xpx',x [,Y])
switch nargin
case 2
switch lower(action),
case {'xpx'}
varargout = {sf_xpx(sX)};
case {'xpx:'}
varargout = {sf_tol(sf_xpx(sX),sX.tol)};
end %-
case 3
%- check dimensions of Y
Y = varargin{3};
if isempty(Y), varargout = {spm_sp(action,sX)}; return, end
if size(Y,1) ~= sf_s2(sX), error('Dim dont match'); end;
switch lower(action),
case {'xpx'}
varargout = {sf_xpx(sX)*Y};
case {'xpx:'}
varargout = {sf_tol(sf_xpx(sX)*Y,sX.tol)};
end %-
otherwise
error('too many input argument in spm_sp');
end % switch nargin
case {'cx->cu','cx->cu:'} %-coordinates in the basis of X -> basis u
%=======================================================================
%
% returns cu such that sX.X*cx == sX.u*cu
switch nargin
case 2
switch lower(action),
case {'cx->cu'}
varargout = {sf_cxtwdcu(sX)};
case {'cx->cu:'}
varargout = {sf_tol(sf_cxtwdcu(sX),sX.tol)};
end %-
case 3
%- check dimensions of Y
Y = varargin{3};
if isempty(Y), varargout = {spm_sp(action,sX)}; return, end
if size(Y,1) ~= sf_s2(sX), error('Dim dont match'); end;
switch lower(action),
case {'cx->cu'}
varargout = {sf_cxtwdcu(sX)*Y};
case {'cx->cu:'}
varargout = {sf_tol(sf_cxtwdcu(sX)*Y,sX.tol)};
end %-
otherwise
error('too many input argument in spm_sp');
end % switch nargin
case {'xxp-','xxp-:','pinvxxp','pinvxxp:'} %-Pseudo-inverse of (XX')
%=======================================================================
% pXXp = spm_sp('pinvxxp',x [,Y])
switch nargin
case 2
switch lower(action),
case {'xxp-','pinvxxp'}
varargout = {sf_pinvxxp(sX)};
case {'xxp-:','pinvxxp:'}
varargout = {sf_tol(sf_pinvxxp(sX),sX.tol)};
end %-
case 3
%- check dimensions of Y
Y = varargin{3};
if isempty(Y), varargout = {spm_sp(action,sX)}; return, end
if size(Y,1) ~= sf_s1(sX), error('Dim dont match'); end;
switch lower(action),
case {'xxp-','pinvxxp'}
varargout = {sf_pinvxxp(sX)*Y};
case {'xxp-:','pinvxxp:'}
varargout = {sf_tol(sf_pinvxxp(sX)*Y,sX.tol)};
end %-
otherwise
error('too many input argument in spm_sp');
end % switch nargin
case {'xxp','xxp:'} %-Computation of (X*X')
%=======================================================================
% XXp = spm_sp('xxp',x)
switch nargin
case 2
switch lower(action),
case {'xxp'}
varargout = {sf_xxp(sX)};
case {'xxp:'}
varargout = {sf_tol(sf_xxp(sX),sX.tol)};
end %-
case 3
%- check dimensions of Y
Y = varargin{3};
if isempty(Y), varargout = {spm_sp(action,sX)}; return, end
if size(Y,1) ~= sf_s1(sX), error('Dim dont match'); end;
switch lower(action),
case {'xxp'}
varargout = {sf_xxpY(sX,Y)};
case {'xxp:'}
varargout = {sf_tol(sf_xxpY(sX,Y),sX.tol)};
end %-
otherwise
error('too many input argument in spm_sp');
end % switch nargin
case {'^p','^p:'} %-Computation of v*(diag(s.^n))*v'
%=======================================================================
switch nargin
case {2,3}
if nargin==2, n = 1; else n = varargin{3}; end;
if ~isnumeric(n), error('~isnumeric(n)'), end;
switch lower(action),
case {'^p'}
varargout = {sf_jbp(sX,n)};
case {'^p:'}
varargout = {sf_tol(sf_jbp(sX,n),sX.tol)};
end %-
case 4
n = varargin{3};
if ~isnumeric(n), error('~isnumeric(n)'), end;
Y = varargin{4};
if isempty(Y), varargout = {spm_sp(action,sX,n)}; return, end
if size(Y,1) ~= sf_s2(sX), error('Dim dont match'); end;
switch lower(action),
case {'^p'}
varargout = {sf_jbp(sX,n)*Y};
case {'^p:'}
varargout = {sf_tol(sf_jbp(sX,n)*Y,sX.tol)};
end %-
otherwise
error('too many input argument in spm_sp');
end % switch nargin
case {'^','^:'} %-Computation of v*(diag(s.^n))*v'
%=======================================================================
switch nargin
case {2,3}
if nargin==2, n = 1; else n = varargin{3}; end;
if ~isnumeric(n), error('~isnumeric(n)'), end;
switch lower(action),
case {'^'}
varargout = {sf_jb(sX,n)};
case {'^:'}
varargout = {sf_tol(sf_jb(sX,n),sX.tol)};
end %-
case 4
n = varargin{3};
if ~isnumeric(n), error('~isnumeric(n)'), end;
Y = varargin{4};
if isempty(Y), varargout = {spm_sp(action,sX,n)}; return, end
if size(Y,1) ~= sf_s1(sX), error('Dim dont match'); end;
switch lower(action),
case {'^'}
varargout = {sf_jbY(sX,n,Y)};
case {'^:'}
varargout = {sf_tol(sf_jbY(sX,n,Y),sX.tol)};
end %-
otherwise
error('too many input argument in spm_sp');
end % switch nargin
case {'n'} %-Null space of sX
%=======================================================================
switch nargin
case 2
varargout = {sf_n(sX)};
otherwise
error('too many input argument in spm_sp');
end % switch nargin
case {'np'} %-Null space of sX'
%=======================================================================
switch nargin
case 2
varargout = {sf_n(sf_transp(sX))};
otherwise
error('too many input argument in spm_sp');
end % switch nargin
case {'nop', 'nop:'} %- project(or)(ion) into null space
%=======================================================================
%
%
%
switch nargin
case 2
switch lower(action),
case {'nop'}
n = sf_n(sX);
varargout = {n*n'};
case {'nop:'}
n = sf_n(sX);
varargout = {sf_tol(n*n',sX.tol)};
end %-
case 3
%- check dimensions of Y
Y = varargin{3};
if isempty(Y), varargout = {spm_sp(action,sX)}; return, end
if size(Y,1) ~= sf_s2(sX), error('Dim dont match'); end;
switch lower(action),
case {'nop'}
n = sf_n(sX);
varargout = {n*(n'*Y)};
case {'nop:'}
n = sf_n(sX);
varargout = {sf_tol(n*(n'*Y),sX.tol)};
end %-
otherwise
error('too many input argument in spm_sp');
end % switch nargin
case {'nopp', 'nopp:'} %- projector(ion) into null space of X'
%=======================================================================
%
%
switch nargin
case 2
switch lower(action),
case {'nopp'}
varargout = {spm_sp('nop',sf_transp(sX))};
case {'nopp:'}
varargout = {spm_sp('nop:',sf_transp(sX))};
end %-
case 3
switch lower(action),
case {'nopp'}
varargout = {spm_sp('nop',sf_transp(sX),varargin{3})};
case {'nopp:'}
varargout = {spm_sp('nop:',sf_transp(sX),varargin{3})};
end %-
otherwise
error('too many input argument in spm_sp');
end % switch nargin
case {'res', 'r','r:'} %-Residual formaing matrix / residuals
%=======================================================================
% r = spm_sp('res',sX[,Y])
%
%- 'res' will become obsolete : use 'r' or 'r:' instead
%- At some stage, should be merged with 'nop'
switch nargin
case 2
switch lower(action)
case {'r','res'}
varargout = {sf_r(sX)};
case {'r:','res:'}
varargout = {sf_tol(sf_r(sX),sX.tol)};
end %-
case 3
%- check dimensions of Y
Y = varargin{3};
if isempty(Y), varargout = {spm_sp(action,sX)}; return, end
if size(Y,1) ~= sf_s1(sX), error('Dim dont match'); end;
switch lower(action)
case {'r','res'}
varargout = {sf_rY(sX,Y)};
case {'r:','res:'}
varargout = {sf_tol(sf_rY(sX,Y),sX.tol)};
end %-
otherwise
error('too many input argument in spm_sp');
end % switch nargin
case {':'}
%=======================================================================
% spm_sp(':',sX [,Y [,tol]])
%- Sets Y and tol according to arguments
if nargin > 4
error('too many input argument in spm_sp');
else
if nargin > 3
if isnumeric(varargin{4}), tol = varargin{4};
else error('tol must be numeric');
end
else
tol = sX.tol;
end
if nargin > 2
Y = varargin{3}; %- if isempty, returns empty, end
else
Y = sX.X;
end
end
varargout = {sf_tol(Y,tol)};
case {'isinsp', 'isinspp'} %- is in space or is in dual space
%=======================================================================
% b = spm_sp('isinsp',x,c[,tol])
% b = spm_sp('isinspp',x,c[,tol])
%-Check whether vectors are in row/column space of X
%-Check arguments
%-----------------------------------------------------------------------
if nargin<3, error('insufficient arguments - action,x,c required'), end
c = varargin{3}; %- if isempty(c), dim wont match exept for empty sp.
if nargin<4, tol=sX.tol; else, tol = varargin{4}; end
%-Compute according to case
%-----------------------------------------------------------------------
switch lower(action)
case 'isinsp'
%-Check dimensions
if size(sX.X,1) ~= size(c,1)
warning('Vector dim don''t match col. dim : not in space !');
varargout = { 0 }; return;
end
varargout = {all(all( abs(sf_op(sX)*c - c) <= tol ))};
case 'isinspp'
%- check dimensions
if size(sX.X,2) ~= size(c,1)
warning('Vector dim don''t match row dim : not in space !');
varargout = { 0 }; return;
end
varargout = {all(all( abs(sf_opp(sX)*c - c) <= tol ))};
end
case {'eachinsp', 'eachinspp'} %- each column of c in space or in dual space
%=======================================================================
% b = spm_sp('eachinsp',x,c[,tol])
% b = spm_sp('eachinspp',x,c[,tol])
%-Check whether vectors are in row/column space of X
%-Check arguments
%-----------------------------------------------------------------------
if nargin<3, error('insufficient arguments - action,x,c required'), end
c = varargin{3}; %- if isempty(c), dim wont match exept for empty sp.
if nargin<4, tol=sX.tol; else, tol = varargin{4}; end
%-Compute according to case
%-----------------------------------------------------------------------
switch lower(action)
case 'eachinsp'
%-Check dimensions
if size(sX.X,1) ~= size(c,1)
warning('Vector dim don''t match col. dim : not in space !');
varargout = { 0 }; return;
end
varargout = {all( abs(sf_op(sX)*c - c) <= tol )};
case 'eachinspp'
%- check dimensions
if size(sX.X,2) ~= size(c,1)
warning('Vector dim don''t match row dim : not in space !');
varargout = { 0 }; return;
end
varargout = {all( abs(sf_opp(sX)*c - c) <= tol )};
end
case '==' % test wether two spaces are the same
%=======================================================================
% b = spm_sp('==',x1,X2)
if nargin~=3, error('too few/many input arguments - need 3');
else X2 = varargin{3}; end;
if isempty(sX.X)
if isempty(X2),
warning('Both spaces empty');
varargout = { 1 };
else
warning('one space empty');
varargout = { 0 };
end;
else
x2 = spm_sp('Set',X2);
maxtol = max(sX.tol,x2.tol);
varargout = { all( spm_sp('isinsp',sX,X2,maxtol)) & ...
all( spm_sp('isinsp',x2,sX.X,maxtol) ) };
%- I have encountered one case where the max of tol was needed.
end;
case 'isspc' %-Space structure check
%=======================================================================
% [b,str] = spm_sp('isspc',x)
if nargin~=2, error('too few/many input arguments - need 2'), end
%-Check we've been passed a structure
if ~isstruct(varargin{2}), varargout={0}; return, end
%-Go through required field names checking their existance
% (Get fieldnames once and compare: isfield doesn't work for multiple )
% (fields, and repeated calls to isfield would result in unnecessary )
% (replicate calls to fieldnames(varargin{2}). )
b = 1;
fnames = fieldnames(varargin{2});
for str = fieldnames(sf_create)'
b = b & any(strcmp(str,fnames));
if ~b, break, end
end
if nargout > 1,
if b, str = 'ok'; else, str = 'not a space'; end;
varargout = {b,str};
else, varargout = {b}; end;
case 'issetspc' %-Is this a completed space structure?
%=======================================================================
% [b,e] = spm_sp('issetspc',x)
if nargin~=2, error('too few/many input arguments - need 2'), end
if ~spm_sp('isspc',varargin{2})
varargout = {0,'not a space structure (wrong fieldnames)'};
elseif ~sf_isset(varargin{2})
%-Basic fields aren't filled in
varargout = {0,'space not defined (use ''set'')'};
else
varargout = {1,'OK!'};
end
case 'size' %- gives the size of sX
%=======================================================================
% size = spm_sp('size',x,dim)
%
if nargin > 3, error('too many input arguments'), end
if nargin == 2, dim = []; else dim = varargin{3}; end
if ~isempty(dim)
switch dim
case 1, varargout = { sf_s1(sX) };
case 2, varargout = { sf_s2(sX) };
otherwise, error(['unknown dimension in ' action]);
end
else %- assumes want both dim
switch nargout
case {0,1}
varargout = { sf_si(sX) };
case 2
varargout = { sf_s1(sX), sf_s2(sX) };
otherwise
error(['too many output arg in ' mfilename ' ' action]);
end
end
otherwise
%=======================================================================
error(['Invalid action (',action,')'])
%=======================================================================
end % (case lower(action))
%=======================================================================
%- S U B - F U N C T I O N S
%=======================================================================
%
% The rule I tried to follow is that the space structure is accessed
% only in this sub function part : any sX.whatever should be
% prohibited elsewhere .... still a lot to clean !!!
function x = sf_create
%=======================================================================
x = struct(...
'X', [],... % Matrix
'tol', [],... % tolerance
'ds', [],... % vectors of singular values
'u', [],... % u as in X = u*diag(ds)*v'
'v', [], ... % v as in X = u*diag(ds)*v'
'rk', [],... % rank
'oP', [],... % orthogonal projector on X
'oPp', [],... % orthogonal projector on X'
'ups', [],... % space in which this one is embeded
'sus', []); % subspace
function x = sf_set(X)
%=======================================================================
x = sf_create;
x.X = X;
%-- Compute the svd with svd(X,0) : find all the singular values of x.X
%-- SVD(FULL(A)) will usually perform better than SVDS(A,MIN(SIZE(A)))
%- if more column that lines, performs on X'
if size(X,1) < size(X,2)
[x.v, s, x.u] = svd(full(X'),0);
else
[x.u, s, x.v] = svd(full(X),0);
end
x.ds = diag(s); clear s;
%-- compute the tolerance
x.tol = max(size(x.X))*max(abs(x.ds))*eps;
%-- compute the rank
x.rk = sum(x.ds > x.tol);
function x = sf_transp(x)
%=======================================================================
%
%- Tranpspose the space : note that tmp is not touched, therefore
%- only contains the address, no duplication of data is performed.
x.X = x.X';
tmp = x.v;
x.v = x.u;
x.u = tmp;
tmp = x.oP;
x.oP = x.oPp;
x.oPp = tmp;
clear tmp;
function b = sf_isset(x)
%=======================================================================
b = ~( isempty(x.X) |...
isempty(x.u) |...
isempty(x.v) |...
isempty(x.ds) |...
isempty(x.tol) |...
isempty(x.rk) );
function s1 = sf_s1(x)
%=======================================================================
s1 = size(x.X,1);
function s2 = sf_s2(x)
%=======================================================================
s2 = size(x.X,2);
function si = sf_si(x)
%=======================================================================
si = size(x.X);
function r = sf_rk(x)
%=======================================================================
r = x.rk;
function uk = sf_uk(x)
%=======================================================================
uk = x.u(:,1:sf_rk(x));
function vk = sf_vk(x)
%=======================================================================
vk = x.v(:,1:sf_rk(x));
function sk = sf_sk(x)
%=======================================================================
sk = x.ds(1:sf_rk(x));
function t = sf_t(x)
%=======================================================================
t = x.tol;
function x = sf_tol(x,t)
%=======================================================================
x(abs(x) < t) = 0;
function op = sf_op(sX)
%=======================================================================
if sX.rk > 0
op = sX.u(:,[1:sX.rk])*sX.u(:,[1:sX.rk])';
else
op = zeros( size(sX.X,1) );
end;
%!!!! to implement : a clever version of sf_opY (see sf_rY)
function opp = sf_opp(sX)
%=======================================================================
if sX.rk > 0
opp = sX.v(:,[1:sX.rk])*sX.v(:,[1:sX.rk])';
else
opp = zeros( size(sX.X,2) );
end;
%!!!! to implement : a clever version of sf_oppY (see sf_rY)
function px = sf_pinv(sX)
%=======================================================================
r = sX.rk;
if r > 0
px = sX.v(:,1:r)*diag( ones(r,1)./sX.ds(1:r) )*sX.u(:,1:r)';
else
px = zeros(size(sX.X,2),size(sX.X,1));
end
function px = sf_pinvxp(sX)
%=======================================================================
r = sX.rk;
if r > 0
px = sX.u(:,1:r)*diag( ones(r,1)./sX.ds(1:r) )*sX.v(:,1:r)';
else
px = zeros(size(sX.X));
end
function px = sf_pinvxpx(sX)
%=======================================================================
r = sX.rk;
if r > 0
px = sX.v(:,1:r)*diag( sX.ds(1:r).^(-2) )*sX.v(:,1:r)';
else
px = zeros(size(sX.X,2));
end
function px = sf_jbp(sX,n)
%=======================================================================
r = sX.rk;
if r > 0
px = sX.v(:,1:r)*diag( sX.ds(1:r).^(n) )*sX.v(:,1:r)';
else
px = zeros(size(sX.X,2));
end
function x = sf_jb(sX,n)
%=======================================================================
r = sX.rk;
if r > 0
x = sX.u(:,1:r)*diag( sX.ds(1:r).^(n) )*sX.u(:,1:r)';
else
x = zeros(size(sX.X,1));
end
function y = sf_jbY(sX,n,Y)
%=======================================================================
r = sX.rk;
if r > 0
y = ( sX.u(:,1:r)*diag(sX.ds(1:r).^n) )*(sX.u(:,1:r)'*Y);
else
y = zeros(size(sX.X,1),size(Y,2));
end
%!!!! to implement : a clever version of sf_jbY (see sf_rY)
function x = sf_cxtwdcu(sX)
%=======================================================================
%- coordinates in sX.X -> coordinates in sX.u(:,1:rk)
x = diag(sX.ds)*sX.v';
function x = sf_cukpinvxp(sX)
%=======================================================================
%- coordinates of pinv(sX.X') in the basis sX.u(:,1:rk)
r = sX.rk;
if r > 0
x = diag( ones(r,1)./sX.ds(1:r) )*sX.v(:,1:r)';
else
x = zeros( size(sX.X,2) );
end
function x = sf_cukx(sX)
%=======================================================================
%- coordinates of sX.X in the basis sX.u(:,1:rk)
r = sX.rk;
if r > 0
x = diag( sX.ds(1:r) )*sX.v(:,1:r)';
else
x = zeros( size(sX.X,2) );
end
function x = sf_xpx(sX)
%=======================================================================
r = sX.rk;
if r > 0
x = sX.v(:,1:r)*diag( sX.ds(1:r).^2 )*sX.v(:,1:r)';
else
x = zeros(size(sX.X,2));
end
function x = sf_xxp(sX)
%=======================================================================
r = sX.rk;
if r > 0
x = sX.u(:,1:r)*diag( sX.ds(1:r).^2 )*sX.u(:,1:r)';
else
x = zeros(size(sX.X,1));
end
function x = sf_xxpY(sX,Y)
%=======================================================================
r = sX.rk;
if r > 0
x = sX.u(:,1:r)*diag( sX.ds(1:r).^2 )*(sX.u(:,1:r)'*Y);
else
x = zeros(size(sX.X,1),size(Y,2));
end
function x = sf_pinvxxp(sX)
%=======================================================================
r = sX.rk;
if r > 0
x = sX.u(:,1:r)*diag( sX.ds(1:r).^(-2) )*sX.u(:,1:r)';
else
x = zeros(size(sX.X,1));
end
function n = sf_n(sX)
%=======================================================================
% if the null space is in sX.v, returns it
% otherwise, performs Gramm Schmidt orthogonalisation.
%
%
r = sX.rk;
[q p]= size(sX.X);
if r > 0
if q >= p %- the null space is entirely in v
if r == p, n = zeros(p,1); else, n = sX.v(:,r+1:p); end
else %- only part of n is in v: same as computing the null sp of sX'
n = null(sX.X);
%----- BUG !!!! in that part ----------------------------------------
%- v = zeros(p,p-q); j = 1; i = 1; z = zeros(p,1);
%- while i <= p
%- o = z; o(i) = 1; vpoi = [sX.v(i,:) v(i,1:j-1)]';
%- o = sf_tol(o - [sX.v v(:,1:j-1)]*vpoi,sX.tol);
%- if any(o), v(:,j) = o/((o'*o)^(1/2)); j = j + 1; end;
%- i = i + 1; %- if i>p, error('gramm shmidt error'); end;
%- end
%- n = [sX.v(:,r+1:q) v];
%--------------------------------------------------------------------
end
else
n = eye(p);
end
function r = sf_r(sX)
%=======================================================================
%-
%- returns the residual forming matrix for the space sX
%- for internal use. doesn't Check whether oP exist.
r = eye(size(sX.X,1)) - sf_op(sX) ;
function Y = sf_rY(sX,Y)
%=======================================================================
% r = spm_sp('r',sX[,Y])
%
%- tries to minimise the computation by looking whether we should do
%- I - u*(u'*Y) or n*(n'*Y) as in 'nop'
r = sX.rk;
[q p]= size(sX.X);
if r > 0 %- else returns the input;
if r < q-r %- we better do I - u*u'
Y = Y - sX.u(:,[1:r])*(sX.u(:,[1:r])'*Y); % warning('route1');
else
%- is it worth computing the n ortho basis ?
if size(Y,2) < 5*q
Y = sf_r(sX)*Y; % warning('route2');
else
n = sf_n(sf_transp(sX)); % warning('route3');
Y = n*(n'*Y);
end
end
end
|
github
|
philippboehmsturm/antx-master
|
spm_dicom_essentials.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_dicom_essentials.m
| 3,313 |
utf_8
|
eaddd814bd4e7aa9c9fa338cb76f42fc
|
function hdr1 = spm_dicom_essentials(hdr0)
% Remove unused fields from DICOM header
% FORMAT hdr1 = spm_dicom_essentials(hdr0)
% hdr0 - original DICOM header
% hdr1 - Stripped down DICOM header.
%
% With lots of DICOM files, the size of all the headers can become too
% big for all the fields to be saved. The idea here is to strip down
% the headers to their essentials.
%
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_dicom_essentials.m 647 2011-07-19 10:20:21Z vglauche $
% do nothing in FBI version
hdr1 = hdr0;
return
used_fields = {...
'AcquisitionDate',...
'AcquisitionNumber',...
'AcquisitionTime',...
'BitsAllocated',...
'BitsStored',...
'CSAImageHeaderInfo',...
'Columns',...
'EchoNumbers',...
'EchoTime',...
'Filename',...
'FlipAngle',...
'HighBit',...
'ImageOrientationPatient',...
'ImagePositionPatient',...
'ImageType',...
'InstanceNumber',...
'MagneticFieldStrength',...
'Manufacturer',...
'Modality',...
'MRAcquisitionType',...
'PatientID',...
'PatientsName',...
'PixelRepresentation',...
'PixelSpacing',...
'Private_0029_1110',...
'Private_0029_1210',...
'ProtocolName',...
'RepetitionTime',...
'RescaleIntercept',...
'RescaleSlope',...
'Rows',...
'SOPClassUID',...
'SamplesperPixel',...
'ScanningSequence',...
'SequenceName',...
'SeriesDescription',...
'SeriesInstanceUID',...
'SeriesNumber',...
'SliceNormalVector',...
'SliceThickness',...
'SpacingBetweenSlices',...
'StartOfPixelData',...
'StudyDate',...
'StudyTime',...
'TransferSyntaxUID',...
'VROfPixelData',...
'ScanOptions'};
fnames = fieldnames(hdr0);
for i=1:numel(used_fields)
if ismember(used_fields{i},fnames)
hdr1.(used_fields{i}) = hdr0.(used_fields{i});
end
end
Private_spectroscopy_fields = {...
'Columns',...
'Rows',...
'ImageOrientationPatient',...
'ImagePositionPatient',...
'SliceThickness',...
'PixelSpacing',...
'VoiPhaseFoV',...
'VoiReadoutFoV',...
'VoiThickness'};
if isfield(hdr1,'Private_0029_1110')
hdr1.Private_0029_1110 = ...
getfields(hdr1.Private_0029_1110,...
Private_spectroscopy_fields);
end
if isfield(hdr1,'Private_0029_1210')
hdr1.Private_0029_1210 = ...
getfields(hdr1.Private_0029_1210,...
Private_spectroscopy_fields);
end
if isfield(hdr1,'CSAImageHeaderInfo')
CSAImageHeaderInfo_fields = {...
'SliceNormalVector',...
'NumberOfImagesInMosaic',...
'AcquisitionMatrixText',...
'ICE_Dims'};
hdr1.CSAImageHeaderInfo = ...
getfields(hdr1.CSAImageHeaderInfo,...
CSAImageHeaderInfo_fields);
end
if isfield(hdr1,'CSASeriesHeaderInfo')
CSASeriesHeaderInfo_fields = {};
hdr1.CSASeriesHeaderInfo = ...
getfields(hdr1.CSASeriesHeaderInfo,...
CSASeriesHeaderInfo_fields);
end
function str1 = getfields(str0,names)
str1 = [];
for i=1:numel(names)
for j=1:numel(str0)
if strcmp(str0(j).name,names{i})
str1 = [str1,str0(j)];
end
end
end
|
github
|
philippboehmsturm/antx-master
|
spm_ecat2nifti.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_ecat2nifti.m
| 16,572 |
utf_8
|
753e9a7e6e367abce74e0a0c4878f6c5
|
function N = spm_ecat2nifti(fname,opts)
% Import ECAT 7 images from CTI PET scanners.
% FORMAT N = spm_ecat2nifti(fname)
% fname - name of ECAT file
% _______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner & Roger Gunn
% $Id: spm_ecat2nifti.m 3691 2010-01-20 17:08:30Z guillaume $
if nargin==1
opts = struct('ext','.nii');
else
if opts.ext(1) ~= '.', opts.ext = ['.' opts.ext]; end
end
fp = fopen(fname,'r','ieee-be');
if fp == -1,
error(['Can''t open "' fname '".']);
return;
end
mh = ECAT7_mheader(fp);
if ~strcmp(mh.MAGIC_NUMBER,'MATRIX70v') &&...
~strcmp(mh.MAGIC_NUMBER,'MATRIX71v') &&...
~strcmp(mh.MAGIC_NUMBER,'MATRIX72v'),
error(['"' fname '" does not appear to be ECAT 7 format.']);
fclose(fp);
return;
end
if mh.FILE_TYPE ~= 7,
error(['"' fname '" does not appear to be an image file.']);
fclose(fp);
return;
end
list = s7_matlist(fp);
matches = find((list(:,4) == 1) | (list(:,4) == 2));
llist = list(matches,:);
for i=1:size(llist,1),
sh(i) = ECAT7_sheader(fp,llist(i,2));
end;
fclose(fp);
for i=1:size(llist,1),
dim = [sh(i).X_DIMENSION sh(i).Y_DIMENSION sh(i).Z_DIMENSION];
dtype = [4 1];
off = 512*llist(i,2);
scale = sh(i).SCALE_FACTOR*mh.ECAT_CALIBRATION_FACTOR;
inter = 0;
dati = file_array(fname,dim,dtype,off,scale,inter);
dircos = diag([-1 -1 -1]);
step = ([sh(i).X_PIXEL_SIZE sh(i).Y_PIXEL_SIZE sh(i).Z_PIXEL_SIZE]*10);
start = -(dim(1:3)'/2).*step';
mat = [[dircos*diag(step) dircos*start] ; [0 0 0 1]];
matnum = sprintf('%.8x',list(i,1));
[pth,nam,ext] = fileparts(fname);
fnameo = fullfile(pwd,[nam '_' matnum opts.ext]);
dato = file_array(fnameo,dim,[4 spm_platform('bigend')],0,scale,inter);
N = nifti;
N.dat = dato;
N.mat = mat;
N.mat0 = mat;
N.mat_intent = 'aligned';
N.mat0_intent = 'scanner';
N.descrip = sh(i).ANNOTATION;
N.timing = struct('toffset',sh(i).FRAME_START_TIME/1000,'tspace',sh(i).FRAME_DURATION/1000);
create(N);
for j=1:dim(3),
N.dat(:,:,j) = dati(:,:,j);
end;
N.extras = struct('mh',mh,'sh',sh(i));
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
%S7_MATLIST List the available matrixes in an ECAT 7 file.
% LIST = S7_MATLIST(FP) lists the available matrixes
% in the file specified by FP.
%
% Columns in LIST:
% 1 - Matrix identifier.
% 2 - Matrix subheader record number
% 3 - Last record number of matrix data block.
% 4 - Matrix status:
% 1 - exists - rw
% 2 - exists - ro
% 3 - matrix deleted
%
function list = s7_matlist(fp)
% I believe fp should be opened with:
% fp = fopen(filename,'r','ieee-be');
fseek(fp,512,'bof');
block = fread(fp,128,'int');
if size(block,1) ~= 128
list = [];
return;
end;
block = reshape(block,4,32);
list = [];
while block(2,1) ~= 2,
if block(1,1)+block(4,1) ~= 31,
list = []; return;
end;
list = [list block(:,2:32)];
fseek(fp,512*(block(2,1)-1),'bof');
block = fread(fp,128,'int');
if size(block,1) ~= 128, list = []; return; end;
block = reshape(block,4,32);
end
list = [list block(:,2:(block(4,1)+1))];
list = list';
return;
%_______________________________________________________________________
%_______________________________________________________________________
function SHEADER=ECAT7_sheader(fid,record)
%
% Sub header read routine for ECAT 7 image files
%
% Roger Gunn, 260298
off = (record-1)*512;
status = fseek(fid, off,'bof');
data_type = fread(fid,1,'uint16',0);
num_dimensions = fread(fid,1,'uint16',0);
x_dimension = fread(fid,1,'uint16',0);
y_dimension = fread(fid,1,'uint16',0);
z_dimension = fread(fid,1,'uint16',0);
x_offset = fread(fid,1,'float32',0);
y_offset = fread(fid,1,'float32',0);
z_offset = fread(fid,1,'float32',0);
recon_zoom = fread(fid,1,'float32',0);
scale_factor = fread(fid,1,'float32',0);
image_min = fread(fid,1,'int16',0);
image_max = fread(fid,1,'int16',0);
x_pixel_size = fread(fid,1,'float32',0);
y_pixel_size = fread(fid,1,'float32',0);
z_pixel_size = fread(fid,1,'float32',0);
frame_duration = fread(fid,1,'uint32',0);
frame_start_time = fread(fid,1,'uint32',0);
filter_code = fread(fid,1,'uint16',0);
x_resolution = fread(fid,1,'float32',0);
y_resolution = fread(fid,1,'float32',0);
z_resolution = fread(fid,1,'float32',0);
num_r_elements = fread(fid,1,'float32',0);
num_angles = fread(fid,1,'float32',0);
z_rotation_angle = fread(fid,1,'float32',0);
decay_corr_fctr = fread(fid,1,'float32',0);
corrections_applied = fread(fid,1,'uint32',0);
gate_duration = fread(fid,1,'uint32',0);
r_wave_offset = fread(fid,1,'uint32',0);
num_accepted_beats = fread(fid,1,'uint32',0);
filter_cutoff_frequency = fread(fid,1,'float32',0);
filter_resolution = fread(fid,1,'float32',0);
filter_ramp_slope = fread(fid,1,'float32',0);
filter_order = fread(fid,1,'uint16',0);
filter_scatter_fraction = fread(fid,1,'float32',0);
filter_scatter_slope = fread(fid,1,'float32',0);
annotation = fread(fid,40,'char',0);
mt_1_1 = fread(fid,1,'float32',0);
mt_1_2 = fread(fid,1,'float32',0);
mt_1_3 = fread(fid,1,'float32',0);
mt_2_1 = fread(fid,1,'float32',0);
mt_2_2 = fread(fid,1,'float32',0);
mt_2_3 = fread(fid,1,'float32',0);
mt_3_1 = fread(fid,1,'float32',0);
mt_3_2 = fread(fid,1,'float32',0);
mt_3_3 = fread(fid,1,'float32',0);
rfilter_cutoff = fread(fid,1,'float32',0);
rfilter_resolution = fread(fid,1,'float32',0);
rfilter_code = fread(fid,1,'uint16',0);
rfilter_order = fread(fid,1,'uint16',0);
zfilter_cutoff = fread(fid,1,'float32',0);
zfilter_resolution = fread(fid,1,'float32',0);
zfilter_code = fread(fid,1,'uint16',0);
zfilter_order = fread(fid,1,'uint16',0);
mt_4_1 = fread(fid,1,'float32',0);
mt_4_2 = fread(fid,1,'float32',0);
mt_4_3 = fread(fid,1,'float32',0);
scatter_type = fread(fid,1,'uint16',0);
recon_type = fread(fid,1,'uint16',0);
recon_views = fread(fid,1,'uint16',0);
fill = fread(fid,1,'uint16',0);
annotation = deblank(char(annotation.*(annotation>0))');
SHEADER = struct('DATA_TYPE', data_type, ...
'NUM_DIMENSIONS', num_dimensions, ...
'X_DIMENSION', x_dimension, ...
'Y_DIMENSION', y_dimension, ...
'Z_DIMENSION', z_dimension, ...
'X_OFFSET', x_offset, ...
'Y_OFFSET', y_offset, ...
'Z_OFFSET', z_offset, ...
'RECON_ZOOM', recon_zoom, ...
'SCALE_FACTOR', scale_factor, ...
'IMAGE_MIN', image_min, ...
'IMAGE_MAX', image_max, ...
'X_PIXEL_SIZE', x_pixel_size, ...
'Y_PIXEL_SIZE', y_pixel_size, ...
'Z_PIXEL_SIZE', z_pixel_size, ...
'FRAME_DURATION', frame_duration, ...
'FRAME_START_TIME', frame_start_time, ...
'FILTER_CODE', filter_code, ...
'X_RESOLUTION', x_resolution, ...
'Y_RESOLUTION', y_resolution, ...
'Z_RESOLUTION', z_resolution, ...
'NUM_R_ELEMENTS', num_r_elements, ...
'NUM_ANGLES', num_angles, ...
'Z_ROTATION_ANGLE', z_rotation_angle, ...
'DECAY_CORR_FCTR', decay_corr_fctr, ...
'CORRECTIONS_APPLIED', corrections_applied, ...
'GATE_DURATION', gate_duration, ...
'R_WAVE_OFFSET', r_wave_offset, ...
'NUM_ACCEPTED_BEATS', num_accepted_beats, ...
'FILTER_CUTOFF_FREQUENCY', filter_cutoff_frequency, ...
'FILTER_RESOLUTION', filter_resolution, ...
'FILTER_RAMP_SLOPE', filter_ramp_slope, ...
'FILTER_ORDER', filter_order, ...
'FILTER_SCATTER_CORRECTION', filter_scatter_fraction, ...
'FILTER_SCATTER_SLOPE', filter_scatter_slope, ...
'ANNOTATION', annotation, ...
'MT_1_1', mt_1_1, ...
'MT_1_2', mt_1_2, ...
'MT_1_3', mt_1_3, ...
'MT_2_1', mt_2_1, ...
'MT_2_2', mt_2_2, ...
'MT_2_3', mt_2_3, ...
'MT_3_1', mt_3_1, ...
'MT_3_2', mt_3_2, ...
'MT_3_3', mt_3_3, ...
'RFILTER_CUTOFF', rfilter_cutoff, ...
'RFILTER_RESOLUTION', rfilter_resolution, ...
'RFILTER_CODE', rfilter_code, ...
'RFILTER_ORDER', rfilter_order, ...
'ZFILTER_CUTOFF', zfilter_cutoff, ...
'ZFILTER_RESOLUTION', zfilter_resolution, ...
'ZFILTER_CODE', zfilter_code, ...
'ZFILTER_ORDER', zfilter_order, ...
'MT_4_1', mt_4_1, ...
'MT_4_2', mt_4_2, ...
'MT_4_3', mt_4_3, ...
'SCATTER_TYPE', scatter_type, ...
'RECON_TYPE', recon_type, ...
'RECON_VIEWS', recon_views, ...
'FILL', fill);
return;
%_______________________________________________________________________
function [MHEADER]=ECAT7_mheader(fid)
%
% Main header read routine for ECAT 7 image files
%
% Roger Gunn, 260298
status = fseek(fid, 0,'bof');
magic_number = fread(fid,14,'char',0);
original_file_name = fread(fid,32,'char',0);
sw_version = fread(fid,1,'uint16',0);
system_type = fread(fid,1,'uint16',0);
file_type = fread(fid,1,'uint16',0);
serial_number = fread(fid,10,'char',0);
scan_start_time = fread(fid,1,'uint32',0);
isotope_name = fread(fid,8,'char',0);
isotope_halflife = fread(fid,1,'float32',0);
radiopharmaceutical = fread(fid,32,'char',0);
gantry_tilt = fread(fid,1,'float32',0);
gantry_rotation = fread(fid,1,'float32',0);
bed_elevation = fread(fid,1,'float32',0);
intrinsic_tilt = fread(fid,1,'float32',0);
wobble_speed = fread(fid,1,'uint16',0);
transm_source_type = fread(fid,1,'uint16',0);
distance_scanned = fread(fid,1,'float32',0);
transaxial_fov = fread(fid,1,'float32',0);
angular_compression = fread(fid,1,'uint16',0);
coin_samp_mode = fread(fid,1,'uint16',0);
axial_samp_mode = fread(fid,1,'uint16',0);
ecat_calibration_factor = fread(fid,1,'float32',0);
calibration_units = fread(fid,1,'uint16',0);
calibration_units_type = fread(fid,1,'uint16',0);
compression_code = fread(fid,1,'uint16',0);
study_type = fread(fid,12,'char',0);
patient_id = fread(fid,16,'char',0);
patient_name = fread(fid,32,'char',0);
patient_sex = fread(fid,1,'char',0);
patient_dexterity = fread(fid,1,'char',0);
patient_age = fread(fid,1,'float32',0);
patient_height = fread(fid,1,'float32',0);
patient_weight = fread(fid,1,'float32',0);
patient_birth_date = fread(fid,1,'uint32',0);
physician_name = fread(fid,32,'char',0);
operator_name = fread(fid,32,'char',0);
study_description = fread(fid,32,'char',0);
acquisition_type = fread(fid,1,'uint16',0);
patient_orientation = fread(fid,1,'uint16',0);
facility_name = fread(fid,20,'char',0);
num_planes = fread(fid,1,'uint16',0);
num_frames = fread(fid,1,'uint16',0);
num_gates = fread(fid,1,'uint16',0);
num_bed_pos = fread(fid,1,'uint16',0);
init_bed_position = fread(fid,1,'float32',0);
bed_position = zeros(15,1);
for bed=1:15,
tmp = fread(fid,1,'float32',0);
if ~isempty(tmp), bed_position(bed) = tmp; end;
end;
plane_separation = fread(fid,1,'float32',0);
lwr_sctr_thres = fread(fid,1,'uint16',0);
lwr_true_thres = fread(fid,1,'uint16',0);
upr_true_thres = fread(fid,1,'uint16',0);
user_process_code = fread(fid,10,'char',0);
acquisition_mode = fread(fid,1,'uint16',0);
bin_size = fread(fid,1,'float32',0);
branching_fraction = fread(fid,1,'float32',0);
dose_start_time = fread(fid,1,'uint32',0);
dosage = fread(fid,1,'float32',0);
well_counter_corr_factor = fread(fid,1,'float32',0);
data_units = fread(fid,32,'char',0);
septa_state = fread(fid,1,'uint16',0);
fill = fread(fid,1,'uint16',0);
magic_number = deblank(char(magic_number.*(magic_number>32))');
original_file_name = deblank(char(original_file_name.*(original_file_name>0))');
serial_number = deblank(char(serial_number.*(serial_number>0))');
isotope_name = deblank(char(isotope_name.*(isotope_name>0))');
radiopharmaceutical = deblank(char(radiopharmaceutical.*(radiopharmaceutical>0))');
study_type = deblank(char(study_type.*(study_type>0))');
patient_id = deblank(char(patient_id.*(patient_id>0))');
patient_name = deblank(char(patient_name.*(patient_name>0))');
patient_sex = deblank(char(patient_sex.*(patient_sex>0))');
patient_dexterity = deblank(char(patient_dexterity.*(patient_dexterity>0))');
physician_name = deblank(char(physician_name.*(physician_name>0))');
operator_name = deblank(char(operator_name.*(operator_name>0))');
study_description = deblank(char(study_description.*(study_description>0))');
facility_name = deblank(char(facility_name.*(facility_name>0))');
user_process_code = deblank(char(user_process_code.*(user_process_code>0))');
data_units = deblank(char(data_units.*(data_units>0))');
MHEADER = struct('MAGIC_NUMBER', magic_number, ...
'ORIGINAL_FILE_NAME', original_file_name, ...
'SW_VERSION', sw_version, ...
'SYSTEM_TYPE', system_type, ...
'FILE_TYPE', file_type, ...
'SERIAL_NUMBER', serial_number, ...
'SCAN_START_TIME', scan_start_time, ...
'ISOTOPE_NAME', isotope_name, ...
'ISOTOPE_HALFLIFE', isotope_halflife, ...
'RADIOPHARMACEUTICAL', radiopharmaceutical, ...
'GANTRY_TILT', gantry_tilt, ...
'GANTRY_ROTATION', gantry_rotation, ...
'BED_ELEVATION', bed_elevation, ...
'INTRINSIC_TILT', intrinsic_tilt, ...
'WOBBLE_SPEED', wobble_speed, ...
'TRANSM_SOURCE_TYPE', transm_source_type, ...
'DISTANCE_SCANNED', distance_scanned, ...
'TRANSAXIAL_FOV', transaxial_fov, ...
'ANGULAR_COMPRESSION', angular_compression, ...
'COIN_SAMP_MODE', coin_samp_mode, ...
'AXIAL_SAMP_MODE', axial_samp_mode, ...
'ECAT_CALIBRATION_FACTOR', ecat_calibration_factor, ...
'CALIBRATION_UNITS', calibration_units, ...
'CALIBRATION_UNITS_TYPE', calibration_units_type, ...
'COMPRESSION_CODE', compression_code, ...
'STUDY_TYPE', study_type, ...
'PATIENT_ID', patient_id, ...
'PATIENT_NAME', patient_name, ...
'PATIENT_SEX', patient_sex, ...
'PATIENT_DEXTERITY', patient_dexterity, ...
'PATIENT_AGE', patient_age, ...
'PATIENT_HEIGHT', patient_height, ...
'PATIENT_WEIGHT', patient_weight, ...
'PATIENT_BIRTH_DATE', patient_birth_date, ...
'PHYSICIAN_NAME', physician_name, ...
'OPERATOR_NAME', operator_name, ...
'STUDY_DESCRIPTION', study_description, ...
'ACQUISITION_TYPE', acquisition_type, ...
'PATIENT_ORIENTATION', patient_orientation, ...
'FACILITY_NAME', facility_name, ...
'NUM_PLANES', num_planes, ...
'NUM_FRAMES', num_frames, ...
'NUM_GATES', num_gates, ...
'NUM_BED_POS', num_bed_pos, ...
'INIT_BED_POSITION', init_bed_position, ...
'BED_POSITION', bed_position, ...
'PLANE_SEPARATION', plane_separation, ...
'LWR_SCTR_THRES', lwr_sctr_thres, ...
'LWR_TRUE_THRES', lwr_true_thres, ...
'UPR_TRUE_THRES', upr_true_thres, ...
'USER_PROCESS_CODE', user_process_code, ...
'ACQUISITION_MODE', acquisition_mode, ...
'BIN_SIZE', bin_size, ...
'BRANCHING_FRACTION', branching_fraction, ...
'DOSE_START_TIME', dose_start_time, ...
'DOSAGE', dosage, ...
'WELL_COUNTER_CORR_FACTOR', well_counter_corr_factor, ...
'DATA_UNITS', data_units, ...
'SEPTA_STATE', septa_state, ...
'FILL', fill);
return;
%_______________________________________________________________________
|
github
|
philippboehmsturm/antx-master
|
spm_platform.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_platform.m
| 8,916 |
utf_8
|
1ead463af23059fb998f62b124a12a6d
|
function varargout=spm_platform(varargin)
% Platform specific configuration parameters for SPM
%
% FORMAT ans = spm_platform(arg)
% arg - optional string argument, can be
% - 'bigend' - return whether this architecture is bigendian
% - 0 - is little endian
% - 1 - is big endian
% - 'filesys' - type of filesystem
% - 'unx' - UNIX
% - 'win' - DOS
% - 'sepchar' - returns directory separator
% - 'user' - returns username
% - 'host' - returns system's host name
% - 'tempdir' - returns name of temp directory
% - 'drives' - returns string containing valid drive letters
%
% FORMAT PlatFontNames = spm_platform('fonts')
% Returns structure with fields named after the generic (UNIX) fonts, the
% field containing the name of the platform specific font.
%
% FORMAT PlatFontName = spm_platform('font',GenFontName)
% Maps generic (UNIX) FontNames to platform specific FontNames
%
% FORMAT PLATFORM = spm_platform('init',comp)
% Initialises platform specific parameters in persistent PLATFORM
% (External gateway to init_platform(comp) subfunction)
% comp - computer to use [defaults to MATLAB's `computer`]
% PLATFORM - copy of persistent PLATFORM
%
% FORMAT spm_platform
% Initialises platform specific parameters in persistent PLATFORM
% (External gateway to init_platform(computer) subfunction)
%
% ----------------
% SUBFUNCTIONS:
%
% FORMAT init_platform(comp)
% Initialise platform specific parameters in persistent PLATFORM
% comp - computer to use [defaults to MATLAB's `computer`]
%
%--------------------------------------------------------------------------
%
% Since calls to spm_platform will be made frequently, most platform
% specific parameters are stored as a structure in the persistent variable
% PLATFORM. Subsequent calls use the information from this persistent
% variable, if it exists.
%
% Platform specific definitions are contained in the data structures at
% the beginning of the init_platform subfunction at the end of this
% file.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Matthew Brett
% $Id: spm_platform.m 4137 2010-12-15 17:18:32Z guillaume $
%-Initialise
%--------------------------------------------------------------------------
persistent PLATFORM
if isempty(PLATFORM), PLATFORM = init_platform; end
if nargin==0, return, end
switch lower(varargin{1}), case 'init' %-(re)initialise
%==========================================================================
init_platform(varargin{2:end});
varargout = {PLATFORM};
case 'bigend' %-Return endian for this architecture
%==========================================================================
varargout = {PLATFORM.bigend};
case 'filesys' %-Return file system
%==========================================================================
varargout = {PLATFORM.filesys};
case 'sepchar' %-Return file separator character
%==========================================================================
warning('use filesep instead (supported by MathWorks)')
varargout = {PLATFORM.sepchar};
case 'rootlen' %-Return length in chars of root directory name
%=======================================================================
varargout = {PLATFORM.rootlen};
case 'user' %-Return user string
%==========================================================================
varargout = {PLATFORM.user};
case 'host' %-Return hostname
%==========================================================================
varargout = {PLATFORM.host};
case 'drives' %-Return drives
%==========================================================================
varargout = {PLATFORM.drives};
case 'tempdir' %-Return temporary directory
%==========================================================================
twd = getenv('SPMTMP');
if isempty(twd)
twd = tempdir;
end
varargout = {twd};
case {'font','fonts'} %-Map default font names to platform font names
%==========================================================================
if nargin<2, varargout={PLATFORM.font}; return, end
switch lower(varargin{2})
case 'times'
varargout = {PLATFORM.font.times};
case 'courier'
varargout = {PLATFORM.font.courier};
case 'helvetica'
varargout = {PLATFORM.font.helvetica};
case 'symbol'
varargout = {PLATFORM.font.symbol};
otherwise
warning(['Unknown font ',varargin{2},', using default'])
varargout = {PLATFORM.font.helvetica};
end
otherwise %-Unknown Action string
%==========================================================================
error('Unknown Action string')
%==========================================================================
end
%==========================================================================
%- S U B - F U N C T I O N S
%==========================================================================
function PLATFORM = init_platform(comp) %-Initialise platform variables
%==========================================================================
if nargin<1
comp = computer;
if any(comp=='-') % Octave
if isunix
switch uname.machine
case 'x86_64'
comp = 'GLNXA64';
case {'i586','i686'}
comp = 'GLNX86';
end
elseif ispc
comp = 'PCWIN';
elseif ismac
comp = 'MACI';
end
end
end
%-Platform definitions
%--------------------------------------------------------------------------
PDefs = {'PCWIN', 'win', 0;...
'PCWIN64', 'win', 0;...
'MAC', 'unx', 1;...
'MACI', 'unx', 0;...
'MACI64', 'unx', 0;...
'SOL2', 'unx', 1;...
'SOL64', 'unx', 1;...
'GLNX86', 'unx', 0;...
'GLNXA64', 'unx', 0};
PDefs = cell2struct(PDefs,{'computer','filesys','endian'},2);
%-Which computer?
%--------------------------------------------------------------------------
[issup, ci] = ismember(comp,{PDefs.computer});
if ~issup
error([comp ' not supported architecture for ' spm('Ver')]);
end
%-Set byte ordering
%--------------------------------------------------------------------------
PLATFORM.bigend = PDefs(ci).endian;
%-Set filesystem type
%--------------------------------------------------------------------------
PLATFORM.filesys = PDefs(ci).filesys;
%-File separator character
%--------------------------------------------------------------------------
PLATFORM.sepchar = filesep;
%-Username
%--------------------------------------------------------------------------
switch PLATFORM.filesys
case 'unx'
PLATFORM.user = getenv('USER');
case 'win'
PLATFORM.user = getenv('USERNAME');
otherwise
error(['Don''t know filesystem ',PLATFORM.filesys])
end
if isempty(PLATFORM.user), PLATFORM.user = 'anonymous'; end
%-Hostname
%--------------------------------------------------------------------------
[sts, Host] = system('hostname');
if sts
if strcmp(PLATFORM.filesys,'win')
Host = getenv('COMPUTERNAME');
else
Host = getenv('HOSTNAME');
end
Host = regexp(Host,'(.*?)\.','tokens','once');
else
Host = Host(1:end-1);
end
PLATFORM.host = Host;
%-Drives
%--------------------------------------------------------------------------
PLATFORM.drives = '';
if strcmp(PLATFORM.filesys,'win')
driveLett = cellstr(char(('C':'Z')'));
for i=1:numel(driveLett)
if exist([driveLett{i} ':\'],'dir')
PLATFORM.drives = [PLATFORM.drives driveLett{i}];
end
end
end
%-Fonts
%--------------------------------------------------------------------------
switch comp
case {'MAC','MACI','MACI64'}
PLATFORM.font.helvetica = 'TrebuchetMS';
PLATFORM.font.times = 'Times';
PLATFORM.font.courier = 'Courier';
PLATFORM.font.symbol = 'Symbol';
case {'SOL2','SOL64','GLNX86','GLNXA64'}
PLATFORM.font.helvetica = 'Helvetica';
PLATFORM.font.times = 'Times';
PLATFORM.font.courier = 'Courier';
PLATFORM.font.symbol = 'Symbol';
case {'PCWIN','PCWIN64'}
PLATFORM.font.helvetica = 'Arial Narrow';
PLATFORM.font.times = 'Times New Roman';
PLATFORM.font.courier = 'Courier New';
PLATFORM.font.symbol = 'Symbol';
end
|
github
|
philippboehmsturm/antx-master
|
spm_vb_graphcut.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_vb_graphcut.m
| 6,187 |
utf_8
|
e66c1e4a9a6d484998db51df14cba084
|
function labels = spm_vb_graphcut(labels,index,I,W,depth,grnd_type,CUTOFF,DIM)
% Recursive bi-partition of a graph using the isoperimetric algorithm
%
% FORMAT labels = spm_vb_graphcut(labels,index,I,W,depth,grnd_type,CUTOFF,DIM)
%
% labels each voxel is lableled depending on whihc segment is belongs
% index index of current node set in labels vector
% I InMask XYZ voxel (node set) indices
% W weight matrix i.e. adjacency matrix containing edge weights
% of graph
% depth depth of recursion
% grnd_type 'random' or 'max' - ground node selected at random or the
% node with maximal degree
% CUTOFF minimal number of voxels in a segment of the partition
% DIM dimensions of data
%__________________________________________________________________________
%
% Recursive bi-partition of a graph using the isoperimetric algorithm by
% Grady et al. This routine is adapted from "The Graph Analysis Toolbox:
% Image Processing on Arbitrary Graphs", available through Matlab Central
% File Exchange. See also Grady, L. Schwartz, E. L. (2006) "Isoperimetric
% graph partitioning for image segmentation",
% IEEE Trans Pattern Anal Mach Intell, 28(3),pp469-75
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Lee Harrison
% $Id: spm_vb_graphcut.m 2923 2009-03-23 18:34:51Z guillaume $
try, grnd_type; catch, grnd_type = 'random'; end
%-Initialize
s = rand('twister'); rand('seed',0);
N = length(index);
terminate = 0;
%-Partition current graph
if N > CUTOFF
reject = 1;
d = sum(W,2); % "degree" of each node
switch grnd_type
case 'max'
id = find(d==max(d));
ground = id(ceil(rand(1)*length(id)));
case 'random'
ground = ceil(rand(1)*N);
end
while reject == 1,
if N < 1e5, method = 'direct'; else, method = 'cg'; end
parts = bipartition(W,CUTOFF,ground,method);
nparts = [length(parts{1}),length(parts{2})];
if min(nparts) < CUTOFF, terminate = 1; break, end
for k = 1:2, % check if partitions are contiguous
bw = zeros(DIM(1),DIM(2),DIM(3));
bw(I(parts{k})) = 1;
[tmp,NUM] = spm_bwlabel(bw,6);
if NUM > 1
reject = 1;
ground = ceil(rand(1)*N); % re-select ground node
fprintf('depth %1.0f, partition %1.0f of 2, reject ',depth,k); fprintf('\n')
break
else
reject = 0;
fprintf('depth %1.0f, partition %1.0f of 2, accept ',depth,k);
fprintf('\n')
end
end
end
else
terminate = 1;
end
if terminate
labels = labels;
fprintf('depth %1.0f, end of branch ',depth);
fprintf('\n')
rand('twister',s);
else
%Accept partition and update labels
tmpInd = find(labels>labels(index(1)));
labels(tmpInd) = labels(tmpInd) + 1; %Make room for new class
labels(index(parts{2})) = labels(index(parts{2})) + 1; %Mark new class
%Continue recursion on each partition
if nparts(1) > CUTOFF
labels = spm_vb_graphcut(labels,index(parts{1}),I(parts{1}),...
W(parts{1},parts{1}),depth + 1,grnd_type,CUTOFF,DIM);
end
if nparts(2) > CUTOFF
labels = spm_vb_graphcut(labels,index(parts{2}),I(parts{2}),...
W(parts{2},parts{2}),depth + 1,grnd_type,CUTOFF,DIM);
end
end
%==========================================================================
% function parts = bipartition(W,CUTOFF,ground,method)
%==========================================================================
function parts = bipartition(W,CUTOFF,ground,method)
% Computes bi-partition of a graph using isoperimetric algorithm.
% FORMAT parts = bipartition(W,CUTOFF,ground,method)
% parts 1x2 cell containing indices of each partition
% W weight matrix
% CUTOFF minimal number of voxels in a segment of the partition
% ground ground node index
% method used to solve L0*x0=d0. Options are 'direct' or 'cg', which
% x0 = L0\d0 or preconditioned conjugate gradients (see Matlab
% rountine pcg.m)
try, method; catch, method = 'direct'; end
%-Laplacian matrix
d = sum(W,2);
L = diag(d) - W;
N = length(d);
%-Compute reduced Laplacian matrix, i.e. remove ground node
index = [1:(ground-1),(ground+1):N];
d0 = d(index);
L0 = L(index,index);
%-Solve system of equations L0*x0=d0
switch method
case 'direct'
x0 = L0\d0;
case 'cg'
x0 = pcg(L0,d0,[],N,diag(d0));
end
%-Error catch if numerical instability occurs (due to ill-conditioned or
%singular matrix)
minVal = min(min(x0));
if minVal < 0
x0(find(x0 < 0)) = max(max(x0)) + 1;
end
%-Re-insert ground point
x0 = [x0(1:(ground-1));0;x0((ground):(N-1))];
%-Remove sparseness of output
x0 = full(x0);
%-Determine cut point (ratio cut method)
indicator = sparse(N,1);
%-Sort values
sortX = sortrows([x0,[1:N]'],1)';
%-Find total volume
totalVolume = sum(d);
halfTotalVolume = totalVolume/2;
%-Calculate denominators
sortedDegree = d(sortX(2,:))';
denominators = cumsum(sortedDegree);
tmpIndex = find(denominators > halfTotalVolume);
denominators(tmpIndex) = totalVolume - denominators(tmpIndex);
%-Calculate numerators
L = L(sortX(2,:),sortX(2,:)) - diag(sortedDegree);
numerators = cumsum(sum((L - 2*triu(L)),2))';
if min(numerators) < 0
%Line used to avoid negative values due to precision issues
numerators = numerators - min(numerators) + eps;
end
%-Calculate ratios for Isoperimetric criteria
sw = warning('off','MATLAB:divideByZero');
[constant,minCut] = min(numerators(CUTOFF:(N-CUTOFF))./ ...
denominators(CUTOFF:(N-CUTOFF)));
minCut = minCut + CUTOFF - 1;
warning(sw);
%-Output partitions
parts{1} = sortX(2,1:(minCut))';
parts{2} = sortX(2,(minCut+1):N);
|
github
|
philippboehmsturm/antx-master
|
spm_preproc.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_preproc.m
| 20,562 |
utf_8
|
4fb344b9d6037ec12448af8a5f36eaff
|
function results = spm_preproc(varargin)
% Combined Segmentation and Spatial Normalisation
%
% FORMAT results = spm_preproc(V,opts)
% V - image to work with
% opts - options
% opts.tpm - n tissue probability images for each class
% opts.ngaus - number of Gaussians per class (n+1 classes)
% opts.warpreg - warping regularisation
% opts.warpco - cutoff distance for DCT basis functions
% opts.biasreg - regularisation for bias correction
% opts.biasfwhm - FWHM of Gausian form for bias regularisation
% opts.regtype - regularisation for affine part
% opts.fudge - a fudge factor
% opts.msk - unused
%__________________________________________________________________________
% Copyright (C) 2005-2011 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_preproc.m 4677 2012-03-05 15:39:35Z john $
opts0 = spm_get_defaults('preproc');
opts0 = rmfield(opts0,'output');
opts0.tpm = char(opts0.tpm); % In defaults, tpms are stored as cellstr
opts0.msk = '';
if ~nargin
V = spm_select(1,'image');
else
V = varargin{1};
end
if ischar(V), V = spm_vol(V); end
if nargin < 2
opts = opts0;
else
opts = varargin{2};
fnms = fieldnames(opts0);
for i=1:length(fnms)
if ~isfield(opts,fnms{i}), opts.(fnms{i}) = opts0.(fnms{i}); end
end
end
if length(opts.ngaus) ~= size(opts.tpm,1)+1
error('Number of Gaussians per class is not compatible with number of classes');
end
K = sum(opts.ngaus);
Kb = length(opts.ngaus);
lkp = [];
for k=1:Kb
lkp = [lkp ones(1,opts.ngaus(k))*k];
end
B = spm_vol(opts.tpm);
b0 = spm_load_priors(B);
d = V(1).dim(1:3);
vx = sqrt(sum(V(1).mat(1:3,1:3).^2));
sk = max([1 1 1],round(opts.samp*[1 1 1]./vx));
[x0,y0,o] = ndgrid(1:sk(1):d(1),1:sk(2):d(2),1);
z0 = 1:sk(3):d(3);
tiny = eps;
vx = sqrt(sum(V(1).mat(1:3,1:3).^2));
kron = inline('spm_krutil(a,b)','a','b');
% BENDING ENERGY REGULARIZATION for warping
%-----------------------------------------------------------------------
lam = 0.001;
d2 = max(round((V(1).dim(1:3).*vx)/opts.warpco),[1 1 1]);
kx = (pi*((1:d2(1))'-1)/d(1)/vx(1)).^2;
ky = (pi*((1:d2(2))'-1)/d(2)/vx(2)).^2;
kz = (pi*((1:d2(3))'-1)/d(3)/vx(3)).^2;
Cwarp = (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)) );
Cwarp = Cwarp*opts.warpreg;
Cwarp = [Cwarp*vx(1)^4 ; Cwarp*vx(2)^4 ; Cwarp*vx(3)^4];
Cwarp = sparse(1:length(Cwarp),1:length(Cwarp),Cwarp,length(Cwarp),length(Cwarp));
B3warp = spm_dctmtx(d(3),d2(3),z0);
B2warp = spm_dctmtx(d(2),d2(2),y0(1,:)');
B1warp = spm_dctmtx(d(1),d2(1),x0(:,1));
lmR = speye(size(Cwarp));
Twarp = zeros([d2 3]);
% GAUSSIAN REGULARISATION for bias correction
%--------------------------------------------------------------------------
fwhm = opts.biasfwhm;
sd = vx(1)*V(1).dim(1)/fwhm; d3(1) = ceil(sd*2); krn_x = exp(-(0:(d3(1)-1)).^2/sd.^2)/sqrt(vx(1));
sd = vx(2)*V(1).dim(2)/fwhm; d3(2) = ceil(sd*2); krn_y = exp(-(0:(d3(2)-1)).^2/sd.^2)/sqrt(vx(2));
sd = vx(3)*V(1).dim(3)/fwhm; d3(3) = ceil(sd*2); krn_z = exp(-(0:(d3(3)-1)).^2/sd.^2)/sqrt(vx(3));
Cbias = kron(krn_z,kron(krn_y,krn_x)).^(-2)*opts.biasreg;
Cbias = sparse(1:length(Cbias),1:length(Cbias),Cbias,length(Cbias),length(Cbias));
B3bias = spm_dctmtx(d(3),d3(3),z0);
B2bias = spm_dctmtx(d(2),d3(2),y0(1,:)');
B1bias = spm_dctmtx(d(1),d3(1),x0(:,1));
lmRb = speye(size(Cbias));
Tbias = zeros(d3);
% Fudge Factor - to (approximately) account for non-independence of voxels
ff = opts.fudge;
ff = max(1,ff^3/prod(sk)/abs(det(V.mat(1:3,1:3))));
Cwarp = Cwarp*ff;
Cbias = Cbias*ff;
ll = -Inf;
llr = 0;
llrb = 0;
tol1 = 1e-4; % Stopping criterion. For more accuracy, use a smaller value
d = [size(x0) length(z0)];
f = zeros(d);
for z=1:length(z0)
f(:,:,z) = spm_sample_vol(V,x0,y0,o*z0(z),0);
end
[thresh,mx] = spm_minmax(f);
mn = zeros(K,1);
% give same results each time
st = rand('state'); % st = rng;
rand('state',0); % rng(0,'v5uniform'); % rng('defaults');
for k1=1:Kb
kk = sum(lkp==k1);
mn(lkp==k1) = rand(kk,1)*mx;
end
rand('state',st); % rng(st);
vr = ones(K,1)*mx^2;
mg = ones(K,1)/K;
if ~isempty(opts.msk)
VM = spm_vol(opts.msk);
if sum(sum((VM.mat-V(1).mat).^2)) > 1e-6 || any(VM.dim(1:3) ~= V(1).dim(1:3))
error('Mask must have the same dimensions and orientation as the image.');
end
end
Affine = eye(4);
if isfield(opts,'Affine'), % A request from Rik Henson
Affine = opts.Affine;
fprintf(1,'Using user-defined matrix for initial affine transformation\n');
end;
if ~isempty(opts.regtype)
Affine = spm_maff(V,{x0,y0,z0},b0,B(1).mat,Affine,opts.regtype,ff*100);
Affine = spm_maff(V,{x0,y0,z0},b0,B(1).mat,Affine,opts.regtype,ff);
end
M = B(1).mat\Affine*V(1).mat;
nm = 0;
for z=1:length(z0)
x1 = M(1,1)*x0 + M(1,2)*y0 + (M(1,3)*z0(z) + M(1,4));
y1 = M(2,1)*x0 + M(2,2)*y0 + (M(2,3)*z0(z) + M(2,4));
z1 = M(3,1)*x0 + M(3,2)*y0 + (M(3,3)*z0(z) + M(3,4));
buf(z).msk = spm_sample_priors(b0{end},x1,y1,z1,1)<(1-1/512);
fz = f(:,:,z);
%buf(z).msk = fz>thresh;
buf(z).msk = buf(z).msk & isfinite(fz) & (fz~=0);
if ~isempty(opts.msk),
msk = spm_sample_vol(VM,x0,y0,o*z0(z),0);
buf(z).msk = buf(z).msk & msk;
end
buf(z).nm = sum(buf(z).msk(:));
buf(z).f = fz(buf(z).msk);
nm = nm + buf(z).nm;
buf(z).bf(1:buf(z).nm,1) = single(1);
buf(z).dat = single(0);
if buf(z).nm,
buf(z).dat(buf(z).nm,Kb) = single(0);
end
end
clear f
finalit = 0;
spm_plot_convergence('Init','Processing','Log-likelihood','Iteration');
for iter=1:100
if finalit
% THIS CODE MAY BE USED IN FUTURE
% Reload the data for the final iteration. This iteration
% does not do any registration, so there is no need to
% mask out the background voxels.
%------------------------------------------------------------------
llrb = -0.5*Tbias(:)'*Cbias*Tbias(:);
for z=1:length(z0)
fz = spm_sample_vol(V,x0,y0,o*z0(z),0);
buf(z).msk = fz~=0;
if ~isempty(opts.msk)
msk = spm_sample_vol(VM,x0,y0,o*z0(z),0);
buf(z).msk = buf(z).msk & msk;
end
buf(z).nm = sum(buf(z).msk(:));
buf(z).f = fz(buf(z).msk);
nm = nm + buf(z).nm;
buf(z).bf(1:buf(z).nm,1) = single(1);
buf(z).dat = single(0);
if buf(z).nm
buf(z).dat(buf(z).nm,Kb) = single(0);
end
if buf(z).nm
bf = transf(B1bias,B2bias,B3bias(z,:),Tbias);
tmp = bf(buf(z).msk);
llrb = llrb + sum(tmp);
buf(z).bf = single(exp(tmp));
end
end
% The background won't fit well any more, so increase the
% variances of these Gaussians in order to give it a chance
vr(lkp(K)) = vr(lkp(K))*8;
spm_plot_convergence('Init','Processing','Log-likelihood','Iteration');
end
% Load the warped prior probability images into the buffer
%----------------------------------------------------------------------
for z=1:length(z0)
if ~buf(z).nm, continue; end
[x1,y1,z1] = defs(Twarp,z,B1warp,B2warp,B3warp,x0,y0,z0,M,buf(z).msk);
for k1=1:Kb
tmp = spm_sample_priors(b0{k1},x1,y1,z1,k1==Kb);
buf(z).dat(:,k1) = single(tmp);
end
end
for iter1=1:10
% Estimate cluster parameters
%==================================================================
for subit=1:40
oll = ll;
mom0 = zeros(K,1)+tiny;
mom1 = zeros(K,1);
mom2 = zeros(K,1);
mgm = zeros(Kb,1);
ll = llr+llrb;
for z=1:length(z0)
if ~buf(z).nm, continue; end
bf = double(buf(z).bf);
cr = double(buf(z).f).*bf;
q = zeros(buf(z).nm,K);
b = zeros(buf(z).nm,Kb);
s = zeros(buf(z).nm,1)+tiny;
for k1=1:Kb
pr = double(buf(z).dat(:,k1));
b(:,k1) = pr;
s = s + pr*sum(mg(lkp==k1));
end
for k1=1:Kb
b(:,k1) = b(:,k1)./s;
end
mgm = mgm + sum(b,1)';
for k=1:K
q(:,k) = mg(k)*b(:,lkp(k)) .* exp((cr-mn(k)).^2/(-2*vr(k)))/sqrt(2*pi*vr(k));
end
sq = sum(q,2)+tiny;
ll = ll + sum(log(sq));
for k=1:K % Moments
p1 = q(:,k)./sq; mom0(k) = mom0(k) + sum(p1(:));
p1 = p1.*cr; mom1(k) = mom1(k) + sum(p1(:));
p1 = p1.*cr; mom2(k) = mom2(k) + sum(p1(:));
end
end
% Mixing proportions, Means and Variances
for k=1:K
mg(k) = (mom0(k)+eps)/(mgm(lkp(k))+eps);
mn(k) = mom1(k)/(mom0(k)+eps);
vr(k) =(mom2(k)-mom1(k)*mom1(k)/mom0(k)+1e6*eps)/(mom0(k)+eps);
vr(k) = max(vr(k),eps);
end
if subit>1 || (iter>1 && ~finalit),
spm_plot_convergence('Set',ll);
end;
if finalit, fprintf('Mix: %g\n',ll); end;
if subit == 1
ooll = ll;
elseif (ll-oll)<tol1*nm
% Improvement is small, so go to next step
break;
end
end
% Estimate bias
%==================================================================
if prod(d3)>0
for subit=1:40
% Compute objective function and its 1st and second derivatives
Alpha = zeros(prod(d3),prod(d3)); % Second derivatives
Beta = zeros(prod(d3),1); % First derivatives
ollrb = llrb;
oll = ll;
ll = llr+llrb;
for z=1:length(z0)
if ~buf(z).nm, continue; end
bf = double(buf(z).bf);
cr = double(buf(z).f).*bf;
q = zeros(buf(z).nm,K);
for k=1:K
q(:,k) = double(buf(z).dat(:,lkp(k)))*mg(k);
end
s = sum(q,2)+tiny;
for k=1:K
q(:,k) = q(:,k)./s .* exp((cr-mn(k)).^2/(-2*vr(k)))/sqrt(2*pi*vr(k));
end
sq = sum(q,2)+tiny;
ll = ll + sum(log(sq));
w1 = zeros(buf(z).nm,1);
w2 = zeros(buf(z).nm,1);
for k=1:K
tmp = q(:,k)./sq/vr(k);
w1 = w1 + tmp.*(mn(k) - cr);
w2 = w2 + tmp;
end
wt1 = zeros(d(1:2)); wt1(buf(z).msk) = 1 + cr.*w1;
wt2 = zeros(d(1:2)); wt2(buf(z).msk) = cr.*(cr.*w2 - w1);
b3 = B3bias(z,:)';
Beta = Beta + kron(b3,spm_krutil(wt1,B1bias,B2bias,0));
Alpha = Alpha + kron(b3*b3',spm_krutil(wt2,B1bias,B2bias,1));
clear w1 w2 wt1 wt2 b3
end
if finalit, fprintf('Bia: %g\n',ll); end
if subit > 1 && ~(ll>oll)
% Hasn't improved, so go back to previous solution
Tbias = oTbias;
llrb = ollrb;
for z=1:length(z0)
if ~buf(z).nm, continue; end
bf = transf(B1bias,B2bias,B3bias(z,:),Tbias);
buf(z).bf = single(exp(bf(buf(z).msk)));
end
break;
else
% Accept new solution
spm_plot_convergence('Set',ll);
oTbias = Tbias;
if subit > 1 && ~((ll-oll)>tol1*nm)
% Improvement is only small, so go to next step
break;
else
% Use new solution and continue the Levenberg-Marquardt iterations
Tbias = reshape((Alpha + Cbias + lmRb)\((Alpha+lmRb)*Tbias(:) + Beta),d3);
llrb = -0.5*Tbias(:)'*Cbias*Tbias(:);
for z=1:length(z0)
if ~buf(z).nm, continue; end
bf = transf(B1bias,B2bias,B3bias(z,:),Tbias);
tmp = bf(buf(z).msk);
llrb = llrb + sum(tmp);
buf(z).bf = single(exp(tmp));
end
end
end
end
if ~((ll-ooll)>tol1*nm), break; end
end
end
if finalit, break; end
% Estimate deformations
%======================================================================
mg1 = full(sparse(lkp,1,mg));
ll = llr+llrb;
for z=1:length(z0)
if ~buf(z).nm, continue; end
bf = double(buf(z).bf);
cr = double(buf(z).f).*bf;
q = zeros(buf(z).nm,Kb);
tmp = zeros(buf(z).nm,1)+tiny;
s = zeros(buf(z).nm,1)+tiny;
for k1=1:Kb
s = s + mg1(k1)*double(buf(z).dat(:,k1));
end
for k1=1:Kb
kk = find(lkp==k1);
pp = zeros(buf(z).nm,1);
for k=kk
pp = pp + exp((cr-mn(k)).^2/(-2*vr(k)))/sqrt(2*pi*vr(k))*mg(k);
end
q(:,k1) = pp;
tmp = tmp+pp.*double(buf(z).dat(:,k1))./s;
end
ll = ll + sum(log(tmp));
for k1=1:Kb
buf(z).dat(:,k1) = single(q(:,k1));
end
end
for subit=1:20
oll = ll;
A = cell(3,3);
A{1,1} = zeros(prod(d2));
A{1,2} = zeros(prod(d2));
A{1,3} = zeros(prod(d2));
A{2,2} = zeros(prod(d2));
A{2,3} = zeros(prod(d2));
A{3,3} = zeros(prod(d2));
Beta = zeros(prod(d2)*3,1);
for z=1:length(z0)
if ~buf(z).nm, continue; end
[x1,y1,z1] = defs(Twarp,z,B1warp,B2warp,B3warp,x0,y0,z0,M,buf(z).msk);
b = zeros(buf(z).nm,Kb);
db1 = zeros(buf(z).nm,Kb);
db2 = zeros(buf(z).nm,Kb);
db3 = zeros(buf(z).nm,Kb);
s = zeros(buf(z).nm,1)+tiny;
ds1 = zeros(buf(z).nm,1);
ds2 = zeros(buf(z).nm,1);
ds3 = zeros(buf(z).nm,1);
p = zeros(buf(z).nm,1)+tiny;
dp1 = zeros(buf(z).nm,1);
dp2 = zeros(buf(z).nm,1);
dp3 = zeros(buf(z).nm,1);
for k1=1:Kb
[b(:,k1),db1(:,k1),db2(:,k1),db3(:,k1)] = spm_sample_priors(b0{k1},x1,y1,z1,k1==Kb);
s = s + mg1(k1)* b(:,k1);
ds1 = ds1 + mg1(k1)*db1(:,k1);
ds2 = ds2 + mg1(k1)*db2(:,k1);
ds3 = ds3 + mg1(k1)*db3(:,k1);
end
for k1=1:Kb
b(:,k1) = b(:,k1)./s;
db1(:,k1) = (db1(:,k1)-b(:,k1).*ds1)./s;
db2(:,k1) = (db2(:,k1)-b(:,k1).*ds2)./s;
db3(:,k1) = (db3(:,k1)-b(:,k1).*ds3)./s;
pp = double(buf(z).dat(:,k1));
p = p + pp.*b(:,k1);
dp1 = dp1 + pp.*(M(1,1)*db1(:,k1) + M(2,1)*db2(:,k1) + M(3,1)*db3(:,k1));
dp2 = dp2 + pp.*(M(1,2)*db1(:,k1) + M(2,2)*db2(:,k1) + M(3,2)*db3(:,k1));
dp3 = dp3 + pp.*(M(1,3)*db1(:,k1) + M(2,3)*db2(:,k1) + M(3,3)*db3(:,k1));
end
clear x1 y1 z1 b db1 db2 db3 s ds1 ds2 ds3
tmp = zeros(d(1:2));
tmp(buf(z).msk) = dp1./p; dp1 = tmp;
tmp(buf(z).msk) = dp2./p; dp2 = tmp;
tmp(buf(z).msk) = dp3./p; dp3 = tmp;
b3 = B3warp(z,:)';
Beta = Beta - [...
kron(b3,spm_krutil(dp1,B1warp,B2warp,0))
kron(b3,spm_krutil(dp2,B1warp,B2warp,0))
kron(b3,spm_krutil(dp3,B1warp,B2warp,0))];
b3b3 = b3*b3';
A{1,1} = A{1,1} + kron(b3b3,spm_krutil(dp1.*dp1,B1warp,B2warp,1));
A{1,2} = A{1,2} + kron(b3b3,spm_krutil(dp1.*dp2,B1warp,B2warp,1));
A{1,3} = A{1,3} + kron(b3b3,spm_krutil(dp1.*dp3,B1warp,B2warp,1));
A{2,2} = A{2,2} + kron(b3b3,spm_krutil(dp2.*dp2,B1warp,B2warp,1));
A{2,3} = A{2,3} + kron(b3b3,spm_krutil(dp2.*dp3,B1warp,B2warp,1));
A{3,3} = A{3,3} + kron(b3b3,spm_krutil(dp3.*dp3,B1warp,B2warp,1));
clear b3 b3b3 tmp p dp1 dp2 dp3
end
Alpha = [A{1,1} A{1,2} A{1,3} ; A{1,2} A{2,2} A{2,3}; A{1,3} A{2,3} A{3,3}];
clear A
for subit1 = 1:3
if iter==1,
nTwarp = (Alpha+lmR*lam + 10*Cwarp)\((Alpha+lmR*lam)*Twarp(:) - Beta);
else
nTwarp = (Alpha+lmR*lam + Cwarp)\((Alpha+lmR*lam)*Twarp(:) - Beta);
end
nTwarp = reshape(nTwarp,[d2 3]);
nllr = -0.5*nTwarp(:)'*Cwarp*nTwarp(:);
nll = nllr+llrb;
for z=1:length(z0)
if ~buf(z).nm, continue; end
[x1,y1,z1] = defs(nTwarp,z,B1warp,B2warp,B3warp,x0,y0,z0,M,buf(z).msk);
sq = zeros(buf(z).nm,1) + tiny;
b = zeros(buf(z).nm,Kb);
s = zeros(buf(z).nm,1)+tiny;
for k1=1:Kb
b(:,k1) = spm_sample_priors(b0{k1},x1,y1,z1,k1==Kb);
s = s + mg1(k1)*b(:,k1);
end
for k1=1:Kb
sq = sq + double(buf(z).dat(:,k1)).*b(:,k1)./s;
end
clear b
nll = nll + sum(log(sq));
clear sq x1 y1 z1
end
if nll<ll
% Worse solution, so use old solution and increase regularisation
lam = lam*10;
else
% Accept new solution
ll = nll;
llr = nllr;
Twarp = nTwarp;
lam = lam*0.5;
break
end
end
spm_plot_convergence('Set',ll);
if (ll-oll)<tol1*nm, break; end
end
if ~((ll-ooll)>tol1*nm)
finalit = 1;
break; % This can be commented out.
end
end
spm_plot_convergence('Clear');
results = opts;
results.image = V;
results.tpm = B;
results.Affine = Affine;
results.Twarp = Twarp;
results.Tbias = Tbias;
results.mg = mg;
results.mn = mn;
results.vr = vr;
results.thresh = 0; %thresh;
results.ll = ll;
return
%=======================================================================
%=======================================================================
function t = transf(B1,B2,B3,T)
if ~isempty(T),
d2 = [size(T) 1];
t1 = reshape(reshape(T, d2(1)*d2(2),d2(3))*B3', d2(1), d2(2));
t = B1*t1*B2';
else
t = zeros(size(B1,1),size(B2,1));
end;
return;
%=======================================================================
%=======================================================================
function [x1,y1,z1] = defs(Twarp,z,B1,B2,B3,x0,y0,z0,M,msk)
x1a = x0 + transf(B1,B2,B3(z,:),Twarp(:,:,:,1));
y1a = y0 + transf(B1,B2,B3(z,:),Twarp(:,:,:,2));
z1a = z0(z) + transf(B1,B2,B3(z,:),Twarp(:,:,:,3));
if nargin>=10,
x1a = x1a(msk);
y1a = y1a(msk);
z1a = z1a(msk);
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;
%=======================================================================
|
github
|
philippboehmsturm/antx-master
|
spm_preproc_write.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_preproc_write.m
| 8,906 |
utf_8
|
6313e4e753e749911aac1143ba425149
|
function spm_preproc_write(p,opts)
% Write out VBM preprocessed data
% FORMAT spm_preproc_write(p,opts)
% p - results from spm_prep2sn
% opts - writing options. A struct containing these fields:
% biascor - write bias corrected image
% GM - flags for which images should be written
% WM - similar to GM
% CSF - similar to GM
%__________________________________________________________________________
% Copyright (C) 2005-2011 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_preproc_write.m 4199 2011-02-10 20:07:17Z guillaume $
if ischar(p), p = load(p); end
if nargin==1
opts = spm_get_defaults('preproc.output');
end
if numel(p)>0
b0 = spm_load_priors(p(1).VG);
end
for i=1:numel(p)
preproc_apply(p(i),opts,b0);
end
return;
%==========================================================================
%==========================================================================
function preproc_apply(p,opts,b0)
%sopts = [opts.GM ; opts.WM ; opts.CSF];
nclasses = size(fieldnames(opts),1) - 2 ;
switch nclasses
case 3
sopts = [opts.GM ; opts.WM ; opts.CSF];
case 4
sopts = [opts.GM ; opts.WM ; opts.CSF ; opts.EXTRA1];
case 5
sopts = [opts.GM ; opts.WM ; opts.CSF ; opts.EXTRA1 ; opts.EXTRA2];
otherwise
error('Unsupported number of classes!')
end
[pth,nam,ext]=fileparts(p.VF.fname);
T = p.flags.Twarp;
bsol = p.flags.Tbias;
d2 = [size(T) 1];
d = p.VF.dim(1:3);
[x1,x2,o] = ndgrid(1:d(1),1:d(2),1);
x3 = 1:d(3);
d3 = [size(bsol) 1];
B1 = spm_dctmtx(d(1),d2(1));
B2 = spm_dctmtx(d(2),d2(2));
B3 = spm_dctmtx(d(3),d2(3));
bB3 = spm_dctmtx(d(3),d3(3),x3);
bB2 = spm_dctmtx(d(2),d3(2),x2(1,:)');
bB1 = spm_dctmtx(d(1),d3(1),x1(:,1));
mg = p.flags.mg;
mn = p.flags.mn;
vr = p.flags.vr;
K = length(p.flags.mg);
Kb = length(p.flags.ngaus);
for k1=1:size(sopts,1),
%dat{k1} = zeros(d(1:3),'uint8');
dat{k1} = uint8(0);
dat{k1}(d(1),d(2),d(3)) = 0;
if sopts(k1,3),
Vt = struct('fname', fullfile(pth,['c', num2str(k1), nam, ext]),...
'dim', p.VF.dim,...
'dt', [spm_type('uint8') spm_platform('bigend')],...
'pinfo', [1/255 0 0]',...
'mat', p.VF.mat,...
'n', [1 1],...
'descrip', ['Tissue class ' num2str(k1)]);
Vt = spm_create_vol(Vt);
VO(k1) = Vt;
end;
end;
if opts.biascor,
VB = struct('fname', fullfile(pth,['m', nam, ext]),...
'dim', p.VF.dim(1:3),...
'dt', [spm_type('float32') spm_platform('bigend')],...
'pinfo', [1 0 0]',...
'mat', p.VF.mat,...
'n', [1 1],...
'descrip', 'Bias Corrected');
VB = spm_create_vol(VB);
end;
lkp = []; for k=1:Kb, lkp = [lkp ones(1,p.flags.ngaus(k))*k]; end;
spm_progress_bar('init',length(x3),['Working on ' nam],'Planes completed');
M = p.VG(1).mat\p.flags.Affine*p.VF.mat;
for z=1:length(x3),
% Bias corrected image
f = spm_sample_vol(p.VF,x1,x2,o*x3(z),0);
cr = exp(transf(bB1,bB2,bB3(z,:),bsol)).*f;
if opts.biascor,
% Write a plane of bias corrected data
VB = spm_write_plane(VB,cr,z);
end;
if any(sopts(:)),
msk = (f==0) | ~isfinite(f);
[t1,t2,t3] = defs(T,z,B1,B2,B3,x1,x2,x3,M);
q = zeros([d(1:2) Kb]);
bt = zeros([d(1:2) Kb]);
for k1=1:Kb,
bt(:,:,k1) = spm_sample_priors(b0{k1},t1,t2,t3,k1==Kb);
end;
b = zeros([d(1:2) K]);
for k=1:K,
b(:,:,k) = bt(:,:,lkp(k))*mg(k);
end;
s = sum(b,3);
for k=1:K,
p1 = exp((cr-mn(k)).^2/(-2*vr(k)))/sqrt(2*pi*vr(k)+eps);
q(:,:,lkp(k)) = q(:,:,lkp(k)) + p1.*b(:,:,k)./s;
end;
sq = sum(q,3)+eps;
sw = warning('off','MATLAB:divideByZero');
for k1=1:size(sopts,1),
tmp = q(:,:,k1);
tmp(msk) = 0;
tmp = tmp./sq;
dat{k1}(:,:,z) = uint8(round(255 * tmp));
end;
warning(sw);
end;
spm_progress_bar('set',z);
end;
spm_progress_bar('clear');
if opts.cleanup > 0,
[dat{1},dat{2},dat{3}] = clean_gwc(dat{1},dat{2},dat{3}, opts.cleanup);
end;
if any(sopts(:,3)),
for z=1:length(x3),
for k1=1:size(sopts,1),
if sopts(k1,3),
tmp = double(dat{k1}(:,:,z))/255;
spm_write_plane(VO(k1),tmp,z);
end;
end;
end;
end;
for k1=1:size(sopts,1),
if any(sopts(k1,1:2)),
so = struct('wrap',[0 0 0],'interp',1,'vox',[NaN NaN NaN],...
'bb',ones(2,3)*NaN,'preserve',0);
ovx = abs(det(p.VG(1).mat(1:3,1:3)))^(1/3);
fwhm = max(ovx./sqrt(sum(p.VF.mat(1:3,1:3).^2))-1,0.1);
dat{k1} = decimate(dat{k1},fwhm);
fn = fullfile(pth,['c', num2str(k1), nam, ext]);
dim = [size(dat{k1}) 1];
VT = struct('fname',fn,'dim',dim(1:3),...
'dt', [spm_type('uint8') spm_platform('bigend')],...
'pinfo',[1/255 0]','mat',p.VF.mat,'dat',dat{k1});
if sopts(k1,2),
spm_write_sn(VT,p,so);
end;
so.preserve = 1;
if sopts(k1,1),
VN = spm_write_sn(VT,p,so);
VN.fname = fullfile(pth,['mwc', num2str(k1), nam, ext]);
spm_write_vol(VN,VN.dat);
end;
end;
end;
return;
%==========================================================================
%==========================================================================
function [x1,y1,z1] = defs(sol,z,B1,B2,B3,x0,y0,z0,M)
x1a = x0 + transf(B1,B2,B3(z,:),sol(:,:,:,1));
y1a = y0 + transf(B1,B2,B3(z,:),sol(:,:,:,2));
z1a = z0(z) + transf(B1,B2,B3(z,:),sol(:,:,:,3));
x1 = M(1,1)*x1a + M(1,2)*y1a + M(1,3)*z1a + M(1,4);
y1 = M(2,1)*x1a + M(2,2)*y1a + M(2,3)*z1a + M(2,4);
z1 = M(3,1)*x1a + M(3,2)*y1a + M(3,3)*z1a + M(3,4);
return;
%==========================================================================
%==========================================================================
function t = transf(B1,B2,B3,T)
if ~isempty(T)
d2 = [size(T) 1];
t1 = reshape(reshape(T, d2(1)*d2(2),d2(3))*B3', d2(1), d2(2));
t = B1*t1*B2';
else
t = zeros(size(B1,1),size(B2,1),size(B3,1));
end;
return;
%==========================================================================
%==========================================================================
function dat = decimate(dat,fwhm)
% Convolve the volume in memory (fwhm in voxels).
lim = ceil(2*fwhm);
x = -lim(1):lim(1); x = spm_smoothkern(fwhm(1),x); x = x/sum(x);
y = -lim(2):lim(2); y = spm_smoothkern(fwhm(2),y); y = y/sum(y);
z = -lim(3):lim(3); z = spm_smoothkern(fwhm(3),z); z = z/sum(z);
i = (length(x) - 1)/2;
j = (length(y) - 1)/2;
k = (length(z) - 1)/2;
spm_conv_vol(dat,dat,x,y,z,-[i j k]);
return;
%==========================================================================
%==========================================================================
function [g,w,c] = clean_gwc(g,w,c, level)
if nargin<4, level = 1; end;
b = w;
b(1) = w(1);
% Build a 3x3x3 seperable smoothing kernel
%--------------------------------------------------------------------------
kx=[0.75 1 0.75];
ky=[0.75 1 0.75];
kz=[0.75 1 0.75];
sm=sum(kron(kron(kz,ky),kx))^(1/3);
kx=kx/sm; ky=ky/sm; kz=kz/sm;
th1 = 0.15;
if level==2, th1 = 0.2; end;
% Erosions and conditional dilations
%--------------------------------------------------------------------------
niter = 32;
spm_progress_bar('Init',niter,'Extracting Brain','Iterations completed');
for j=1:niter,
if j>2, th=th1; else th=0.6; end; % Dilate after two its of erosion.
for i=1:size(b,3),
gp = double(g(:,:,i));
wp = double(w(:,:,i));
bp = double(b(:,:,i))/255;
bp = (bp>th).*(wp+gp);
b(:,:,i) = uint8(round(bp));
end;
spm_conv_vol(b,b,kx,ky,kz,-[1 1 1]);
spm_progress_bar('Set',j);
end;
th = 0.05;
for i=1:size(b,3),
gp = double(g(:,:,i))/255;
wp = double(w(:,:,i))/255;
cp = double(c(:,:,i))/255;
bp = double(b(:,:,i))/255;
bp = ((bp>th).*(wp+gp))>th;
g(:,:,i) = uint8(round(255*gp.*bp./(gp+wp+cp+eps)));
w(:,:,i) = uint8(round(255*wp.*bp./(gp+wp+cp+eps)));
c(:,:,i) = uint8(round(255*(cp.*bp./(gp+wp+cp+eps)+cp.*(1-bp))));
end;
spm_progress_bar('Clear');
return;
%==========================================================================
|
github
|
philippboehmsturm/antx-master
|
spm_robust_glm.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_robust_glm.m
| 3,455 |
utf_8
|
bcb212d68b21aa060a764bdf025894e1
|
function [B, W] = spm_robust_glm(Y, X, dim, ks)
% Apply robust GLM
% FORMAT [B, W] = spm_robust_glm(Y, X, dim, ks)
% Y - data matrix
% X - design matrix
% dim - the dimension along which the function will work
% ks - offset of the weighting function (default: 3)
%
% OUTPUT:
% B - parameter estimates
% W - estimated weights
%
% Implementation of:
% Wager TD, Keller MC, Lacey SC, Jonides J.
% Increased sensitivity in neuroimaging analyses using robust regression.
% Neuroimage. 2005 May 15;26(1):99-113
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% James Kilner, Vladimir Litvak
% $Id: spm_robust_glm.m 4407 2011-07-26 12:13:00Z vladimir $
if nargin < 3 || isempty(ks)
ks = 3;
end
if nargin < 2 || isempty(dim)
dim = 1;
end
%-Remember the original data size and size of the mean
%--------------------------------------------------------------------------
origsize = size(Y);
borigsize = origsize;
borigsize(dim) = size(X, 2);
%-Convert the data to repetitions x points matrix
%--------------------------------------------------------------------------
if dim > 1
Y = shiftdim(Y, dim-1);
end
if length(origsize) > 2
Y = reshape(Y, size(Y, 1), []);
end
%-Check the design matrix and compute leverages
%--------------------------------------------------------------------------
if size(X, 1) ~= size(Y, 1)
error('The number of rows in the design matrix should match dimension of interest.');
end
H = diag(X*inv(X'*X)*X');
H = repmat(H(:), 1, size(Y, 2));
%-Rescale the data
%--------------------------------------------------------------------------
[Y, scalefactor] = spm_cond_units(Y);
%-Actual robust GLM
%--------------------------------------------------------------------------
ores=1;
nres=10;
n=0;
YY = Y;
YY(isnan(YY)) = 0;
while max(abs(ores-nres))>sqrt(1E-8)
ores=nres;
n=n+1;
if n == 1
W = ones(size(Y));
W(isnan(Y)) = 0;
end
B = zeros(size(X, 2), size(Y, 2));
for i = 1:size(Y, 2);
B(:, i) = inv(X'*diag(W(:, i))*X)*X'*diag(W(:, i))*YY(:, i);
end
if n > 200
warning('Robust GLM could not converge. Maximal number of iterations exceeded.');
break;
end
res = Y-X*B;
mad = nanmedian(abs(res-repmat(nanmedian(res), size(res, 1), 1)));
res = res./repmat(mad, size(res, 1), 1);
res = res.*H;
res = abs(res)-ks;
res(res<0)=0;
nres= (sum(res(~isnan(res)).^2));
W = (abs(res)<1) .* ((1 - res.^2).^2);
W(isnan(Y)) = 0;
W(Y == 0) = 0; %Assuming X is a real measurement
end
disp(['Robust GLM finished after ' num2str(n) ' iterations.']);
%-Restore the betas and weights to the original data dimensions
%--------------------------------------------------------------------------
B = B./scalefactor;
if length(origsize) > 2
B = reshape(B, circshift(borigsize, [1 -(dim-1)]));
W = reshape(W, circshift(origsize, [1 -(dim-1)]));
end
if dim > 1
B = shiftdim(B, length(origsize)-dim+1);
W = shiftdim(W, length(origsize)-dim+1);
end
%-Helper function
%--------------------------------------------------------------------------
function Y = nanmedian(X)
if ~any(any(isnan(X)))
Y = median(X);
else
Y = zeros(1, size(X,2));
for i = 1:size(X, 2)
Y(i) = median(X(~isnan(X(:, i)), i));
end
end
|
github
|
philippboehmsturm/antx-master
|
spm_inv_spd.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_inv_spd.m
| 2,156 |
utf_8
|
cd4bba226b2f3ecf23302491c65f9bfe
|
function X = spm_inv_spd(A, TOL)
% inverse for symmetric positive (semi)definite matrices
% FORMAT X = spm_inv_spd(A,TOL)
%
% A - symmetric positive definite matrix (e.g. covariance or precision)
% X - inverse (should remain symmetric positive definite)
%
% TOL - tolerance: default = exp(-32)
%__________________________________________________________________________
% Copyright (C) 2011 Wellcome Trust Centre for Neuroimaging
% Ged Ridgway
% $Id: spm_inv_spd.m 4360 2011-06-14 16:46:37Z ged $
% if ~all(isfinite(A(:))), error('Matrix has non-finite elements!'); end
if nargin < 2
TOL = exp(-32);
end
[i j] = find(A);
if isempty(i)
% Special cases: empty or all-zero matrix, return identity/TOL
%----------------------------------------------------------------------
X = eye(length(A)) / TOL;
elseif all(i == j)
% diagonal matrix
%----------------------------------------------------------------------
d = diag(A);
d = invtol(d, TOL);
if issparse(A)
n = length(A);
X = sparse(1:n, 1:n, d);
else
X = diag(d);
end
elseif norm(A - A', 1) < TOL
% symmetric, try LDL factorisation (but with L->X to save memory)
%----------------------------------------------------------------------
[X D P] = ldl(full(A)); % P'*A*P = L*D*L', A = P*L*D*L'*P'
[i j d] = find(D);
% non-diagonal values indicate not positive semi-definite
if all(i == j)
d = invtol(d, TOL);
% inv(A) = P*inv(L')*inv(D)*inv(L)*P' = (L\P')'*inv(D)*(L\P')
% triangular system should be quick to solve and stay approx tri.
X = X\P';
X = X'*diag(d)*X;
if issparse(A), X = sparse(X); end
else
error('Matrix is not positive semi-definite according to ldl')
end
else
error('Matrix is not symmetric to given tolerance');
end
% if ~all(isfinite(X(:))), error('Inverse has non-finite elements!'); end
function d = invtol(d, TOL)
% compute reciprocal of values, clamped to lie between TOL and 1/TOL
if any(d < -TOL)
error('Matrix is not positive semi-definite at given tolerance')
end
d = max(d, TOL);
d = 1./d;
d = max(d, TOL);
|
github
|
philippboehmsturm/antx-master
|
spm.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm.m
| 48,527 |
utf_8
|
2bc361410222c891200e28d5b187502d
|
function varargout=spm(varargin)
% SPM: Statistical Parametric Mapping (startup function)
%_______________________________________________________________________
% ___ ____ __ __
% / __)( _ \( \/ )
% \__ \ )___/ ) ( Statistical Parametric Mapping
% (___/(__) (_/\/\_) SPM - http://www.fil.ion.ucl.ac.uk/spm/
%_______________________________________________________________________
%
% SPM (Statistical Parametric Mapping) is a package for the analysis
% functional brain mapping experiments. It is the in-house package of
% the Wellcome Trust Centre for Neuroimaging, and is available to the
% scientific community as copyright freeware under the terms of the
% GNU General Public Licence.
%
% Theoretical, computational and other details of the package are
% available in SPM's "Help" facility. This can be launched from the
% main SPM Menu window using the "Help" button, or directly from the
% command line using the command `spm_help`.
%
% Details of this release are available via the "About SPM" help topic
% (file spm.man), accessible from the SPM splash screen. (Or type
% `spm_help spm.man` in the MATLAB command window)
%
% This spm function initialises the default parameters, and displays a
% splash screen with buttons leading to the PET, fMRI and M/EEG
% modalities. Alternatively, `spm('pet')`, `spm('fmri')`, `spm('eeg')`
% (equivalently `spm pet`, `spm fmri` and `spm eeg`) lead directly to
% the respective modality interfaces.
%
% Once the modality is chosen, (and it can be toggled mid-session) the
% SPM user interface is displayed. This provides a constant visual
% environment in which data analysis is implemented. The layout has
% been designed to be simple and at the same time show all the
% facilities that are available. The interface consists of three
% windows: A menu window with pushbuttons for the SPM routines (each
% button has a 'CallBack' string which launches the appropriate
% function/script); A blank panel used for interaction with the user;
% And a graphics figure with various editing and print facilities (see
% spm_figure.m). (These windows are 'Tag'ged 'Menu', 'Interactive', and
% 'Graphics' respectively, and should be referred to by their tags
% rather than their figure numbers.)
%
% Further interaction with the user is (mainly) via questioning in the
% 'Interactive' window (managed by spm_input), and file selection
% (managed by spm_select). See the help on spm_input.m and spm_select.m for
% details on using these functions.
%
% If a "message of the day" file named spm_motd.man exists in the SPM
% directory (alongside spm.m) then it is displayed in the Graphics
% window on startup.
%
% Arguments to this routine (spm.m) lead to various setup facilities,
% mainly of use to SPM power users and programmers. See programmers
% FORMAT & help in the main body of spm.m
%
%_______________________________________________________________________
% SPM is developed by members and collaborators of the
% Wellcome Trust Centre for Neuroimaging
%-SVN ID and authorship of this program...
%-----------------------------------------------------------------------
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Andrew Holmes
% $Id: spm.m 647 2011-07-19 10:20:21Z vglauche $
%=======================================================================
% - 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. Recall )
%( MATLAB's command-function duality: `spm Welcome` is equivalent to )
%( `spm('Welcome')`. )
%
% FORMAT spm
% Defaults to spm('Welcome')
%
% FORMAT spm('Welcome')
% Clears command window, deletes all figures, prints welcome banner and
% splash screen, sets window defaults.
%
% FORMAT spm('AsciiWelcome')
% Prints ASCII welcome banner in MATLAB command window.
%
% FORMAT spm('PET') spm('FMRI') spm('EEG')
% Closes all windows and draws new Menu, Interactive, and Graphics
% windows for an SPM session. The buttons in the Menu window launch the
% main analysis routines.
%
% FORMAT spm('ChMod',Modality)
% Changes modality of SPM: Currently SPM supports PET & MRI modalities,
% each of which have a slightly different Menu window and different
% defaults. This function switches to the specified modality, setting
% defaults and displaying the relevant buttons.
%
% FORMAT spm('defaults',Modality)
% Sets default global variables for the specified modality.
%
% FORMAT [Modality,ModNum]=spm('CheckModality',Modality)
% Checks the specified modality against those supported, returns
% upper(Modality) and the Modality number, it's position in the list of
% supported Modalities.
%
% FORMAT Fmenu = spm('CreateMenuWin',Vis)
% Creates SPM menu window, 'Tag'ged 'Menu'
% F - handle of figure created
% Vis - Visibility, 'on' or 'off'
%
% Finter = FORMAT spm('CreateIntWin',Vis)
% Creates an SPM Interactive window, 'Tag'ged 'Interactive'
% F - handle of figure created
% Vis - Visibility, 'on' or 'off'
%
% FORMAT [Finter,Fgraph,CmdLine] = spm('FnUIsetup',Iname,bGX,CmdLine)
% Robust UIsetup procedure for functions:
% Returns handles of 'Interactive' and 'Graphics' figures.
% Creates 'Interactive' figure if ~CmdLine, creates 'Graphics' figure if bGX.
% Iname - Name for 'Interactive' window
% bGX - Need a Graphics window? [default 1]
% CmdLine - CommandLine usage? [default spm('CmdLine')]
% Finter - handle of 'Interactive' figure
% Fgraph - handle of 'Graphics' figure
% CmdLine - CommandLine usage?
%
% FORMAT WS=spm('WinScale')
% Returns ratios of current display dimensions to that of a 1152 x 900
% Sun display. WS=[Xratio,Yratio,Xratio,Yratio]. Used for scaling other
% GUI elements.
% (Function duplicated in spm_figure.m, repeated to reduce inter-dependencies.)
%
% FORMAT [FS,sf] = spm('FontSize',FS)
% FORMAT [FS,sf] = spm('FontSizes',FS)
% Returns fontsizes FS scaled for the current display.
% FORMAT sf = spm('FontScale')
% Returns font scaling factor
% FS - (vector of) Font sizes to scale [default [1:36]]
% sf - font scaling factor (FS(out) = floor(FS(in)*sf)
%
% Rect = spm('WinSize',Win,raw)
% Returns sizes and positions for SPM windows.
% Win - 'Menu', 'Interactive', 'Graphics', or '0'
% - Window whose position is required. Only first character is
% examined. '0' returns size of root workspace.
% raw - If specified, then positions are for a 1152 x 900 Sun display.
% Otherwise the positions are scaled for the current display.
%
% FORMAT [c,cName] = spm('Colour')
% Returns the RGB triple and a description for the current en-vogue SPM
% colour, the background colour for the Menu and Help windows.
%
% FORMAT F = spm('FigName',Iname,F,CmdLine)
% Set name of figure F to "SPMver (User): Iname" if ~CmdLine
% Robust to absence of figure.
% Iname - Name for figure
% F (input) - Handle (or 'Tag') of figure to name [default 'Interactive']
% CmdLine - CommandLine usage? [default spm('CmdLine')]
% F (output) - Handle of figure named
%
% FORMAT Fs = spm('Show')
% Opens all SPM figure windows (with HandleVisibility) using `figure`.
% Maintains current figure.
% Fs - vector containing all HandleVisible figures (i.e. get(0,'Children'))
%
% FORMAT spm('Clear',Finter, Fgraph)
% Clears and resets SPM-GUI, clears and timestamps MATLAB command window.
% Finter - handle or 'Tag' of 'Interactive' figure [default 'Interactive']
% Fgraph - handle or 'Tag' of 'Graphics' figure [default 'Graphics']
%
% FORMAT SPMid = spm('FnBanner', Fn,FnV)
% Prints a function start banner, for version FnV of function Fn, & datestamps
% FORMAT SPMid = spm('SFnBanner',Fn,FnV)
% Prints a sub-function start banner
% FORMAT SPMid = spm('SSFnBanner',Fn,FnV)
% Prints a sub-sub-function start banner
% Fn - Function name (string)
% FnV - Function version (string)
% SPMid - ID string: [SPMver: Fn (FnV)]
%
% FORMAT SPMdir = spm('Dir',Mfile)
% Returns the directory containing the version of spm in use,
% identified as the first in MATLABPATH containing the Mfile spm (this
% file) (or Mfile if specified).
%
% FORMAT [v,r] = spm('Ver',Mfile,ReDo)
% Returns the current version (v) and release (r) of file Mfile. This
% corresponds to the Last changed Revision number extracted from the
% Subversion Id tag.
% If Mfile is absent or empty then it returns the current SPM version (v)
% and release (r), extracted from the file Contents.m in the SPM directory
% (these information are cached in a persistent variable to enable repeat
% use without recomputation).
% If Redo [default false] is true, then the cached current SPM information
% are not used but recomputed (and recached).
%
% FORMAT v = spm('MLver')
% Returns MATLAB version, truncated to major & minor revision numbers
%
% FORMAT xTB = spm('TBs')
% Identifies installed SPM toolboxes: SPM toolboxes are defined as the
% contents of sub-directories of fullfile(spm('Dir'),'toolbox') - the
% SPM toolbox installation directory. For SPM to pick a toolbox up,
% there must be a single mfile in the directory whose name ends with
% the toolbox directory name. (I.e. A toolbox called "test" would be in
% the "test" subdirectory of spm('Dir'), with a single file named
% *test.m.) This M-file is regarded as the launch file for the
% toolbox.
% xTB - structure array containing toolbox definitions
% xTB.name - name of toolbox (taken as toolbox directory name)
% xTB.prog - launch program for toolbox
% xTB.dir - toolbox directory
%
% FORMAT spm('TBlaunch',xTB,i)
% Launch a toolbox, prepending TBdir to path if necessary
% xTB - toolbox definition structure (i.e. from spm('TBs')
% xTB.name - name of toolbox
% xTB.prog - name of program to launch toolbox
% xTB.dir - toolbox directory (prepended to path if not on path)
%
% FORMAT [v1,v2,...] = spm('GetGlobal',name1,name2,...)
% Returns values of global variables (without declaring them global)
% name1, name2,... - name strings of desired globals
% a1, a2,... - corresponding values of global variables with given names
% ([] is returned as value if global variable doesn't exist)
%
% FORMAT CmdLine = spm('CmdLine',CmdLine)
% Command line SPM usage?
% CmdLine (input) - CmdLine preference
% [defaults (missing or empty) to global defaults.cmdline,]
% [if it exists, or 0 (GUI) otherwise. ]
% CmdLine (output) - true if global CmdLine if true,
% or if on a terminal with no support for graphics windows.
%
% FORMAT spm('PopUpCB',h)
% Callback handler for PopUp UI menus with multiple callbacks as cellstr UserData
%
% FORMAT str = spm('GetUser',fmt)
% Returns current users login name, extracted from the hosting environment
% fmt - format string: If USER is defined then sprintf(fmt,USER) is returned
%
% FORMAT spm('Beep')
% Plays the keyboard beep!
%
% FORMAT spm('time')
% Returns the current time and date as hh:mm dd/mm/yyyy
%
% FORMAT spm('Pointer',Pointer)
% Changes pointer on all SPM (HandleVisible) windows to type Pointer
% Pointer defaults to 'Arrow'. Robust to absence of windows
%
% FORMAT h = spm('alert',Message,Title,CmdLine,wait)
% FORMAT h = spm('alert"',Message,Title,CmdLine,wait)
% FORMAT h = spm('alert*',Message,Title,CmdLine,wait)
% FORMAT h = spm('alert!',Message,Title,CmdLine,wait)
% Displays an alert, either in a GUI msgbox, or as text in the command window.
% ( 'alert"' uses the 'help' msgbox icon, 'alert*' the )
% ( 'error' icon, 'alert!' the 'warn' icon )
% Message - string (or cellstr) containing message to print
% Title - title string for alert
% CmdLine - CmdLine preference [default spm('CmdLine')]
% - If CmdLine is complex, then a CmdLine alert is always used,
% possibly in addition to a msgbox (the latter according
% to spm('CmdLine').)
% wait - if true, waits until user dismisses GUI / confirms text alert
% [default 0] (if doing both GUI & text, waits on GUI alert)
% h - handle of msgbox created, empty if CmdLine used
%
% FORMAT spm('Delete',file)
% Delete file(s), using spm_select and confirmation dialogs.
%
% FORMAT spm('Run',mscript)
% Run M-script(s), using spm_select.
%
% FORMAT spm('Clean')
% Clear all variables, globals, functions, MEX links and class definitions.
%
% FORMAT spm('Help',varargin)
% Merely a gateway to spm_help(varargin) - so you can type "spm help"
%
% FORMAT spm('Quit')
% Quit SPM, delete all windows and clear the command window.
%
%_______________________________________________________________________
%-Parameters
%-----------------------------------------------------------------------
Modalities = {'PET','FMRI','EEG'};
%-Format arguments
%-----------------------------------------------------------------------
if nargin == 0, Action = 'Welcome'; else Action = varargin{1}; end
%=======================================================================
switch lower(Action), case 'welcome' %-Welcome splash screen
%=======================================================================
% spm('Welcome')
spm_check_installation('basic');
defaults = spm('GetGlobal','defaults');
if isfield(defaults,'modality')
spm(defaults.modality);
return
end
%-Open startup window, set window defaults
%-----------------------------------------------------------------------
Fwelcome = openfig(fullfile(spm('Dir'),'spm_Welcome.fig'),'new','invisible');
set(Fwelcome,'name',sprintf('%s%s',spm('ver'),spm('GetUser',' (%s)')));
set(get(findobj(Fwelcome,'Type','axes'),'children'),'FontName',spm_platform('Font','Times'));
set(findobj(Fwelcome,'Tag','SPM_VER'),'String',spm('Ver'));
RectW = spm('WinSize','W',1); Rect0 = spm('WinSize','0',1);
set(Fwelcome,'Units','pixels', 'Position',...
[Rect0(1)+(Rect0(3)-RectW(3))/2, Rect0(2)+(Rect0(4)-RectW(4))/2, RectW(3), RectW(4)]);
set(Fwelcome,'Visible','on');
%=======================================================================
case 'asciiwelcome' %-ASCII SPM banner welcome
%=======================================================================
% spm('AsciiWelcome')
disp( ' ___ ____ __ __ ');
disp( '/ __)( _ \( \/ ) ');
disp( '\__ \ )___/ ) ( Statistical Parametric Mapping ');
disp(['(___/(__) (_/\/\_) ',spm('Ver'),' - http://www.fil.ion.ucl.ac.uk/spm/']);
fprintf('\n');
%=======================================================================
case lower(Modalities) %-Initialise SPM in PET, fMRI, EEG modality
%=======================================================================
% spm(Modality)
spm_check_installation('basic');
try, feature('JavaFigures',0); end
%-Initialisation and workspace canonicalisation
%-----------------------------------------------------------------------
% local_clc;
% spm('AsciiWelcome'); fprintf('\n\nInitialising SPM');
Modality = upper(Action); fprintf('.');
% spm_figure('close',allchild(0)); fprintf('.');
%-Load startup global defaults
%-----------------------------------------------------------------------
spm_defaults; fprintf('.');
%-Setup for batch system
%-----------------------------------------------------------------------
spm_jobman('initcfg');
spm_select('prevdirs',[spm('Dir') filesep]);
%-Draw SPM windows
%-----------------------------------------------------------------------
if ~spm('CmdLine')
Fmenu = spm('CreateMenuWin','off'); fprintf('.');
Finter = spm('CreateIntWin','off'); fprintf('.');
else
Fmenu = [];
Finter = [];
end
Fgraph = spm_figure('Create','Graphics','Graphics','off'); fprintf('.');
spm_figure('WaterMark',Finter,spm('Ver'),'',45); fprintf('.');
Fmotd = fullfile(spm('Dir'),'spm_motd.man');
if exist(Fmotd,'file'), spm_help('!Disp',Fmotd,'',Fgraph,spm('Ver')); end
fprintf('.');
%-Setup for current modality
%-----------------------------------------------------------------------
spm('ChMod',Modality); fprintf('.');
%-Reveal windows
%-----------------------------------------------------------------------
set([Fmenu,Finter,Fgraph],'Visible','on'); fprintf('done\n\n');
%-Print present working directory
%-----------------------------------------------------------------------
fprintf('SPM present working directory:\n\t%s\n',pwd)
%=======================================================================
case 'chmod' %-Change SPM modality PET<->fMRI<->EEG
%=======================================================================
% spm('ChMod',Modality)
%-----------------------------------------------------------------------
%-Sort out arguments
%-----------------------------------------------------------------------
if nargin<2, Modality = ''; else Modality = varargin{2}; end
[Modality,ModNum] = spm('CheckModality',Modality);
%-Sort out global defaults
%-----------------------------------------------------------------------
spm('defaults',Modality);
%-Sort out visability of appropriate controls on Menu window
%-----------------------------------------------------------------------
Fmenu = spm_figure('FindWin','Menu');
if ~isempty(Fmenu)
if strcmpi(Modality,'PET')
set(findobj(Fmenu, 'Tag', 'FMRI'), 'Visible', 'off');
set(findobj(Fmenu, 'Tag', 'EEG'), 'Visible', 'off');
set(findobj(Fmenu, 'Tag', 'PETFMRI'), 'Visible', 'on' );
set(findobj(Fmenu, 'Tag', 'PET'), 'Visible', 'on' );
elseif strcmpi(Modality,'FMRI')
set(findobj(Fmenu, 'Tag', 'EEG'), 'Visible', 'off');
set(findobj(Fmenu, 'Tag', 'PET'), 'Visible', 'off');
set(findobj(Fmenu, 'Tag', 'PETFMRI'), 'Visible', 'on' );
set(findobj(Fmenu, 'Tag', 'FMRI'), 'Visible', 'on' );
else
set(findobj(Fmenu, 'Tag', 'PETFMRI'), 'Visible', 'off');
set(findobj(Fmenu, 'Tag', 'PET'), 'Visible', 'off');
set(findobj(Fmenu, 'Tag', 'FMRI'), 'Visible', 'off');
set(findobj(Fmenu, 'Tag', 'EEG'), 'Visible', 'on' );
end
set(findobj(Fmenu,'Tag','Modality'),'Value',ModNum,'UserData',ModNum);
else
warning('SPM Menu window not found');
end
%=======================================================================
case 'defaults' %-Set SPM defaults (as global variable)
%=======================================================================
% spm('defaults',Modality)
%-----------------------------------------------------------------------
if nargin<2, Modality=''; else Modality=varargin{2}; end
Modality = spm('CheckModality',Modality);
%-Re-initialise, load defaults (from spm_defaults.m) and store modality
%-----------------------------------------------------------------------
clear global defaults
spm_get_defaults('modality',Modality);
%-Addpath modality-specific toolboxes
%-----------------------------------------------------------------------
if strcmpi(Modality,'EEG') && ~isdeployed
addpath(fullfile(spm('Dir'),'external','fieldtrip'));
ft_defaults;
addpath(fullfile(spm('Dir'),'external','bemcp'));
addpath(fullfile(spm('Dir'),'external','ctf'));
addpath(fullfile(spm('Dir'),'external','eeprobe'));
addpath(fullfile(spm('Dir'),'external','mne'));
addpath(fullfile(spm('Dir'),'external','yokogawa'));
addpath(fullfile(spm('Dir'),'toolbox', 'dcm_meeg'));
addpath(fullfile(spm('Dir'),'toolbox', 'spectral'));
addpath(fullfile(spm('Dir'),'toolbox', 'Neural_Models'));
addpath(fullfile(spm('Dir'),'toolbox', 'Beamforming'));
addpath(fullfile(spm('Dir'),'toolbox', 'MEEGtools'));
end
%-Turn output pagination off in Octave
%-----------------------------------------------------------------------
if strcmpi(spm_check_version,'octave')
try
more('off');
page_screen_output(false);
page_output_immediately(true);
end
end
%-Return defaults variable if asked
%-----------------------------------------------------------------------
if nargout, varargout = {spm_get_defaults}; end
%=======================================================================
case 'checkmodality' %-Check & canonicalise modality string
%=======================================================================
% [Modality,ModNum] = spm('CheckModality',Modality)
%-----------------------------------------------------------------------
if nargin<2, Modality=''; else Modality=upper(varargin{2}); end
if isempty(Modality)
try
Modality = spm_get_defaults('modality');
end
end
if ischar(Modality)
ModNum = find(ismember(Modalities,Modality));
else
if ~any(Modality == 1:length(Modalities))
Modality = 'ERROR';
ModNum = [];
else
ModNum = Modality;
Modality = Modalities{ModNum};
end
end
if isempty(ModNum)
if isempty(Modality)
fprintf('Modality is not set: use spm(''defaults'',''MOD''); ');
fprintf('where MOD is one of PET, FMRI, EEG.\n');
end
error('Unknown Modality.');
end
varargout = {upper(Modality),ModNum};
%=======================================================================
case 'createmenuwin' %-Create SPM menu window
%=======================================================================
% Fmenu = spm('CreateMenuWin',Vis)
%-----------------------------------------------------------------------
if nargin<2, Vis='on'; else Vis=varargin{2}; end
%-Close any existing 'Menu' 'Tag'ged windows
%-----------------------------------------------------------------------
delete(spm_figure('FindWin','Menu'))
Fmenu = openfig(fullfile(spm('Dir'),'spm_Menu.fig'),'new','invisible');
set(Fmenu,'name',sprintf('%s%s: Menu',spm('ver'),spm('GetUser',' (%s)')));
S0 = spm('WinSize','0',1);
SM = spm('WinSize','M');
set(Fmenu,'Units','pixels', 'Position',[S0(1) S0(2) 0 0] + SM);
%-Set SPM colour
%-----------------------------------------------------------------------
set(findobj(Fmenu,'Tag', 'frame'),'backgroundColor',spm('colour'));
try
if ismac
b = findobj(Fmenu,'Style','pushbutton');
set(b,'backgroundColor',get(b(1),'backgroundColor')+0.002);
end
end
%-Set Utils
%-----------------------------------------------------------------------
set(findobj(Fmenu,'Tag', 'Utils'), 'String',{'Utils...',...
'CD',...
'PWD',...
'Run M-file',...
'Load MAT-file',...
'Save MAT-file',...
'Delete files',...
'Show SPM'});
set(findobj(Fmenu,'Tag', 'Utils'), 'UserData',{...
['spm(''FnBanner'',''CD'');' ...
'cd(spm_select(1,''dir'',''Select new working directory''));' ...
'spm(''alert"'',{''New working directory:'',['' '',pwd]},''CD'',1);'],...
['spm(''FnBanner'',''PWD'');' ...
'spm(''alert"'',{''Present working directory:'',['' '',pwd]},''PWD'',1);'],...
['spm(''FnBanner'',''Run M-file'');' ...
'spm(''Run'');'],...
['spm(''FnBanner'',''Load MAT-file'');' ...
'load(spm_select(1,''mat'',''Select MAT-file''));'],...
['spm(''FnBanner'',''Save MAT-file'');' ...
'save(spm_input(''Output filename'',1,''s''));'],...
['spm(''FnBanner'',''Delete files'');' ...
'spm(''Delete'');'],...
['spm(''FnBanner'',''Show SPM'');' ...
'spm(''Show'');']});
%-Set Toolboxes
%-----------------------------------------------------------------------
xTB = spm('tbs');
if ~isempty(xTB)
set(findobj(Fmenu,'Tag', 'Toolbox'),'String',{'Toolbox:' xTB.name });
set(findobj(Fmenu,'Tag', 'Toolbox'),'UserData',xTB);
else
set(findobj(Fmenu,'Tag', 'Toolbox'),'Visible','off')
end
set(Fmenu,'Visible',Vis);
varargout = {Fmenu};
%=======================================================================
case 'createintwin' %-Create SPM interactive window
%=======================================================================
% Finter = spm('CreateIntWin',Vis)
%-----------------------------------------------------------------------
if nargin<2, Vis='on'; else Vis=varargin{2}; end
%-Close any existing 'Interactive' 'Tag'ged windows
%-----------------------------------------------------------------------
delete(spm_figure('FindWin','Interactive'))
%-Create SPM Interactive window
%-----------------------------------------------------------------------
FS = spm('FontSizes');
PF = spm_platform('fonts');
S0 = spm('WinSize','0',1);
SI = spm('WinSize','I');
Finter = figure('IntegerHandle','off',...
'Tag','Interactive',...
'Name',spm('Ver'),...
'NumberTitle','off',...
'Units','pixels',...
'Position',[S0(1) S0(2) 0 0] + SI,...
'Resize','on',...
'Color',[1 1 1]*.8,...
'MenuBar','none',...
'DefaultTextFontName',PF.helvetica,...
'DefaultTextFontSize',FS(10),...
'DefaultAxesFontName',PF.helvetica,...
'DefaultUicontrolBackgroundColor',[1 1 1]*.7,...
'DefaultUicontrolFontName',PF.helvetica,...
'DefaultUicontrolFontSize',FS(10),...
'DefaultUicontrolInterruptible','on',...
'Renderer','painters',...
'Visible',Vis);
varargout = {Finter};
%=======================================================================
case 'fnuisetup' %-Robust UI setup for main SPM functions
%=======================================================================
% [Finter,Fgraph,CmdLine] = spm('FnUIsetup',Iname,bGX,CmdLine)
%-----------------------------------------------------------------------
if nargin<4, CmdLine=spm('CmdLine'); else CmdLine=varargin{4}; end
if nargin<3, bGX=1; else bGX=varargin{3}; end
if nargin<2, Iname=''; else Iname=varargin{2}; end
if CmdLine
Finter = spm_figure('FindWin','Interactive');
if ~isempty(Finter), spm_figure('Clear',Finter), end
%if ~isempty(Iname), fprintf('%s:\n',Iname), end
else
Finter = spm_figure('GetWin','Interactive');
spm_figure('Clear',Finter)
if ~isempty(Iname)
str = sprintf('%s (%s): %s',spm('ver'),spm('GetUser'),Iname);
else
str = '';
end
set(Finter,'Name',str)
end
if bGX
Fgraph = spm_figure('GetWin','Graphics');
spm_figure('Clear',Fgraph)
else
Fgraph = spm_figure('FindWin','Graphics');
end
varargout = {Finter,Fgraph,CmdLine};
%=======================================================================
case 'winscale' %-Window scale factors (to fit display)
%=======================================================================
% WS = spm('WinScale')
%-----------------------------------------------------------------------
S0 = spm('WinSize','0',1);
if all(ismember(S0(:),[0 1]))
varargout = {[1 1 1 1]};
return;
end
tmp = [S0(3)/1152 (S0(4)-50)/900];
varargout = {min(tmp)*[1 1 1 1]};
% Make sure that aspect ratio is about right - for funny shaped screens
% varargout = {[S0(3)/1152 (S0(4)-50)/900 S0(3)/1152 (S0(4)-50)/900]};
%=======================================================================
case {'fontsize','fontsizes','fontscale'} %-Font scaling
%=======================================================================
% [FS,sf] = spm('FontSize',FS)
% [FS,sf] = spm('FontSizes',FS)
% sf = spm('FontScale')
%-----------------------------------------------------------------------
if nargin<2, FS=1:36; else FS=varargin{2}; end
offset = 1;
%try, if ismac, offset = 1.4; end; end
sf = offset + 0.85*(min(spm('WinScale'))-1);
if strcmpi(Action,'fontscale')
varargout = {sf};
else
varargout = {ceil(FS*sf),sf};
end
%=======================================================================
case 'winsize' %-Standard SPM window locations and sizes
%=======================================================================
% Rect = spm('WinSize',Win,raw)
%-----------------------------------------------------------------------
if nargin<3, raw=0; else raw=1; end
if nargin<2, Win=''; else Win=varargin{2}; end
Rect = [[108 466 400 445];...
[108 045 400 395];...
[515 015 600 865];...
[326 310 500 280]];
if isempty(Win)
%-All windows
elseif upper(Win(1))=='M'
%-Menu window
Rect = Rect(1,:);
elseif upper(Win(1))=='I'
%-Interactive window
Rect = Rect(2,:);
elseif upper(Win(1))=='G'
%-Graphics window
Rect = Rect(3,:);
elseif upper(Win(1))=='W'
%-Welcome window
Rect = Rect(4,:);
elseif Win(1)=='0'
%-Root workspace
Rect = get(0, 'MonitorPosition');
if all(ismember(Rect(:),[0 1]))
warning('SPM:noDisplay','Unable to open display.');
end
if size(Rect,1) > 1 % Multiple Monitors
%-Use Monitor containing the Pointer
pl = get(0,'PointerLocation');
Rect(:,[3 4]) = Rect(:,[3 4]) + Rect(:,[1 2]);
w = find(pl(1)>=Rect(:,1) & pl(1)<=Rect(:,3) &...
pl(2)>=Rect(:,2) & pl(2)<=Rect(:,4));
if numel(w)~=1, w = 1; end
Rect = Rect(w,:);
%-Make sure that the format is [x y width height]
Rect(1,[3 4]) = Rect(1,[3 4]) - Rect(1,[1 2]) + 1;
end
else
error('Unknown Win type');
end
if ~raw
WS = repmat(spm('WinScale'),size(Rect,1),1);
Rect = Rect.*WS;
end
varargout = {Rect};
%=======================================================================
case 'colour' %-SPM interface colour
%=======================================================================
% spm('Colour')
%-----------------------------------------------------------------------
%-Pre-developmental livery
% varargout = {[1.0,0.2,0.3],'fightening red'};
%-Developmental livery
% varargout = {[0.7,1.0,0.7],'flourescent green'};
%-Alpha release livery
% varargout = {[0.9,0.9,0.5],'over-ripe banana'};
%-Beta release livery
% varargout = {[0.9 0.8 0.9],'blackcurrant purple'};
%-Distribution livery
varargout = {[0.8 0.8 1.0],'vile violet'};
try
varargout = {spm_get_defaults('ui.colour'),'bluish'};
end
%=======================================================================
case 'figname' %-Robust SPM figure naming
%=======================================================================
% F = spm('FigName',Iname,F,CmdLine)
%-----------------------------------------------------------------------
if nargin<4, CmdLine=spm('CmdLine'); else CmdLine=varargin{4}; end
if nargin<3, F='Interactive'; else F=varargin{3}; end
if nargin<2, Iname=''; else Iname=varargin{2}; end
%if ~isempty(Iname), fprintf('\t%s\n',Iname), end
if CmdLine, varargout={[]}; return, end
F = spm_figure('FindWin',F);
if ~isempty(F) && ~isempty(Iname)
set(F,'Name',sprintf('%s (%s): %s',spm('ver'),spm('GetUser'),Iname))
end
varargout={F};
%=======================================================================
case 'show' %-Bring visible MATLAB windows to the fore
%=======================================================================
% Fs = spm('Show')
%-----------------------------------------------------------------------
cF = get(0,'CurrentFigure');
Fs = get(0,'Children');
Fs = findobj(Fs,'flat','Visible','on');
for F=Fs(:)', figure(F), end
try, figure(cF), set(0,'CurrentFigure',cF); end
varargout={Fs};
%=======================================================================
case 'clear' %-Clear SPM GUI
%=======================================================================
% spm('Clear',Finter, Fgraph)
%-----------------------------------------------------------------------
if nargin<3, Fgraph='Graphics'; else Fgraph=varargin{3}; end
if nargin<2, Finter='Interactive'; else Finter=varargin{2}; end
spm_figure('Clear',Fgraph)
spm_figure('Clear',Finter)
spm('Pointer','Arrow')
spm_conman('Initialise','reset');
local_clc;
fprintf('\n');
%evalin('base','clear')
%=======================================================================
case {'fnbanner','sfnbanner','ssfnbanner'} %-Text banners for functions
%=======================================================================
% SPMid = spm('FnBanner', Fn,FnV)
% SPMid = spm('SFnBanner',Fn,FnV)
% SPMid = spm('SSFnBanner',Fn,FnV)
%-----------------------------------------------------------------------
time = spm('time');
str = spm('ver');
if nargin>=2, str = [str,': ',varargin{2}]; end
if nargin>=3
v = regexp(varargin{3},'\$Rev: (\d*) \$','tokens','once');
if ~isempty(v)
str = [str,' (v',v{1},')'];
else
str = [str,' (v',varargin{3},')'];
end
end
switch lower(Action)
case 'fnbanner'
tab = '';
wid = 72;
lch = '=';
case 'sfnbanner'
tab = sprintf('\t');
wid = 72-8;
lch = '-';
case 'ssfnbanner'
tab = sprintf('\t\t');
wid = 72-2*8;
lch = '-';
end
fprintf('\n%s%s',tab,str)
fprintf('%c',repmat(' ',1,wid-length([str,time])))
fprintf('%s\n%s',time,tab)
fprintf('%c',repmat(lch,1,wid)),fprintf('\n')
varargout = {str};
%=======================================================================
case 'dir' %-Identify specific (SPM) directory
%=======================================================================
% spm('Dir',Mfile)
%-----------------------------------------------------------------------
if nargin<2, Mfile='spm'; else Mfile=varargin{2}; end
SPMdir = which(Mfile);
if isempty(SPMdir) %-Not found or full pathname given
if exist(Mfile,'file')==2 %-Full pathname
SPMdir = Mfile;
else
error(['Can''t find ',Mfile,' on MATLABPATH']);
end
end
SPMdir = fileparts(SPMdir);
varargout = {SPMdir};
%=======================================================================
case 'ver' %-SPM version
%=======================================================================
% [SPMver, SPMrel] = spm('Ver',Mfile,ReDo)
%-----------------------------------------------------------------------
if nargin > 3, warning('This usage of "spm ver" is now deprecated.'); end
if nargin ~= 3, ReDo = false; else ReDo = logical(varargin{3}); end
if nargin == 1 || (nargin > 1 && isempty(varargin{2}))
Mfile = '';
else
Mfile = which(varargin{2});
if isempty(Mfile)
error('Can''t find %s on MATLABPATH.',varargin{2});
end
end
v = spm_version(ReDo);
if isempty(Mfile)
varargout = {v.Release v.Version};
else
unknown = struct('file',Mfile,'id','???','date','','author','');
if ~isdeployed
fp = fopen(Mfile,'rt');
if fp == -1, error('Can''t read %s.',Mfile); end
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','once');
if isempty(r), r = unknown; end
else
r = unknown;
end
varargout = {r(1).id v.Release};
end
%=======================================================================
case 'mlver' %-MATLAB major & point version number
%=======================================================================
% v = spm('MLver')
%-----------------------------------------------------------------------
v = version; tmp = find(v=='.');
if length(tmp)>1, varargout={v(1:tmp(2)-1)}; end
%=======================================================================
case 'tbs' %-Identify installed toolboxes
%=======================================================================
% xTB = spm('TBs')
%-----------------------------------------------------------------------
% Toolbox directory
%-----------------------------------------------------------------------
Tdir = fullfile(spm('Dir'),'toolbox');
%-List of potential installed toolboxes directories
%-----------------------------------------------------------------------
if exist(Tdir,'dir')
d = dir(Tdir);
d = {d([d.isdir]).name};
d = {d{cellfun('isempty',regexp(d,'^\.'))}};
else
d = {};
end
%-Look for a "main" M-file in each potential directory
%-----------------------------------------------------------------------
xTB = [];
for i = 1:length(d)
tdir = fullfile(Tdir,d{i});
fn = cellstr(spm_select('List',tdir,['^.*' d{i} '\.m$']));
if ~isempty(fn{1}),
xTB(end+1).name = strrep(d{i},'_','');
xTB(end).prog = spm_str_manip(fn{1},'r');
xTB(end).dir = tdir;
end
end
varargout{1} = xTB;
%=======================================================================
case 'tblaunch' %-Launch an SPM toolbox
%=======================================================================
% xTB = spm('TBlaunch',xTB,i)
%-----------------------------------------------------------------------
if nargin < 3, i = 1; else i = varargin{3}; end
if nargin < 2, xTB = spm('TBs'); else xTB = varargin{2}; end
if i > 0
%-Addpath (& report)
%-------------------------------------------------------------------
if isempty(strfind(path,xTB(i).dir))
if ~isdeployed, addpath(xTB(i).dir,'-begin'); end
spm('alert"',{'Toolbox directory prepended to MATLAB path:',...
xTB(i).dir},...
[xTB(i).name,' toolbox'],1);
end
%-Launch
%-------------------------------------------------------------------
evalin('base',xTB(i).prog);
end
%=======================================================================
case 'getglobal' %-Get global variable cleanly
%=======================================================================
% varargout = spm('GetGlobal',varargin)
%-----------------------------------------------------------------------
wg = who('global');
for i=1:nargin-1
if any(strcmp(wg,varargin{i+1}))
eval(['global ',varargin{i+1},', tmp=',varargin{i+1},';'])
varargout{i} = tmp;
else
varargout{i} = [];
end
end
%=======================================================================
case 'cmdline' %-SPM command line mode?
%=======================================================================
% CmdLine = spm('CmdLine',CmdLine)
%-----------------------------------------------------------------------
if nargin<2, CmdLine=[]; else CmdLine=varargin{2}; end
if isempty(CmdLine)
try
CmdLine = spm_get_defaults('cmdline');
catch
CmdLine = 0;
end
end
varargout = { CmdLine | ...
(get(0,'ScreenDepth')==0) | ...
strcmpi(spm_check_version,'octave') };
%=======================================================================
case 'popupcb' %-Callback handling utility for PopUp menus
%=======================================================================
% spm('PopUpCB',h)
%-----------------------------------------------------------------------
if nargin<2, h=gcbo; else h=varargin{2}; end
v = get(h,'Value');
if v==1, return, end
set(h,'Value',1)
CBs = get(h,'UserData');
CB = CBs{v-1};
if ischar(CB)
evalin('base',CB)
elseif isa(CB,'function_handle')
feval(CB);
elseif iscell(CB)
feval(CB{:});
else
error('Invalid CallBack.');
end
%=======================================================================
case 'getuser' %-Get user name
%=======================================================================
% str = spm('GetUser',fmt)
%-----------------------------------------------------------------------
str = spm_platform('user');
if ~isempty(str) && nargin>1, str = sprintf(varargin{2},str); end
varargout = {str};
%=======================================================================
case 'beep' %-Produce beep sound
%=======================================================================
% spm('Beep')
%-----------------------------------------------------------------------
beep;
%=======================================================================
case 'time' %-Return formatted date/time string
%=======================================================================
% [timestr, date_vec] = spm('Time')
%-----------------------------------------------------------------------
tmp = clock;
varargout = {sprintf('%02d:%02d:%02d - %02d/%02d/%4d',...
tmp(4),tmp(5),floor(tmp(6)),tmp(3),tmp(2),tmp(1)), tmp};
%=======================================================================
case 'memory'
%=======================================================================
% m = spm('Memory')
%-----------------------------------------------------------------------
maxmemdef = 200*1024*1024; % 200 MB
%m = spm_get_defaults('stats.maxmem');
m = maxmemdef;
varargout = {m};
%=======================================================================
case 'pointer' %-Set mouse pointer in all MATLAB windows
%=======================================================================
% spm('Pointer',Pointer)
%-----------------------------------------------------------------------
if nargin<2, Pointer='Arrow'; else Pointer=varargin{2}; end
set(get(0,'Children'),'Pointer',lower(Pointer))
%=======================================================================
case {'alert','alert"','alert*','alert!'} %-Alert dialogs
%=======================================================================
% h = spm('alert',Message,Title,CmdLine,wait)
%-----------------------------------------------------------------------
%- Globals
%-----------------------------------------------------------------------
if nargin<5, wait = 0; else wait = varargin{5}; end
if nargin<4, CmdLine = []; else CmdLine = varargin{4}; end
if nargin<3, Title = ''; else Title = varargin{3}; end
if nargin<2, Message = ''; else Message = varargin{2}; end
Message = cellstr(Message);
if isreal(CmdLine)
CmdLine = spm('CmdLine',CmdLine);
CmdLine2 = 0;
else
CmdLine = spm('CmdLine');
CmdLine2 = 1;
end
timestr = spm('Time');
SPMv = spm('ver');
switch(lower(Action))
case 'alert', icon = 'none'; str = '--- ';
case 'alert"', icon = 'help'; str = '~ - ';
case 'alert*', icon = 'error'; str = '* - ';
case 'alert!', icon = 'warn'; str = '! - ';
end
if CmdLine || CmdLine2
Message(strcmp(Message,'')) = {' '};
tmp = sprintf('%s: %s',SPMv,Title);
fprintf('\n %s%s %s\n\n',str,tmp,repmat('-',1,62-length(tmp)))
fprintf(' %s\n',Message{:})
fprintf('\n %s %s\n\n',repmat('-',1,62-length(timestr)),timestr)
h = [];
end
if ~CmdLine
tmp = max(size(char(Message),2),42) - length(SPMv) - length(timestr);
str = sprintf('%s %s %s',SPMv,repmat(' ',1,tmp-4),timestr);
h = msgbox([{''};Message(:);{''};{''};{str}],...
sprintf('%s%s: %s',SPMv,spm('GetUser',' (%s)'),Title),...
icon,'non-modal');
drawnow
set(h,'windowstyle','modal');
end
if wait
if isempty(h)
input(' press ENTER to continue...');
else
uiwait(h)
h = [];
end
end
if nargout, varargout = {h}; end
%=======================================================================
case 'run' %-Run script(s)
%=======================================================================
% spm('Run',mscript)
%-----------------------------------------------------------------------
if nargin<2
[mscript, sts] = spm_select(Inf,'.*\.m$','Select M-file(s) to run');
if ~sts || isempty(mscript), return; end
else
mscript = varargin{2};
end
mscript = cellstr(mscript);
for i=1:numel(mscript)
if isdeployed
[p,n,e] = fileparts(mscript{i});
if isempty(p), p = pwd; end
if isempty(e), e = '.m'; end
mscript{i} = fullfile(p,[n e]);
fid = fopen(mscript{i});
if fid == -1, error('Cannot open %s',mscript{i}); end
S = fscanf(fid,'%c');
fclose(fid);
try
evalin('base',S);
catch
fprintf('Execution failed: %s\n',mscript{i});
rethrow(lasterror);
end
else
try
run(mscript{i});
catch
fprintf('Execution failed: %s\n',mscript{i});
rethrow(lasterror);
end
end
end
%=======================================================================
case 'delete' %-Delete file(s)
%=======================================================================
% spm('Delete',file)
%-----------------------------------------------------------------------
if nargin<2
[P, sts] = spm_select(Inf,'.*','Select file(s) to delete');
if ~sts, return; end
else
P = varargin(2:end);
end
P = cellstr(P); P = P(:);
n = numel(P);
if n==0 || (n==1 && isempty(P{1})), return; end
if n<4
str=[{' '};P];
elseif n<11
str=[{' '};P;{' ';sprintf('(%d files)',n)}];
else
str=[{' '};P(1:min(n,10));{'...';' ';sprintf('(%d files)',n)}];
end
if spm_input(str,-1,'bd','delete|cancel',[1,0],[],'confirm file delete')
feval(@spm_unlink,P{:});
spm('alert"',P,'file delete',1);
end
%=======================================================================
case 'clean' %-Clean MATLAB workspace
%=======================================================================
% spm('Clean')
%-----------------------------------------------------------------------
evalin('base','clear all');
evalc('clear classes');
%=======================================================================
case 'help' %-Pass through for spm_help
%=======================================================================
% spm('Help',varargin)
%-----------------------------------------------------------------------
if nargin>1, spm_help(varargin{2:end}), else spm_help, end
%=======================================================================
case 'quit' %-Quit SPM and clean up
%=======================================================================
% spm('Quit')
%-----------------------------------------------------------------------
% if isdeployed || strcmp(questdlg('Exit Matlab?','Quit SPM','Yes','No','Yes'),'Yes')
% spm_figure('close',allchild(0));
% quit;
% else
% spm_figure('close',allchild(0));
% local_clc;
% fprintf('Bye for now...\n\n');
% end;
%% hack
close(findobj(0,'tag','Graphics'));
close(findobj(0,'tag','Menu'));
close(findobj(0,'tag','Interactive'));
% spm_figure('close',allchild(0));%% ORIGINAL
% local_clc;
% fprintf('Bye for now...\n\n');
%=======================================================================
otherwise %-Unknown action string
%=======================================================================
error('Unknown action string');
%=======================================================================
end
%=======================================================================
function local_clc %-Clear command window
%=======================================================================
if ~isdeployed
clc;
end
%=======================================================================
function v = spm_version(ReDo) %-Retrieve SPM version
%=======================================================================
persistent SPM_VER;
v = SPM_VER;
if isempty(SPM_VER) || (nargin > 0 && ReDo)
v = struct('Name','','Version','','Release','','Date','');
try
if isdeployed
% in deployed mode, M-files are encrypted
% (even if first two lines of Contents.m "should" be preserved)
vfile = fullfile(spm('Dir'),'Contents.txt');
else
vfile = fullfile(spm('Dir'),'Contents.m');
end
fid = fopen(vfile,'rt');
if fid == -1, error(str); 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
error('Can''t obtain SPM Revision information.');
end
SPM_VER = v;
end
|
github
|
philippboehmsturm/antx-master
|
spm_orthviews.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_orthviews.m
| 84,652 |
utf_8
|
27f3fe78186242409fcb89b828ddb4f4
|
function varargout = spm_orthviews(action,varargin)
% Display orthogonal views of a set of images
% FORMAT H = spm_orthviews('Image',filename[,position])
% filename - name of image to display
% area - position of image {relative}
% - area(1) - position x
% - area(2) - position y
% - area(3) - size x
% - area(4) - size y
% H - handle for ortho sections
%
% FORMAT spm_orthviews('Redraw')
% Redraws the images
%
% FORMAT spm_orthviews('Reposition',centre)
% centre - X, Y & Z coordinates of centre voxel
%
% FORMAT spm_orthviews('Space'[,handle[,M,dim]])
% handle - the view to define the space by, optionally with extra
% transformation matrix and dimensions (e.g. one of the blobs
% of a view)
% with no arguments - puts things into mm space
%
% FORMAT H = spm_orthviews('Caption', handle, string, [Property, Value])
% handle - the view to which a caption should be added
% string - the caption text to add
% optional: Property-Value pairs, e.g. 'FontWeight', 'Bold'
%
% H - the handle to the object whose String property has the caption
%
% FORMAT spm_orthviews('BB',bb)
% bb - bounding box
% [loX loY loZ
% hiX hiY hiZ]
%
% FORMAT spm_orthviews('MaxBB')
% sets the bounding box big enough display the whole of all images
%
% FORMAT spm_orthviews('Resolution'[,res])
% res - resolution (mm)
% sets the sampling resolution for all images. The effective resolution
% will be the minimum of res and the voxel sizes of all images. If no
% resolution is specified, the minimum of 1mm and the voxel sizes of the
% images is used.
%
% FORMAT spm_orthviews('Zoom'[,fov[,res]])
% fov - half width of field of view (mm)
% res - resolution (mm)
% sets the displayed part and sampling resolution for all images. The
% image display will be centered at the current crosshair position. The
% image region [xhairs-fov xhairs+fov] will be shown.
% If no argument is given or fov == Inf, the image display will be reset to
% "Full Volume". If fov == 0, the image will be zoomed to the bounding box
% from spm_get_bbox for the non-zero voxels of the image. If fov is NaN,
% then a threshold can be entered, and spm_get_bbox will be used to derive
% the bounding box of the voxels above this threshold.
% Optionally, the display resolution can be set as well.
%
% FORMAT spm_orthviews('Delete', handle)
% handle - image number to delete
%
% FORMAT spm_orthviews('Reset')
% clears the orthogonal views
%
% FORMAT spm_orthviews('Pos')
% returns the co-ordinate of the crosshairs in millimetres in the
% standard space.
%
% FORMAT spm_orthviews('Pos', i)
% returns the voxel co-ordinate of the crosshairs in the image in the
% ith orthogonal section.
%
% FORMAT spm_orthviews('Xhairs','off') OR spm_orthviews('Xhairs')
% disables the cross-hairs on the display.
%
% FORMAT spm_orthviews('Xhairs','on')
% enables the cross-hairs.
%
% FORMAT spm_orthviews('Interp',hld)
% sets the hold value to hld (see spm_slice_vol).
%
% FORMAT spm_orthviews('AddBlobs',handle,XYZ,Z,mat,name)
% Adds blobs from a pointlist to the image specified by the handle(s).
% handle - image number to add blobs to
% XYZ - blob voxel locations
% Z - blob voxel intensities
% mat - matrix from voxels to millimeters of blob.
% name - a name for this blob
% This method only adds one set of blobs, and displays them using a
% split colour table.
%
% FORMAT spm_orthviews('SetBlobsMax', vn, bn, mx)
% Set maximum value for blobs overlay number bn of view number vn to mx.
%
% FORMAT spm_orthviews('AddColouredBlobs',handle,XYZ,Z,mat,colour,name)
% Adds blobs from a pointlist to the image specified by the handle(s).
% handle - image number to add blobs to
% XYZ - blob voxel locations
% Z - blob voxel intensities
% mat - matrix from voxels to millimeters of blob.
% colour - the 3 vector containing the colour that the blobs should be
% name - a name for this blob
% Several sets of blobs can be added in this way, and it uses full colour.
% Although it may not be particularly attractive on the screen, the colour
% blobs print well.
%
% FORMAT spm_orthviews('AddColourBar',handle,blobno)
% Adds colourbar for a specified blob set.
% handle - image number
% blobno - blob number
%
% FORMAT spm_orthviews('RemoveBlobs',handle)
% Removes all blobs from the image specified by the handle(s).
%
% FORMAT spm_orthviews('Addtruecolourimage',handle,filename,colourmap,prop,mx,mn)
% Adds blobs from an image in true colour.
% handle - image number to add blobs to [default: 1]
% filename - image containing blob data [default: request via GUI]
% colourmap - colormap to display blobs in [default: GUI input]
% prop - intensity proportion of activation cf grayscale [default: 0.4]
% mx - maximum intensity to scale to [maximum value in activation image]
% mn - minimum intensity to scale to [minimum value in activation image]
%
% FORMAT spm_orthviews('Register',hReg)
% hReg - Handle of HandleGraphics object to build registry in.
% See spm_XYZreg for more information.
%
% FORMAT spm_orthviews('AddContext',handle)
% handle - image number to add context menu to
%
% FORMAT spm_orthviews('RemoveContext',handle)
% handle - image number to remove context menu from
%
% FORMAT spm_orthviews('ZoomMenu',zoom,res)
% FORMAT [zoom, res] = spm_orthviews('ZoomMenu')
% zoom - A list of predefined zoom values
% res - A list of predefined resolutions
% This list is used by spm_image and spm_orthviews('addcontext',...) to
% create the 'Zoom' menu. The values can be retrieved by calling
% spm_orthviews('ZoomMenu') with 2 output arguments. Values of 0, NaN and
% Inf are treated specially, see the help for spm_orthviews('Zoom' ...).
%__________________________________________________________________________
%
% PLUGINS
% The display capabilities of spm_orthviews can be extended with plugins.
% These are located in the spm_orthviews subdirectory of the SPM
% distribution.
% The functionality of plugins can be accessed via calls to
% spm_orthviews('plugin_name', plugin_arguments). For detailed descriptions
% of each plugin see help spm_orthviews/spm_ov_'plugin_name'.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner et al
% $Id: spm_orthviews.m 4405 2011-07-22 12:54:59Z guillaume $
% The basic fields of st are:
% n - the number of images currently being displayed
% vols - a cell array containing the data on each of the
% displayed images.
% Space - a mapping between the displayed images and the
% mm space of each image.
% bb - the bounding box of the displayed images.
% centre - the current centre of the orthogonal views
% callback - a callback to be evaluated on a button-click.
% xhairs - crosshairs off/on
% hld - the interpolation method
% fig - the figure that everything is displayed in
% mode - the position/orientation of the sagittal view.
% - currently always 1
%
% st.registry.hReg \_ See spm_XYZreg for documentation
% st.registry.hMe /
%
% For each of the displayed images, there is a non-empty entry in the
% vols cell array. Handles returned by "spm_orthviews('Image',.....)"
% indicate the position in the cell array of the newly created ortho-view.
% Operations on each ortho-view require the handle to be passed.
%
% When a new image is displayed, the cell entry contains the information
% returned by spm_vol (type help spm_vol for more info). In addition,
% there are a few other fields, some of which are documented here:
%
% premul - a matrix to premultiply the .mat field by. Useful
% for re-orienting images.
% window - either 'auto' or an intensity range to display the
% image with.
% mapping - Mapping of image intensities to grey values. Currently
% one of 'linear', 'histeq', loghisteq',
% 'quadhisteq'. Default is 'linear'.
% Histogram equalisation depends on the image toolbox
% and is only available if there is a license available
% for it.
% ax - a cell array containing an element for the three
% views. The fields of each element are handles for
% the axis, image and crosshairs.
%
% blobs - optional. Is there for using to superimpose blobs.
% vol - 3D array of image data
% mat - a mapping from vox-to-mm (see spm_vol, or
% help on image formats).
% max - maximum intensity for scaling to. If it
% does not exist, then images are auto-scaled.
%
% There are two colouring modes: full colour, and split
% colour. When using full colour, there should be a
% 'colour' field for each cell element. When using
% split colourscale, there is a handle for the colorbar
% axis.
%
% colour - if it exists it contains the
% red,green,blue that the blobs should be
% displayed in.
% cbar - handle for colorbar (for split colourscale).
%
% PLUGINS
% The plugin concept has been developed to extend the display capabilities
% of spm_orthviews without the need to rewrite parts of it. Interaction
% between spm_orthviews and plugins takes place
% a) at startup: The subfunction 'reset_st' looks for folders
% 'spm_orthviews' in spm('Dir') and each toolbox
% folder. Files with a name spm_ov_PLUGINNAME.m in any of
% these folders will be treated as plugins.
% For each such file, PLUGINNAME will be added to the list
% st.plugins{:}.
% The subfunction 'add_context' calls each plugin with
% feval(['spm_ov_', st.plugins{k}], ...
% 'context_menu', i, parent_menu)
% Each plugin may add its own submenu to the context
% menu.
% b) at redraw: After images and blobs of st.vols{i} are drawn, the
% struct st.vols{i} is checked for field names that occur in
% the plugin list st.plugins{:}. For each matching entry, the
% corresponding plugin is called with the command 'redraw':
% feval(['spm_ov_', st.plugins{k}], ...
% 'redraw', i, TM0, TD, CM0, CD, SM0, SD);
% The values of TM0, TD, CM0, CD, SM0, SD are defined in the
% same way as in the redraw subfunction of spm_orthviews.
% It is up to the plugin to do all necessary redraw
% operations for its display contents. Each displayed item
% must have set its property 'HitTest' to 'off' to let events
% go through to the underlying axis, which is responsible for
% callback handling. The order in which plugins are called is
% undefined.
global st;
persistent zoomlist;
persistent reslist;
if isempty(st), reset_st; end
if nargin == 0, action = ''; end
if ~any(strcmpi(action,{'reposition','pos'}))
spm('Pointer','Watch');
end
switch lower(action)
case 'image',
H = specify_image(varargin{1});
if ~isempty(H)
if numel(varargin)>=2
st.vols{H}.area = varargin{2};
else
st.vols{H}.area = [0 0 1 1];
end
if isempty(st.bb), st.bb = maxbb; end
resolution;
bbox;
cm_pos;
end
varargout{1} = H;
mmcentre = mean(st.Space*[maxbb';1 1],2)';
st.centre = mmcentre(1:3);
redraw_all
case 'caption'
vh = valid_handles(varargin{1});
nh = numel(vh);
xlh = nan(nh, 1);
for i = 1:nh
xlh(i) = get(st.vols{vh(i)}.ax{3}.ax, 'XLabel');
if iscell(varargin{2})
if i <= length(varargin{2})
set(xlh(i), 'String', varargin{2}{i});
end
else
set(xlh(i), 'String', varargin{2});
end
for np = 4:2:nargin
property = varargin{np-1};
value = varargin{np};
set(xlh(i), property, value);
end
end
varargout{1} = xlh;
case 'bb',
if ~isempty(varargin) && all(size(varargin{1})==[2 3]), st.bb = varargin{1}; end
bbox;
redraw_all;
case 'redraw',
redraw_all;
eval(st.callback);
if isfield(st,'registry'),
spm_XYZreg('SetCoords',st.centre,st.registry.hReg,st.registry.hMe);
end
case 'reposition',
if isempty(varargin), tmp = findcent;
else tmp = varargin{1}; end
if numel(tmp) == 3
h = valid_handles(st.snap);
if ~isempty(h)
tmp = st.vols{h(1)}.mat * ...
round(st.vols{h(1)}.mat\[tmp(:); 1]);
end
st.centre = tmp(1:3);
end
redraw_all;
eval(st.callback);
if isfield(st,'registry')
spm_XYZreg('SetCoords',st.centre,st.registry.hReg,st.registry.hMe);
end
cm_pos;
case 'setcoords',
st.centre = varargin{1};
st.centre = st.centre(:);
redraw_all;
eval(st.callback);
cm_pos;
case 'space',
if numel(varargin)<1
st.Space = eye(4);
st.bb = maxbb;
resolution;
bbox;
redraw_all;
else
space(varargin{:});
resolution;
bbox;
redraw_all;
end
case 'maxbb',
st.bb = maxbb;
bbox;
redraw_all;
case 'resolution',
resolution(varargin{:});
bbox;
redraw_all;
case 'window',
if numel(varargin)<2
win = 'auto';
elseif numel(varargin{2})==2
win = varargin{2};
end
for i=valid_handles(varargin{1})
st.vols{i}.window = win;
end
redraw(varargin{1});
case 'delete',
my_delete(varargin{1});
case 'move',
move(varargin{1},varargin{2});
% redraw_all;
case 'reset',
my_reset;
case 'pos',
if isempty(varargin)
H = st.centre(:);
else
H = pos(varargin{1});
end
varargout{1} = H;
case 'interp',
st.hld = varargin{1};
redraw_all;
case 'xhairs',
xhairs(varargin{1});
case 'register',
register(varargin{1});
case 'addblobs',
addblobs(varargin{:});
% redraw(varargin{1});
case 'setblobsmax'
st.vols{varargin{1}}.blobs{varargin{2}}.max = varargin{3};
spm_orthviews('redraw')
case 'addcolouredblobs',
addcolouredblobs(varargin{:});
% redraw(varargin{1});
case 'addimage',
addimage(varargin{1}, varargin{2});
% redraw(varargin{1});
case 'addcolouredimage',
addcolouredimage(varargin{1}, varargin{2},varargin{3});
% redraw(varargin{1});
case 'addtruecolourimage',
if nargin < 2
varargin(1) = {1};
end
if nargin < 3
varargin(2) = {spm_select(1, 'image', 'Image with activation signal')};
end
if nargin < 4
actc = [];
while isempty(actc)
actc = getcmap(spm_input('Colourmap for activation image', '+1','s'));
end
varargin(3) = {actc};
end
if nargin < 5
varargin(4) = {0.4};
end
if nargin < 6
actv = spm_vol(varargin{2});
varargin(5) = {max([eps maxval(actv)])};
end
if nargin < 7
varargin(6) = {min([0 minval(actv)])};
end
addtruecolourimage(varargin{1}, varargin{2},varargin{3}, varargin{4}, ...
varargin{5}, varargin{6});
% redraw(varargin{1});
case 'addcolourbar',
addcolourbar(varargin{1}, varargin{2});
case {'removeblobs','rmblobs'},
rmblobs(varargin{1});
redraw(varargin{1});
case 'addcontext',
if nargin == 1
handles = 1:24;
else
handles = varargin{1};
end
addcontexts(handles);
case {'removecontext','rmcontext'},
if nargin == 1
handles = 1:24;
else
handles = varargin{1};
end
rmcontexts(handles);
case 'context_menu',
c_menu(varargin{:});
case 'valid_handles',
if nargin == 1
handles = 1:24;
else
handles = varargin{1};
end
varargout{1} = valid_handles(handles);
case 'zoom',
zoom_op(varargin{:});
case 'zoommenu',
if isempty(zoomlist)
zoomlist = [NaN 0 5 10 20 40 80 Inf];
reslist = [1 1 .125 .25 .5 .5 1 1 ];
end
if nargin >= 3
if all(cellfun(@isnumeric,varargin(1:2))) && ...
numel(varargin{1})==numel(varargin{2})
zoomlist = varargin{1}(:);
reslist = varargin{2}(:);
else
warning('spm_orthviews:zoom',...
'Invalid zoom or resolution list.')
end
end
if nargout > 0
varargout{1} = zoomlist;
end
if nargout > 1
varargout{2} = reslist;
end
otherwise,
addonaction = strcmpi(st.plugins,action);
if any(addonaction)
feval(['spm_ov_' st.plugins{addonaction}],varargin{:});
end
end
spm('Pointer','Arrow');
return;
%_______________________________________________________________________
%_______________________________________________________________________
function addblobs(handle, xyz, t, mat, name)
global st
if nargin < 5
name = '';
end;
for i=valid_handles(handle),
if ~isempty(xyz),
rcp = round(xyz);
dim = max(rcp,[],2)';
off = rcp(1,:) + dim(1)*(rcp(2,:)-1 + dim(2)*(rcp(3,:)-1));
vol = zeros(dim)+NaN;
vol(off) = t;
vol = reshape(vol,dim);
st.vols{i}.blobs=cell(1,1);
mx = max([eps max(t)]);
mn = min([0 min(t)]);
st.vols{i}.blobs{1} = struct('vol',vol,'mat',mat,'max',mx, 'min',mn,'name',name);
addcolourbar(handle,1);
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function addimage(handle, fname)
global st
for i=valid_handles(handle),
if isstruct(fname),
vol = fname(1);
else
vol = spm_vol(fname);
end;
mat = vol.mat;
st.vols{i}.blobs=cell(1,1);
mx = max([eps maxval(vol)]);
mn = min([0 minval(vol)]);
st.vols{i}.blobs{1} = struct('vol',vol,'mat',mat,'max',mx,'min',mn);
addcolourbar(handle,1);
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function addcolouredblobs(handle, xyz, t, mat, colour, name)
if nargin < 6
name = '';
end;
global st
for i=valid_handles(handle),
if ~isempty(xyz),
rcp = round(xyz);
dim = max(rcp,[],2)';
off = rcp(1,:) + dim(1)*(rcp(2,:)-1 + dim(2)*(rcp(3,:)-1));
vol = zeros(dim)+NaN;
vol(off) = t;
vol = reshape(vol,dim);
if ~isfield(st.vols{i},'blobs'),
st.vols{i}.blobs=cell(1,1);
bset = 1;
else
bset = numel(st.vols{i}.blobs)+1;
end;
mx = max([eps maxval(vol)]);
mn = min([0 minval(vol)]);
st.vols{i}.blobs{bset} = struct('vol',vol, 'mat',mat, ...
'max',mx, 'min',mn, ...
'colour',colour, 'name',name);
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function addcolouredimage(handle, fname,colour)
global st
for i=valid_handles(handle),
if isstruct(fname),
vol = fname(1);
else
vol = spm_vol(fname);
end;
mat = vol.mat;
if ~isfield(st.vols{i},'blobs'),
st.vols{i}.blobs=cell(1,1);
bset = 1;
else
bset = numel(st.vols{i}.blobs)+1;
end;
mx = max([eps maxval(vol)]);
mn = min([0 minval(vol)]);
st.vols{i}.blobs{bset} = struct('vol',vol,'mat',mat,'max',mx,'min',mn,'colour',colour);
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function addtruecolourimage(handle,fname,colourmap,prop,mx,mn)
% adds true colour image to current displayed image
global st
for i=valid_handles(handle),
if isstruct(fname),
vol = fname(1);
else
vol = spm_vol(fname);
end;
mat = vol.mat;
if ~isfield(st.vols{i},'blobs'),
st.vols{i}.blobs=cell(1,1);
bset = 1;
else
bset = numel(st.vols{i}.blobs)+1;
end;
c = struct('cmap', colourmap,'prop',prop);
st.vols{i}.blobs{bset} = struct('vol',vol,'mat',mat,'max',mx, ...
'min',mn,'colour',c);
addcolourbar(handle,bset);
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function addcolourbar(vh,bh)
global st
if st.mode == 0,
axpos = get(st.vols{vh}.ax{2}.ax,'Position');
else
axpos = get(st.vols{vh}.ax{1}.ax,'Position');
end;
st.vols{vh}.blobs{bh}.cbar = axes('Parent',st.fig,...
'Position',[(axpos(1)+axpos(3)+0.05+(bh-1)*.1) (axpos(2)+0.005) 0.05 (axpos(4)-0.01)],...
'Box','on', 'YDir','normal', 'XTickLabel',[], 'XTick',[]);
if isfield(st.vols{vh}.blobs{bh},'name')
ylabel(st.vols{vh}.blobs{bh}.name,'parent',st.vols{vh}.blobs{bh}.cbar);
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function rmblobs(handle)
global st
for i=valid_handles(handle),
if isfield(st.vols{i},'blobs'),
for j=1:numel(st.vols{i}.blobs),
if isfield(st.vols{i}.blobs{j},'cbar') && ishandle(st.vols{i}.blobs{j}.cbar),
delete(st.vols{i}.blobs{j}.cbar);
end;
end;
st.vols{i} = rmfield(st.vols{i},'blobs');
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function register(hreg)
global st
tmp = uicontrol('Position',[0 0 1 1],'Visible','off','Parent',st.fig);
h = valid_handles(1:24);
if ~isempty(h),
tmp = st.vols{h(1)}.ax{1}.ax;
st.registry = struct('hReg',hreg,'hMe', tmp);
spm_XYZreg('Add2Reg',st.registry.hReg,st.registry.hMe, 'spm_orthviews');
else
warning('Nothing to register with');
end;
st.centre = spm_XYZreg('GetCoords',st.registry.hReg);
st.centre = st.centre(:);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function xhairs(arg1)
global st
st.xhairs = 0;
opt = 'on';
if ~strcmp(arg1,'on'),
opt = 'off';
else
st.xhairs = 1;
end;
for i=valid_handles(1:24),
for j=1:3,
set(st.vols{i}.ax{j}.lx,'Visible',opt);
set(st.vols{i}.ax{j}.ly,'Visible',opt);
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function H = pos(arg1)
global st
H = [];
for arg1=valid_handles(arg1),
is = inv(st.vols{arg1}.premul*st.vols{arg1}.mat);
H = is(1:3,1:3)*st.centre(:) + is(1:3,4);
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function my_reset
global st
if ~isempty(st) && isfield(st,'registry') && ishandle(st.registry.hMe),
delete(st.registry.hMe); st = rmfield(st,'registry');
end;
my_delete(1:24);
reset_st;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function my_delete(arg1)
global st
% remove blobs (and colourbars, if any)
rmblobs(arg1);
% remove displayed axes
for i=valid_handles(arg1),
kids = get(st.fig,'Children');
for j=1:3,
if any(kids == st.vols{i}.ax{j}.ax),
set(get(st.vols{i}.ax{j}.ax,'Children'),'DeleteFcn','');
delete(st.vols{i}.ax{j}.ax);
end;
end;
st.vols{i} = [];
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function resolution(arg1)
global st
if nargin == 0
res = 1; % Default minimum resolution 1mm
else
res = arg1;
end
for i=valid_handles(1:24)
% adapt resolution to smallest voxel size of displayed images
res = min([res,sqrt(sum((st.vols{i}.mat(1:3,1:3)).^2))]);
end
res = res/mean(svd(st.Space(1:3,1:3)));
Mat = diag([res res res 1]);
st.Space = st.Space*Mat;
st.bb = st.bb/res;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function move(handle,pos)
global st
for handle = valid_handles(handle),
st.vols{handle}.area = pos;
end;
bbox;
% redraw(valid_handles(handle));
return;
%_______________________________________________________________________
%_______________________________________________________________________
function bb = maxbb
global st
mn = [Inf Inf Inf];
mx = -mn;
for i=valid_handles(1:24)
premul = st.Space \ st.vols{i}.premul;
bb = spm_get_bbox(st.vols{i}, 'fv', premul);
mx = max([bb ; mx]);
mn = min([bb ; mn]);
end;
bb = [mn ; mx];
return;
%_______________________________________________________________________
%_______________________________________________________________________
function space(arg1,M,dim)
global st
if ~isempty(st.vols{arg1})
num = arg1;
if nargin < 2
M = st.vols{num}.mat;
dim = st.vols{num}.dim(1:3);
end;
Mat = st.vols{num}.premul(1:3,1:3)*M(1:3,1:3);
vox = sqrt(sum(Mat.^2));
if det(Mat(1:3,1:3))<0, vox(1) = -vox(1); end;
Mat = diag([vox 1]);
Space = (M)/Mat;
bb = [1 1 1; dim];
bb = [bb [1;1]];
bb=bb*Mat';
bb=bb(:,1:3);
bb=sort(bb);
st.Space = Space;
st.bb = bb;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function zoom_op(varargin)
global st
if nargin > 0
fov = varargin{1};
else
fov = Inf;
end
if nargin > 1
res = varargin{2};
else
res = Inf;
end
if isinf(fov)
st.bb = maxbb;
elseif isnan(fov) || fov == 0
current_handle = valid_handles(1:24);
if numel(current_handle) > 1 % called from check reg context menu
current_handle = get_current_handle;
end
if fov == 0
% zoom to bounding box of current image ~= 0
thr = 'nz';
else
% zoom to bounding box of current image > chosen threshold
thr = spm_input('Threshold (Y > ...)', '+1', 'r', '0', 1);
end
premul = st.Space \ st.vols{current_handle}.premul;
st.bb = spm_get_bbox(st.vols{current_handle}, thr, premul);
else
vx = sqrt(sum(st.Space(1:3,1:3).^2));
vx = vx.^(-1);
pos = spm_orthviews('pos');
pos = st.Space\[pos ; 1];
pos = pos(1:3)';
st.bb = [pos-fov*vx; pos+fov*vx];
end;
resolution(res);
bbox;
redraw_all;
if isfield(st.vols{1},'sdip')
spm_eeg_inv_vbecd_disp('RedrawDip');
end
return;
%_______________________________________________________________________
%_______________________________________________________________________
function H = specify_image(arg1)
global st
H=[];
if isstruct(arg1),
V = arg1(1);
else
try
V = spm_vol(arg1);
catch
fprintf('Can not use image "%s"\n', arg1);
return;
end;
end;
if numel(V)>1, V=V(1); end
ii = 1;
while ~isempty(st.vols{ii}), ii = ii + 1; end;
DeleteFcn = ['spm_orthviews(''Delete'',' num2str(ii) ');'];
V.ax = cell(3,1);
for i=1:3,
ax = axes('Visible','off','DrawMode','fast','Parent',st.fig,'DeleteFcn',DeleteFcn,...
'YDir','normal','ButtonDownFcn',@repos_start);
d = image(0,'Tag','Transverse','Parent',ax,...
'DeleteFcn',DeleteFcn);
set(ax,'Ydir','normal','ButtonDownFcn',@repos_start);
lx = line(0,0,'Parent',ax,'DeleteFcn',DeleteFcn);
ly = line(0,0,'Parent',ax,'DeleteFcn',DeleteFcn);
if ~st.xhairs,
set(lx,'Visible','off');
set(ly,'Visible','off');
end;
V.ax{i} = struct('ax',ax,'d',d,'lx',lx,'ly',ly);
end;
V.premul = eye(4);
V.window = 'auto';
V.mapping = 'linear';
st.vols{ii} = V;
H = ii;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function repos_start(varargin)
% don't use right mouse button to start reposition
if ~strcmpi(get(gcbf,'SelectionType'),'alt')
set(gcbf,'windowbuttonmotionfcn',@repos_move, 'windowbuttonupfcn',@repos_end);
spm_orthviews('reposition');
end
%_______________________________________________________________________
%_______________________________________________________________________
function repos_move(varargin)
spm_orthviews('reposition');
%_______________________________________________________________________
%_______________________________________________________________________
function repos_end(varargin)
set(gcbf,'windowbuttonmotionfcn','', 'windowbuttonupfcn','');
%_______________________________________________________________________
%_______________________________________________________________________
function addcontexts(handles)
for ii = valid_handles(handles),
addcontext(ii);
end;
spm_orthviews('reposition',spm_orthviews('pos'));
return;
%_______________________________________________________________________
%_______________________________________________________________________
function rmcontexts(handles)
global st
for ii = valid_handles(handles),
for i=1:3,
set(st.vols{ii}.ax{i}.ax,'UIcontextmenu',[]);
st.vols{ii}.ax{i} = rmfield(st.vols{ii}.ax{i},'cm');
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function bbox
global st
Dims = diff(st.bb)'+1;
TD = Dims([1 2])';
CD = Dims([1 3])';
if st.mode == 0, SD = Dims([3 2])'; else SD = Dims([2 3])'; end;
un = get(st.fig,'Units');set(st.fig,'Units','Pixels');
sz = get(st.fig,'Position');set(st.fig,'Units',un);
sz = sz(3:4);
sz(2) = sz(2)-40;
for i=valid_handles(1:24),
area = st.vols{i}.area(:);
area = [area(1)*sz(1) area(2)*sz(2) area(3)*sz(1) area(4)*sz(2)];
if st.mode == 0,
sx = area(3)/(Dims(1)+Dims(3))/1.02;
else
sx = area(3)/(Dims(1)+Dims(2))/1.02;
end;
sy = area(4)/(Dims(2)+Dims(3))/1.02;
s = min([sx sy]);
offy = (area(4)-(Dims(2)+Dims(3))*1.02*s)/2 + area(2);
sky = s*(Dims(2)+Dims(3))*0.02;
if st.mode == 0,
offx = (area(3)-(Dims(1)+Dims(3))*1.02*s)/2 + area(1);
skx = s*(Dims(1)+Dims(3))*0.02;
else
offx = (area(3)-(Dims(1)+Dims(2))*1.02*s)/2 + area(1);
skx = s*(Dims(1)+Dims(2))*0.02;
end;
% Transverse
set(st.vols{i}.ax{1}.ax,'Units','pixels', ...
'Position',[offx offy s*Dims(1) s*Dims(2)],...
'Units','normalized','Xlim',[0 TD(1)]+0.5,'Ylim',[0 TD(2)]+0.5,...
'Visible','on','XTick',[],'YTick',[]);
% Coronal
set(st.vols{i}.ax{2}.ax,'Units','Pixels',...
'Position',[offx offy+s*Dims(2)+sky s*Dims(1) s*Dims(3)],...
'Units','normalized','Xlim',[0 CD(1)]+0.5,'Ylim',[0 CD(2)]+0.5,...
'Visible','on','XTick',[],'YTick',[]);
% Sagittal
if st.mode == 0,
set(st.vols{i}.ax{3}.ax,'Units','Pixels', 'Box','on',...
'Position',[offx+s*Dims(1)+skx offy s*Dims(3) s*Dims(2)],...
'Units','normalized','Xlim',[0 SD(1)]+0.5,'Ylim',[0 SD(2)]+0.5,...
'Visible','on','XTick',[],'YTick',[]);
else
set(st.vols{i}.ax{3}.ax,'Units','Pixels', 'Box','on',...
'Position',[offx+s*Dims(1)+skx offy+s*Dims(2)+sky s*Dims(2) s*Dims(3)],...
'Units','normalized','Xlim',[0 SD(1)]+0.5,'Ylim',[0 SD(2)]+0.5,...
'Visible','on','XTick',[],'YTick',[]);
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function redraw_all
redraw(1:24);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function mx = maxval(vol)
if isstruct(vol),
mx = -Inf;
for i=1:vol.dim(3),
tmp = spm_slice_vol(vol,spm_matrix([0 0 i]),vol.dim(1:2),0);
imx = max(tmp(isfinite(tmp)));
if ~isempty(imx),mx = max(mx,imx);end
end;
else
mx = max(vol(isfinite(vol)));
end;
%_______________________________________________________________________
%_______________________________________________________________________
function mn = minval(vol)
if isstruct(vol),
mn = Inf;
for i=1:vol.dim(3),
tmp = spm_slice_vol(vol,spm_matrix([0 0 i]),vol.dim(1:2),0);
imn = min(tmp(isfinite(tmp)));
if ~isempty(imn),mn = min(mn,imn);end
end;
else
mn = min(vol(isfinite(vol)));
end;
%_______________________________________________________________________
%_______________________________________________________________________
function redraw(arg1)
global st
bb = st.bb;
Dims = round(diff(bb)'+1);
is = inv(st.Space);
cent = is(1:3,1:3)*st.centre(:) + is(1:3,4);
for i = valid_handles(arg1),
M = st.Space\st.vols{i}.premul*st.vols{i}.mat;
TM0 = [ 1 0 0 -bb(1,1)+1
0 1 0 -bb(1,2)+1
0 0 1 -cent(3)
0 0 0 1];
TM = inv(TM0*M);
TD = Dims([1 2]);
CM0 = [ 1 0 0 -bb(1,1)+1
0 0 1 -bb(1,3)+1
0 1 0 -cent(2)
0 0 0 1];
CM = inv(CM0*M);
CD = Dims([1 3]);
if st.mode ==0,
SM0 = [ 0 0 1 -bb(1,3)+1
0 1 0 -bb(1,2)+1
1 0 0 -cent(1)
0 0 0 1];
SM = inv(SM0*M);
SD = Dims([3 2]);
else
SM0 = [ 0 -1 0 +bb(2,2)+1
0 0 1 -bb(1,3)+1
1 0 0 -cent(1)
0 0 0 1];
SM = inv(SM0*M);
SD = Dims([2 3]);
end;
try
imgt = spm_slice_vol(st.vols{i},TM,TD,st.hld)';
imgc = spm_slice_vol(st.vols{i},CM,CD,st.hld)';
imgs = spm_slice_vol(st.vols{i},SM,SD,st.hld)';
ok = true;
catch
fprintf('Image "%s" can not be resampled\n', st.vols{i}.fname);
ok = false;
end
if ok,
% get min/max threshold
if strcmp(st.vols{i}.window,'auto')
mn = -Inf;
mx = Inf;
else
mn = min(st.vols{i}.window);
mx = max(st.vols{i}.window);
end;
% threshold images
imgt = max(imgt,mn); imgt = min(imgt,mx);
imgc = max(imgc,mn); imgc = min(imgc,mx);
imgs = max(imgs,mn); imgs = min(imgs,mx);
% compute intensity mapping, if histeq is available
if license('test','image_toolbox') == 0
st.vols{i}.mapping = 'linear';
end;
switch st.vols{i}.mapping,
case 'linear',
case 'histeq',
% scale images to a range between 0 and 1
imgt1=(imgt-min(imgt(:)))/(max(imgt(:)-min(imgt(:)))+eps);
imgc1=(imgc-min(imgc(:)))/(max(imgc(:)-min(imgc(:)))+eps);
imgs1=(imgs-min(imgs(:)))/(max(imgs(:)-min(imgs(:)))+eps);
img = histeq([imgt1(:); imgc1(:); imgs1(:)],1024);
imgt = reshape(img(1:numel(imgt1)),size(imgt1));
imgc = reshape(img(numel(imgt1)+(1:numel(imgc1))),size(imgc1));
imgs = reshape(img(numel(imgt1)+numel(imgc1)+(1:numel(imgs1))),size(imgs1));
mn = 0;
mx = 1;
case 'quadhisteq',
% scale images to a range between 0 and 1
imgt1=(imgt-min(imgt(:)))/(max(imgt(:)-min(imgt(:)))+eps);
imgc1=(imgc-min(imgc(:)))/(max(imgc(:)-min(imgc(:)))+eps);
imgs1=(imgs-min(imgs(:)))/(max(imgs(:)-min(imgs(:)))+eps);
img = histeq([imgt1(:).^2; imgc1(:).^2; imgs1(:).^2],1024);
imgt = reshape(img(1:numel(imgt1)),size(imgt1));
imgc = reshape(img(numel(imgt1)+(1:numel(imgc1))),size(imgc1));
imgs = reshape(img(numel(imgt1)+numel(imgc1)+(1:numel(imgs1))),size(imgs1));
mn = 0;
mx = 1;
case 'loghisteq',
sw = warning('off','MATLAB:log:logOfZero');
imgt = log(imgt-min(imgt(:)));
imgc = log(imgc-min(imgc(:)));
imgs = log(imgs-min(imgs(:)));
warning(sw);
imgt(~isfinite(imgt)) = 0;
imgc(~isfinite(imgc)) = 0;
imgs(~isfinite(imgs)) = 0;
% scale log images to a range between 0 and 1
imgt1=(imgt-min(imgt(:)))/(max(imgt(:)-min(imgt(:)))+eps);
imgc1=(imgc-min(imgc(:)))/(max(imgc(:)-min(imgc(:)))+eps);
imgs1=(imgs-min(imgs(:)))/(max(imgs(:)-min(imgs(:)))+eps);
img = histeq([imgt1(:); imgc1(:); imgs1(:)],1024);
imgt = reshape(img(1:numel(imgt1)),size(imgt1));
imgc = reshape(img(numel(imgt1)+(1:numel(imgc1))),size(imgc1));
imgs = reshape(img(numel(imgt1)+numel(imgc1)+(1:numel(imgs1))),size(imgs1));
mn = 0;
mx = 1;
end;
% recompute min/max for display
if strcmp(st.vols{i}.window,'auto')
mx = -inf; mn = inf;
end;
if ~isempty(imgt),
tmp = imgt(isfinite(imgt));
mx = max([mx max(max(tmp))]);
mn = min([mn min(min(tmp))]);
end;
if ~isempty(imgc),
tmp = imgc(isfinite(imgc));
mx = max([mx max(max(tmp))]);
mn = min([mn min(min(tmp))]);
end;
if ~isempty(imgs),
tmp = imgs(isfinite(imgs));
mx = max([mx max(max(tmp))]);
mn = min([mn min(min(tmp))]);
end;
if mx==mn, mx=mn+eps; end;
if isfield(st.vols{i},'blobs'),
if ~isfield(st.vols{i}.blobs{1},'colour'),
% Add blobs for display using the split colourmap
scal = 64/(mx-mn);
dcoff = -mn*scal;
imgt = imgt*scal+dcoff;
imgc = imgc*scal+dcoff;
imgs = imgs*scal+dcoff;
if isfield(st.vols{i}.blobs{1},'max'),
mx = st.vols{i}.blobs{1}.max;
else
mx = max([eps maxval(st.vols{i}.blobs{1}.vol)]);
st.vols{i}.blobs{1}.max = mx;
end;
if isfield(st.vols{i}.blobs{1},'min'),
mn = st.vols{i}.blobs{1}.min;
else
mn = min([0 minval(st.vols{i}.blobs{1}.vol)]);
st.vols{i}.blobs{1}.min = mn;
end;
vol = st.vols{i}.blobs{1}.vol;
M = st.Space\st.vols{i}.premul*st.vols{i}.blobs{1}.mat;
tmpt = spm_slice_vol(vol,inv(TM0*M),TD,[0 NaN])';
tmpc = spm_slice_vol(vol,inv(CM0*M),CD,[0 NaN])';
tmps = spm_slice_vol(vol,inv(SM0*M),SD,[0 NaN])';
%tmpt_z = find(tmpt==0);tmpt(tmpt_z) = NaN;
%tmpc_z = find(tmpc==0);tmpc(tmpc_z) = NaN;
%tmps_z = find(tmps==0);tmps(tmps_z) = NaN;
sc = 64/(mx-mn);
off = 65.51-mn*sc;
msk = find(isfinite(tmpt)); imgt(msk) = off+tmpt(msk)*sc;
msk = find(isfinite(tmpc)); imgc(msk) = off+tmpc(msk)*sc;
msk = find(isfinite(tmps)); imgs(msk) = off+tmps(msk)*sc;
cmap = get(st.fig,'Colormap');
if size(cmap,1)~=128
figure(st.fig)
spm_figure('Colormap','gray-hot')
end;
redraw_colourbar(i,1,[mn mx],(1:64)'+64);
elseif isstruct(st.vols{i}.blobs{1}.colour),
% Add blobs for display using a defined
% colourmap
% colourmaps
gryc = (0:63)'*ones(1,3)/63;
actc = ...
st.vols{1}.blobs{1}.colour.cmap;
actp = ...
st.vols{1}.blobs{1}.colour.prop;
% scale grayscale image, not isfinite -> black
imgt = scaletocmap(imgt,mn,mx,gryc,65);
imgc = scaletocmap(imgc,mn,mx,gryc,65);
imgs = scaletocmap(imgs,mn,mx,gryc,65);
gryc = [gryc; 0 0 0];
% get max for blob image
if isfield(st.vols{i}.blobs{1},'max'),
cmx = st.vols{i}.blobs{1}.max;
else
cmx = max([eps maxval(st.vols{i}.blobs{1}.vol)]);
end;
if isfield(st.vols{i}.blobs{1},'min'),
cmn = st.vols{i}.blobs{1}.min;
else
cmn = -cmx;
end;
% get blob data
vol = st.vols{i}.blobs{1}.vol;
M = st.Space\st.vols{i}.premul*st.vols{i}.blobs{1}.mat;
tmpt = spm_slice_vol(vol,inv(TM0*M),TD,[0 NaN])';
tmpc = spm_slice_vol(vol,inv(CM0*M),CD,[0 NaN])';
tmps = spm_slice_vol(vol,inv(SM0*M),SD,[0 NaN])';
% actimg scaled round 0, black NaNs
topc = size(actc,1)+1;
tmpt = scaletocmap(tmpt,cmn,cmx,actc,topc);
tmpc = scaletocmap(tmpc,cmn,cmx,actc,topc);
tmps = scaletocmap(tmps,cmn,cmx,actc,topc);
actc = [actc; 0 0 0];
% combine gray and blob data to
% truecolour
imgt = reshape(actc(tmpt(:),:)*actp+ ...
gryc(imgt(:),:)*(1-actp), ...
[size(imgt) 3]);
imgc = reshape(actc(tmpc(:),:)*actp+ ...
gryc(imgc(:),:)*(1-actp), ...
[size(imgc) 3]);
imgs = reshape(actc(tmps(:),:)*actp+ ...
gryc(imgs(:),:)*(1-actp), ...
[size(imgs) 3]);
csz = size(st.vols{i}.blobs{1}.colour.cmap);
cdata = reshape(st.vols{i}.blobs{1}.colour.cmap, [csz(1) 1 csz(2)]);
redraw_colourbar(i,1,[cmn cmx],cdata);
else
% Add full colour blobs - several sets at once
scal = 1/(mx-mn);
dcoff = -mn*scal;
wt = zeros(size(imgt));
wc = zeros(size(imgc));
ws = zeros(size(imgs));
imgt = repmat(imgt*scal+dcoff,[1,1,3]);
imgc = repmat(imgc*scal+dcoff,[1,1,3]);
imgs = repmat(imgs*scal+dcoff,[1,1,3]);
cimgt = zeros(size(imgt));
cimgc = zeros(size(imgc));
cimgs = zeros(size(imgs));
colour = zeros(numel(st.vols{i}.blobs),3);
for j=1:numel(st.vols{i}.blobs) % get colours of all images first
if isfield(st.vols{i}.blobs{j},'colour'),
colour(j,:) = reshape(st.vols{i}.blobs{j}.colour, [1 3]);
else
colour(j,:) = [1 0 0];
end;
end;
%colour = colour/max(sum(colour));
for j=1:numel(st.vols{i}.blobs),
if isfield(st.vols{i}.blobs{j},'max'),
mx = st.vols{i}.blobs{j}.max;
else
mx = max([eps max(st.vols{i}.blobs{j}.vol(:))]);
st.vols{i}.blobs{j}.max = mx;
end;
if isfield(st.vols{i}.blobs{j},'min'),
mn = st.vols{i}.blobs{j}.min;
else
mn = min([0 min(st.vols{i}.blobs{j}.vol(:))]);
st.vols{i}.blobs{j}.min = mn;
end;
vol = st.vols{i}.blobs{j}.vol;
M = st.Space\st.vols{i}.premul*st.vols{i}.blobs{j}.mat;
tmpt = spm_slice_vol(vol,inv(TM0*M),TD,[0 NaN])';
tmpc = spm_slice_vol(vol,inv(CM0*M),CD,[0 NaN])';
tmps = spm_slice_vol(vol,inv(SM0*M),SD,[0 NaN])';
% check min/max of sampled image
% against mn/mx as given in st
tmpt(tmpt(:)<mn) = mn;
tmpc(tmpc(:)<mn) = mn;
tmps(tmps(:)<mn) = mn;
tmpt(tmpt(:)>mx) = mx;
tmpc(tmpc(:)>mx) = mx;
tmps(tmps(:)>mx) = mx;
tmpt = (tmpt-mn)/(mx-mn);
tmpc = (tmpc-mn)/(mx-mn);
tmps = (tmps-mn)/(mx-mn);
tmpt(~isfinite(tmpt)) = 0;
tmpc(~isfinite(tmpc)) = 0;
tmps(~isfinite(tmps)) = 0;
cimgt = cimgt + cat(3,tmpt*colour(j,1),tmpt*colour(j,2),tmpt*colour(j,3));
cimgc = cimgc + cat(3,tmpc*colour(j,1),tmpc*colour(j,2),tmpc*colour(j,3));
cimgs = cimgs + cat(3,tmps*colour(j,1),tmps*colour(j,2),tmps*colour(j,3));
wt = wt + tmpt;
wc = wc + tmpc;
ws = ws + tmps;
cdata=permute(shiftdim((1/64:1/64:1)'* ...
colour(j,:),-1),[2 1 3]);
redraw_colourbar(i,j,[mn mx],cdata);
end;
imgt = repmat(1-wt,[1 1 3]).*imgt+cimgt;
imgc = repmat(1-wc,[1 1 3]).*imgc+cimgc;
imgs = repmat(1-ws,[1 1 3]).*imgs+cimgs;
imgt(imgt<0)=0; imgt(imgt>1)=1;
imgc(imgc<0)=0; imgc(imgc>1)=1;
imgs(imgs<0)=0; imgs(imgs>1)=1;
end;
else
scal = 64/(mx-mn);
dcoff = -mn*scal;
imgt = imgt*scal+dcoff;
imgc = imgc*scal+dcoff;
imgs = imgs*scal+dcoff;
end;
set(st.vols{i}.ax{1}.d,'HitTest','off', 'Cdata',imgt);
set(st.vols{i}.ax{1}.lx,'HitTest','off',...
'Xdata',[0 TD(1)]+0.5,'Ydata',[1 1]*(cent(2)-bb(1,2)+1));
set(st.vols{i}.ax{1}.ly,'HitTest','off',...
'Ydata',[0 TD(2)]+0.5,'Xdata',[1 1]*(cent(1)-bb(1,1)+1));
set(st.vols{i}.ax{2}.d,'HitTest','off', 'Cdata',imgc);
set(st.vols{i}.ax{2}.lx,'HitTest','off',...
'Xdata',[0 CD(1)]+0.5,'Ydata',[1 1]*(cent(3)-bb(1,3)+1));
set(st.vols{i}.ax{2}.ly,'HitTest','off',...
'Ydata',[0 CD(2)]+0.5,'Xdata',[1 1]*(cent(1)-bb(1,1)+1));
set(st.vols{i}.ax{3}.d,'HitTest','off','Cdata',imgs);
if st.mode ==0,
set(st.vols{i}.ax{3}.lx,'HitTest','off',...
'Xdata',[0 SD(1)]+0.5,'Ydata',[1 1]*(cent(2)-bb(1,2)+1));
set(st.vols{i}.ax{3}.ly,'HitTest','off',...
'Ydata',[0 SD(2)]+0.5,'Xdata',[1 1]*(cent(3)-bb(1,3)+1));
else
set(st.vols{i}.ax{3}.lx,'HitTest','off',...
'Xdata',[0 SD(1)]+0.5,'Ydata',[1 1]*(cent(3)-bb(1,3)+1));
set(st.vols{i}.ax{3}.ly,'HitTest','off',...
'Ydata',[0 SD(2)]+0.5,'Xdata',[1 1]*(bb(2,2)+1-cent(2)));
end;
if ~isempty(st.plugins) % process any addons
for k = 1:numel(st.plugins),
if isfield(st.vols{i},st.plugins{k}),
feval(['spm_ov_', st.plugins{k}], ...
'redraw', i, TM0, TD, CM0, CD, SM0, SD);
end;
end;
end;
end;
end;
drawnow;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function redraw_colourbar(vh,bh,interval,cdata)
global st
if isfield(st.vols{vh}.blobs{bh},'cbar')
if st.mode == 0,
axpos = get(st.vols{vh}.ax{2}.ax,'Position');
else
axpos = get(st.vols{vh}.ax{1}.ax,'Position');
end;
% only scale cdata if we have out-of-range truecolour values
if ndims(cdata)==3 && max(cdata(:))>1
cdata=cdata./max(cdata(:));
end;
image([0 1],interval,cdata,'Parent',st.vols{vh}.blobs{bh}.cbar);
set(st.vols{vh}.blobs{bh}.cbar, ...
'Position',[(axpos(1)+axpos(3)+0.05+(bh-1)*.1)...
(axpos(2)+0.005) 0.05 (axpos(4)-0.01)],...
'YDir','normal','XTickLabel',[],'XTick',[]);
if isfield(st.vols{vh}.blobs{bh},'name')
ylabel(st.vols{vh}.blobs{bh}.name,'parent',st.vols{vh}.blobs{bh}.cbar);
end;
end;
%_______________________________________________________________________
%_______________________________________________________________________
function centre = findcent
global st
obj = get(st.fig,'CurrentObject');
centre = [];
cent = [];
cp = [];
for i=valid_handles(1:24),
for j=1:3,
if ~isempty(obj),
if (st.vols{i}.ax{j}.ax == obj),
cp = get(obj,'CurrentPoint');
end;
end;
if ~isempty(cp),
cp = cp(1,1:2);
is = inv(st.Space);
cent = is(1:3,1:3)*st.centre(:) + is(1:3,4);
switch j,
case 1,
cent([1 2])=[cp(1)+st.bb(1,1)-1 cp(2)+st.bb(1,2)-1];
case 2,
cent([1 3])=[cp(1)+st.bb(1,1)-1 cp(2)+st.bb(1,3)-1];
case 3,
if st.mode ==0,
cent([3 2])=[cp(1)+st.bb(1,3)-1 cp(2)+st.bb(1,2)-1];
else
cent([2 3])=[st.bb(2,2)+1-cp(1) cp(2)+st.bb(1,3)-1];
end;
end;
break;
end;
end;
if ~isempty(cent), break; end;
end;
if ~isempty(cent), centre = st.Space(1:3,1:3)*cent(:) + st.Space(1:3,4); end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function handles = valid_handles(handles)
global st;
if isempty(st) || ~isfield(st,'vols')
handles = [];
else
handles = handles(:)';
handles = handles(handles<=24 & handles>=1 & ~rem(handles,1));
for h=handles,
if isempty(st.vols{h}), handles(handles==h)=[]; end;
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function reset_st
global st
fig = spm_figure('FindWin','Graphics');
bb = []; %[ [-78 78]' [-112 76]' [-50 85]' ];
st = struct('n', 0, 'vols',[], 'bb',bb,'Space',eye(4),'centre',[0 0 0],'callback',';','xhairs',1,'hld',1,'fig',fig,'mode',1,'plugins',{{}},'snap',[]);
st.vols = cell(24,1);
xTB = spm('TBs');
if ~isempty(xTB)
pluginbase = {spm('Dir') xTB.dir};
else
pluginbase = {spm('Dir')};
end
for k = 1:numel(pluginbase)
pluginpath = fullfile(pluginbase{k},'spm_orthviews');
if isdir(pluginpath)
pluginfiles = dir(fullfile(pluginpath,'spm_ov_*.m'));
if ~isempty(pluginfiles)
if ~isdeployed, addpath(pluginpath); end
% fprintf('spm_orthviews: Using Plugins in %s\n', pluginpath);
for l = 1:numel(pluginfiles)
[p, pluginname, e, v] = spm_fileparts(pluginfiles(l).name);
st.plugins{end+1} = strrep(pluginname, 'spm_ov_','');
% fprintf('%s\n',st.plugins{k});
end;
end;
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function img = scaletocmap(inpimg,mn,mx,cmap,miscol)
if nargin < 5, miscol=1;end
cml = size(cmap,1);
scf = (cml-1)/(mx-mn);
img = round((inpimg-mn)*scf)+1;
img(img<1) = 1;
img(img>cml) = cml;
img(~isfinite(img)) = miscol;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function cmap = getcmap(acmapname)
% get colormap of name acmapname
if ~isempty(acmapname),
cmap = evalin('base',acmapname,'[]');
if isempty(cmap), % not a matrix, is .mat file?
[p, f, e] = fileparts(acmapname);
acmat = fullfile(p, [f '.mat']);
if exist(acmat, 'file'),
s = struct2cell(load(acmat));
cmap = s{1};
end;
end;
end;
if size(cmap, 2)~=3,
warning('Colormap was not an N by 3 matrix')
cmap = [];
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function item_parent = addcontext(volhandle)
global st;
%create context menu
fg = spm_figure('Findwin','Graphics');set(0,'CurrentFigure',fg);
%contextmenu
item_parent = uicontextmenu;
%contextsubmenu 0
item00 = uimenu(item_parent, 'Label','unknown image');
spm_orthviews('context_menu','image_info',item00,volhandle);
item0a = uimenu(item_parent, 'UserData','pos_mm', 'Callback','spm_orthviews(''context_menu'',''repos_mm'');','Separator','on');
item0b = uimenu(item_parent, 'UserData','pos_vx', 'Callback','spm_orthviews(''context_menu'',''repos_vx'');');
item0c = uimenu(item_parent, 'UserData','v_value');
%contextsubmenu 1
item1 = uimenu(item_parent,'Label','Zoom','Separator','on');
[zl, rl] = spm_orthviews('ZoomMenu');
for cz = numel(zl):-1:1
if isinf(zl(cz))
czlabel = 'Full Volume';
elseif isnan(zl(cz))
czlabel = 'BBox, this image > ...';
elseif zl(cz) == 0
czlabel = 'BBox, this image nonzero';
else
czlabel = sprintf('%dx%d mm', 2*zl(cz), 2*zl(cz));
end
item1_x = uimenu(item1, 'Label',czlabel,...
'Callback', sprintf(...
'spm_orthviews(''context_menu'',''zoom'',%d,%d)',...
zl(cz),rl(cz)));
if isinf(zl(cz)) % default display is Full Volume
set(item1_x, 'Checked','on');
end
end
%contextsubmenu 2
checked={'off','off'};
checked{st.xhairs+1} = 'on';
item2 = uimenu(item_parent,'Label','Crosshairs');
item2_1 = uimenu(item2, 'Label','on', 'Callback','spm_orthviews(''context_menu'',''Xhair'',''on'');','Checked',checked{2});
item2_2 = uimenu(item2, 'Label','off', 'Callback','spm_orthviews(''context_menu'',''Xhair'',''off'');','Checked',checked{1});
%contextsubmenu 3
if st.Space == eye(4)
checked = {'off', 'on'};
else
checked = {'on', 'off'};
end;
item3 = uimenu(item_parent,'Label','Orientation');
item3_1 = uimenu(item3, 'Label','World space', 'Callback','spm_orthviews(''context_menu'',''orientation'',3);','Checked',checked{2});
item3_2 = uimenu(item3, 'Label','Voxel space (1st image)', 'Callback','spm_orthviews(''context_menu'',''orientation'',2);','Checked',checked{1});
item3_3 = uimenu(item3, 'Label','Voxel space (this image)', 'Callback','spm_orthviews(''context_menu'',''orientation'',1);','Checked','off');
%contextsubmenu 3
if isempty(st.snap)
checked = {'off', 'on'};
else
checked = {'on', 'off'};
end;
item3 = uimenu(item_parent,'Label','Snap to Grid');
item3_1 = uimenu(item3, 'Label','Don''t snap', 'Callback','spm_orthviews(''context_menu'',''snap'',3);','Checked',checked{2});
item3_2 = uimenu(item3, 'Label','Snap to 1st image', 'Callback','spm_orthviews(''context_menu'',''snap'',2);','Checked',checked{1});
item3_3 = uimenu(item3, 'Label','Snap to this image', 'Callback','spm_orthviews(''context_menu'',''snap'',1);','Checked','off');
%contextsubmenu 4
if st.hld == 0,
checked = {'off', 'off', 'on'};
elseif st.hld > 0,
checked = {'off', 'on', 'off'};
else
checked = {'on', 'off', 'off'};
end;
item4 = uimenu(item_parent,'Label','Interpolation');
item4_1 = uimenu(item4, 'Label','NN', 'Callback','spm_orthviews(''context_menu'',''interpolation'',3);', 'Checked',checked{3});
item4_2 = uimenu(item4, 'Label','Bilin', 'Callback','spm_orthviews(''context_menu'',''interpolation'',2);','Checked',checked{2});
item4_3 = uimenu(item4, 'Label','Sinc', 'Callback','spm_orthviews(''context_menu'',''interpolation'',1);','Checked',checked{1});
%contextsubmenu 5
% item5 = uimenu(item_parent,'Label','Position', 'Callback','spm_orthviews(''context_menu'',''position'');');
%contextsubmenu 6
item6 = uimenu(item_parent,'Label','Image','Separator','on');
item6_1 = uimenu(item6, 'Label','Window');
item6_1_1 = uimenu(item6_1, 'Label','local');
item6_1_1_1 = uimenu(item6_1_1, 'Label','auto', 'Callback','spm_orthviews(''context_menu'',''window'',2);');
item6_1_1_2 = uimenu(item6_1_1, 'Label','manual', 'Callback','spm_orthviews(''context_menu'',''window'',1);');
item6_1_2 = uimenu(item6_1, 'Label','global');
item6_1_2_1 = uimenu(item6_1_2, 'Label','auto', 'Callback','spm_orthviews(''context_menu'',''window_gl'',2);');
item6_1_2_2 = uimenu(item6_1_2, 'Label','manual', 'Callback','spm_orthviews(''context_menu'',''window_gl'',1);');
if license('test','image_toolbox') == 1
offon = {'off', 'on'};
checked = offon(strcmp(st.vols{volhandle}.mapping, ...
{'linear', 'histeq', 'loghisteq', 'quadhisteq'})+1);
item6_2 = uimenu(item6, 'Label','Intensity mapping');
item6_2_1 = uimenu(item6_2, 'Label','local');
item6_2_1_1 = uimenu(item6_2_1, 'Label','Linear', 'Checked',checked{1}, ...
'Callback','spm_orthviews(''context_menu'',''mapping'',''linear'');');
item6_2_1_2 = uimenu(item6_2_1, 'Label','Equalised histogram', 'Checked',checked{2}, ...
'Callback','spm_orthviews(''context_menu'',''mapping'',''histeq'');');
item6_2_1_3 = uimenu(item6_2_1, 'Label','Equalised log-histogram', 'Checked',checked{3}, ...
'Callback','spm_orthviews(''context_menu'',''mapping'',''loghisteq'');');
item6_2_1_4 = uimenu(item6_2_1, 'Label','Equalised squared-histogram', 'Checked',checked{4}, ...
'Callback','spm_orthviews(''context_menu'',''mapping'',''quadhisteq'');');
item6_2_2 = uimenu(item6_2, 'Label','global');
item6_2_2_1 = uimenu(item6_2_2, 'Label','Linear', 'Checked',checked{1}, ...
'Callback','spm_orthviews(''context_menu'',''mapping_gl'',''linear'');');
item6_2_2_2 = uimenu(item6_2_2, 'Label','Equalised histogram', 'Checked',checked{2}, ...
'Callback','spm_orthviews(''context_menu'',''mapping_gl'',''histeq'');');
item6_2_2_3 = uimenu(item6_2_2, 'Label','Equalised log-histogram', 'Checked',checked{3}, ...
'Callback','spm_orthviews(''context_menu'',''mapping_gl'',''loghisteq'');');
item6_2_2_4 = uimenu(item6_2_2, 'Label','Equalised squared-histogram', 'Checked',checked{4}, ...
'Callback','spm_orthviews(''context_menu'',''mapping_gl'',''quadhisteq'');');
end;
%contextsubmenu 7
item7 = uimenu(item_parent,'Label','Blobs');
item7_1 = uimenu(item7, 'Label','Add blobs');
item7_1_1 = uimenu(item7_1, 'Label','local', 'Callback','spm_orthviews(''context_menu'',''add_blobs'',2);');
item7_1_2 = uimenu(item7_1, 'Label','global', 'Callback','spm_orthviews(''context_menu'',''add_blobs'',1);');
item7_2 = uimenu(item7, 'Label','Add image');
item7_2_1 = uimenu(item7_2, 'Label','local', 'Callback','spm_orthviews(''context_menu'',''add_image'',2);');
item7_2_2 = uimenu(item7_2, 'Label','global', 'Callback','spm_orthviews(''context_menu'',''add_image'',1);');
item7_3 = uimenu(item7, 'Label','Add colored blobs','Separator','on');
item7_3_1 = uimenu(item7_3, 'Label','local', 'Callback','spm_orthviews(''context_menu'',''add_c_blobs'',2);');
item7_3_2 = uimenu(item7_3, 'Label','global', 'Callback','spm_orthviews(''context_menu'',''add_c_blobs'',1);');
item7_4 = uimenu(item7, 'Label','Add colored image');
item7_4_1 = uimenu(item7_4, 'Label','local', 'Callback','spm_orthviews(''context_menu'',''add_c_image'',2);');
item7_4_2 = uimenu(item7_4, 'Label','global', 'Callback','spm_orthviews(''context_menu'',''add_c_image'',1);');
item7_5 = uimenu(item7, 'Label','Remove blobs', 'Visible','off','Separator','on');
item7_6 = uimenu(item7, 'Label','Remove colored blobs','Visible','off');
item7_6_1 = uimenu(item7_6, 'Label','local', 'Visible','on');
item7_6_2 = uimenu(item7_6, 'Label','global','Visible','on');
item7_7 = uimenu(item7, 'Label','Set blobs max', 'Visible','off');
for i=1:3,
set(st.vols{volhandle}.ax{i}.ax,'UIcontextmenu',item_parent);
st.vols{volhandle}.ax{i}.cm = item_parent;
end;
% process any plugins
for k = 1:numel(st.plugins),
feval(['spm_ov_', st.plugins{k}], ...
'context_menu', volhandle, item_parent);
if k==1
h = get(item_parent,'Children');
set(h(1),'Separator','on');
end
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function c_menu(varargin)
global st
switch lower(varargin{1}),
case 'image_info',
if nargin <3,
current_handle = get_current_handle;
else
current_handle = varargin{3};
end;
if isfield(st.vols{current_handle},'fname'),
[p,n,e,v] = spm_fileparts(st.vols{current_handle}.fname);
if isfield(st.vols{current_handle},'n')
v = sprintf(',%d',st.vols{current_handle}.n);
end;
set(varargin{2}, 'Label',[n e v]);
end;
delete(get(varargin{2},'children'));
if exist('p','var')
item1 = uimenu(varargin{2}, 'Label', p);
end;
if isfield(st.vols{current_handle},'descrip'),
item2 = uimenu(varargin{2}, 'Label',...
st.vols{current_handle}.descrip);
end;
dt = st.vols{current_handle}.dt(1);
item3 = uimenu(varargin{2}, 'Label', sprintf('Data type: %s', spm_type(dt)));
str = 'Intensity: varied';
if size(st.vols{current_handle}.pinfo,2) == 1,
if st.vols{current_handle}.pinfo(2),
str = sprintf('Intensity: Y = %g X + %g',...
st.vols{current_handle}.pinfo(1:2)');
else
str = sprintf('Intensity: Y = %g X', st.vols{current_handle}.pinfo(1)');
end;
end;
item4 = uimenu(varargin{2}, 'Label',str);
item5 = uimenu(varargin{2}, 'Label', 'Image dims', 'Separator','on');
item51 = uimenu(varargin{2}, 'Label',...
sprintf('%dx%dx%d', st.vols{current_handle}.dim(1:3)));
prms = spm_imatrix(st.vols{current_handle}.mat);
item6 = uimenu(varargin{2}, 'Label','Voxel size', 'Separator','on');
item61 = uimenu(varargin{2}, 'Label', sprintf('%.2f %.2f %.2f', prms(7:9)));
item7 = uimenu(varargin{2}, 'Label','Origin', 'Separator','on');
item71 = uimenu(varargin{2}, 'Label',...
sprintf('%.2f %.2f %.2f', prms(1:3)));
R = spm_matrix([0 0 0 prms(4:6)]);
item8 = uimenu(varargin{2}, 'Label','Rotations', 'Separator','on');
item81 = uimenu(varargin{2}, 'Label', sprintf('%.2f %.2f %.2f', R(1,1:3)));
item82 = uimenu(varargin{2}, 'Label', sprintf('%.2f %.2f %.2f', R(2,1:3)));
item83 = uimenu(varargin{2}, 'Label', sprintf('%.2f %.2f %.2f', R(3,1:3)));
item9 = uimenu(varargin{2},...
'Label','Specify other image...',...
'Callback','spm_orthviews(''context_menu'',''swap_img'');',...
'Separator','on');
case 'repos_mm',
oldpos_mm = spm_orthviews('pos');
newpos_mm = spm_input('New Position (mm)','+1','r',sprintf('%.2f %.2f %.2f',oldpos_mm),3);
spm_orthviews('reposition',newpos_mm);
case 'repos_vx'
current_handle = get_current_handle;
oldpos_vx = spm_orthviews('pos', current_handle);
newpos_vx = spm_input('New Position (voxels)','+1','r',sprintf('%.2f %.2f %.2f',oldpos_vx),3);
newpos_mm = st.vols{current_handle}.mat*[newpos_vx;1];
spm_orthviews('reposition',newpos_mm(1:3));
case 'zoom'
zoom_all(varargin{2:end});
bbox;
redraw_all;
case 'xhair',
spm_orthviews('Xhairs',varargin{2});
cm_handles = get_cm_handles;
for i = 1:numel(cm_handles),
z_handle = get(findobj(cm_handles(i),'label','Crosshairs'),'Children');
set(z_handle,'Checked','off'); %reset check
if strcmp(varargin{2},'off'), op = 1; else op = 2; end
set(z_handle(op),'Checked','on');
end;
case 'orientation',
cm_handles = get_cm_handles;
for i = 1:numel(cm_handles),
z_handle = get(findobj(cm_handles(i),'label','Orientation'),'Children');
set(z_handle,'Checked','off');
end;
if varargin{2} == 3,
spm_orthviews('Space');
for i = 1:numel(cm_handles),
z_handle = findobj(cm_handles(i),'label','World space');
set(z_handle,'Checked','on');
end;
elseif varargin{2} == 2,
spm_orthviews('Space',1);
for i = 1:numel(cm_handles),
z_handle = findobj(cm_handles(i),'label',...
'Voxel space (1st image)');
set(z_handle,'Checked','on');
end;
else
spm_orthviews('Space',get_current_handle);
z_handle = findobj(st.vols{get_current_handle}.ax{1}.cm, ...
'label','Voxel space (this image)');
set(z_handle,'Checked','on');
return;
end;
case 'snap',
cm_handles = get_cm_handles;
for i = 1:numel(cm_handles),
z_handle = get(findobj(cm_handles(i),'label','Snap to Grid'),'Children');
set(z_handle,'Checked','off');
end;
if varargin{2} == 3,
st.snap = [];
elseif varargin{2} == 2,
st.snap = 1;
else
st.snap = get_current_handle;
z_handle = get(findobj(st.vols{get_current_handle}.ax{1}.cm,'label','Snap to Grid'),'Children');
set(z_handle(1),'Checked','on');
return;
end;
for i = 1:numel(cm_handles),
z_handle = get(findobj(cm_handles(i),'label','Snap to Grid'),'Children');
set(z_handle(varargin{2}),'Checked','on');
end;
case 'interpolation',
tmp = [-4 1 0];
st.hld = tmp(varargin{2});
cm_handles = get_cm_handles;
for i = 1:numel(cm_handles),
z_handle = get(findobj(cm_handles(i),'label','Interpolation'),'Children');
set(z_handle,'Checked','off');
set(z_handle(varargin{2}),'Checked','on');
end;
redraw_all;
case 'window',
current_handle = get_current_handle;
if varargin{2} == 2,
spm_orthviews('window',current_handle);
else
if isnumeric(st.vols{current_handle}.window)
defstr = sprintf('%.2f %.2f', st.vols{current_handle}.window);
else
defstr = '';
end;
[w yp] = spm_input('Range','+1','e',defstr,[1 inf]);
while numel(w) < 1 || numel(w) > 2
uiwait(warndlg('Window must be one or two numbers','Wrong input size','modal'));
[w yp] = spm_input('Range',yp,'e',defstr,[1 inf]);
end
if numel(w) == 1
w(2) = w(1)+eps;
end
spm_orthviews('window',current_handle,w);
end;
case 'window_gl',
if varargin{2} == 2,
for i = 1:numel(get_cm_handles),
st.vols{i}.window = 'auto';
end;
else
current_handle = get_current_handle;
if isnumeric(st.vols{current_handle}.window)
defstr = sprintf('%d %d', st.vols{current_handle}.window);
else
defstr = '';
end;
[w yp] = spm_input('Range','+1','e',defstr,[1 inf]);
while numel(w) < 1 || numel(w) > 2
uiwait(warndlg('Window must be one or two numbers','Wrong input size','modal'));
[w yp] = spm_input('Range',yp,'e',defstr,[1 inf]);
end
if numel(w) == 1
w(2) = w(1)+eps;
end
for i = 1:numel(get_cm_handles),
st.vols{i}.window = w;
end;
end;
redraw_all;
case 'mapping',
checked = strcmp(varargin{2}, ...
{'linear', 'histeq', 'loghisteq', ...
'quadhisteq'});
checked = checked(end:-1:1); % Handles are stored in inverse order
current_handle = get_current_handle;
cm_handles = get_cm_handles;
st.vols{current_handle}.mapping = varargin{2};
z_handle = get(findobj(cm_handles(current_handle), ...
'label','Intensity mapping'),'Children');
for k = 1:numel(z_handle)
c_handle = get(z_handle(k), 'Children');
set(c_handle, 'checked', 'off');
set(c_handle(checked), 'checked', 'on');
end;
redraw_all;
case 'mapping_gl',
checked = strcmp(varargin{2}, ...
{'linear', 'histeq', 'loghisteq', 'quadhisteq'});
checked = checked(end:-1:1); % Handles are stored in inverse order
cm_handles = get_cm_handles;
for k = valid_handles(1:24),
st.vols{k}.mapping = varargin{2};
z_handle = get(findobj(cm_handles(k), ...
'label','Intensity mapping'),'Children');
for l = 1:numel(z_handle)
c_handle = get(z_handle(l), 'Children');
set(c_handle, 'checked', 'off');
set(c_handle(checked), 'checked', 'on');
end;
end;
redraw_all;
case 'swap_img',
current_handle = get_current_handle;
newimg = spm_select(1,'image','select new image');
if ~isempty(newimg)
new_info = spm_vol(newimg);
fn = fieldnames(new_info);
for k=1:numel(fn)
st.vols{current_handle}.(fn{k}) = new_info.(fn{k});
end;
spm_orthviews('context_menu','image_info',get(gcbo, 'parent'));
redraw_all;
end
case 'add_blobs',
% Add blobs to the image - in split colortable
cm_handles = valid_handles(1:24);
if varargin{2} == 2, cm_handles = get_current_handle; end;
spm_input('!DeleteInputObj');
[SPM,xSPM] = spm_getSPM;
if ~isempty(SPM)
for i = 1:numel(cm_handles),
addblobs(cm_handles(i),xSPM.XYZ,xSPM.Z,xSPM.M);
% Add options for removing blobs
c_handle = findobj(findobj(st.vols{cm_handles(i)}.ax{1}.cm,'label','Blobs'),'Label','Remove blobs');
set(c_handle,'Visible','on');
delete(get(c_handle,'Children'));
item7_3_1 = uimenu(c_handle,'Label','local','Callback','spm_orthviews(''context_menu'',''remove_blobs'',2);');
if varargin{2} == 1,
item7_3_2 = uimenu(c_handle,'Label','global','Callback','spm_orthviews(''context_menu'',''remove_blobs'',1);');
end;
% Add options for setting maxima for blobs
c_handle = findobj(findobj(st.vols{cm_handles(i)}.ax{1}.cm,'label','Blobs'),'Label','Set blobs max');
set(c_handle,'Visible','on');
delete(get(c_handle,'Children'));
uimenu(c_handle,'Label','local','Callback','spm_orthviews(''context_menu'',''setblobsmax'',2);');
if varargin{2} == 1,
uimenu(c_handle,'Label','global','Callback','spm_orthviews(''context_menu'',''setblobsmax'',1);');
end;
end;
redraw_all;
end
case 'remove_blobs',
cm_handles = valid_handles(1:24);
if varargin{2} == 2, cm_handles = get_current_handle; end;
for i = 1:numel(cm_handles),
rmblobs(cm_handles(i));
% Remove options for removing blobs
c_handle = findobj(findobj(st.vols{cm_handles(i)}.ax{1}.cm,'label','Blobs'),'Label','Remove blobs');
delete(get(c_handle,'Children'));
set(c_handle,'Visible','off');
% Remove options for setting maxima for blobs
c_handle = findobj(findobj(st.vols{cm_handles(i)}.ax{1}.cm,'label','Blobs'),'Label','Set blobs max');
set(c_handle,'Visible','off');
end;
redraw_all;
case 'add_image',
% Add blobs to the image - in split colortable
cm_handles = valid_handles(1:24);
if varargin{2} == 2, cm_handles = get_current_handle; end;
spm_input('!DeleteInputObj');
fname = spm_select(1,'image','select image');
if ~isempty(fname)
for i = 1:numel(cm_handles),
addimage(cm_handles(i),fname);
% Add options for removing blobs
c_handle = findobj(findobj(st.vols{cm_handles(i)}.ax{1}.cm,'label','Blobs'),'Label','Remove blobs');
set(c_handle,'Visible','on');
delete(get(c_handle,'Children'));
item7_3_1 = uimenu(c_handle,'Label','local','Callback','spm_orthviews(''context_menu'',''remove_blobs'',2);');
if varargin{2} == 1,
item7_3_2 = uimenu(c_handle,'Label','global','Callback','spm_orthviews(''context_menu'',''remove_blobs'',1);');
end;
% Add options for setting maxima for blobs
c_handle = findobj(findobj(st.vols{cm_handles(i)}.ax{1}.cm,'label','Blobs'),'Label','Set blobs max');
set(c_handle,'Visible','on');
delete(get(c_handle,'Children'));
uimenu(c_handle,'Label','local','Callback','spm_orthviews(''context_menu'',''setblobsmax'',2);');
if varargin{2} == 1,
uimenu(c_handle,'Label','global','Callback','spm_orthviews(''context_menu'',''setblobsmax'',1);');
end;
end;
redraw_all;
end
case 'add_c_blobs',
% Add blobs to the image - in full colour
cm_handles = valid_handles(1:24);
if varargin{2} == 2, cm_handles = get_current_handle; end;
spm_input('!DeleteInputObj');
[SPM,xSPM] = spm_getSPM;
if ~isempty(SPM)
c = spm_input('Colour','+1','m',...
'Red blobs|Yellow blobs|Green blobs|Cyan blobs|Blue blobs|Magenta blobs',[1 2 3 4 5 6],1);
colours = [1 0 0;1 1 0;0 1 0;0 1 1;0 0 1;1 0 1];
c_names = {'red';'yellow';'green';'cyan';'blue';'magenta'};
hlabel = sprintf('%s (%s)',xSPM.title,c_names{c});
for i = 1:numel(cm_handles),
addcolouredblobs(cm_handles(i),xSPM.XYZ,xSPM.Z,xSPM.M,colours(c,:),xSPM.title);
addcolourbar(cm_handles(i),numel(st.vols{cm_handles(i)}.blobs));
c_handle = findobj(findobj(st.vols{cm_handles(i)}.ax{1}.cm,'label','Blobs'),'Label','Remove colored blobs');
ch_c_handle = get(c_handle,'Children');
set(c_handle,'Visible','on');
%set(ch_c_handle,'Visible',on');
item7_4_1 = uimenu(ch_c_handle(2),'Label',hlabel,'ForegroundColor',colours(c,:),...
'Callback','c = get(gcbo,''UserData'');spm_orthviews(''context_menu'',''remove_c_blobs'',2,c);',...
'UserData',c);
if varargin{2} == 1,
item7_4_2 = uimenu(ch_c_handle(1),'Label',hlabel,'ForegroundColor',colours(c,:),...
'Callback','c = get(gcbo,''UserData'');spm_orthviews(''context_menu'',''remove_c_blobs'',1,c);',...
'UserData',c);
end;
end;
redraw_all;
end
case 'remove_c_blobs',
cm_handles = valid_handles(1:24);
if varargin{2} == 2, cm_handles = get_current_handle; end;
colours = [1 0 0;1 1 0;0 1 0;0 1 1;0 0 1;1 0 1];
for i = 1:numel(cm_handles),
if isfield(st.vols{cm_handles(i)},'blobs'),
for j = 1:numel(st.vols{cm_handles(i)}.blobs),
if all(st.vols{cm_handles(i)}.blobs{j}.colour == colours(varargin{3},:));
if isfield(st.vols{cm_handles(i)}.blobs{j},'cbar')
delete(st.vols{cm_handles(i)}.blobs{j}.cbar);
end
st.vols{cm_handles(i)}.blobs(j) = [];
break;
end;
end;
rm_c_menu = findobj(st.vols{cm_handles(i)}.ax{1}.cm,'Label','Remove colored blobs');
delete(gcbo);
if isempty(st.vols{cm_handles(i)}.blobs),
st.vols{cm_handles(i)} = rmfield(st.vols{cm_handles(i)},'blobs');
set(rm_c_menu, 'Visible', 'off');
end;
end;
end;
redraw_all;
case 'add_c_image',
% Add truecolored image
cm_handles = valid_handles(1:24);
if varargin{2} == 2, cm_handles = get_current_handle;end;
spm_input('!DeleteInputObj');
fname = spm_select([1 Inf],'image','select image(s)');
for k = 1:size(fname,1)
c = spm_input(sprintf('Image %d: Colour',k),'+1','m','Red blobs|Yellow blobs|Green blobs|Cyan blobs|Blue blobs|Magenta blobs',[1 2 3 4 5 6],1);
colours = [1 0 0;1 1 0;0 1 0;0 1 1;0 0 1;1 0 1];
c_names = {'red';'yellow';'green';'cyan';'blue';'magenta'};
hlabel = sprintf('%s (%s)',fname(k,:),c_names{c});
for i = 1:numel(cm_handles),
addcolouredimage(cm_handles(i),fname(k,:),colours(c,:));
addcolourbar(cm_handles(i),numel(st.vols{cm_handles(i)}.blobs));
c_handle = findobj(findobj(st.vols{cm_handles(i)}.ax{1}.cm,'label','Blobs'),'Label','Remove colored blobs');
ch_c_handle = get(c_handle,'Children');
set(c_handle,'Visible','on');
%set(ch_c_handle,'Visible',on');
item7_4_1 = uimenu(ch_c_handle(2),'Label',hlabel,'ForegroundColor',colours(c,:),...
'Callback','c = get(gcbo,''UserData'');spm_orthviews(''context_menu'',''remove_c_blobs'',2,c);','UserData',c);
if varargin{2} == 1
item7_4_2 = uimenu(ch_c_handle(1),'Label',hlabel,'ForegroundColor',colours(c,:),...
'Callback','c = get(gcbo,''UserData'');spm_orthviews(''context_menu'',''remove_c_blobs'',1,c);',...
'UserData',c);
end
end
redraw_all;
end
case 'setblobsmax'
if varargin{2} == 1
% global
cm_handles = valid_handles(1:24);
mx = -inf;
for i = 1:numel(cm_handles)
if ~isfield(st.vols{cm_handles(i)}, 'blobs'), continue, end
for j = 1:numel(st.vols{cm_handles(i)}.blobs)
mx = max(mx, st.vols{cm_handles(i)}.blobs{j}.max);
end
end
mx = spm_input('Maximum value', '+1', 'r', mx, 1);
for i = 1:numel(cm_handles)
if ~isfield(st.vols{cm_handles(i)}, 'blobs'), continue, end
for j = 1:numel(st.vols{cm_handles(i)}.blobs)
st.vols{cm_handles(i)}.blobs{j}.max = mx;
end
end
else
% local (should handle coloured blobs, but not implemented yet)
cm_handle = get_current_handle;
colours = [1 0 0;1 1 0;0 1 0;0 1 1;0 0 1;1 0 1];
if ~isfield(st.vols{cm_handle}, 'blobs'), return, end
for j = 1:numel(st.vols{cm_handle}.blobs)
if nargin < 4 || ...
all(st.vols{cm_handle}.blobs{j}.colour == colours(varargin{3},:))
mx = st.vols{cm_handle}.blobs{j}.max;
mx = spm_input('Maximum value', '+1', 'r', mx, 1);
st.vols{cm_handle}.blobs{j}.max = mx;
end
end
end
redraw_all;
end;
%_______________________________________________________________________
%_______________________________________________________________________
function current_handle = get_current_handle
cm_handle = get(gca,'UIContextMenu');
cm_handles = get_cm_handles;
current_handle = find(cm_handles==cm_handle);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function cm_pos
global st
for i = 1:numel(valid_handles(1:24)),
if isfield(st.vols{i}.ax{1},'cm')
set(findobj(st.vols{i}.ax{1}.cm,'UserData','pos_mm'),...
'Label',sprintf('mm: %.1f %.1f %.1f',spm_orthviews('pos')));
pos = spm_orthviews('pos',i);
set(findobj(st.vols{i}.ax{1}.cm,'UserData','pos_vx'),...
'Label',sprintf('vx: %.1f %.1f %.1f',pos));
set(findobj(st.vols{i}.ax{1}.cm,'UserData','v_value'),...
'Label',sprintf('Y = %g',spm_sample_vol(st.vols{i},pos(1),pos(2),pos(3),st.hld)));
end
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function cm_handles = get_cm_handles
global st
cm_handles = [];
for i=valid_handles(1:24),
cm_handles = [cm_handles st.vols{i}.ax{1}.cm];
end
return;
%_______________________________________________________________________
%_______________________________________________________________________
function zoom_all(zoom,res)
global st
cm_handles = get_cm_handles;
zoom_op(zoom,res);
for i = 1:numel(cm_handles)
z_handle = get(findobj(cm_handles(i),'label','Zoom'),'Children');
set(z_handle,'Checked','off');
if isinf(zoom)
set(findobj(z_handle,'Label','Full Volume'),'Checked','on');
elseif zoom > 0
set(findobj(z_handle,'Label',sprintf('%dx%d mm', 2*zoom, 2*zoom)),'Checked','on');
end % leave all unchecked if either bounding box option was chosen
end
return;
|
github
|
philippboehmsturm/antx-master
|
spm_FcUtil.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_FcUtil.m
| 30,975 |
utf_8
|
0d64cc7e875dbb54242a27a69ebaee99
|
function varargout = spm_FcUtil(varargin)
% Contrast utilities
% FORMAT varargout = spm_FcUtil(action,varargin)
%_______________________________________________________________________
%
% spm_FcUtil is a multi-function function containing various utilities
% for contrast construction and manipulation. In general, it accepts
% design matrices as plain matrices or as space structures setup by
% spm_sp (that is preferable in general).
%
% The use of spm_FcUtil should help with robustness issues and
% maintainability of SPM. % Note that when space structures are passed
% as arguments is is assummed that their basic fields are filled in.
% See spm_sp for details of (design) space structures and their
% manipulation.
%
%
% ======================================================================
% case 'fconfields' %- fields of F contrast
% Fc = spm_FcUtil('FconFields')
%
%- simply returns the fields of a contrast structure.
%
%=======================================================================
% case 'set' %- Create an F contrast
% Fc = spm_FcUtil('Set',name, STAT, set_action, value, sX)
%
%- Set will fill in the contrast structure, in particular
%- c (in the contrast space), X1o (the space actually tested) and
%- X0 (the space left untested), such that space([X1o X0]) == sX.
%- STAT is either 'F' or 'T';
%- name is a string descibing the contrast.
%
%- There are three ways to set a contrast :
%- set_action is 'c','c+' : value can then be zeros.
%- dimensions are in X',
%- f c+ is used, value is projected onto sX';
%- iX0 is set to 'c' or 'c+';
%- set_action is 'iX0' : defines the indices of the columns
%- that will not be tested. Can be empty.
%- set_action is 'X0' : defines the space that will remain
%- unchanged. The orthogonal complement is
%- tested; iX0 is set to 'X0';
%-
%=======================================================================
% case 'isfcon' %- Is it an F contrast ?
% b = spm_FcUtil('IsFcon',Fc)
%
%=======================================================================
% case 'fconedf' %- F contrast edf
% [edf_tsp edf_Xsp] = spm_FcUtil('FconEdf', Fc, sX [, V])
%
%- compute the effective degrees of freedom of the numerator edf_tsp
%- and (optionally) the denominator edf_Xsp of the contrast.
%
%=======================================================================
% case 'hsqr' %-Extra sum of squares sqr matrix for beta's from contrast
% hsqr = spm_FcUtil('Hsqr',Fc, sX)
%
%- This computes the matrix hsqr such that a the numerator of an F test
%- will be beta'*hsqr'*hsqr*beta
%
%=======================================================================
% case 'h' %-Extra sum of squares matrix for beta's from contrast
% H = spm_FcUtil('H',Fc, sX)
%
%- This computes the matrix H such that a the numerator of an F test
%- will be beta'*H*beta
%-
%=======================================================================
% case 'yc' %- Fitted data corrected for confounds defined by Fc
% Yc = spm_FcUtil('Yc',Fc, sX, b)
%
%- Input : b : the betas
%- Returns the corrected data Yc for given contrast. Y = Yc + Y0 + error
%
%=======================================================================
% case 'y0' %- Confounds data defined by Fc
% Y0 = spm_FcUtil('Y0',Fc, sX, b)
%
%- Input : b : the betas
%- Returns the confound data Y0 for a given contrast. Y = Yc + Y0 + error
%
%=======================================================================
% case {'|_'} %- Fc orthogonalisation
% Fc = spm_FcUtil('|_',Fc1, sX, Fc2)
%
%- Orthogonolise a (list of) contrasts Fc1 wrt a (list of) contrast Fc2
%- such that the space these contrasts test are orthogonal.
%- If contrasts are not estimable contrasts, works with the estimable
%- part. In any case, returns estimable contrasts.
%
%=======================================================================
% case {'|_?'} %- Are contrasts orthogonals
% b = spm_FcUtil('|_?',Fc1, sX [, Fc2])
%
%- Tests whether a (list of) contrast is orthogonal. Works with the
%- estimable part if they are not estimable. With only one argument,
%- tests whether the list is made of orthogonal contrasts. With Fc2
%- provided, tests whether the two (list of) contrast are orthogonal.
%
%=======================================================================
% case 'in' %- Fc1 is in list of contrasts Fc2
% [iFc2 iFc1] = spm_FcUtil('In', Fc1, sX, Fc2)
%
%- Tests wether a (list of) contrast Fc1 is in a list of contrast Fc2.
%- returns the indices iFc2 where element of Fc1 have been found
%- in Fc2 and the indices iFc1 of the element of Fc1 found in Fc2.
%- These indices are not necessarily unique.
%
%=======================================================================
% case '~unique' %- Fc list unique
% idx = spm_FcUtil('~unique', Fc, sX)
%
%- returns indices ofredundant contrasts in Fc
%- such that Fc(idx) = [] makes Fc unique.
%
%=======================================================================
% case {'0|[]','[]|0'} %- Fc is null or empty
% b = spm_FcUtil('0|[]', Fc, sX)
%
%- NB : for the "null" part, checks if the contrast is in the null space
%- of sX (completely non estimable !)
%=======================================================================
%
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Jean-Baptiste Poline
% $Id: spm_FcUtil.m 4137 2010-12-15 17:18:32Z guillaume $
%-Format arguments
%-----------------------------------------------------------------------
if nargin==0, error('do what? no arguments given...')
else action = varargin{1}; end
switch lower(action),
case 'fconfields' %- fields of F contrast
%=======================================================================
% Fc = spm_FcUtil('FconFields')
if nargout > 1, error('Too many output arguments: FconFields'), end
if nargin > 1, error('Too many input arguments: FconFields'), end
varargout = {sf_FconFields};
case {'set','v1set'} %- Create an F contrast
%=======================================================================
% Fc = spm_FcUtil('Set',name, STAT, set_action, value, sX)
%
% Sets the contrast structure with set_action either 'c', 'X0' or 'iX0'
% resp. for a contrast, the null hyp. space or the indices of which.
% STAT can be 'T' or 'F'.
%
% If not set by iX0 (in which case field .iX0 containes the indices),
% field .iX0 is set as a string containing the set_action: {'X0','c','c+','ukX0'}
%
% if STAT is T, then set_action should be 'c' or 'c+'
% (at the moment, just a warning...)
% if STAT is T and set_action is 'c' or 'c+', then
% checks whether it is a real T.
%
% 'v1set' is NOT provided for backward compatibility so far ...
%-check # arguments...
%--------------------------------------------------------------------------
if nargin<6, error('insufficient arguments'), end
if nargout > 1, error('Too many output arguments Set'), end
%-check arguments...
%--------------------------------------------------------------------------
if ~ischar(varargin{2}), error('~ischar(name)'), end
if ~(varargin{3}=='F'||varargin{3}=='T'||varargin{3}=='P'),
error('~(STAT==F|STAT==T|STAT==P)'), end
if ~ischar(varargin{4}), error('~ischar(varargin{4})');
else set_action = varargin{4}; end
sX = varargin{6};
if ~spm_sp('isspc',sX), sX = spm_sp('set',sX); end
if isempty(sX.X), error('Empty space X in Set'); end
Fc = sf_FconFields;
%- use the name as a flag to insure that F-contrast has been
%- properly created;
Fc.name = varargin{2};
Fc.STAT = varargin{3};
if Fc.STAT=='T' && ~(any(strcmp(set_action,{'c+','c'})))
warning('enter T stat with contrast - here no check rank == 1');
end
[sC sL] = spm_sp('size',sX);
%- allow to define the contrast the old (version 1) way ?
%- NO. v1 = strcmp(action,'v1set');
switch set_action,
case {'c','c+'}
Fc.iX0 = set_action;
c = spm_sp(':', sX, varargin{5});
if isempty(c)
[Fc.X1o.ukX1o Fc.X0.ukX0] = spm_SpUtil('+c->Tsp',sX,[]);
%- v1 [Fc.X1o Fc.X0] = spm_SpUtil('c->Tsp',sX,[]);
Fc.c = c;
elseif size(c,1) ~= sL,
error(['not contrast dim. in ' mfilename ' ' set_action]);
else
if strcmp(set_action,'c+')
if ~spm_sp('isinspp',sX,c), c = spm_sp('oPp:',sX,c); end
end;
if Fc.STAT=='T' && ~sf_is_T(sX,c)
%- Could be make more self-correcting by giving back an F
error('trying to define a t that looks like an F');
end
Fc.c = c;
[Fc.X1o.ukX1o Fc.X0.ukX0] = spm_SpUtil('+c->Tsp',sX,c);
%- v1 [Fc.X1o Fc.X0] = spm_SpUtil('c->Tsp',sX,c);
end
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% 'option given for completeness - not for SPM use'
case {'X0'}
warning('option given for completeness - not for SPM use');
Fc.iX0 = set_action;
X0 = spm_sp(':', sX, varargin{5});
if isempty(X0),
Fc.c = spm_sp('xpx',sX);
Fc.X1o.ukX1o = spm_sp('cukx',sX);
Fc.X0.ukX0 = [];
elseif size(X0,1) ~= sC,
error('dimension of X0 wrong in Set');
else
Fc.c = spm_SpUtil('X0->c',sX,X0);
Fc.X0.ukX0 = spm_sp('ox',sX)'*X0;
Fc.X1o.ukX1o = spm_SpUtil('+c->Tsp',sX,Fc.c);
end
case 'ukX0'
warning('option given for completeness - not for SPM use');
Fc.iX0 = set_action;
if isempty(ukX0),
Fc.c = spm_sp('xpx',sX);
Fc.X1o.ukX1o = spm_sp('cukx',sX);
Fc.X0.ukX0 = [];
elseif size(ukX0,1) ~= spm_sp('rk',sX),
error('dimension of cukX0 wrong in Set');
else
Fc.c = spm_SpUtil('+X0->c',sX,ukX0);
Fc.X0.ukX0 = ukX0;
Fc.X1o.ukX1o = spm_SpUtil('+c->Tsp',sX,Fc.c);
end
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case 'iX0'
iX0 = varargin{5};
iX0 = spm_SpUtil('iX0check',iX0,sL);
Fc.iX0 = iX0;
Fc.X0.ukX0 = spm_sp('ox',sX)' * spm_sp('Xi',sX,iX0);
if isempty(iX0),
Fc.c = spm_sp('xpx',sX);
Fc.X1o.ukX1o = spm_sp('cukx',sX);
else
Fc.c = spm_SpUtil('i0->c',sX,iX0);
Fc.X1o.ukX1o = spm_SpUtil('+c->Tsp',sX,Fc.c);
end
otherwise
error('wrong action in Set ');
end
varargout = {Fc};
case 'x0' % spm_FcUtil('X0',Fc,sX)
%=======================================================================
if nargin ~= 3,
error('too few/many input arguments - need 2');
else
Fc = varargin{2}; sX = varargin{3};
end
if nargout ~= 1, error('too few/many output arguments - need 1'), end
if ~sf_IsFcon(Fc), error('argument is not a contrast struct'), end
if ~spm_sp('isspc',sX), sX = spm_sp('set',sX); end
varargout = {sf_X0(Fc,sX)};
case 'x1o' % spm_FcUtil('X1o',Fc,sX)
%=======================================================================
if nargin ~= 3,
error('too few/many input arguments - need 2');
else
Fc = varargin{2}; sX = varargin{3};
end
if nargout ~= 1, error('too few/many output arguments - need 1'), end
if ~sf_IsFcon(Fc), error('argument is not a contrast struct'), end
if ~spm_sp('isspc',sX), sX = spm_sp('set',sX); end
varargout = {sf_X1o(Fc,sX)};
case 'isfcon' %- Is it an F contrast ?
%=======================================================================
% yes_no = spm_FcUtil('IsFcon',Fc)
if nargin~=2, error('too few/many input arguments - need 2'), end
if ~isstruct(varargin{2}), varargout={0};
else varargout = {sf_IsFcon(varargin{2})};
end
case 'fconedf' %- F contrast edf
%=======================================================================
% [edf_tsp edf_Xsp] = spm_FcUtil('FconEdf', Fc, sX [, V])
if nargin<3, error('Insufficient arguments'), end
if nargout >= 3, error('Too many output argument.'), end
Fc = varargin{2};
sX = varargin{3};
if nargin == 4, V = varargin{4}; else V = []; end
if ~sf_IsFcon(Fc), error('Fc must be Fcon'), end
if ~spm_sp('isspc',sX)
sX = spm_sp('set',sX); end
if ~sf_isempty_X1o(Fc)
[trMV, trMVMV] = spm_SpUtil('trMV',sf_X1o(Fc,sX),V);
else
trMV = 0;
trMVMV = 0;
end
if ~trMVMV, edf_tsp = 0; warning('edf_tsp = 0'),
else edf_tsp = trMV^2/trMVMV; end;
if nargout == 2
[trRV, trRVRV] = spm_SpUtil('trRV',sX,V);
if ~trRVRV, edf_Xsp = 0; warning('edf_Xsp = 0'),
else edf_Xsp = trRV^2/trRVRV; end;
varargout = {edf_tsp, edf_Xsp};
else
varargout = {edf_tsp};
end
%=======================================================================
%=======================================================================
% parts that use F contrast
%=======================================================================
%=======================================================================
%
% Quick reference : L : can be lists of ...
%-------------------------
% ('Hsqr',Fc, sX) : Out: Hsqr / ESS = b' * Hsqr' * Hsqr * b
% ('H',Fc, sX) : Out: H / ESS = b' * H * b
% ('Yc',Fc, sX, b) : Out: Y corrected = X*b - X0*X0- *Y
% ('Y0',Fc, sX, b) : Out: Y0 = X0*X0- *Y
% ('|_',LFc1, sX, LFc2) : Out: Fc1 orthog. wrt Fc2
% ('|_?',LFc1,sX [,LFc2]): Out: is Fc2 ortho to Fc1 or is Fc1 ortho ?
% ('In', LFc1, sX, LFc2) : Out: indices of Fc2 if "in", 0 otherwise
% ('~unique', LFc, sX) : Out: indices of redundant contrasts
% ('0|[]', Fc, sX) : Out: 1 if Fc is zero or empty, 0 otherwise
case 'hsqr' %-Extra sum of squares matrix for beta's from contrast
%=======================================================================
% hsqr = spm_FcUtil('Hsqr',Fc, sX)
if nargin<3, error('Insufficient arguments'), end
if nargout>1, error('Too many output argument.'), end
Fc = varargin{2};
sX = varargin{3};
if ~sf_IsFcon(Fc), error('Fc must be F-contrast'), end
if ~sf_IsSet(Fc), error('Fcon must be set'); end; %-
if ~spm_sp('isspc',sX), sX = spm_sp('set',sX); end;
if sf_isempty_X1o(Fc)
if ~sf_isempty_X0(Fc)
%- assumes that X0 is sX.X
%- warning(' Empty X1o in spm_FcUtil(''Hsqr'',Fc,sX) ');
varargout = { zeros(1,spm_sp('size',sX,2)) };
else
error(' Fc must be set ');
end
else
varargout = { sf_Hsqr(Fc,sX) };
end
case 'h' %-Extra sum of squares matrix for beta's from contrast
%=======================================================================
% H = spm_FcUtil('H',Fc, sX)
% Empty and zeros dealing :
% This routine never returns an empty matrix.
% If sf_isempty_X1o(Fc) | isempty(Fc.c) it explicitly
% returns a zeros projection matrix.
if nargin<2, error('Insufficient arguments'), end
if nargout>1, error('Too many output argument.'), end
Fc = varargin{2};
sX = varargin{3};
if ~sf_IsFcon(Fc), error('Fc must be F-contrast'), end
if ~sf_IsSet(Fc), error('Fcon must be set'); end; %-
if ~spm_sp('isspc',sX), sX = spm_sp('set',sX); end;
if sf_isempty_X1o(Fc)
if ~sf_isempty_X0(Fc)
%- assumes that X0 is sX.X
%- warning(' Empty X1o in spm_FcUtil(''H'',Fc,sX) ');
varargout = { zeros(spm_sp('size',sX,2)) };
else
error(' Fc must be set ');
end
else
varargout = { sf_H(Fc,sX) };
end
case 'yc' %- Fitted data corrected for confounds defined by Fc
%=======================================================================
% Yc = spm_FcUtil('Yc',Fc, sX, b)
if nargin < 4, error('Insufficient arguments'), end
if nargout > 1, error('Too many output argument.'), end
Fc = varargin{2}; sX = varargin{3}; b = varargin{4};
if ~sf_IsFcon(Fc), error('Fc must be F-contrast'), end
if ~sf_IsSet(Fc), error('Fcon must be set'); end;
if ~spm_sp('isspc',sX), sX = spm_sp('set',sX); end;
% if ~spm_FcUtil('Rcompatible',Fc,sX), ...
% error('sX and Fc must be compatible'), end;
if spm_sp('size',sX,2) ~= size(b,1),
error('sX and b must be compatible'), end;
if sf_isempty_X1o(Fc)
if ~sf_isempty_X0(Fc)
%- if space of interest empty or null, returns zeros !
varargout = { zeros(spm_sp('size',sX,1),size(b,2)) };
else
error(' Fc must be set ');
end
else
varargout = { sf_Yc(Fc,sX,b) };
end
case 'y0' %- Fitted data corrected for confounds defined by Fc
%=======================================================================
% Y0 = spm_FcUtil('Y0',Fc, sX, b)
if nargin < 4, error('Insufficient arguments'), end
if nargout > 1, error('Too many output argument.'), end
Fc = varargin{2}; sX = varargin{3}; b = varargin{4};
if ~sf_IsFcon(Fc), error('Fc must be F-contrast'), end
if ~sf_IsSet(Fc), error('Fcon must be set'); end;
if ~spm_sp('isspc',sX), sX = spm_sp('set',sX); end;
if spm_sp('size',sX,2) ~= size(b,1),
error('sX and b must be compatible'), end;
if sf_isempty_X1o(Fc)
if ~sf_isempty_X0(Fc)
%- if space of interest empty or null, returns zeros !
varargout = { sX.X*b };
else
error(' Fc must be set ');
end
else
varargout = { sf_Y0(Fc,sX,b) };
end
case {'|_'} %- Fc orthogonalisation
%=======================================================================
% Fc = spm_FcUtil('|_',Fc1, sX, Fc2)
% returns Fc1 orthogonolised wrt Fc2
if nargin < 4, error('Insufficient arguments'), end
if nargout > 1, error('Too many output argument.'), end
Fc1 = varargin{2}; sX = varargin{3}; Fc2 = varargin{4};
%-check arguments
%-----------------------------------------------------------------------
L1 = length(Fc1);
if ~L1, warning('no contrast given to |_'); varargout = {[]}; return; end
for i=1:L1
if ~sf_IsFcon(Fc1(i)), error('Fc1(i) must be a contrast'), end
end
L2 = length(Fc2);
if ~L2, error('must have at least a contrast in Fc2'); end
for i=1:L2
if ~sf_IsFcon(Fc2(i)), error('Fc2(i) must be a contrast'), end
end
if ~spm_sp('isspc',sX), sX = spm_sp('set',sX); end;
%-create an F-contrast for all the Fc2
%--------------------------------------------------------------------------
str = Fc2(1).name; for i=2:L2 str = [str ' ' Fc2(i).name]; end;
Fc2 = spm_FcUtil('Set',str,'F','c+',cat(2,Fc2(:).c),sX);
if sf_isempty_X1o(Fc2) || sf_isnull(Fc2,sX)
varargout = {Fc1};
else
for i=1:L1
if sf_isempty_X1o(Fc1(i)) || sf_isnull(Fc1(i),sX)
%- Fc1(i) is an [] or 0 contrast : ortho to anything;
out(i) = Fc1(i);
else
out(i) = sf_fcortho(Fc1(i), sX, Fc2);
end
end
varargout = {out};
end
case {'|_?'} %- Are contrasts orthogonals
%=======================================================================
% b = spm_FcUtil('|_?',Fc1, sX [, Fc2])
if nargin < 3, error('Insufficient arguments'), end
Fc1 = varargin{2}; sX = varargin{3};
if nargin > 3, Fc2 = varargin{4}; else Fc2 = []; end;
if isempty(Fc1), error('give at least one non empty contrast'), end;
if ~spm_sp('isspc',sX), sX = spm_sp('set',sX); end;
for i=1:length(Fc1)
if ~sf_IsFcon(Fc1(i)), error('Fc1(i) must be a contrast'), end
end
for i=1:length(Fc2)
if ~sf_IsFcon(Fc2(i)), error('Fc2(i) must be a contrast'), end
end
varargout = { sf_Rortho(Fc1,sX,Fc2) };
case 'in' %- Fc1 is in list of contrasts Fc2
%=======================================================================
% [iFc2 iFc1] = spm_FcUtil('In', Fc1, sX, Fc2)
% returns indice of Fc2 if "in", 0 otherwise
% NB : If T- stat, the routine checks whether Fc.c is of
% size one. This is ensure if contrast is set
% or manipulated (ortho ..) with spm_FcUtil
% note that the algorithmn works \emph{only because} Fc2(?).c
% and Fc1.c are in space(X')
if nargin < 4, error('Insufficient arguments'), end
if nargout > 2, error('Too many output argument.'), end
Fc1 = varargin{2}; Fc2 = varargin{4}; sX = varargin{3};
L1 = length(Fc1);
if ~L1, warning('no contrast given to in');
if nargout == 2, varargout = {[] []};
else varargout = {[]}; end;
return;
end
for i=1:L1
if ~sf_IsFcon(Fc1(i)), error('Fc1(i) must be a contrast'), end
end
L2 = length(Fc2);
if ~L2, error('must have at least a contrast in Fc2'); end
for i=1:L2
if ~sf_IsFcon(Fc2(i)), error('Fc2(i) must be F-contrast'), end
end
if ~spm_sp('isspc',sX), sX = spm_sp('set',sX); end;
[idxFc2 idxFc1] = sf_in(Fc1, sX, Fc2);
if isempty(idxFc2), idxFc2 = 0; end
if isempty(idxFc1), idxFc1 = 0; end
switch nargout
case {0,1}
varargout = { idxFc2 };
case 2
varargout = { idxFc2 idxFc1 };
otherwise
error('Too many or not enough output arguments');
end
case '~unique' %- Fc list unique
%=======================================================================
% idx = spm_FcUtil('~unique', Fc, sX)
%- returns indices of redundant contrasts in Fc
%- such that Fc(idx) = [] makes Fc unique.
%- if already unique returns []
if nargin ~= 3, error('Insufficient/too many arguments'), end
Fc = varargin{2}; sX = varargin{3};
%----------------------------
L1 = length(Fc);
if ~L1, warning('no contrast given '); varargout = {[]}; return; end
for i=1:L1
if ~sf_IsFcon(Fc(i)), error('Fc(i) must be a contrast'), end
end
if ~spm_sp('isspc',sX), sX = spm_sp('set',sX); end;
%----------------------------
varargout = { unique(sf_notunique(Fc, sX))};
case {'0|[]','[]|0'} %- Fc is null or empty
%=======================================================================
% b = spm_FcUtil('0|[]', Fc, sX)
% returns 1 if F-contrast is empty or null; assumes the contrast is set.
if nargin ~= 3, error('Insufficient/too many arguments'), end
Fc = varargin{2}; sX = varargin{3};
%----------------------------
L1 = length(Fc);
if ~L1, warning('no contrast given to |_'); varargout = {[]}; return; end
for i=1:L1
if ~sf_IsFcon(Fc(i)), error('Fc(i) must be a contrast'), end
end
if ~spm_sp('isspc',sX), sX = spm_sp('set',sX); end;
%----------------------------
idx = [];
for i=1:L1
if sf_isempty_X1o(Fc(i)) || sf_isnull(Fc(i),sX), idx = [idx i]; end
end
if isempty(idx)
varargout = {0};
else
varargout = {idx};
end
%=======================================================================
otherwise
%=======================================================================
error('Unknown action string in spm_FcUtil')
end; %---- switch lower(action),
%=======================================================================
%=======================================================================
% Sub Functions
%=======================================================================
%=======================================================================
%=======================================================================
% Fcon = spm_FcUtil('FconFields')
function Fc = sf_FconFields
Fc = struct(...
'name', '',...
'STAT', '',...
'c', [],...
'X0', struct('ukX0',[]),...
'iX0', [],...
'X1o', struct('ukX1o',[]),...
'eidf', [],...
'Vcon', [],...
'Vspm', []);
%=======================================================================
% used internally. Minimum contrast structure
function minFc = sf_MinFcFields
minFc = struct(...
'name', '',...
'STAT', '',...
'c', [],...
'X0', [],...
'X1o', []);
%=======================================================================
% yes_no = spm_FcUtil('IsFcon',Fc)
function b = sf_IsFcon(Fc)
%- check that minimum fields of a contrast are in Fc
b = 1;
minnames = fieldnames(sf_MinFcFields);
FCnames = fieldnames(Fc);
for str = minnames'
b = b & any(strcmp(str,FCnames));
if ~b, break, end
end
%=======================================================================
% used internally; To be set, a contrast structure should have
% either X1o or X0 non empty. X1o can be non empty because c
% is non empty.
function b = sf_IsSet(Fc)
b = ~sf_isempty_X0(Fc) | ~sf_isempty_X1o(Fc);
%=======================================================================
% used internally
%
function v = sf_ver(Fc)
if isstruct(Fc.X0), v = 2; else v = 1; end
%=======================================================================
% used internally
function b = sf_isempty_X1o(Fc)
if sf_ver(Fc) > 1,
b = isempty(Fc.X1o.ukX1o);
%- consistency check
if b ~= isempty(Fc.c),
Fc.c, Fc.X1o.ukX1o, error('Contrast internally not consistent');
end
else
b = isempty(Fc.X1o);
%- consistency check
if b ~= isempty(Fc.c),
Fc.c, Fc.X1o, error('Contrast internally not consistent');
end
end
%=======================================================================
% used internally
function b = sf_X1o(Fc,sX)
if sf_ver(Fc) > 1,
b = spm_sp('ox',sX)*Fc.X1o.ukX1o;
else
b = Fc.X1o;
end
%=======================================================================
% used internally
function b = sf_X0(Fc,sX)
if sf_ver(Fc) > 1,
b = spm_sp('ox',sX)*Fc.X0.ukX0;
else
b = Fc.X0;
end
%=======================================================================
% used internally
function b = sf_isempty_X0(Fc)
if sf_ver(Fc) > 1,
b = isempty(Fc.X0.ukX0);
else
b = isempty(Fc.X0);
end
%=======================================================================
% Hsqr = spm_Fcutil('Hsqr',Fc,sX)
function hsqr = sf_Hsqr(Fc,sX)
%
% Notations : H equiv to X1o, H = uk*a1, X = uk*ax, r = rk(sX),
% sX.X is (n,p), H is (n,q), a1 is (r,q), ax is (r,p)
% oxa1 is an orthonormal basis for a1, oxa1 is (r,qo<=q)
% Algorithm :
% v1 : Y'*H*(H'*H)-*H'*Y = b'*X'*H*(H'*H)-*H'*X*b
% = b'*X'*oxH*oxH'*X*b
% so hsrq is set to oxH'*X, a (q,n)*(n,p) op. + computation of oxH
% v2 : X'*H*(H'*H)-*H'*X = ax'*uk'*uk*a1*(a1'*uk'*uk*a1)-*a1'*uk'*uk*ax
% = ax'*a1*(a1'*a1)-*a1'*ax
% = ax'*oxa1*oxa1'*ax
%
% so hsrq is set to oxa1'*ax : a (qo,r)*(r,p) operation! -:))
% + computation of oxa1.
%-**** fprintf('v%d\n',sf_ver(Fc));
if sf_ver(Fc) > 1,
hsqr = spm_sp('ox',spm_sp('set',Fc.X1o.ukX1o))' * spm_sp('cukx',sX);
else
hsqr = spm_sp('ox',spm_sp('set',Fc.X1o))'*spm_sp('x',sX);
end
%=======================================================================
% H = spm_FcUtil('H',Fc)
function H = sf_H(Fc,sX)
%
% Notations : H equiv to X1o, H = uk*a1, X = uk*ax
% Algorithm :
% v1 : Y'*H*(H'*H)-*H'*Y = b'*X'*H*(H'*H)-*H'*X*b
% = b'*c*(H'*H)-*c'*b
% = b'*c*(c'*(X'*X)-*c)-*c'*b
%- v1 : Note that pinv(Fc.X1o' * Fc.X1o) is not too bad
%- because dimensions are only (q,q). See sf_hsqr for notations.
%- Fc.c and Fc.X1o should match. This is ensure by using FcUtil.
%-**** fprintf('v%d\n',sf_ver(Fc));
if sf_ver(Fc) > 1,
hsqr = sf_Hsqr(Fc,sX);
H = hsqr' * hsqr;
else
H = Fc.c * pinv(Fc.X1o' * Fc.X1o) * Fc.c';
% H = {c*spm_sp('x-',spm_sp('Set',c'*spm_sp('xpx-',sX)*c) )*c'}
end
%=======================================================================
% Yc = spm_FcUtil('Yc',Fc,sX,b)
function Yc = sf_Yc(Fc,sX,b)
Yc = sX.X*spm_sp('xpx-',sX)*sf_H(Fc,sX)*b;
%=======================================================================
% Y0 = spm_FcUtil('Y0',Fc,sX,b)
function Y0 = sf_Y0(Fc,sX,b)
Y0 = sX.X*(eye(spm_sp('size',sX,2)) - spm_sp('xpx-',sX)*sf_H(Fc,sX))*b;
%=======================================================================
% Fc = spm_FcUtil('|_',Fc1, sX, Fc2)
function Fc1o = sf_fcortho(Fc1, sX, Fc2)
%--- use the space facility to ensure the proper tolerance dealing...
c1_2 = Fc1.c - sf_H(Fc2,sX)*spm_sp('xpx-:',sX,Fc1.c);
Fc1o = spm_FcUtil('Set',['(' Fc1.name ' |_ (' Fc2.name '))'], ...
Fc1.STAT, 'c+',c1_2,sX);
%- In the large (scans) dimension :
%- c = sX.X'*spm_sp('r:',spm_sp('set',Fc2.X1o),Fc1.X1o);
%- Fc1o = spm_FcUtil('Set',['(' Fc1.name ' |_ (' Fc2.name '))'], ...
%- Fc1.STAT, 'c',c,sX);
%=======================================================================
function b = sf_Rortho(Fc1,sX,Fc2)
if isempty(Fc2)
if length(Fc1) <= 1, b = 0;
else
c1 = cat(2,Fc1(:).c);
b = ~any(any( abs(triu(c1'*spm_sp('xpx-:',sX,c1), 1)) > sX.tol));
end
else
c1 = cat(2,Fc1(:).c); c2 = cat(2,Fc2(:).c);
b = ~any(any( abs(c1'*spm_sp('xpx-:',sX,c2)) > sX.tol ));
end
%=======================================================================
% b = spm_FcUtil('0|[]', Fc, sX)
%- returns 1 if F-contrast is empty or null; assumes the contrast is set.
%- Assumes that if Fc.c contains only zeros, so does Fc.X1o.
%- this is ensured if spm_FcUtil is used
function boul = sf_isnull(Fc,sX)
%
boul = ~any(any(spm_sp('oPp:',sX,Fc.c)));
%=======================================================================
% Fc = spm_FcUtil('Set',name, STAT, set_action, value, sX)
function boul = sf_is_T(sX,c)
%- assumes that the dimensions are OK
%- assumes c is not empty
%- Does NOT assumes that c is space of sX'
%- A rank of zero can be defined
%- if the rank == 1, checks whether same directions
boul = 1;
if ~spm_sp('isinspp',sX,c), c = spm_sp('oPp:',sX,c); end;
if rank(c) > 1 || any(any(c'*c < 0)), boul = 0; end;
%=======================================================================
function [idxFc2, idxFc1] = sf_in(Fc1, sX, Fc2)
L2 = length(Fc2);
L1 = length(Fc1);
idxFc1 = []; idxFc2 = [];
for j=1:L1
%- project Fc1(j).c if not estimable
if ~spm_sp('isinspp',sX,Fc1(j).c), %- warning ?
c1 = spm_sp('oPp:',sX,Fc1(j).c);
else
c1 = Fc1(j).c;
end
sc1 = spm_sp('Set',c1);
S = Fc1(j).STAT;
boul = 0;
for i =1:L2
if Fc2(i).STAT == S
%- the same statistics. else just go on to the next contrast
boul = spm_sp('==',sc1,spm_sp('oPp',sX,Fc2(i).c));
%- if they are the same space and T stat (same direction),
%- then check wether they are in the same ORIENTATION
%- works because size(X1o,2) == 1, else .* with (Fc1(j).c'*Fc2(i).c)
if boul && S == 'T'
atmp = sf_X1o(Fc1(j),sX);
btmp = sf_X1o(Fc2(i),sX);
boul = ~any(any( (atmp' * btmp) < 0 ));
end
%- note the indices
if boul, idxFc1 = [idxFc1 j]; idxFc2 = [idxFc2 i]; end
end
end
end %- for j=1:L1
%=======================================================================
function idx = sf_notunique(Fc, sX)
%- works recursively ...
%- and use the fact that [] + i == []
%- quite long for large sets ...
l = length(Fc);
if l == 1, idx = [];
else
idx = [ (1+sf_in(Fc(1),sX,Fc(2:l))) (1+sf_notunique(Fc(2:l), sX))];
end
|
github
|
philippboehmsturm/antx-master
|
spm_read_hdr.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_read_hdr.m
| 5,627 |
utf_8
|
785bdd356119ce704a546f3774cd819e
|
function [hdr,otherendian] = spm_read_hdr(fname)
% Read (SPM customised) Analyze header
% FORMAT [hdr,otherendian] = spm_read_hdr(fname)
% fname - .hdr filename
% hdr - structure containing Analyze header
% otherendian - byte swapping necessary flag
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_read_hdr.m 4310 2011-04-18 16:07:35Z guillaume $
fid = fopen(fname,'r','native');
otherendian = 0;
if (fid > 0)
dime = read_dime(fid);
if dime.dim(1)<0 || dime.dim(1)>15, % Appears to be other-endian
% Re-open other-endian
fclose(fid);
if spm_platform('bigend'), fid = fopen(fname,'r','ieee-le');
else fid = fopen(fname,'r','ieee-be'); end;
otherendian = 1;
dime = read_dime(fid);
end;
hk = read_hk(fid);
hist = read_hist(fid);
hdr.hk = hk;
hdr.dime = dime;
hdr.hist = hist;
% SPM specific bit - unused
%if hdr.hk.sizeof_hdr > 348,
% spmf = read_spmf(fid,dime.dim(5));
% if ~isempty(spmf),
% hdr.spmf = spmf;
% end;
%end;
fclose(fid);
else
hdr = [];
otherendian = NaN;
%error(['Problem opening header file (' fopen(fid) ').']);
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function hk = read_hk(fid)
% read (struct) header_key
%-----------------------------------------------------------------------
fseek(fid,0,'bof');
hk.sizeof_hdr = fread(fid,1,'int32');
hk.data_type = mysetstr(fread(fid,10,'uchar'))';
hk.db_name = mysetstr(fread(fid,18,'uchar'))';
hk.extents = fread(fid,1,'int32');
hk.session_error = fread(fid,1,'int16');
hk.regular = mysetstr(fread(fid,1,'uchar'))';
hk.hkey_un0 = mysetstr(fread(fid,1,'uchar'))';
if isempty(hk.hkey_un0), error(['Problem reading "hk" of header file (' fopen(fid) ').']); end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function dime = read_dime(fid)
% read (struct) image_dimension
%-----------------------------------------------------------------------
fseek(fid,40,'bof');
dime.dim = fread(fid,8,'int16')';
dime.vox_units = mysetstr(fread(fid,4,'uchar'))';
dime.cal_units = mysetstr(fread(fid,8,'uchar'))';
dime.unused1 = fread(fid,1,'int16');
dime.datatype = fread(fid,1,'int16');
dime.bitpix = fread(fid,1,'int16');
dime.dim_un0 = fread(fid,1,'int16');
dime.pixdim = fread(fid,8,'float')';
dime.vox_offset = fread(fid,1,'float');
dime.funused1 = fread(fid,1,'float');
dime.funused2 = fread(fid,1,'float');
dime.funused3 = fread(fid,1,'float');
dime.cal_max = fread(fid,1,'float');
dime.cal_min = fread(fid,1,'float');
dime.compressed = fread(fid,1,'int32');
dime.verified = fread(fid,1,'int32');
dime.glmax = fread(fid,1,'int32');
dime.glmin = fread(fid,1,'int32');
if isempty(dime.glmin), error(['Problem reading "dime" of header file (' fopen(fid) ').']); end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function hist = read_hist(fid)
% read (struct) data_history
%-----------------------------------------------------------------------
fseek(fid,148,'bof');
hist.descrip = mysetstr(fread(fid,80,'uchar'))';
hist.aux_file = mysetstr(fread(fid,24,'uchar'))';
hist.orient = fread(fid,1,'uchar');
hist.origin = fread(fid,5,'int16')';
hist.generated = mysetstr(fread(fid,10,'uchar'))';
hist.scannum = mysetstr(fread(fid,10,'uchar'))';
hist.patient_id = mysetstr(fread(fid,10,'uchar'))';
hist.exp_date = mysetstr(fread(fid,10,'uchar'))';
hist.exp_time = mysetstr(fread(fid,10,'uchar'))';
hist.hist_un0 = mysetstr(fread(fid,3,'uchar'))';
hist.views = fread(fid,1,'int32');
hist.vols_added = fread(fid,1,'int32');
hist.start_field= fread(fid,1,'int32');
hist.field_skip = fread(fid,1,'int32');
hist.omax = fread(fid,1,'int32');
hist.omin = fread(fid,1,'int32');
hist.smax = fread(fid,1,'int32');
hist.smin = fread(fid,1,'int32');
if isempty(hist.smin), error(['Problem reading "hist" of header file (' fopen(fid) ').']); end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function spmf = read_spmf(fid,n)
% Read SPM specific fields
% This bit may be used in the future for extending the Analyze header.
fseek(fid,348,'bof');
mgc = fread(fid,1,'int32'); % Magic number
if mgc ~= 20020417, spmf = []; return; end;
for j=1:n,
spmf(j).mat = fread(fid,16,'double'); % Orientation information
spmf(j).unused = fread(fid,384,'uchar'); % Extra unused stuff
if length(spmf(j).unused)<384,
error(['Problem reading "spmf" of header file (' fopen(fid) ').']);
end;
spmf(j).mat = reshape(spmf(j).mat,[4 4]);
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function out = mysetstr(in)
tmp = find(in == 0);
tmp = min([min(tmp) length(in)]);
out = char([in(1:tmp)' zeros(1,length(in)-(tmp))])';
return;
%_______________________________________________________________________
%_______________________________________________________________________
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_inv_visu3D_api.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_eeg_inv_visu3D_api.m
| 28,460 |
utf_8
|
31ed5e0329581a73574a4b7986a89440
|
function varargout = spm_eeg_inv_visu3D_api(varargin)
% SPM_EEG_INV_VISU3D_API M-file for spm_eeg_inv_visu3D_api.fig
% - FIG = SPM_EEG_INV_VISU3D_API launch spm_eeg_inv_visu3D_api GUI.
% - D = SPM_EEG_INV_VISU3D_API(D) open with D
% - SPM_EEG_INV_VISU3D_API(filename) where filename is the eeg/meg .mat file
% - SPM_EEG_INV_VISU3D_API('callback_name', ...) invoke the named callback.
%
% Last Modified by GUIDE v2.5 18-Feb-2011 14:23:27
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Jeremie Mattout
% $Id: spm_eeg_inv_visu3D_api.m 4211 2011-02-23 16:00:02Z vladimir $
% INITIALISATION CODE
%--------------------------------------------------------------------------
if nargin == 0 || nargin == 1 % LAUNCH GUI
% open new api
%----------------------------------------------------------------------
fig = openfig(mfilename,'new');
handles = guihandles(fig);
handles.fig = fig;
guidata(fig,handles);
set(fig,'Color',get(0,'defaultUicontrolBackgroundColor'));
% load D if possible and try to open
%----------------------------------------------------------------------
try
handles.D = spm_eeg_inv_check(varargin{1});
set(handles.DataFile,'String',handles.D.fname)
spm_eeg_inv_visu3D_api_OpeningFcn(fig, [], handles)
end
% return figure handle if necessary
%----------------------------------------------------------------------
if nargout > 0
varargout{1} = fig;
end
elseif ischar(varargin{1})
try
if (nargout)
[varargout{1:nargout}] = feval(varargin{:}); % FEVAL switchyard
else
feval(varargin{:}); % FEVAL switchyard
end
catch
disp(lasterror);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% --- Executes just before spm_eeg_inv_visu3D_api is made visible.
function spm_eeg_inv_visu3D_api_OpeningFcn(hObject, eventdata, handles)
% 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)
% LOAD DATA
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
try
D = handles.D;
catch
D = spm_eeg_load(spm_select(1, '.mat', 'Select EEG/MEG mat file'));
end
if ~isfield(D,'inv')
error('Please specify and invert a forward model\n');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% GET RESULTS (default: current or last analysis)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
figure(handles.fig);
axes(handles.sensors_axes);
try, val = D.val; catch, val = 1; D.val = 1; end
try, con = D.con; catch, con = 1; D.con = 1; end
if (D.con == 0) || (D.con > length(D.inv{D.val}.inverse.J))
con = 1; D.con = 1;
end
handles.D = D;
set(handles.DataFile,'String',D.fname);
set(handles.next,'String',sprintf('model %i',val));
set(handles.con, 'String',sprintf('condition %i',con));
set(handles.fig,'name',['Source visualisation -' D.fname])
if strcmp(D.inv{val}.method,'ECD')
warndlg('Please create an imaging solution');
guidata(hObject,handles);
return
end
set(handles.LogEv,'String',num2str(D.inv{val}.inverse.F));
set(handles.LogEv,'Enable','inactive');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% OBSERVED ACTIVITY
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% start with response
%--------------------------------------------------------------------------
try
% Load Gain or Lead field matrix
%----------------------------------------------------------------------
dimT = 256;
dimS = D.inv{val}.inverse.Nd;
Is = D.inv{val}.inverse.Is;
L = D.inv{val}.inverse.L;
U = D.inv{val}.inverse.U;
T = D.inv{val}.inverse.T;
Y = D.inv{val}.inverse.Y{con};
Ts = ceil(linspace(1,size(T,1),dimT));
% source data
%----------------------------------------------------------------------
set(handles.Activity,'Value',1);
J = sparse(dimS,dimT);
J(Is,:) = D.inv{val}.inverse.J{con}*T(Ts,:)';
handles.dimT = dimT;
handles.dimS = dimS;
handles.pst = D.inv{val}.inverse.pst(Ts);
handles.srcs_data = J;
handles.Nmax = max(abs(J(:)));
handles.Is = Is;
% sensor data
%----------------------------------------------------------------------
if ~iscell(U)
U = {U'};
end
A = spm_pinv(spm_cat(spm_diag(U))')';
handles.sens_data = A*Y*T(Ts,:)';
handles.pred_data = A*L*J(Is,:);
catch
warndlg({'Please invert your model';'inverse solution not valid'});
return
end
% case 'windowed response' or contrast'
%--------------------------------------------------------------------------
try
JW = sparse(dimS,1);
GW = sparse(dimS,1);
JW(Is,:) = D.inv{val}.contrast.JW{con};
GW(Is,:) = D.inv{val}.contrast.GW{con};
handles.woi = D.inv{val}.contrast.woi;
handles.fboi = D.inv{val}.contrast.fboi;
handles.W = D.inv{val}.contrast.W(Ts,:);
handles.srcs_data_w = JW;
handles.sens_data_w = handles.sens_data*handles.W(:,1);
handles.pred_data_w = handles.pred_data*handles.W(:,1);
handles.srcs_data_ev = GW;
handles.sens_data_ev = sum((handles.sens_data*handles.W).^2,2);
handles.pred_data_ev = sum((handles.pred_data*handles.W).^2,2);
set(handles.Activity,'enable','on');
catch
set(handles.Activity,'enable','off');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% LOAD CORTICAL MESH (default: Individual)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
try
vert = D.inv{val}.mesh.tess_mni.vert;
face = D.inv{val}.mesh.tess_mni.face;
set(handles.Template, 'Value',1);
set(handles.Individual,'Value',0);
catch
try
vert = D.inv{val}.mesh.tess_ctx.vert;
face = D.inv{val}.mesh.tess_ctx.face;
set(handles.Template, 'Value',0);
set(handles.Individual,'Value',1);
catch
warndlg('There is no mesh associated with these data');
return
end
end
handles.vert = vert;
handles.face = face;
handles.grayc = sqrt(sum((vert.^2),2)); handles.grayc = handles.grayc'/max(handles.grayc);
clear vert face
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SLIDER INITIALISATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
set(handles.slider_transparency,'Min',0,'Max',1,'Value',1,'sliderstep',[0.01 0.05]);
set(handles.slider_srcs_up, 'Min',0,'Max',1,'Value',0,'sliderstep',[0.01 0.05]);
set(handles.slider_srcs_down, 'Min',0,'Max',1,'Value',1,'sliderstep',[0.01 0.05]);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% INITIAL SOURCE LEVEL DISPLAY
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
axes(handles.sources_axes);
cla; axis off
set(handles.slider_time, 'Enable','on');
set(handles.time_bin, 'Enable','on');
set(handles.slider_time, 'Value',1);
set(handles.time_bin, 'String',num2str(fix(handles.pst(1))));
set(handles.slider_time, 'Min',1,'Max',handles.dimT,'sliderstep',[1/(handles.dimT-1) 2/(handles.dimT-1)]);
set(handles.checkbox_absv,'Enable','on','Value',1);
set(handles.checkbox_norm,'Enable','on','Value',0);
srcs_disp = full(abs(handles.srcs_data(:,1)));
handles.fig1 = patch('vertices',handles.vert,'faces',handles.face,'FaceVertexCData',srcs_disp);
% display
%--------------------------------------------------------------------------
set(handles.fig1,'FaceColor',[.5 .5 .5],'EdgeColor','none');
shading interp
lighting gouraud
camlight
zoom off
lightangle(0,270);lightangle(270,0),lightangle(0,0),lightangle(90,0);
material([.1 .1 .4 .5 .4]);
view(140,15);
axis image
handles.colorbar = colorbar;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% LOAD SENSOR FILE
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Ic = {};
if iscell(D.inv{val}.inverse.Ic)
for i = 1:numel(D.inv{val}.inverse.Ic)
if i == 1
Ic{i} = 1:length(D.inv{val}.inverse.Ic{i});
else
Ic{i} = Ic{i-1}(end)+(1:length(D.inv{val}.inverse.Ic{i}));
end
end
else
Ic{1} = 1:length(D.inv{val}.inverse.Ic);
end
handles.Ic = Ic;
coor = D.coor2D(full(spm_cat(D.inv{val}.inverse.Ic)));
xp = coor(1,:)';
yp = coor(2,:)';
x = linspace(min(xp),max(xp),64);
y = linspace(min(yp),max(yp),64);
[xm,ym] = meshgrid(x,y);
handles.sens_coord = [xp yp];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% INITIAL SENSOR LEVEL DISPLAY
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if isfield(D.inv{val}.inverse, 'modality')
set(handles.modality, 'String', D.inv{val}.inverse.modality);
else
set(handles.modality, 'String', 'MEEG'); % This is for backward compatibility with old DCM-IMG
end
figure(handles.fig)
axes(handles.sensors_axes);
cla; axis off
im = get(handles.modality, 'Value');
ic = handles.Ic{im};
disp = full(handles.sens_data(ic,1));
imagesc(x,y,griddata(xp(ic),yp(ic),disp,xm,ym));
axis image xy off
handles.sens_coord_x = x;
handles.sens_coord_y = y;
handles.sens_coord2D_X = xm;
handles.sens_coord2D_Y = ym;
hold on
handles.sensor_loc = plot(handles.sens_coord(ic,1),handles.sens_coord(ic,2),'o','MarkerFaceColor',[1 1 1]/2,'MarkerSize',6);
set(handles.checkbox_sensloc,'Value',1);
hold off
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% INITIAL SENSOR LEVEL DISPLAY - PREDICTED
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
axes(handles.pred_axes); cla;
disp = full(handles.pred_data(ic,1));
imagesc(x,y,griddata(xp(ic),yp(ic),disp,xm,ym));
axis image xy off
drawnow
guidata(hObject,handles);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% UPDATE SOURCE LEVEL DISPLAY
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function UpDate_Display_SRCS(hObject,handles)
axes(handles.sources_axes);
if isfield(handles,'fig1')
ActToDisp = get(handles.Activity,'Value');
A = get(handles.checkbox_absv,'Value');
N = get(handles.checkbox_norm,'Value');
switch ActToDisp
% case 1: response (J)
%------------------------------------------------------------------
case 1
TS = fix(get(handles.slider_time,'Value'));
if A
srcs_disp = abs(handles.srcs_data(:,TS));
else
srcs_disp = handles.srcs_data(:,TS);
end
if N
if A
handles.Vmin = 0;
handles.Vmax = handles.Nmax;
else
handles.Vmin = -handles.Nmax;
handles.Vmax = handles.Nmax;
end
else
handles.Vmin = min(srcs_disp);
handles.Vmax = max(srcs_disp);
end
% case 2: Windowed response (JW)
%------------------------------------------------------------------
case 2
handles.Vmin = min(handles.srcs_data_w);
handles.Vmax = max(handles.srcs_data_w);
srcs_disp = handles.srcs_data_w;
% case 3: Evoked power (JWWJ)
%------------------------------------------------------------------
case 3
handles.Vmin = min(handles.srcs_data_ev);
handles.Vmax = max(handles.srcs_data_ev);
srcs_disp = handles.srcs_data_ev;
% case 4: Induced power (JWWJ)
%------------------------------------------------------------------
case 4
handles.Vmin = min(handles.srcs_data_ind);
handles.Vmax = max(handles.srcs_data_ind);
srcs_disp = handles.srcs_data_ind;
end
set(handles.fig1,'FaceVertexCData',full(srcs_disp));
set(handles.sources_axes,'CLim',[handles.Vmin handles.Vmax]);
set(handles.sources_axes,'CLimMode','manual');
end
% Adjust the threshold
%--------------------------------------------------------------------------
Set_colormap(hObject, [], handles);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% UPDATE SENSOR LEVEL DISPLAY
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function UpDate_Display_SENS(hObject,handles)
TypOfDisp = get(handles.sens_display,'Value');
ActToDisp = get(handles.Activity,'Value');
im = get(handles.modality, 'Value');
ic = handles.Ic{im};
% topography
%--------------------------------------------------------------------------
if TypOfDisp == 1
% responses at one pst
%----------------------------------------------------------------------
if ActToDisp == 1
TS = fix(get(handles.slider_time,'Value'));
sens_disp = handles.sens_data(ic,TS);
pred_disp = handles.pred_data(ic,TS);
% contrast
%----------------------------------------------------------------------
elseif ActToDisp == 2
sens_disp = handles.sens_data_w;
pred_disp = handles.pred_data_w;
% power
%----------------------------------------------------------------------
elseif ActToDisp == 3
sens_disp = handles.sens_data_ev;
pred_disp = handles.pred_data_ev;
end
axes(handles.sensors_axes);
disp = griddata(handles.sens_coord(ic,1),handles.sens_coord(ic,2),full(sens_disp),handles.sens_coord2D_X,handles.sens_coord2D_Y);
imagesc(handles.sens_coord_x,handles.sens_coord_y,disp);
axis image xy off
% add sensor locations
%----------------------------------------------------------------------
try, delete(handles.sensor_loc); end
hold(handles.sensors_axes, 'on');
handles.sensor_loc = plot(handles.sensors_axes,...
handles.sens_coord(ic,1),handles.sens_coord(ic,2),'o','MarkerFaceColor',[1 1 1]/2,'MarkerSize',6);
hold(handles.sensors_axes, 'off');
axes(handles.pred_axes);
disp = griddata(handles.sens_coord(ic,1),handles.sens_coord(ic,2),full(pred_disp),handles.sens_coord2D_X,handles.sens_coord2D_Y);
imagesc(handles.sens_coord_x,handles.sens_coord_y,disp);
axis image xy off;
checkbox_sensloc_Callback(hObject, [], handles);
% time series
%--------------------------------------------------------------------------
elseif TypOfDisp == 2
axes(handles.sensors_axes)
daspect('auto')
handles.fig2 = ...
plot(handles.pst,handles.sens_data(ic, :),'b-.',handles.pst,handles.pred_data(ic, :),'r:');
if ActToDisp > 1
hold on
Scal = norm(handles.sens_data,1)/norm(handles.W,1);
plot(handles.pst,handles.W*Scal,'k')
hold off
end
axis on tight;
axes(handles.pred_axes); cla, axis off
end
% Adjust the threshold
%--------------------------------------------------------------------------
Set_colormap(hObject, [], handles);
guidata(hObject,handles);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% LOAD DATA FILE
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function DataFile_Callback(hObject, eventdata, handles)
S = get(handles.DataFile,'String');
try
D = spm_eeg_ldata(S);
catch
LoadData_Callback(hObject, eventdata, handles);
end
% --- Executes on button press in LoadData.
function LoadData_Callback(hObject, eventdata, handles)
S = spm_select(1, '.mat', 'Select EEG/MEG mat file');
handles.D = spm_eeg_load(S);
spm_eeg_inv_visu3D_api_OpeningFcn(hObject, [], handles);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% ACTIVITY TO DISPLAY
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% --- Executes on selection change in Activity.
function Activity_Callback(hObject, eventdata, handles)
ActToDisp = get(handles.Activity,'Value');
if ActToDisp == 1
set(handles.checkbox_absv, 'Enable','on');
set(handles.checkbox_norm, 'Enable','on');
set(handles.slider_time, 'Enable','on');
set(handles.time_bin, 'Enable','on');
else
set(handles.checkbox_norm, 'Enable','off');
set(handles.slider_time, 'Enable','off');
set(handles.time_bin, 'Enable','off');
end
if ActToDisp == 2
set(handles.checkbox_absv, 'Enable','off');
end
% update displays
%--------------------------------------------------------------------------
UpDate_Display_SRCS(hObject,handles);
UpDate_Display_SENS(hObject,handles);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SWITCH FROM TEMPLATE MESH TO INDIVIDUAL MESH AND BACK
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Individual_Callback(hObject, eventdata, handles)
set(handles.Template,'Value',0);
try
tess_ctx = gifti(handles.D.inv{handles.D.val}.mesh.tess_ctx);
handles.vert = tess_ctx.vertices;
set(handles.Template, 'Value',0);
set(handles.Individual,'Value',1);
end
handles.grayc = sqrt(sum((handles.vert.^2)')); handles.grayc = handles.grayc'/max(handles.grayc);
set(handles.fig1,'vertices',handles.vert,'faces',handles.face);
UpDate_Display_SRCS(hObject,handles);
axes(handles.sources_axes);
axis image;
guidata(hObject,handles);
%--------------------------------------------------------------------------
function Template_Callback(hObject, eventdata, handles)
set(handles.Individual,'Value',0);
try
handles.vert = handles.D.inv{handles.D.val}.mesh.tess_mni.vert;
set(handles.Template, 'Value',1);
set(handles.Individual,'Value',0);
end
handles.grayc = sqrt(sum((handles.vert.^2)')); handles.grayc = handles.grayc'/max(handles.grayc);
set(handles.fig1,'vertices',handles.vert,'faces',handles.face);
UpDate_Display_SRCS(hObject,handles);
axes(handles.sources_axes);
axis image;
guidata(hObject,handles);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% THRESHOLD SLIDERS - SOURCE LEVEL
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% upper threshold
% --- Executes on slider movement.
function slider_srcs_up_Callback(hObject, eventdata, handles)
Set_colormap(hObject, eventdata, handles);
%%% lower threshold
% --- Executes on slider movement.
function slider_srcs_down_Callback(hObject, eventdata, handles)
Set_colormap(hObject, eventdata, handles);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% TRANSPARENCY SLIDER
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% --- Executes on slider movement.
function slider_transparency_Callback(hObject, eventdata, handles)
Transparency = get(hObject,'Value');
set(handles.fig1,'facealpha',Transparency);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% NORMALISE VALUES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% --- Executes on button press in checkbox_norm.
function checkbox_norm_Callback(hObject, eventdata, handles)
UpDate_Display_SRCS(hObject,handles);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% USE ABSOLUTE VALUES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% --- Executes on button press in checkbox_absv.
function checkbox_absv_Callback(hObject, eventdata, handles)
UpDate_Display_SRCS(hObject,handles);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% DISPLAY SENSOR LOCATIONS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% --- Executes on button press in checkbox_sensloc.
function checkbox_sensloc_Callback(hObject, eventdata, handles)
try
if get(handles.checkbox_sensloc,'Value')
set(handles.sensor_loc,'Visible','on');
else
set(handles.sensor_loc,'Visible','off');
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% TIME SLIDER - SOURCE & SENSOR LEVEL
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% --- Executes on slider movement.
function slider_time_Callback(hObject, eventdata, handles)
ST = fix(handles.pst(fix(get(hObject,'Value'))));
set(handles.time_bin,'String',num2str(ST));
% Source and sensor space update
%--------------------------------------------------------------------------
UpDate_Display_SRCS(hObject,handles);
UpDate_Display_SENS(hObject,handles);
% --- Callback function
function time_bin_Callback(hObject, eventdata, handles)
[i ST] = min(abs(handles.pst - str2double(get(hObject,'String'))));
set(handles.slider_time,'Value',fix(ST));
% Source and sensor space update
%--------------------------------------------------------------------------
UpDate_Display_SRCS(hObject,handles);
UpDate_Display_SENS(hObject,handles);
% --- Executes on button press in movie.
%--------------------------------------------------------------------------
function movie_Callback(hObject, eventdata, handles)
global MOVIE
for t = 1:length(handles.pst)
set(handles.slider_time,'Value',t);
ST = fix(handles.pst(t));
set(handles.time_bin,'String',num2str(ST));
UpDate_Display_SRCS(hObject,handles);
% record movie if requested
%----------------------------------------------------------------------
if MOVIE, M(t) = getframe(handles.sources_axes); end;
end
UpDate_Display_SENS(hObject,handles);
try
filename = fullfile(handles.D.path,'SourceMovie');
movie2avi(M,filename,'compression','Indeo3','FPS',24)
end
% --- Executes on button press in movie_sens.
%--------------------------------------------------------------------------
function movie_sens_Callback(hObject, eventdata, handles)
global MOVIE
for t = 1:length(handles.pst)
set(handles.slider_time,'Value',t);
ST = fix(handles.pst(t));
set(handles.time_bin,'String',num2str(ST));
UpDate_Display_SENS(hObject,handles);
% record movie if requested
%----------------------------------------------------------------------
if MOVIE, M(t) = getframe(handles.sensors_axes); end;
end
UpDate_Display_SRCS(hObject,handles);
try
filename = fullfile(handles.D.path,'SensorMovie');
movie2avi(M,filename,'compression','Indeo3','FPS',24)
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% TYPE OF SENSOR LEVEL DISPLAY
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% --- Executes on selection change in sens_display.
function sens_display_Callback(hObject, eventdata, handles)
TypOfDisp = get(handles.sens_display,'Value');
% if time series
%--------------------------------------------------------------------------
if TypOfDisp == 2
set(handles.checkbox_sensloc,'Value',0);
set(handles.checkbox_sensloc,'Enable','off');
else
set(handles.checkbox_sensloc,'Value',1);
set(handles.checkbox_sensloc,'Enable','on');
end
UpDate_Display_SENS(hObject,handles);
% --- Executes on button press in Exit.
%--------------------------------------------------------------------------
function Exit_Callback(hObject, eventdata, handles)
spm_eeg_inv_visu3D_api_OutputFcn(hObject, eventdata, handles);
close(handles.fig);
% --- Executes on button press in Mip.
%--------------------------------------------------------------------------
function Mip_Callback(hObject, eventdata, handles)
ActToDisp = get(handles.Activity,'Value');
if get(handles.Activity,'Value') == 1
PST = str2num(get(handles.time_bin,'String'));
spm_eeg_invert_display(handles.D,PST);
else
spm_eeg_inv_results_display(handles.D);
end
% --- Outputs from this function are returned to the command line.
%--------------------------------------------------------------------------
function varargout = spm_eeg_inv_visu3D_api_OutputFcn(hObject, eventdata, handles)
D = handles.D;
if nargout == 1
varargout{1} = D;
end
% --- rest threshold
%--------------------------------------------------------------------------
function Set_colormap(hObject, eventdata, handles)
NewMap = jet;
% unsigned values
%--------------------------------------------------------------------------
if get(handles.checkbox_absv,'Value') || get(handles.Activity,'Value') == 3
UpTh = get(handles.slider_srcs_up, 'Value');
N = length(NewMap);
Low = fix(N*UpTh);
Hig = fix(N - N*UpTh);
i = [ones(Low,1); [1:Hig]'*N/Hig];
NewMap = NewMap(fix(i),:);
% signed values
%--------------------------------------------------------------------------
else
UpTh = get(handles.slider_srcs_up, 'Value');
DoTh = 1 - get(handles.slider_srcs_down,'Value');
N = length(NewMap)/2;
Low = fix(N - N*DoTh);
Hig = fix(N - N*UpTh);
i = [[1:Low]'*N/Low; ones(N + N - Hig - Low,1)*N; [1:Hig]'*N/Hig + N];
NewMap = NewMap(fix(i),:);
end
colormap(NewMap);
drawnow
% --- Executes on button press in next.
%--------------------------------------------------------------------------
function next_Callback(hObject, eventdata, handles)
if length(handles.D.inv) == 1
set(handles.next,'Value',0);
return
end
handles.D.val = handles.D.val + 1;
handles.D.con = 1;
if handles.D.val > length(handles.D.inv)
handles.D.val = 1;
end
set(handles.next,'String',sprintf('model %d',handles.D.val),'Value',0);
spm_eeg_inv_visu3D_api_OpeningFcn(hObject, eventdata, handles)
% --- Executes on button press in previous.
%--------------------------------------------------------------------------
function con_Callback(hObject, eventdata, handles)
if length(handles.D.inv{handles.D.val}.inverse.J) == 1
set(handles.con,'Value',0);
return
end
handles.D.con = handles.D.con + 1;
if handles.D.con > length(handles.D.inv{handles.D.val}.inverse.J)
handles.D.con = 1;
end
set(handles.con,'String',sprintf('condition %d',handles.D.con),'Value',0);
spm_eeg_inv_visu3D_api_OpeningFcn(hObject, eventdata, handles)
% --- Executes on button press in VDE.
%--------------------------------------------------------------------------
function Velec_Callback(hObject, eventdata, handles)
axes(handles.sources_axes);
rotate3d off;
datacursormode off;
if isfield(handles, 'velec')
delete(handles.velec);
handles = rmfield(handles, 'velec');
end
set(handles.fig1, 'ButtonDownFcn', @Velec_ButtonDown)
guidata(hObject,handles);
function Velec_ButtonDown(hObject, eventdata)
handles = guidata(hObject);
vert = handles.vert(handles.Is, :);
coord = get(handles.sources_axes, 'CurrentPoint');
dist = sum((vert - repmat(coord(1, :), size(vert, 1), 1)).^2, 2);
[junk, ind] = min(dist);
coord = vert(ind, :);
axes(handles.sources_axes);
hold on
handles.velec = plot3(coord(1), coord(2), coord(3), 'rv', 'MarkerSize', 10);
spm_eeg_invert_display(handles.D, coord);
set(handles.fig1, 'ButtonDownFcn', '');
guidata(hObject,handles);
% --- Executes on button press in Rot.
function Rot_Callback(hObject, eventdata, handles)
%--------------------------------------------------------------------------
rotate3d(handles.sources_axes)
return
% --- Executes on selection change in modality.
function modality_Callback(hObject, eventdata, handles)
% hObject handle to modality (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns modality contents as cell array
% contents{get(hObject,'Value')} returns selected item from modality
UpDate_Display_SENS(hObject,handles)
|
github
|
philippboehmsturm/antx-master
|
spm_load.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_load.m
| 1,187 |
utf_8
|
9e2a506bf52d19a51a627ece881f02b2
|
function [x] = spm_load(f)
% function to load ascii file data as matrix
% FORMAT [x] = spm_load(f)
% f - file {ascii file containing a regular array of numbers
% x - corresponding data matrix
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Karl Friston
% $Id: spm_load.m 1143 2008-02-07 19:33:33Z spm $
%-Get a filename if none was passed
%-----------------------------------------------------------------------
x = [];
if nargin == 0
[f,p] = uigetfile({'*.mat';'*.txt';'*.dat'});
try
f = fullfile(p,f);
end
end
%-Load the data file into double precision matrix x
%-----------------------------------------------------------------------
try
x = load(f,'-ascii');
return
end
try
x = load(f,'-mat');
x = getdata(x);
end
if ~isnumeric(x), x = []; end
function x = getdata(s)
% get numberic data x from the fields of structure s
%--------------------------------------------------------------------------
x = [];
f = fieldnames(s);
for i = 1:length(f)
x = s.(f{i});
if isnumeric(x),return; end
if isstruct(x), x = getdata(x); end
end
|
github
|
philippboehmsturm/antx-master
|
spm_reslice.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_reslice.m
| 13,297 |
utf_8
|
831352bc3482e5f11321a4d86aac663d
|
function spm_reslice(P,flags)
% Rigid body reslicing of images
% FORMAT spm_reslice(P,flags)
%
% P - matrix or cell array of filenames {one string per row}
% All operations are performed relative to the first image.
% ie. Coregistration is to the first image, and resampling
% of images is into the space of the first image.
%
% flags - a structure containing various options. The fields are:
%
% mask - mask output images (true/false) [default: true]
% To avoid artifactual movement-related variance the
% realigned set of images can be internally masked, within
% the set (i.e. if any image has a zero value at a voxel
% than all images have zero values at that voxel). Zero
% values occur when regions 'outside' the image are moved
% 'inside' the image during realignment.
%
% mean - write mean image (true/false) [default: true]
% The average of all the realigned scans is written to
% an image file with 'mean' prefix.
%
% interp - the B-spline interpolation method [default: 1]
% Non-finite values result in Fourier interpolation. Note
% that Fourier interpolation only works for purely rigid
% body transformations. Voxel sizes must all be identical
% and isotropic.
%
% which - values of 0, 1 or 2 are allowed [default: 2]
% 0 - don't create any resliced images.
% Useful if you only want a mean resliced image.
% 1 - don't reslice the first image.
% The first image is not actually moved, so it may
% not be necessary to resample it.
% 2 - reslice all the images.
% If which is a 2-element vector, flags.mean will be set
% to flags.which(2).
%
% wrap - three values of either 0 or 1, representing wrapping in
% each of the dimensions. For fMRI, [1 1 0] would be used.
% For PET, it would be [0 0 0]. [default: [0 0 0]]
%
% prefix - prefix for resliced images [default: 'r']
%
%__________________________________________________________________________
%
% The spatially realigned images are written to the original subdirectory
% with the same (prefixed) filename. They are all aligned with the first.
%
% Inputs:
% A series of images conforming to SPM data format (see 'Data Format'). The
% relative displacement of the images is stored in their header.
%
% Outputs:
% The routine uses information in their headers and writes the realigned
% image files to the same subdirectory with a prefix.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_reslice.m 4179 2011-01-28 13:57:20Z volkmar $
%__________________________________________________________________________
%
% The headers of the images contain a 4x4 affine transformation matrix 'M',
% usually affected bu the `realignment' and `coregistration' modules.
% What these matrices contain is a mapping from the voxel coordinates
% (x0,y0,z0) (where the first voxel is at coordinate (1,1,1)), to
% coordinates in millimeters (x1,y1,z1).
%
% x1 = M(1,1)*x0 + M(1,2)*y0 + M(1,3)*z0 + M(1,4)
% y1 = M(2,1)*x0 + M(2,2)*y0 + M(2,3)*z0 + M(2,4)
% z1 = M(3,1)*x0 + M(3,2)*y0 + M(3,3)*z0 + M(3,4)
%
% Assuming that image1 has a transformation matrix M1, and image2 has a
% transformation matrix M2, the mapping from image1 to image2 is: M2\M1
% (ie. from the coordinate system of image1 into millimeters, followed
% by a mapping from millimeters into the space of image2).
%
% Several spatial transformations (realignment, coregistration,
% normalisation) can be combined into a single operation (without the
% necessity of resampling the images several times).
%
%__________________________________________________________________________
% Refs:
%
% Friston KJ, Williams SR, Howard R Frackowiak RSJ and Turner R (1995)
% Movement-related effect in fMRI time-series. Mag. Res. Med. 35:346-355
%
% W. F. Eddy, M. Fitzgerald and D. C. Noll (1996) Improved Image
% Registration by Using Fourier Interpolation. Mag. Res. Med. 36(6):923-931
%
% R. W. Cox and A. Jesmanowicz (1999) Real-Time 3D Image Registration
% for Functional MRI. Mag. Res. Med. 42(6):1014-1018
%__________________________________________________________________________
def_flags = spm_get_defaults('realign.write');
def_flags.prefix = 'r';
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
if numel(flags.which) == 2
flags.mean = flags.which(2);
flags.which = flags.which(1);
elseif ~isfield(flags,'mean')
flags.mean = 1;
end
if ~nargin || isempty(P), P = spm_select([2 Inf],'image'); end
if iscellstr(P), P = char(P); end;
if ischar(P), P = spm_vol(P); end;
reslice_images(P,flags);
%==========================================================================
function reslice_images(P,flags)
% Reslices images volume by volume
% FORMAT reslice_images(P,flags)
% See main function for a description of the input parameters
if ~isfinite(flags.interp), % Use Fourier method
% Check for non-rigid transformations in the matrixes
for i=1:numel(P)
pp = P(1).mat\P(i).mat;
if any(abs(svd(pp(1:3,1:3))-1)>1e-7)
fprintf('\n Zooms or shears appear to be needed');
fprintf('\n (probably due to non-isotropic voxels).');
fprintf('\n These can not yet be done using the');
fprintf('\n Fourier reslicing method. Switching to');
fprintf('\n 7th degree B-spline interpolation instead.\n\n');
flags.interp = 7;
break
end
end
end
if flags.mask || flags.mean
spm_progress_bar('Init',P(1).dim(3),'Computing available voxels','planes completed');
x1 = repmat((1:P(1).dim(1))',1,P(1).dim(2));
x2 = repmat( 1:P(1).dim(2) ,P(1).dim(1),1);
if flags.mean
Count = zeros(P(1).dim(1:3));
Integral = zeros(P(1).dim(1:3));
end
if flags.mask, msk = cell(P(1).dim(3),1); end;
for x3 = 1:P(1).dim(3)
tmp = zeros(P(1).dim(1:2));
for i = 1:numel(P)
tmp = tmp + getmask(inv(P(1).mat\P(i).mat),x1,x2,x3,P(i).dim(1:3),flags.wrap);
end
if flags.mask, msk{x3} = find(tmp ~= numel(P)); end;
if flags.mean, Count(:,:,x3) = tmp; end;
spm_progress_bar('Set',x3);
end
end
nread = numel(P);
if ~flags.mean
if flags.which == 1, nread = nread - 1; end;
if flags.which == 0, nread = 0; end;
end
spm_progress_bar('Init',nread,'Reslicing','volumes completed');
[x1,x2] = ndgrid(1:P(1).dim(1),1:P(1).dim(2));
nread = 0;
d = [flags.interp*[1 1 1]' flags.wrap(:)];
for i = 1:numel(P)
if (i>1 && flags.which==1) || flags.which==2
write_vol = 1;
else
write_vol = 0;
end
if write_vol || flags.mean
read_vol = 1;
else
read_vol = 0;
end
if read_vol
if ~isfinite(flags.interp)
v = abs(kspace3d(spm_bsplinc(P(i),[0 0 0 ; 0 0 0]'),P(1).mat\P(i).mat));
for x3 = 1:P(1).dim(3)
if flags.mean
Integral(:,:,x3) = ...
Integral(:,:,x3) + ...
nan2zero(v(:,:,x3) .* ...
getmask(inv(P(1).mat\P(i).mat),x1,x2,x3,P(i).dim(1:3),flags.wrap));
end
if flags.mask
tmp = v(:,:,x3); tmp(msk{x3}) = NaN; v(:,:,x3) = tmp;
end
end
else
C = spm_bsplinc(P(i), d);
v = zeros(P(1).dim);
for x3 = 1:P(1).dim(3)
[tmp,y1,y2,y3] = getmask(inv(P(1).mat\P(i).mat),x1,x2,x3,P(i).dim(1:3),flags.wrap);
v(:,:,x3) = spm_bsplins(C, y1,y2,y3, d);
% v(~tmp) = 0;
if flags.mean
Integral(:,:,x3) = Integral(:,:,x3) + nan2zero(v(:,:,x3));
end
if flags.mask
tmp = v(:,:,x3); tmp(msk{x3}) = NaN; v(:,:,x3) = tmp;
end
end
end
if write_vol
VO = P(i);
[pth,nm,xt,vr] = spm_fileparts(deblank(P(i).fname));
VO.fname = fullfile(pth,[flags.prefix nm xt vr]);
VO.dim = P(1).dim(1:3);
VO.dt = P(i).dt;
VO.pinfo = P(i).pinfo;
VO.mat = P(1).mat;
VO.descrip = 'spm - realigned';
VO = spm_write_vol(VO,v);
end
nread = nread + 1;
end
spm_progress_bar('Set',nread);
end
if flags.mean
% Write integral image (16 bit signed)
%----------------------------------------------------------------------
Integral = Integral./Count;
PO = P(1);
PO = rmfield(PO,'pinfo');
[pth,nm,xt] = spm_fileparts(deblank(P(1).fname));
PO.fname = fullfile(pth,['mean' nm xt]);
PO.pinfo = [max(max(max(Integral)))/32767 0 0]';
PO.descrip = 'spm - mean image';
PO.dt = [spm_type('int16') spm_platform('bigend')];
spm_write_vol(PO,Integral);
end
spm_figure('Clear','Interactive');
%==========================================================================
function v = kspace3d(v,M)
% 3D rigid body transformation performed as shears in 1D Fourier space.
% FORMAT v1 = kspace3d(v,M)
% Inputs:
% v - the image stored as a 3D array.
% M - the rigid body transformation matrix.
% Output:
% v - the transformed image.
%
% The routine is based on the excellent papers:
% R. W. Cox and A. Jesmanowicz (1999)
% Real-Time 3D Image Registration for Functional MRI
% Magnetic Resonance in Medicine 42(6):1014-1018
%
% W. F. Eddy, M. Fitzgerald and D. C. Noll (1996)
% Improved Image Registration by Using Fourier Interpolation
% Magnetic Resonance in Medicine 36(6):923-931
%__________________________________________________________________________
[S0,S1,S2,S3] = shear_decomp(M);
d = [size(v) 1 1 1];
g = 2.^ceil(log2(d));
if any(g~=d)
tmp = v;
v = zeros(g);
v(1:d(1),1:d(2),1:d(3)) = tmp;
clear tmp;
end
% XY-shear
tmp1 = -sqrt(-1)*2*pi*([0:((g(3)-1)/2) 0 (-g(3)/2+1):-1])/g(3);
for j=1:g(2)
t = reshape( exp((j*S3(3,2) + S3(3,1)*(1:g(1)) + S3(3,4)).'*tmp1) ,[g(1) 1 g(3)]);
v(:,j,:) = real(ifft(fft(v(:,j,:),[],3).*t,[],3));
end
% XZ-shear
tmp1 = -sqrt(-1)*2*pi*([0:((g(2)-1)/2) 0 (-g(2)/2+1):-1])/g(2);
for k=1:g(3)
t = exp( (k*S2(2,3) + S2(2,1)*(1:g(1)) + S2(2,4)).'*tmp1);
v(:,:,k) = real(ifft(fft(v(:,:,k),[],2).*t,[],2));
end
% YZ-shear
tmp1 = -sqrt(-1)*2*pi*([0:((g(1)-1)/2) 0 (-g(1)/2+1):-1])/g(1);
for k=1:g(3)
t = exp( tmp1.'*(k*S1(1,3) + S1(1,2)*(1:g(2)) + S1(1,4)));
v(:,:,k) = real(ifft(fft(v(:,:,k),[],1).*t,[],1));
end
% XY-shear
tmp1 = -sqrt(-1)*2*pi*([0:((g(3)-1)/2) 0 (-g(3)/2+1):-1])/g(3);
for j=1:g(2)
t = reshape( exp( (j*S0(3,2) + S0(3,1)*(1:g(1)) + S0(3,4)).'*tmp1) ,[g(1) 1 g(3)]);
v(:,j,:) = real(ifft(fft(v(:,j,:),[],3).*t,[],3));
end
if any(g~=d), v = v(1:d(1),1:d(2),1:d(3)); end
%==========================================================================
function [S0,S1,S2,S3] = shear_decomp(A)
% Decompose rotation and translation matrix A into shears S0, S1, S2 and
% S3, such that A = S0*S1*S2*S3. The original procedure is documented in:
% R. W. Cox and A. Jesmanowicz (1999)
% Real-Time 3D Image Registration for Functional MRI
% Magnetic Resonance in Medicine 42(6):1014-1018
A0 = A(1:3,1:3);
if any(abs(svd(A0)-1)>1e-7), error('Can''t decompose matrix'); end
t = A0(2,3); if t==0, t=eps; end
a0 = pinv(A0([1 2],[2 3])')*[(A0(3,2)-(A0(2,2)-1)/t) (A0(3,3)-1)]';
S0 = [1 0 0; 0 1 0; a0(1) a0(2) 1];
A1 = S0\A0; a1 = pinv(A1([2 3],[2 3])')*A1(1,[2 3])'; S1 = [1 a1(1) a1(2); 0 1 0; 0 0 1];
A2 = S1\A1; a2 = pinv(A2([1 3],[1 3])')*A2(2,[1 3])'; S2 = [1 0 0; a2(1) 1 a2(2); 0 0 1];
A3 = S2\A2; a3 = pinv(A3([1 2],[1 2])')*A3(3,[1 2])'; S3 = [1 0 0; 0 1 0; a3(1) a3(2) 1];
s3 = A(3,4)-a0(1)*A(1,4)-a0(2)*A(2,4);
s1 = A(1,4)-a1(1)*A(2,4);
s2 = A(2,4);
S0 = [[S0 [0 0 s3]'];[0 0 0 1]];
S1 = [[S1 [s1 0 0]'];[0 0 0 1]];
S2 = [[S2 [0 s2 0]'];[0 0 0 1]];
S3 = [[S3 [0 0 0]'];[0 0 0 1]];
%==========================================================================
function [Mask,y1,y2,y3] = getmask(M,x1,x2,x3,dim,wrp)
tiny = 5e-2; % From spm_vol_utils.c
y1 = M(1,1)*x1+M(1,2)*x2+(M(1,3)*x3+M(1,4));
y2 = M(2,1)*x1+M(2,2)*x2+(M(2,3)*x3+M(2,4));
y3 = M(3,1)*x1+M(3,2)*x2+(M(3,3)*x3+M(3,4));
Mask = true(size(y1));
if ~wrp(1), Mask = Mask & (y1 >= (1-tiny) & y1 <= (dim(1)+tiny)); end
if ~wrp(2), Mask = Mask & (y2 >= (1-tiny) & y2 <= (dim(2)+tiny)); end
if ~wrp(3), Mask = Mask & (y3 >= (1-tiny) & y3 <= (dim(3)+tiny)); end
%==========================================================================
function vo = nan2zero(vi)
vo = vi;
vo(~isfinite(vo)) = 0;
|
github
|
philippboehmsturm/antx-master
|
spm_render.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_render.m
| 13,829 |
utf_8
|
9e4e98950ae8331e22d6f4e4d22c6d0c
|
function spm_render(dat,brt,rendfile)
% Render blobs on surface of a 'standard' brain
% FORMAT spm_render(dat,brt,rendfile)
%
% dat - a struct array of length 1 to 3
% each element is a structure containing:
% - XYZ - the x, y & z coordinates of the transformed SPM{.}
% values in units of voxels.
% - t - the SPM{.} values.
% - mat - affine matrix mapping from XYZ voxels to MNI.
% - dim - dimensions of volume from which XYZ is drawn.
% brt - brightness control:
% If NaN, then displays using the old style with hot
% metal for the blobs, and grey for the brain.
% Otherwise, it is used as a ``gamma correction'' to
% optionally brighten the blobs up a little.
% rendfile - the file containing the images to render on to (see also
% spm_surf.m) or a surface mesh file.
%
% Without arguments, spm_render acts as its own UI.
%__________________________________________________________________________
%
% spm_render prompts for details of up to three SPM{.}s that are then
% displayed superimposed on the surface of a 'standard' brain.
%
% The first is shown in red, then green then blue.
%
% The blobs which are displayed are the integral of all transformed t
% values, exponentially decayed according to their depth. Voxels that
% are 10mm behind the surface have half the intensity of ones at the
% surface.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_render.m 510 2010-08-02 07:10:42Z volkmar $
SVNrev = '$Rev: 510 $';
global prevrend
if ~isstruct(prevrend)
prevrend = struct('rendfile','', 'brt',[], 'col',[]);
end
%-Parse arguments, get data if not passed as parameters
%==========================================================================
if nargin < 1
spm('FnBanner',mfilename,SVNrev);
spm('FigName','Results: render');
num = spm_input('Number of sets',1,'1 set|2 sets|3 sets',[1 2 3],1);
for i = 1:num
src = spm_input(sprintf('Source - Set %d', i),1,'SPM.mat|Image',[1 2],1);
switch src
case 1
[SPM,xSPM] = spm_getSPM;
dat(i) = struct( 'XYZ', xSPM.XYZ,...
't', xSPM.Z',...
'mat', xSPM.M,...
'dim', xSPM.DIM);
case 2
V = spm_vol(spm_select(1,'image'));
[X XYZ] = spm_read_vols(V);
XYZ = V.mat\[XYZ; ones(1,size(XYZ,2))];
sel = find(X(:));
dat(i) = struct('XYZ', XYZ(1:3,sel),...
't', X(sel),...
'mat', V.mat,...
'dim', V.dim);
end
end
showbar = 1;
else
num = length(dat);
showbar = 0;
end
%-Get surface
%--------------------------------------------------------------------------
if nargin < 3 || isempty(prevrend.rendfile)
[rendfile, sts] = spm_select(1,'mesh','Render file'); % .mat or .gii file
if ~sts, return; end
end
prevrend.rendfile = rendfile;
[p,f,e] = fileparts(rendfile);
loadgifti = false;
if strcmpi(e,'.mat')
load(rendfile);
if ~exist('rend','var') && ~exist('Matrixes','var')
loadgifti = true;
end
end
if ~strcmpi(e,'.mat') || loadgifti
try
rend = export(gifti(rendfile),'patch');
catch
error('\nCannot read render file "%s".\n', rendfile);
end
if num == 1
col = hot(256);
else
col = eye(3);
if spm_input('Which colours?','!+1','b',{'RGB','Custom'},[0 1],1)
for k = 1:num
col(k,:) = uisetcolor(col(k,:),sprintf('Colour of blob set %d',k));
end
end
end
surf_rend(dat,rend,col);
return
end
%-Get brightness & colours
%--------------------------------------------------------------------------
if nargin < 2 || isempty(prevrend.brt)
brt = 1;
if num==1
brt = spm_input('Style',1,'new|old',[1 NaN], 1);
end
if isfinite(brt)
brt = spm_input('Brighten blobs',1,'none|slightly|more|lots',[1 0.75 0.5 0.25], 1);
col = eye(3);
% ask for custom colours & get rgb values
%------------------------------------------------------------------
if spm_input('Which colours?','!+1','b',{'RGB','Custom'},[0 1],1)
for k = 1:num
col(k,:) = uisetcolor(col(k,:),sprintf('Colour of blob set %d',k));
end
end
else
col = [];
end
elseif isfinite(brt) && isempty(prevrend.col)
col = eye(3);
elseif isfinite(brt) % don't need to check prevrend.col again
col = prevrend.col;
else
col = [];
end
prevrend.brt = brt;
prevrend.col = col;
%-Perform the rendering
%==========================================================================
spm('Pointer','Watch');
if ~exist('rend','var') % Assume old format...
rend = cell(size(Matrixes,1),1);
for i=1:size(Matrixes,1),
rend{i}=struct('M',eval(Matrixes(i,:)),...
'ren',eval(Rens(i,:)),...
'dep',eval(Depths(i,:)));
rend{i}.ren = rend{i}.ren/max(max(rend{i}.ren));
end
end
if showbar, spm_progress_bar('Init', size(dat,1)*length(rend),...
'Formatting Renderings', 'Number completed'); end
for i=1:length(rend),
rend{i}.max=0;
rend{i}.data = cell(size(dat,1),1);
if issparse(rend{i}.ren),
% Assume that images have been DCT compressed
% - the SPM99 distribution was originally too big.
d = size(rend{i}.ren);
B1 = spm_dctmtx(d(1),d(1));
B2 = spm_dctmtx(d(2),d(2));
rend{i}.ren = B1*rend{i}.ren*B2';
% the depths did not compress so well with
% a straight DCT - therefore it was modified slightly
rend{i}.dep = exp(B1*rend{i}.dep*B2')-1;
end
rend{i}.ren(rend{i}.ren>=1) = 1;
rend{i}.ren(rend{i}.ren<=0) = 0;
if showbar, spm_progress_bar('Set', i); end
end
if showbar, spm_progress_bar('Clear'); end
if showbar, spm_progress_bar('Init', length(dat)*length(rend),...
'Making pictures', 'Number completed'); end
mx = zeros(length(rend),1)+eps;
mn = zeros(length(rend),1);
for j=1:length(dat),
XYZ = dat(j).XYZ;
t = dat(j).t;
dim = dat(j).dim;
mat = dat(j).mat;
for i=1:length(rend),
% transform from Talairach space to space of the rendered image
%------------------------------------------------------------------
M1 = rend{i}.M*mat;
zm = sum(M1(1:2,1:3).^2,2).^(-1/2);
M2 = diag([zm' 1 1]);
M = M2*M1;
cor = [1 1 1 ; dim(1) 1 1 ; 1 dim(2) 1; dim(1) dim(2) 1 ;
1 1 dim(3) ; dim(1) 1 dim(3) ; 1 dim(2) dim(3); dim(1) dim(2) dim(3)]';
tcor= M(1:3,1:3)*cor + M(1:3,4)*ones(1,8);
off = min(tcor(1:2,:)');
M2 = spm_matrix(-off+1)*M2;
M = M2*M1;
xyz = (M(1:3,1:3)*XYZ + M(1:3,4)*ones(1,size(XYZ,2)));
d2 = ceil(max(xyz(1:2,:)'));
% Calculate 'depth' of values
%------------------------------------------------------------------
if ~isempty(d2)
dep = spm_slice_vol(rend{i}.dep,spm_matrix([0 0 1])*inv(M2),d2,1);
z1 = dep(round(xyz(1,:))+round(xyz(2,:)-1)*size(dep,1));
if ~isfinite(brt), msk = find(xyz(3,:) < (z1+20) & xyz(3,:) > (z1-5));
else msk = find(xyz(3,:) < (z1+60) & xyz(3,:) > (z1-5)); end
else
msk = [];
end
if ~isempty(msk),
% Generate an image of the integral of the blob values.
%--------------------------------------------------------------
xyz = xyz(:,msk);
if ~isfinite(brt), t0 = t(msk);
else
dst = xyz(3,:) - z1(msk);
dst = max(dst,0);
t0 = t(msk).*exp((log(0.5)/10)*dst)';
end
X0 = full(sparse(round(xyz(1,:)), round(xyz(2,:)), t0, d2(1), d2(2)));
hld = 1; if ~isfinite(brt), hld = 0; end
X = spm_slice_vol(X0,spm_matrix([0 0 1])*M2,size(rend{i}.dep),hld);
msk = find(X<0);
X(msk) = 0;
else
X = zeros(size(rend{i}.dep));
end
% Brighten the blobs
%------------------------------------------------------------------
if isfinite(brt), X = X.^brt; end
mx(j) = max([mx(j) max(max(X))]);
mn(j) = min([mn(j) min(min(X))]);
rend{i}.data{j} = X;
if showbar, spm_progress_bar('Set', i+(j-1)*length(rend)); end
end
end
mxmx = max(mx);
mnmn = min(mn);
if showbar, spm_progress_bar('Clear'); end
Fgraph = spm_figure('GetWin','Graphics');
spm_results_ui('Clear',Fgraph);
nrow = ceil(length(rend)/2);
if showbar, hght = 0.95; else hght = 0.5; end
% subplot('Position',[0, 0, 1, hght]);
ax=axes('Parent',Fgraph,'units','normalized','Position',[0, 0, 1, hght],'Visible','off');
image(0,'Parent',ax);
set(ax,'YTick',[],'XTick',[]);
if ~isfinite(brt),
% Old style split colourmap display.
%----------------------------------------------------------------------
load Split;
colormap(split);
for i=1:length(rend),
ren = rend{i}.ren;
X = (rend{i}.data{1}-mnmn)/(mxmx-mnmn);
msk = find(X);
ren(msk) = X(msk)+(1+1.51/64);
ax=axes('Parent',Fgraph,'units','normalized',...
'Position',[rem(i-1,2)*0.5, floor((i-1)/2)*hght/nrow, 0.5, hght/nrow],...
'Visible','off');
image(ren*64,'Parent',ax);
set(ax,'DataAspectRatio',[1 1 1], ...
'PlotBoxAspectRatioMode','auto',...
'YTick',[],'XTick',[],'XDir','normal','YDir','normal');
end
else
% Combine the brain surface renderings with the blobs, and display using
% 24 bit colour.
%----------------------------------------------------------------------
for i=1:length(rend),
ren = rend{i}.ren;
X = cell(3,1);
for j=1:length(rend{i}.data),
X{j} = rend{i}.data{j}/(mxmx-mnmn)-mnmn;
end
for j=(length(rend{i}.data)+1):3
X{j}=zeros(size(X{1}));
end
rgb = zeros([size(ren) 3]);
tmp = ren.*max(1-X{1}-X{2}-X{3},0);
for k = 1:3
rgb(:,:,k) = tmp + X{1}*col(1,k) + X{2}*col(2,k) +X{3}*col(3,k);
end
rgb(rgb>1) = 1;
ax=axes('Parent',Fgraph,'units','normalized',...
'Position',[rem(i-1,2)*0.5, floor((i-1)/2)*hght/nrow, 0.5, hght/nrow],...
'nextplot','add', ...
'Visible','off');
image(rgb,'Parent',ax);
set(ax,'DataAspectRatio',[1 1 1], ...
'PlotBoxAspectRatioMode','auto',...
'YTick',[],'XTick',[],...
'XDir','normal','YDir','normal');
end
end
spm('Pointer','Arrow');
%==========================================================================
% function surf_rend(dat,rend,col)
%==========================================================================
function surf_rend(dat,rend,col)
%-Setup figure and axis
%--------------------------------------------------------------------------
Fgraph = spm_figure('GetWin','Graphics');
spm_results_ui('Clear',Fgraph);
ax0 = axes(...
'Tag', 'SPMMeshRenderBackground',...
'Parent', Fgraph,...
'Units', 'normalized',...
'Color', [1 1 1],...
'XTick', [],...
'YTick', [],...
'Position', [-0.05, -0.05, 1.05, 0.555]);
ax = axes(...
'Parent', Fgraph,...
'Units', 'normalized',...
'Position', [0.05, 0.05, 0.9, 0.4],...
'Visible', 'off');
H = spm_mesh_render('Disp',rend,struct('parent',ax));
spm_mesh_render('Overlay',H,dat,col);
try
setAllowAxesRotate(H.rotate3d, setxor(findobj(Fgraph,'Type','axes'),ax), false);
end
%-Register with MIP
%--------------------------------------------------------------------------
try % meaningless when called outside spm_results_ui
hReg = spm_XYZreg('FindReg',spm_figure('GetWin','Interactive'));
xyz = spm_XYZreg('GetCoords',hReg);
hs = mydispcursor('Create',ax,dat.mat,xyz);
spm_XYZreg('Add2Reg',hReg,hs,@mydispcursor);
end
%==========================================================================
function varargout = mydispcursor(varargin)
switch lower(varargin{1})
%======================================================================
case 'create'
%======================================================================
% hMe = mydispcursor('Create',ax,M,xyz)
ax = varargin{2};
M = varargin{3};
xyz = varargin{4};
[X,Y,Z] = sphere;
vx = sqrt(sum(M(1:3,1:3).^2));
X = X*vx(1) + xyz(1);
Y = Y*vx(2) + xyz(2);
Z = Z*vx(3) + xyz(3);
hold(ax,'on');
hs = surf(X,Y,Z,'parent',ax,...
'EdgeColor','none','FaceColor',[1 0 0],'FaceLighting', 'phong');
set(hs,'UserData',xyz);
varargout = {hs};
%=======================================================================
case 'setcoords' % Set co-ordinates
%=======================================================================
% [xyz,d] = mydispcursor('SetCoords',xyz,hMe,hC)
hMe = varargin{3};
pxyz = get(hMe,'UserData');
xyz = varargin{2};
set(hMe,'XData',get(hMe,'XData') - pxyz(1) + xyz(1));
set(hMe,'YData',get(hMe,'YData') - pxyz(2) + xyz(2));
set(hMe,'ZData',get(hMe,'ZData') - pxyz(3) + xyz(3));
set(hMe,'UserData',xyz);
varargout = {xyz,[]};
%=======================================================================
otherwise
%=======================================================================
error('Unknown action string')
end
|
github
|
philippboehmsturm/antx-master
|
spm_uitable.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_uitable.m
| 11,862 |
utf_8
|
43cfc4fe369c00f401fbbe0fdf7bc5e8
|
function [varargout] = spm_uitable(varargin)
% WARNING: This feature is not supported in MATLAB
% and the API and functionality may change in a future release.
% UITABLE creates a two dimensional graphic uitable component in a figure window.
% UITABLE creates a 1x1 uitable object using default property values in
% a figure window.
%
% UITABLE(numrows,numcolumns) creates a uitable object with specified
% number of rows and columns.
%
% UITABLE(data,columnNames) creates a uitable object with the specified
% data and columnNames. Data can be a cell array or a vector and
% columnNames should be cell arrays.
%
% UITABLE('PropertyName1',value1,'PropertyName2',value2,...) creates a
% uitable object with specified property values. MATLAB uses default
% property values for any property not explicitly set. The properties
% that user can set are: ColumnNames, Data, GridColor, NumColumns,
% NumRows, Position, ColumnWidth and RowHeight.
%
% UITABLE(figurehandle, ...) creates a uitable object in the figure
% window specified by the figure handle.
%
% HANDLE = UITABLE(...) creates a uitable object and returns its handle.
%
% Properties:
%
% ColumnNames: Cell array of strings for column names.
% Data: Cell array of values to be displayed in the table.
% GridColor: string, RGB vector.
% NumColumns: int specifying number of columns.
% NumRows: int specifying number of rows.
% Parent: Handle to figure or uipanel. If not specified, it is gcf.
% Position: 4 element vector specifying the position.
% ColumnWidth: int specifying the width of columns.
% RowHeight: int specifying the height of columns.
%
% Enabled: Boolean specifying if a column is enabled.
% Editable: Boolean specifying if a column is editable.
% Units: String - pixels/normalized/inches/points/centimeters.
% Visible: Boolean specifying if table is visible.
% DataChangedCallback - Callback function name or handle.
%
%
% Examples:
%
% t = uitable(3, 2);
%
% Creates a 3x2 empty uitable object in a figure window.
%
% f = figure;
% t = uitable(f, rand(5), {'A', 'B', 'C', 'D', 'E'});
%
% Creates a 5x5 uitable object in a figure window with the specified
% data and the column names.
%
% data = rand(3);
% colnames = {'X-Data', 'Y-Data', 'Z-Data'};
% t = uitable(data, colnames,'Position', [20 20 250 100]);
%
% Creates a uitable object with the specified data and column names and
% the specified Position.
%
% See also AWTCREATE, AWTINVOKE, JAVACOMPONENT, UITREE, UITREENODE
% Copyright 2002-2006 The MathWorks, Inc.
% $Revision: 4185 $ $Date: 2006/11/29 21:53:13 $
% Release: R14. This feature will not work in previous versions of MATLAB.
% $Id: spm_uitable.m 4185 2011-02-01 18:46:18Z guillaume $
% Setup and P-V parsing
if isempty(varargin)
if ~isempty(javachk('awt')) || spm_check_version('matlab','7.3') <= 0
varargout{1} = 'off';
else
varargout{1} = 'on';
end
return
end
if ~isempty(javachk('awt')) || spm_check_version('matlab','7.3') <= 0
varargout{1} = [];
varargout{2} = [];
return;
end
if ischar(varargin{1})
switch varargin{1}
case 'set'
data = varargin{2};
columnNames = varargin{3};
[htable,hcontainer] = UiTable(data,columnNames);
varargout{1} = htable;
varargout{2} = hcontainer;
case 'get'
htable = varargin{2};
columnNames = get(htable,'columnNames');
nc = get(htable,'NumColumns');
nr = get(htable,'NumRows');
data = get(htable,'data');
data2 = cell(nr,nc);
for i=1:nc
for j=1:nr
data2{j,i} = data(j,i);
end
end
varargout{1} = data2;
varargout{2} = columnNames;
end
else
[htable,hcontainer] = UiTable(varargin{:});
varargout{1} = htable;
varargout{2} = hcontainer;
end
function [table,container] = UiTable(varargin)
error(nargoutchk(0,2,nargout));
parent = [];
numargs = nargin;
datastatus=false; columnstatus=false;
rownum = 1; colnum = 1; % Default to a 1x1 table.
position = [20 20 200 200];
combo_box_found = false;
check_box_found = false;
import com.mathworks.hg.peer.UitablePeer;
if (numargs > 0 && isscalar(varargin{1}) && ishandle(varargin{1}) && ...
isa(handle(varargin{1}), 'figure'))
parent = varargin{1};
varargin = varargin(2:end);
numargs = numargs - 1;
end
if (numargs > 0 && isscalar(varargin{1}) && ishandle(varargin{1}))
if ~isa(varargin{1}, 'javax.swing.table.DefaultTableModel')
error('MATLAB:uitable:UnrecognizedParameter', ['Unrecognized parameter: ', varargin{1}]);
end
data_model = varargin{1};
varargin = varargin(2:end);
numargs = numargs - 1;
elseif ((numargs > 1) && isscalar(varargin{1}) && isscalar(varargin{2}))
if(isnumeric(varargin{1}) && isnumeric(varargin{2}))
rownum = varargin{1};
colnum = varargin{2};
varargin = varargin(3:end);
numargs = numargs-2;
else
error('MATLAB:uitable:InputMustBeScalar', 'When using UITABLE numrows and numcols have to be numeric scalars.')
end
elseif ((numargs > 1) && isequal(size(varargin{2},1), 1) && iscell(varargin{2}))
if (size(varargin{1},2) == size(varargin{2},2))
if (isnumeric(varargin{1}))
varargin{1} = num2cell(varargin{1});
end
else
error('MATLAB:uitable:MustMatchInfo', 'Number of column names must match number of columns in data');
end
data = varargin{1}; datastatus = true;
coln = varargin{1+1}; columnstatus = true;
varargin = varargin(3:end);
numargs = numargs-2;
end
for i = 1:2:numargs-1
if (~ischar(varargin{i}))
error('MATLAB:uitable:UnrecognizedParameter', ['Unrecognized parameter: ', varargin{i}]);
end
switch lower(varargin{i})
case 'data'
if (isnumeric(varargin{i+1}))
varargin{i+1} = num2cell(varargin{i+1});
end
data = varargin{i+1};
datastatus = true;
case 'columnnames'
if(iscell(varargin{i+1}))
coln = varargin{i+1};
columnstatus = true;
else
error('MATLAB:uitable:InvalidCellArray', 'When using UITABLE Column data should be 1xn cell array')
end
case 'numrows'
if (isnumeric(varargin{i+1}))
rownum = varargin{i+1};
else
error('MATLAB:uitable:NumrowsMustBeScalar', 'numrows has to be a scalar')
end
case 'numcolumns'
if (isnumeric(varargin{i+1}))
colnum = varargin{i+1};
else
error('MATLAB:uitable:NumcolumnsMustBeScalar', 'numcolumns has to be a scalar')
end
case 'gridcolor'
if (ischar(varargin{i+1}))
gridcolor = varargin{i+1};
else if (isnumeric(varargin{i+1}) && (numel(varargin{i+1}) == 3))
gridcolor = varargin{i+1};
else
error('MATLAB:uitable:InvalidString', 'gridcolor has to be a valid string')
end
end
case 'rowheight'
if (isnumeric(varargin{i+1}))
rowheight = varargin{i+1};
else
error('MATLAB:uitable:RowheightMustBeScalar', 'rowheight has to be a scalar')
end
case 'parent'
if ishandle(varargin{i+1})
parent = varargin{i+1};
else
error('MATLAB:uitable:InvalidParent', 'parent must be a valid handle')
end
case 'position'
if (isnumeric(varargin{i+1}))
position = varargin{i+1};
else
error('MATLAB:uitable:InvalidPosition', 'position has to be a 1x4 numeric array')
end
case 'columnwidth'
if (isnumeric(varargin{i+1}))
columnwidth = varargin{i+1};
else
error('MATLAB:uitable:ColumnwidthMustBeScalar', 'columnwidth has to be a scalar')
end
otherwise
error('MATLAB:uitable:UnrecognizedParameter', ['Unrecognized parameter: ', varargin{i}]);
end
end
% ---combo/check box detection--- %
if (datastatus)
if (iscell(data))
rownum = size(data,1);
colnum = size(data,2);
combo_count =0;
check_count = 0;
combo_box_data = num2cell(zeros(1, colnum));
combo_box_column = zeros(1, colnum);
check_box_column = zeros(1, colnum);
for j = 1:rownum
for k = 1:colnum
if (iscell(data{j,k}))
combo_box_found = true;
combo_count = combo_count + 1;
combo_box_data{combo_count} = data{j,k};
combo_box_column(combo_count ) = k;
dc = data{j,k};
data{j,k} = dc{1};
else
if(islogical(data{j,k}))
check_box_found = true;
check_count = check_count + 1;
check_box_column(check_count) = k;
end
end
end
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Check the validity of the parent and/or create a figure.
if isempty(parent)
parent = gcf; % Get the current figure. Create one if not available
end
if ( columnstatus && datastatus )
if(size(data,2) ~= size(coln,2))
error('MATLAB:NeedSameNumberColumns', 'Number of columns in both Data and ColumnNames should match');
end
elseif ( ~columnstatus && datastatus )
for i=1:size(data,2)
coln{i} = num2str(i);
end
columnstatus = true;
elseif ( columnstatus && ~datastatus)
error('MATLAB:uitable:NoDataProvided', 'No Data provided along with ColumnNames');
end
if (~exist('data_model', 'var'))
data_model = javax.swing.table.DefaultTableModel;
end
if exist('rownum', 'var')
data_model.setRowCount(rownum);
end
if exist('colnum', 'var')
data_model.setColumnCount(colnum);
end
table_h= UitablePeer(data_model);
% We should have valid data and column names here.
if (datastatus), table_h.setData(data); end;
if (columnstatus), table_h.setColumnNames(coln); end;
if (combo_box_found),
for i=1:combo_count
table_h.setComboBoxEditor(combo_box_data(i), combo_box_column(i));
end
end
if (check_box_found),
for i = 1: check_count
table_h.setCheckBoxEditor(check_box_column(i));
end
end
% pass the specified parent and let javacomponent decide its validity.
[obj, container] = javacomponent(table_h, position, parent);
% javacomponent returns a UDD handle for the java component passed in.
table = obj;
% Have to do a drawnow here to make the properties stick. Try to restrict
% the drawnow call to only when it is absolutely required.
flushed = false;
if exist('gridcolor', 'var')
pause(.1); drawnow;
flushed = true;
table_h.setGridColor(gridcolor);
end
if exist('rowheight', 'var')
if (~flushed)
drawnow;
end
table_h.setRowHeight(rowheight);
end
if exist('columnwidth', 'var')
table_h.setColumnWidth(columnwidth);
end;
% % Add a predestroy listener so we can call cleanup on the table.
% addlistener(table, 'ObjectBeingDestroyed', {@componentDelete});
varargout{1} = table;
varargout{2} = container;
function componentDelete(src, evd) %#ok
% Clean up the table here so it disengages all its internal listeners.
src.cleanup;
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_convert.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_eeg_convert.m
| 16,945 |
utf_8
|
a71c71902f215e5d6bfa54b043e525d8
|
function D = spm_eeg_convert(S)
% Main function for converting different M/EEG formats to SPM8 format.
% FORMAT D = spm_eeg_convert(S)
% S - can be string (file name) or struct (see below)
%
% If S is a struct it can have the optional following fields:
% S.dataset - file name
% S.continuous - 1 - convert data as continuous
% 0 - convert data as epoched (requires data that is
% already epoched or a trial definition file).
% S.timewindow - [start end] in sec. Boundaries for a sub-segment of
% continuous data [default: all]
% S.outfile - output file name (default 'spm8_' + input)
% S.channels - 'all' - convert all channels
% or cell array of labels
% S.usetrials - 1 - take the trials as defined in the data [default]
% 0 - use trial definition file even though the data is
% already epoched
% S.trlfile - name of the trial definition file
% S.datatype - data type for the data file one of
% 'float32-le' [default], 'float64-le'
% S.inputformat - data type (optional) to force the use of specific data
% reader
% S.eventpadding - 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
% trial borders), in seconds. [default: 0]
% S.conditionlabel - labels for the trials in the data [default: 'Undefined']
% S.blocksize - size of blocks used internally to split large files
% [default: ~100Mb]
% S.checkboundary - 1 - check if there are breaks in the file and do not
% read across those breaks [default]
% 0 - ignore breaks (not recommended).
% S.saveorigheader - 1 - save original data header with the dataset
% 0 - do not keep the original header [default]
%
% % D - MEEG object (also written on disk)
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Vladimir Litvak
% $Id: spm_eeg_convert.m 4430 2011-08-12 18:47:17Z vladimir $
if ischar(S)
temp = S;
S = [];
S.dataset = temp;
end
if ~isfield(S, 'dataset')
error('Dataset must be specified.');
end
if ~isfield(S, 'outfile'), S.outfile = ['spm8_' spm_str_manip(S.dataset,'tr')]; end
if ~isfield(S, 'channels'), S.channels = 'all'; end
if ~isfield(S, 'timewindow'), S.timewindow = []; end
if ~isfield(S, 'blocksize'), S.blocksize = 3276800; end %100 Mb
if ~isfield(S, 'checkboundary'), S.checkboundary = 1; end
if ~isfield(S, 'usetrials'), S.usetrials = 1; end
if ~isfield(S, 'datatype'), S.datatype = 'float32-le'; end
if ~isfield(S, 'eventpadding'), S.eventpadding = 0; end
if ~isfield(S, 'saveorigheader'), S.saveorigheader = 0; end
if ~isfield(S, 'conditionlabel'), S.conditionlabel = 'Undefined' ; end
if ~isfield(S, 'inputformat'), S.inputformat = [] ; end
if ~iscell(S.conditionlabel)
S.conditionlabel = {S.conditionlabel};
end
%--------- Read and check header
hdr = ft_read_header(S.dataset, 'fallback', 'biosig', 'headerformat', S.inputformat);
if isfield(hdr, 'label')
[unique_label junk ind]=unique(hdr.label);
if length(unique_label)~=length(hdr.label)
warning(['Data file contains several channels with ',...
'the same name. These channels cannot be processed and will be disregarded']);
% This finds the repeating labels and removes all their occurences
sortind=sort(ind);
[junk ind2]=setdiff(hdr.label, unique_label(sortind(find(diff(sortind)==0))));
hdr.label=hdr.label(ind2);
hdr.nChans=length(hdr.label);
end
end
if ~isfield(S, 'continuous')
S.continuous = (hdr.nTrials == 1);
end
%--------- Read and prepare events
try
event = ft_read_event(S.dataset, 'detectflank', 'both', 'eventformat', S.inputformat);
if ~isempty(strmatch('UPPT001', hdr.label))
% This is s somewhat ugly fix to the specific problem with event
% coding in FIL CTF. It can also be useful for other CTF systems where the
% pulses in the event channel go downwards.
fil_ctf_events = ft_read_event(S.dataset, 'detectflank', 'down', 'type', 'UPPT001', 'trigshift', -1, 'eventformat', S.inputformat);
if ~isempty(fil_ctf_events)
[fil_ctf_events(:).type] = deal('FIL_UPPT001_down');
event = cat(1, event(:), fil_ctf_events(:));
end
end
if ~isempty(strmatch('UPPT002', hdr.label))
% This is s somewhat ugly fix to the specific problem with event
% coding in FIL CTF. It can also be useful for other CTF systems where the
% pulses in the event channel go downwards.
fil_ctf_events = ft_read_event(S.dataset, 'detectflank', 'down', 'type', 'UPPT002', 'trigshift', -1, 'eventformat', S.inputformat);
if ~isempty(fil_ctf_events)
[fil_ctf_events(:).type] = deal('FIL_UPPT002_down');
event = cat(1, event(:), fil_ctf_events(:));
end
end
% This is another FIL-specific fix that will hopefully not affect other sites
if isfield(hdr, 'orig') && isfield(hdr.orig, 'VERSION') && isequal(uint8(hdr.orig.VERSION),uint8([255 'BIOSEMI']))
ind = strcmp('STATUS', {event(:).type});
val = [event(ind).value];
if any(val>255)
bytes = dec2bin(val);
bytes = bytes(:, end-7:end);
bytes = flipdim(bytes, 2);
val = num2cell(bin2dec(bytes));
[event(ind).value] = deal(val{:});
end
end
catch
warning(['Could not read events from file ' S.dataset]);
event = [];
end
% Replace samples with time
if numel(event)>0
for i = 1:numel(event)
event(i).time = event(i).sample./hdr.Fs;
end
end
%--------- Start making the header
D = [];
D.Fsample = hdr.Fs;
%--------- Select channels
if ~strcmp(S.channels, 'all')
[junk, chansel] = spm_match_str(S.channels, hdr.label);
else
if isfield(hdr, 'nChans')
chansel = 1:hdr.nChans;
else
chansel = 1:length(hdr.label);
end
end
nchan = length(chansel);
D.channels = repmat(struct('bad', 0), 1, nchan);
if isfield(hdr, 'label')
[D.channels(:).label] = deal(hdr.label{chansel});
end
%--------- Preparations specific to reading mode (continuous/epoched)
if S.continuous
if isempty(S.timewindow)
if hdr.nTrials == 1
segmentbounds = [1 hdr.nSamples];
elseif ~S.checkboundary
segmentbounds = [1 hdr.nSamples*hdr.nTrials];
else
error('The data cannot be read without ignoring trial borders');
end
S.timewindow = segmentbounds./D.Fsample;
else
segmentbounds = round(S.timewindow.*D.Fsample);
segmentbounds(1) = max(segmentbounds(1), 1);
end
%--------- Sort events and put in the trial
if ~isempty(event)
event = rmfield(event, {'offset', 'sample'});
event = select_events(event, ...
[S.timewindow(1)-S.eventpadding S.timewindow(2)+S.eventpadding]);
end
D.trials.label = S.conditionlabel{1};
D.trials.events = event;
D.trials.onset = S.timewindow(1);
%--------- Break too long segments into blocks
nblocksamples = floor(S.blocksize/nchan);
nsampl = diff(segmentbounds)+1;
trl = [segmentbounds(1):nblocksamples:segmentbounds(2)];
if (trl(end)==segmentbounds(2))
trl = trl(1:(end-1));
end
trl = [trl(:) [trl(2:end)-1 segmentbounds(2)]'];
ntrial = size(trl, 1);
readbytrials = 0;
D.timeOnset = (trl(1,1)-1)./hdr.Fs;
D.Nsamples = nsampl;
else % Read by trials
if ~S.usetrials
if ~isfield(S, 'trl')
trl = getfield(load(S.trlfile, 'trl'), 'trl');
else
trl = S.trl;
end
trl = double(trl);
if size(trl, 2) >= 3
D.timeOnset = unique(trl(:, 3))./D.Fsample;
trl = trl(:, 1:2);
else
D.timeOnset = 0;
end
if length(D.timeOnset) > 1
error('All trials should have identical baseline');
end
try
conditionlabels = getfield(load(S.trlfile, 'conditionlabels'), 'conditionlabels');
catch
conditionlabels = S.conditionlabel;
end
if ~iscell(conditionlabels)
conditionlabels = {conditionlabels};
end
if numel(conditionlabels) == 1
conditionlabels = repmat(conditionlabels, 1, size(trl, 1));
end
readbytrials = 0;
else
try
trialind = sort([strmatch('trial', {event.type}, 'exact'), ...
strmatch('average', {event.type}, 'exact')]);
trl = [event(trialind).sample];
trl = double(trl(:));
trl = [trl trl+double([event(trialind).duration]')-1];
try
offset = unique([event(trialind).offset]);
catch
offset = [];
end
if length(offset) == 1
D.timeOnset = offset/D.Fsample;
else
D.timeOnset = 0;
end
conditionlabels = {};
for i = 1:length(trialind)
if isempty(event(trialind(i)).value)
conditionlabels{i} = S.conditionlabel{1};
else
if all(ischar(event(trialind(i)).value))
conditionlabels{i} = event(trialind(i)).value;
else
conditionlabels{i} = num2str(event(trialind(i)).value);
end
end
end
if hdr.nTrials>1 && size(trl, 1)~=hdr.nTrials
warning('Mismatch between trial definition in events and in data. Ignoring events');
readbytrials = 1;
else
readbytrials = 0;
end
event = event(setdiff(1:numel(event), trialind));
catch
if hdr.nTrials == 1
error('Could not define trials based on data. Use continuous option or trial definition file.');
else
readbytrials = 1;
end
end
end
if readbytrials
nsampl = hdr.nSamples;
ntrial = hdr.nTrials;
trl = zeros(ntrial, 2);
if exist('conditionlabels', 'var') ~= 1 || length(conditionlabels) ~= ntrial
conditionlabels = repmat(S.conditionlabel, 1, ntrial);
end
else
nsampl = unique(diff(trl, [], 2))+1;
if length(nsampl) > 1
error('All trials should have identical lengths');
end
inbounds = (trl(:,1)>=1 & trl(:, 2)<=hdr.nSamples*hdr.nTrials)';
rejected = find(~inbounds);
if ~isempty(rejected)
trl = trl(inbounds, :);
conditionlabels = conditionlabels(inbounds);
warning([S.dataset ': Trials ' num2str(rejected) ' not read - out of bounds']);
end
ntrial = size(trl, 1);
if ntrial == 0
warning([S.dataset ': No trials to read. Bailing out.']);
D = [];
return;
end
end
D.Nsamples = nsampl;
if isfield(event, 'sample')
event = rmfield(event, 'sample');
end
end
%--------- Prepare for reading the data
[outpath, outfile] = fileparts(S.outfile);
if isempty(outpath)
outpath = pwd;
end
if isempty(outfile)
outfile = 'spm8';
end
D.path = outpath;
D.fname = [outfile '.mat'];
D.data.fnamedat = [outfile '.dat'];
D.data.datatype = S.datatype;
if S.continuous
datafile = file_array(fullfile(D.path, D.data.fnamedat), [nchan nsampl], S.datatype);
else
datafile = file_array(fullfile(D.path, D.data.fnamedat), [nchan nsampl ntrial], S.datatype);
end
% physically initialise file
datafile(end,end) = 0;
spm_progress_bar('Init', ntrial, 'reading and converting'); drawnow;
if ntrial > 100, Ibar = floor(linspace(1, ntrial,100));
else Ibar = [1:ntrial]; end
%--------- Read the data
offset = 1;
for i = 1:ntrial
if readbytrials
dat = ft_read_data(S.dataset,'header', hdr, 'begtrial', i, 'endtrial', i,...
'chanindx', chansel, 'checkboundary', S.checkboundary, 'fallback', 'biosig', 'dataformat', S.inputformat);
else
dat = ft_read_data(S.dataset,'header', hdr, 'begsample', trl(i, 1), 'endsample', trl(i, 2),...
'chanindx', chansel, 'checkboundary', S.checkboundary, 'fallback', 'biosig', 'dataformat', S.inputformat);
end
% Sometimes ft_read_data returns sparse output
dat = full(dat);
if S.continuous
nblocksamples = size(dat,2);
datafile(:, offset:(offset+nblocksamples-1)) = dat;
offset = offset+nblocksamples;
else
datafile(:, :, i) = dat;
D.trials(i).label = conditionlabels{i};
D.trials(i).onset = trl(i, 1)./D.Fsample;
D.trials(i).events = select_events(event, ...
[ trl(i, 1)./D.Fsample-S.eventpadding trl(i, 2)./D.Fsample+S.eventpadding]);
end
if ismember(i, Ibar)
spm_progress_bar('Set', i);
end
end
spm_progress_bar('Clear');
% Specify sensor positions and fiducials
if isfield(hdr, 'grad')
D.sensors.meg = ft_convert_units(hdr.grad, 'mm');
end
if isfield(hdr, 'elec')
D.sensors.eeg = ft_convert_units(hdr.elec, 'mm');
else
try
D.sensors.eeg = ft_convert_units(ft_read_sens(S.dataset, 'fileformat', S.inputformat), 'mm');
% It might be that read_sens will return the grad for MEG datasets
if isfield(D.sensors.eeg, 'ori')
D.sensors.eeg = [];
end
catch
warning('Could not obtain electrode locations automatically.');
end
end
try
D.fiducials = ft_convert_units(ft_read_headshape(S.dataset, 'fileformat', S.inputformat), 'mm');
catch
warning('Could not obtain fiducials automatically.');
end
%--------- Create meeg object
D = meeg(D);
% history
D = D.history('spm_eeg_convert', S);
if isfield(hdr, 'orig')
if S.saveorigheader
D.origheader = hdr.orig;
end
% Uses fileio function to get the information about channel types stored in
% the original header. This is now mainly useful for Neuromag support but might
% have other functions in the future.
origchantypes = ft_chantype(hdr);
[sel1, sel2] = spm_match_str(D.chanlabels, hdr.label);
origchantypes = origchantypes(sel2);
if length(strmatch('unknown', origchantypes, 'exact')) ~= numel(origchantypes)
D.origchantypes = struct([]);
D.origchantypes(1).label = hdr.label(sel2);
D.origchantypes(1).type = origchantypes;
end
end
S1 = [];
S1.task = 'defaulttype';
S1.D = D;
S1.updatehistory = 0;
D = spm_eeg_prep(S1);
% Assign default EEG sensor positions if possible
if ~isempty(strmatch('EEG', D.chantype, 'exact'))
if isempty(D.sensors('EEG'))
S1 = [];
S1.task = 'defaulteegsens';
S1.updatehistory = 0;
S1.D = D;
D = spm_eeg_prep(S1);
else
S1 = [];
S1.task = 'project3D';
S1.modality = 'EEG';
S1.updatehistory = 0;
S1.D = D;
D = spm_eeg_prep(S1);
end
end
% Create 2D positions for MEG
% by projecting the 3D positions to 2D
if ~isempty(strmatch('MEG', D.chantype)) && ~isempty(D.sensors('MEG'))
S1 = [];
S1.task = 'project3D';
S1.modality = 'MEG';
S1.updatehistory = 0;
S1.D = D;
D = spm_eeg_prep(S1);
end
% If channel units are available, store them.
if isfield(hdr, 'unit')
[sel1, sel2] = spm_match_str(D.chanlabels, hdr.label);
D = units(D, sel1, hdr.unit(sel2));
end
% The conditions will later be sorted in the original order they were defined.
if isfield(S, 'trialdef')
D = condlist(D, {S.trialdef(:).conditionlabel});
end
save(D);
%==========================================================================
% select_events
%==========================================================================
function event = select_events(event, timeseg)
% Utility function to select events according to time segment
% FORMAT event = select_events(event, timeseg)
if ~isempty(event)
[time ind] = sort([event(:).time]);
selectind = ind(time>=timeseg(1) & time<=timeseg(2));
event = event(selectind);
end
|
github
|
philippboehmsturm/antx-master
|
spm_maff.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_maff.m
| 8,022 |
utf_8
|
33d6a7e3d4b7305bf9bd04c4ffb4eef5
|
function M = spm_maff(varargin)
% Affine registration to MNI space using mutual information
% FORMAT M = spm_maff(P,samp,x,b0,MF,M,regtyp,ff)
% P - filename or structure handle of image
% x - cell array of {x1,x2,x3}, where x1 and x2 are
% co-ordinates (from ndgrid), and x3 is a list of
% slice numbers to use
% b0 - a cell array of belonging probability images
% (see spm_load_priors.m).
% MF - voxel-to-world transform of belonging probability
% images
% M - starting estimates
% regtype - regularisation type
% 'mni' - registration of European brains with MNI space
% 'eastern' - registration of East Asian brains with MNI space
% 'rigid' - rigid(ish)-body registration
% 'subj' - inter-subject registration
% 'none' - no regularisation
% ff - a fudge factor (derived from the one above)
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_maff.m 4178 2011-01-27 15:12:53Z guillaume $
[buf,MG] = loadbuf(varargin{1:2});
M = affreg(buf, MG, varargin{2:end});
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [buf,MG] = loadbuf(V,x)
if ischar(V), V = spm_vol(V); end;
x1 = x{1};
x2 = x{2};
x3 = x{3};
% Load the image
V = spm_vol(V);
d = V(1).dim(1:3);
o = ones(size(x1));
d = [size(x1) length(x3)];
g = zeros(d);
spm_progress_bar('Init',V.dim(3),'Loading volume','Planes loaded');
for i=1:d(3)
g(:,:,i) = spm_sample_vol(V,x1,x2,o*x3(i),0);
spm_progress_bar('Set',i);
end;
spm_progress_bar('Clear');
% Convert the image to unsigned bytes
[mn,mx] = spm_minmax(g);
sw = warning('off','all');
for z=1:length(x3),
gz = g(:,:,z);
buf(z).msk = gz>mn & isfinite(gz);
buf(z).nm = sum(buf(z).msk(:));
gz = double(gz(buf(z).msk));
buf(z).g = uint8(round(gz*(255/mx)));
end;
warning(sw);
MG = V.mat;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [M,h0] = affreg(buf,MG,x,b0,MF,M,regtyp,ff)
% Do the work
x1 = x{1};
x2 = x{2};
x3 = x{3};
[mu,isig] = spm_affine_priors(regtyp);
mu = [zeros(6,1) ; mu];
isig = [zeros(6,12) ; zeros(6,6) isig];
isig = isig*ff;
Alpha0 = isig;
Beta0 = -isig*mu;
sol = M2P(M);
sol1 = sol;
ll = -Inf;
nsmp = sum(cat(1,buf.nm));
pr = struct('b',[],'db1',[],'db2',[],'db3',[]);
spm_plot_convergence('Init','Registering','Log-likelihood','Iteration');
for iter=1:200
penalty = (sol1-mu)'*isig*(sol1-mu);
T = MF\P2M(sol1)*MG;
R = derivs(MF,sol1,MG);
y1a = T(1,1)*x1 + T(1,2)*x2 + T(1,4);
y2a = T(2,1)*x1 + T(2,2)*x2 + T(2,4);
y3a = T(3,1)*x1 + T(3,2)*x2 + T(3,4);
h0 = zeros(256,length(b0)-1)+eps;
for i=1:length(x3),
if ~buf(i).nm, continue; end;
y1 = y1a(buf(i).msk) + T(1,3)*x3(i);
y2 = y2a(buf(i).msk) + T(2,3)*x3(i);
y3 = y3a(buf(i).msk) + T(3,3)*x3(i);
for k=1:size(h0,2),
pr(k).b = spm_sample_priors(b0{k},y1,y2,y3,k==length(b0));
h0(:,k) = h0(:,k) + spm_hist(buf(i).g,pr(k).b);
end;
end;
h1 = (h0+eps);
ssh = sum(h1(:));
krn = spm_smoothkern(2,(-256:256)',0);
h1 = conv2(h1,krn,'same');
h1 = h1/ssh;
h2 = log2(h1./(sum(h1,2)*sum(h1,1)));
ll1 = sum(sum(h0.*h2))/ssh - penalty/ssh;
spm_plot_convergence('Set',ll1);
if ll1-ll<1e-5, break; end;
ll = ll1;
sol = sol1;
Alpha = zeros(12);
Beta = zeros(12,1);
for i=1:length(x3),
nz = buf(i).nm;
if ~nz, continue; end;
msk = buf(i).msk;
gi = double(buf(i).g)+1;
y1 = y1a(msk) + T(1,3)*x3(i);
y2 = y2a(msk) + T(2,3)*x3(i);
y3 = y3a(msk) + T(3,3)*x3(i);
dmi1 = zeros(nz,1);
dmi2 = zeros(nz,1);
dmi3 = zeros(nz,1);
for k=1:size(h0,2),
[pr(k).b, pr(k).db1, pr(k).db2, pr(k).db3] = spm_sample_priors(b0{k},y1,y2,y3,k==length(b0));
tmp = -h2(gi,k);
dmi1 = dmi1 + tmp.*pr(k).db1;
dmi2 = dmi2 + tmp.*pr(k).db2;
dmi3 = dmi3 + tmp.*pr(k).db3;
end;
x1m = x1(msk);
x2m = x2(msk);
x3m = x3(i);
A = [dmi1.*x1m dmi2.*x1m dmi3.*x1m...
dmi1.*x2m dmi2.*x2m dmi3.*x2m...
dmi1 *x3m dmi2 *x3m dmi3 *x3m...
dmi1 dmi2 dmi3];
Alpha = Alpha + A'*A;
Beta = Beta + sum(A,1)';
end;
drawnow;
Alpha = R'*Alpha*R;
Beta = R'*Beta;
% Gauss-Newton update
sol1 = (Alpha+Alpha0)\(Alpha*sol - Beta - Beta0);
end;
spm_plot_convergence('Clear');
M = P2M(sol);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function P = M2P(M)
% Polar decomposition parameterisation of affine transform,
% based on matrix logs
J = M(1:3,1:3);
V = sqrtm(J*J');
R = V\J;
lV = logm(V);
lR = -logm(R);
if sum(sum(imag(lR).^2))>1e-6
error('Rotations by pi are still a problem.');
else
lR = real(lR);
end
P = zeros(12,1);
P(1:3) = M(1:3,4);
P(4:6) = lR([2 3 6]);
P(7:12) = lV([1 2 3 5 6 9]);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function M = P2M(P)
% Polar decomposition parameterisation of affine transform,
% based on matrix logs
% Translations
D = P(1:3);
D = D(:);
% Rotation part
ind = [2 3 6];
T = zeros(3);
T(ind) = -P(4:6);
R = expm(T-T');
% Symmetric part (zooms and shears)
ind = [1 2 3 5 6 9];
T = zeros(3);
T(ind) = P(7:12);
V = expm(T+T'-diag(diag(T)));
M = [V*R D ; 0 0 0 1];
return;
%_______________________________________________________________________
%_______________________________________________________________________
function R = derivs(MF,P,MG)
% Numerically compute derivatives of Affine transformation matrix w.r.t.
% changes in the parameters.
R = zeros(12,12);
M0 = MF\P2M(P)*MG;
M0 = M0(1:3,:);
for i=1:12
dp = 0.000000001;
P1 = P;
P1(i) = P1(i) + dp;
M1 = MF\P2M(P1)*MG;
M1 = M1(1:3,:);
R(:,i) = (M1(:)-M0(:))/dp;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [h0,d1] = reg_unused(M)
% Try to analytically compute the first and second derivatives of a
% penalty function w.r.t. changes in parameters. It works for first
% derivatives, but I couldn't make it work for the second derivs - so
% I gave up and tried a new strategy.
T = M(1:3,1:3);
[U,S,V] = svd(T);
s = diag(S);
h0 = sum(log(s).^2);
d1s = 2*log(s)./s;
%d2s = 2./s.^2-2*log(s)./s.^2;
d1 = zeros(12,1);
for j=1:3
for i1=1:9
T1 = zeros(3,3);
T1(i1) = 1;
t1 = U(:,j)'*T1*V(:,j);
d1(i1) = d1(i1) + d1s(j)*t1;
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function M = P2M_unused(P)
% SVD parameterisation of affine transform, based on matrix-logs.
% Translations
D = P(1:3);
D = D(:);
% Rotation U
ind = [2 3 6];
T = zeros(3);
T(ind) = P(4:6);
U = expm(T-T');
% Diagonal zooming matrix
S = expm(diag(P(7:9)));
% Rotation V'
T(ind) = P(10:12);
V = expm(T'-T);
M = [U*S*V' D ; 0 0 0 1];
return;
%_______________________________________________________________________
%_______________________________________________________________________
|
github
|
philippboehmsturm/antx-master
|
spm_diff.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_diff.m
| 4,795 |
utf_8
|
ad03f0b9baf443336e6690d292b28a58
|
function [varargout] = spm_diff(varargin)
% matrix high-order numerical differentiation
% FORMAT [dfdx] = spm_diff(f,x,...,n)
% FORMAT [dfdx] = spm_diff(f,x,...,n,V)
% FORMAT [dfdx] = spm_diff(f,x,...,n,'q')
%
% f - [inline] function f(x{1},...)
% x - input argument[s]
% n - arguments to differentiate w.r.t.
%
% V - cell array of matrices that allow for differentiation w.r.t.
% to a linear transformation of the parameters: i.e., returns
%
% df/dy{i}; x = V{i}y{i}; V = dx(i)/dy(i)
%
% q - flag to preclude default concatenation of dfdx
%
% dfdx - df/dx{i} ; n = i
% dfdx{p}...{q} - df/dx{i}dx{j}(q)...dx{k}(p) ; n = [i j ... k]
%
%
% - a cunning recursive routine
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Karl Friston
% $Id: spm_diff.m 4060 2010-09-01 17:17:36Z karl $
% create inline object
%--------------------------------------------------------------------------
f = varargin{1};
% parse input arguments
%--------------------------------------------------------------------------
if iscell(varargin{end})
x = varargin(2:(end - 2));
n = varargin{end - 1};
V = varargin{end};
q = 1;
elseif isnumeric(varargin{end})
x = varargin(2:(end - 1));
n = varargin{end};
V = cell(1,length(x));
q = 1;
elseif ischar(varargin{end})
x = varargin(2:(end - 2));
n = varargin{end - 1};
V = cell(1,length(x));
q = 0;
else
error('improper call')
end
% check transform matrices V = dxdy
%--------------------------------------------------------------------------
for i = 1:length(x)
try
V{i};
catch
V{i} = [];
end
if isempty(V{i}) && any(n == i);
V{i} = speye(length(spm_vec(x{i})));
end
end
% initialise
%--------------------------------------------------------------------------
m = n(end);
xm = spm_vec(x{m});
dx = exp(-8);
J = cell(1,size(V{m},2));
% proceed to derivatives
%==========================================================================
if length(n) == 1
% dfdx
%----------------------------------------------------------------------
f0 = feval(f,x{:});
for i = 1:length(J)
xi = x;
xmi = xm + V{m}(:,i)*dx;
xi{m} = spm_unvec(xmi,x{m});
fi = feval(f,xi{:});
J{i} = spm_dfdx(fi,f0,dx);
end
% return numeric array for first-order derivatives
%======================================================================
% vectorise f
%----------------------------------------------------------------------
f = spm_vec(f0);
% if there are no arguments to differentiate w.r.t. ...
%----------------------------------------------------------------------
if isempty(xm)
J = sparse(length(f),0);
% or there are no arguments to differentiate
%----------------------------------------------------------------------
elseif isempty(f)
J = sparse(0,length(xm));
end
% or differentiation of a vector
%----------------------------------------------------------------------
if isvec(f0) && q
% concatenate into a matrix
%------------------------------------------------------------------
if size(f0,2) == 1
J = spm_cat(J);
else
J = spm_cat(J')';
end
end
% assign output argument and return
%----------------------------------------------------------------------
varargout{1} = J;
varargout{2} = f0;
else
% dfdxdxdx....
%----------------------------------------------------------------------
f0 = cell(1,length(n));
[f0{:}] = spm_diff(f,x{:},n(1:end - 1),V);
for i = 1:length(J)
xi = x;
xmi = xm + V{m}(:,i)*dx;
xi{m} = spm_unvec(xmi,x{m});
fi = spm_diff(f,xi{:},n(1:end - 1),V);
J{i} = spm_dfdx(fi,f0{1},dx);
end
varargout = [{J} f0];
end
function dfdx = spm_dfdx(f,f0,dx)
% cell subtraction
%--------------------------------------------------------------------------
if iscell(f)
dfdx = f;
for i = 1:length(f(:))
dfdx{i} = spm_dfdx(f{i},f0{i},dx);
end
elseif isstruct(f)
dfdx = (spm_vec(f) - spm_vec(f0))/dx;
else
dfdx = (f - f0)/dx;
end
function is = isvec(v)
% isvector(v) returns true if v is 1-by-n or n-by-1 where n>=0
%__________________________________________________________________________
% vec if just two dimensions, and one (or both) unity
%--------------------------------------------------------------------------
is = length(size(v)) == 2 && isnumeric(v);
is = is && (size(v,1) == 1 || size(v,2) == 1);
|
github
|
philippboehmsturm/antx-master
|
spm_DisplayTimeSeries.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_DisplayTimeSeries.m
| 14,298 |
utf_8
|
1c167bc991f31018469bbdda0f340261
|
function [ud] = spm_DisplayTimeSeries(y,options)
% This function builds a GUI for 'smart' time series display.
% FORMAT function [ud] = spm_DisplayTimeSeries(y,options)
% IN:
% - y: the txn data, where t is the number of time sample, and p the
% number of 'channels'
% - options: a structure (default is empty), which allows to adapt this
% function to specific needs. Optional fields are:
% .hp: the handle of the parent figure/object. This is used to
% include the time series display in a panel/figure. By default, a
% new figure will be created.
% .Fsample: the sample rate of the data (in Hz)
% .events: a nex1 structure vector containing the time indices of the
% events and their type (if any). Default is empty. Basic structure
% contains fields .time and .type (see bellow).
% .M: a pxn matrix premultiplied to the data when plotted (default is
% 1).
% .bad a px1 binary vector containing the good/bad status of the
% channels. Default is zeros(p,1).
% .transpose: a binary variable that transposes the data (useful for
% file_array display). Using options.transpose = 1 is similar to do
% something similar to plot(y'). Default is 0.
% .minY: the min value of the plotted data (used to define the main
% axes limit). Default is calculated according to the offset.
% .maxY: the max value of the plotted data (used to define the main
% axes limit). Default is calculated according to the offset.
% .minSizeWindow: minimum size of the plotted window (in number of
% time samples). {min([200,0.5*size(y,1)]}
% .maxSizeWindow: maximum size of the plotted window (in number of
% time samples). {min([5000,size(y,1)])}
% .ds: an integer giving the number of displayed time samples when
% dynamically moving the display time window. Default is 1e4. If you
% set it to Inf, no downsampling is applied.
% .callback: a string or function handle which is evaluated after
% each release of the mouse button (when moving the patch or clicking
% on the slider). Default is empty.
% .tag: a string used to tag both axes
% .pos1: a 4x1 vector containing the position of the main display
% axes {[0.13 0.3 0.775 0.655]}
% .pos2: a 4x1 vector containing the position of the global power
% display axes {[0.13 0.05 0.775 0.15]}
% .pos3: a 4x1 vector containing the position of the temporal slider
% {[0.13 0.01 0.775 0.02]}
% .itw: a vector containing the indices of data time samples
% initially displayed in the main axes {1:minSizeWindow}
% .ytick: the 'ytick' property of the main axes
% .yticklabel: the 'yticklabel' property of the main axes
% .offset: a px1 vector containing the vertical offset that has to be
% added to each of the plotted time series
% !! .ytick, .yticklabel and .offset can be used to display labelled
% time series one above each other !!
% OUT:
% - ud: a structure containing all relevant informations about the
% graphical objects created for the GUI. This is useful for maniupalting
% the figure later on (see bellow).
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Jean Daunizeau
% $Id: spm_DisplayTimeSeries.m 3248 2009-07-03 16:17:30Z vladimir $
if ~exist('options','var')
options = [];
end
% Get optional parameters if any) and set up defaults
%==========================================================================
if ~isempty(options) && isfield(options,'hp')
hp = options.hp;
else
hp = figure;
end
if ~isempty(options) && isfield(options,'Fsample')
Fsample = options.Fsample;
else
Fsample = 1;
end
if ~isempty(options) && isfield(options,'timeOnset')
timeOnset = options.timeOnset;
else
timeOnset = 0;
end
if ~isempty(options) && isfield(options,'events')
events = options.events;
else
events = [];
end
if ~isempty(options) && isfield(options,'transpose')
transpose = options.transpose;
else
transpose = 0;
end
if ~isempty(options) && isfield(options,'M')
M = options.M;
nc = size(M,1);
if ~transpose
nt = size(y,1);
else
nt = size(y,2);
end
else
M = 1;
if ~transpose
[nt,nc] = size(y);
else
[nc,nt] = size(y);
end
end
if ~isempty(options) && isfield(options,'bad')
bad = options.bad;
else
bad = zeros(nc,1);
end
if ~isempty(options) && isfield(options,'minSizeWindow')
minSizeWindow = options.minSizeWindow;
else
minSizeWindow = 200;
end
minSizeWindow = min([minSizeWindow,.5*nt]);
if ~isempty(options) && isfield(options,'maxSizeWindow')
maxSizeWindow = options.maxSizeWindow;
else
maxSizeWindow = 5000;
end
maxSizeWindow = min([maxSizeWindow,nt]);
if ~isempty(options) && isfield(options,'ds')
ds = options.ds;
else
ds = 1e4;
end
if ~isempty(options) && isfield(options,'callback')
callback = options.callback;
else
callback = [];
end
if ~isempty(options) && isfield(options,'tag')
tag = options.tag;
else
tag = '';
end
if ~isempty(options) && isfield(options,'pos1')
pos1 = options.pos1;
else
pos1 = [0.13 0.32 0.775 0.655];
end
if ~isempty(options) && isfield(options,'pos2')
pos2 = options.pos2;
else
pos2 = [0.13 0.12 0.775 0.15];
end
if ~isempty(options) && isfield(options,'pos3')
pos3 = options.pos3;
else
pos3 = [0.10 0.02 0.84 0.05];
end
if ~isempty(options) && isfield(options,'itw')
itw = options.itw;
else
itw = 1:minSizeWindow;
end
if ~isempty(options) && isfield(options,'ytick')
ytick = options.ytick;
else
ytick = [];
end
if ~isempty(options) && isfield(options,'yticklabel')
yticklabel = options.yticklabel;
else
yticklabel = [];
end
if ~isempty(options) && isfield(options,'offset')
offset = options.offset(:);
else
offset = zeros(nc,1);
end
if ~isempty(options) && isfield(options,'minY')
minY = options.minY;
else
yo = y + repmat(offset',nt,1);
minY = min(yo(:));
end
if ~isempty(options) && isfield(options,'maxY')
maxY = options.maxY;
else
try
maxY = max(yo(:));
catch
yo = y + repmat(offset',nt,1);
maxY = max(yo(:));
end
end
% Initialize display
%==========================================================================
% Get basic info about data
ud.y = y;
ud.v.bad = bad;
ud.v.transpose = transpose;
ud.v.nc = nc;
ud.v.nt = nt;
ud.v.ds = ds;
ud.v.M = M;
ud.v.mi = minY;
ud.v.ma = maxY;
ud.v.minSizeWindow = minSizeWindow;
ud.v.maxSizeWindow = maxSizeWindow;
ud.v.offset = offset;
ud.v.et = events;
ud.v.handles.hp = hp;
ud.callback = callback;
% Get downsampled global power
decim = max([1,round(nt./1000)]);
ud.v.ind = 1:decim:nt;
if ~ud.v.transpose
My = ud.v.M*y(ud.v.ind,:)';
ud.v.y2 = sum(My.^2,1);
else
My = ud.v.M*y(:,ud.v.ind);
ud.v.y2 = sum(My.^2,1);
end
mi = min(ud.v.y2);
ma = max(ud.v.y2);
if mi == 0 && ma == 0
mi = -eps;
ma = eps;
else
mi = mi - mi.*1e-3;
ma = ma + ma.*1e-3;
end
% Create axes
ud.v.handles.axes = axes('parent',hp,...
'units','normalized',...
'position',pos1,...
'xtick',[],'xticklabel',[],...
'ytick',ytick,'yticklabel',yticklabel,...
'tag',tag,...
'nextplot','add',...
'drawmode','fast');
ud.v.handles.gpa = axes('parent',hp,...
'units','normalized',...
'position',pos2,...
'tag',tag,'nextplot','add','ytick',[],...
'box','off',...
'color','none',...
'ygrid','off',...
'drawmode','fast');
% Initialize time series
col = colormap(lines);
col = col(1:7,:);
ud.v.handles.hp = zeros(nc,1);
if ~ud.v.transpose
My = ud.v.M*y(itw,:)';
else
My = ud.v.M*y(:,itw);
end
for i=1:ud.v.nc
ii = mod(i+7,7)+1;
ud.v.handles.hp(i) = plot(ud.v.handles.axes,...
itw,My(i,:)+offset(i),...
'color',col(ii,:));
if ud.v.bad(i)
set(ud.v.handles.hp(i),'linestyle',':')
end
end
ud.v.handles.gpp = plot(ud.v.handles.gpa,...
ud.v.ind,ud.v.y2,...
'color',0.5*[1 1 1]);
% Add events if any
if ~isempty(ud.v.et)
for i=1:length(ud.v.et)
ud.v.et(i).col = mod(ud.v.et(i).type+7,7)+1;
ud.v.et(i).hp = plot(ud.v.handles.axes,...
ud.v.et(i).time.*[1 1],...
[ud.v.mi,ud.v.ma],...
'color',col(ud.v.et(i).col,:),...
'userdata',i,...
'ButtonDownFcn','set(gco,''selected'',''on'')',...
'Clipping','on');
end
end
% Add display scrolling patch and borders
ud.v.handles.pa = patch('parent',ud.v.handles.gpa,...
'xdata',[itw(1) itw(end) itw(end) itw(1)],...
'ydata',[mi mi ma ma],...
'edgecolor','none',...
'facecolor',[.5 .5 .5],...
'facealpha',0.5,...
'ButtonDownFcn',@doPatch,...
'interruptible','off');
ud.v.handles.lb = plot(ud.v.handles.gpa,...
[itw(1) itw(1)],[mi ma],...
'k',...
'buttondownfcn',@doLb,...
'interruptible','off');
ud.v.handles.rb = plot(ud.v.handles.gpa,...
[itw(end) itw(end)],[mi ma],...
'k',...
'buttondownfcn',@doRb,...
'interruptible','off');
% Adapt axes properties to display
tgrid = (0:(nt-1))./Fsample + timeOnset;
set(ud.v.handles.gpa,...
'ylim',[mi ma],...
'xlim',[1 nt]);
xtick = floor(get(ud.v.handles.gpa,'xtick'));
xtick(xtick==0) = 1;
a = cell(length(xtick),1);
for i=1:length(xtick)
a{i} = num2str(tgrid(xtick(i)),2);
end
set(ud.v.handles.gpa,...
'xtick',xtick,...
'xticklabel',a);
set(ud.v.handles.axes,...
'xlim',[itw(1) itw(end)],...
'ylim',[ud.v.mi ud.v.ma]);
% Add temporal slider
ud.v.handles.hslider = uicontrol('parent',hp,...
'style','slider',...
'units','normalized',...
'Position',pos3,...
'min',max([1,minSizeWindow/2-1]),...
'max',min([ud.v.nt,ud.v.nt-minSizeWindow/2+1]),...
'value',mean([itw(1),itw(end)]),...
'sliderstep',.1*[minSizeWindow/(ud.v.nt-1) 4*minSizeWindow/(ud.v.nt-1)],...
'callback',@doScroll,...
'userdata',ud.v.handles.gpa,...
'BusyAction','cancel',...
'Interruptible','on',...
'tooltipstring','Scroll data',...
'tag',tag);
% Store required info in global power axes
set(ud.v.handles.gpa,'userdata',ud)
axes(ud.v.handles.gpa)
% Subfunctions
%==========================================================================
function doScroll(src,evt)
gpa = get(src,'userdata');
xm = get(src,'value');
ud = get(gpa,'userdata');
sw = diff(get(ud.v.handles.axes,'xlim'));
xl = xm + [-sw./2,+sw./2];
if xl(1) >= 1 && xl(2) <= ud.v.nt
xl = round(xl);
if ~ud.v.transpose
My = ud.v.M*ud.y(xl(1):xl(2),:)';
else
My = ud.v.M*ud.y(:,xl(1):xl(2));
end
doPlot(My,xl,ud.v,1)
end
if ~isempty(ud.callback)
try eval(ud.callback);end
end
function doPatch(src,evt)
hf = gcf;
set(hf,'WindowButtonDownFcn',@doPatch,...
'WindowButtonUpFcn',@UndoPatch,...
'WindowButtonMotionFcn',{@movePatch},...
'Pointer','fleur')
function doLb(src,evt)
hf = gcf;
set(hf,'WindowButtonDownFcn',@doLb,...
'WindowButtonUpFcn',@UndoPatch,...
'WindowButtonMotionFcn',{@moveLb},...
'Pointer','left')
function doRb(src,evt)
hf = gcf;
set(hf,'WindowButtonDownFcn',@doRb,...
'WindowButtonUpFcn',@UndoPatch,...
'WindowButtonMotionFcn',{@moveRb},...
'Pointer','right')
function UndoPatch(src,evt)
ha = gca;
hf = gcf;
set(hf,'WindowButtonMotionFcn',[],...
'WindowButtonDownFcn',[],...
'WindowButtonUpFcn',[],...
'Pointer','arrow')
ud = get(ha,'userdata');
xw = get(ud.v.handles.axes,'xlim');
if ~ud.v.transpose
My = ud.v.M*ud.y(xw(1):xw(2),:)';
else
My = ud.v.M*ud.y(:,xw(1):xw(2));
end
doPlot(My,xw,ud.v,1);
if ~isempty(ud.callback)
try eval(ud.callback);end
end
function movePatch(src,evt)
ha = gca;
cp = get(ha,'CurrentPoint');
ud = get(ha,'userdata');
xm = cp(1);
sw = diff(get(ud.v.handles.axes,'xlim'));
xl = xm + [-sw./2,+sw./2];
if xl(1) >= 1 && xl(2) <= ud.v.nt
xl = round(xl);
decim = max([1,round(sw./ud.v.ds)]);
if ~ud.v.transpose
My = ud.v.M*ud.y(xl(1):decim:xl(2),:)';
else
My = ud.v.M*ud.y(:,xl(1):decim:xl(2));
end
doPlot(My,xl,ud.v,decim)
elseif xl(2) > ud.v.nt
xl = [ud.v.nt-sw,ud.v.nt];
decim = max([1,round(sw./ud.v.ds)]);
if ~ud.v.transpose
My = ud.v.M*ud.y(xl(1):decim:xl(2),:)';
else
My = ud.v.M*ud.y(:,xl(1):decim:xl(2));
end
doPlot(My,xl,ud.v,decim)
elseif xl(1) < 1
xl = [1,sw+1];
decim = max([1,round(sw./ud.v.ds)]);
if ~ud.v.transpose
My = ud.v.M*ud.y(xl(1):decim:xl(2),:)';
else
My = ud.v.M*ud.y(:,xl(1):decim:xl(2));
end
doPlot(My,xl,ud.v,decim)
end
function moveLb(src,evt)
ha = gca;
cp = get(ha,'CurrentPoint');
cp = max([cp(1),1]);
ud = get(ha,'userdata');
xw = get(ud.v.handles.pa,'xdata');
if cp(1) <= xw(2) - ud.v.minSizeWindow ...
&& diff([cp(1) xw(2)]) <= ud.v.maxSizeWindow
cp = [round(cp(1)) xw(2)];
sw = diff(cp);
decim = max([1,round(sw./ud.v.ds)]);
if ~ud.v.transpose
My = ud.v.M*ud.y(cp(1):decim:cp(2),:)';
else
My = ud.v.M*ud.y(:,cp(1):decim:cp(2));
end
doPlot(My,cp,ud.v,decim)
end
function moveRb(src,evt)
ha = gca;
cp = get(ha,'CurrentPoint');
ud = get(ha,'userdata');
cp = min([cp(1),ud.v.ind(end)]);
xw = get(ud.v.handles.pa,'xdata');
if xw(1) <= cp(1) - ud.v.minSizeWindow ...
&& diff([xw(1) cp(1)]) <= ud.v.maxSizeWindow
cp = [xw(1) round(cp(1))];
sw = diff(cp);
decim = max([1,round(sw./ud.v.ds)]);
if ~ud.v.transpose
My = ud.v.M*ud.y(cp(1):decim:cp(2),:)';
else
My = ud.v.M*ud.y(:,cp(1):decim:cp(2));
end
doPlot(My,cp,ud.v,decim)
end
function doPlot(y,xw,v,decim)
for i=1:v.nc
set(v.handles.hp(i),...
'xdata',xw(1):decim:xw(2),...
'ydata',y(i,:)+v.offset(i))
end
set(v.handles.axes,...
'ylim',[v.mi v.ma],'xlim',xw);
set(v.handles.pa,...
'xdata',[xw,fliplr(xw)]);
set(v.handles.lb,...
'xdata',[xw(1) xw(1)]);
set(v.handles.rb,...
'xdata',[xw(2) xw(2)]);
sw = diff(xw);
set(v.handles.hslider,...
'value',mean(xw),...
'min',max([1,sw/2-1]),...
'max',max([v.nt,v.nt-sw/2+1]),...
'sliderstep',.1*[sw/(v.nt-1) 4*sw/(v.nt-1)]);
|
github
|
philippboehmsturm/antx-master
|
loadxml.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/loadxml.m
| 4,985 |
utf_8
|
9429ec4334b8abc0ff9910e7c9019fdc
|
function varargout = loadxml(filename,varargin)
%LOADXML Load workspace variables from disk (XML file).
% LOADXML FILENAME retrieves all variables from a file given a full
% pathname or a MATLABPATH relative partial pathname (see PARTIALPATH).
% If FILENAME has no extension LOAD looks for FILENAME and FILENAME.xml
% and treats it as an XML file.
%
% LOAD, by itself, uses the XML file named 'matlab.xml'. It is an error
% if 'matlab.xml' is not found.
%
% LOAD FILENAME X loads only X.
% LOAD FILENAME X Y Z ... loads just the specified variables. The
% wildcard '*' loads variables that match a pattern.
% Requested variables from FILENAME are created in the workspace.
%
% S = LOAD(...) returns the contents of FILENAME in variable S. S is
% a struct containing fields matching the variables retrieved.
%
% Use the functional form of LOAD, such as LOAD('filename'), when the
% file name is stored in a string, when an output argument is requested,
% or if FILENAME contains spaces.
%
% See also LOAD, XML2MAT, XMLTREE.
% Copyright 2003 Guillaume Flandin.
% $Revision: 4393 $ $Date: 2003/07/10 13:50 $
% $Id: loadxml.m 4393 2011-07-18 14:52:32Z guillaume $
if nargin == 0
filename = 'matlab.xml';
fprintf('\nLoading from: %s\n\n',filename);
end
if ~ischar(filename)
error('[LOADXML] Argument must contain a string.');
end
if ~exist(filename,'file')
filename = [filename '.xml'];
if ~exist(filename,'file')
error(sprintf(...
'[LOADXML] Unable to read file %s: file does not exist',filename));
end
end
if nargout > 1,
error('[LOADXML] Too many output arguments.');
end
t = xmltree(filename);
uid = children(t,root(t));
if nargout == 1
% varargout{1} = struct([]); % Matlab 6.0 and above
end
flagfirstvar = 1;
for i=1:length(uid)
if strcmp(get(t,uid(i),'type'),'element')
vname = get(t,uid(i),'name');
% TODO % No need to parse the whole tree
if isempty(varargin) | ismember(varargin,vname)
v = xml_create_var(t,uid(i));
if nargout == 1
if flagfirstvar
varargout{1} = struct(vname,v);
flagfirstvar = 0;
else
varargout{1} = setfield(varargout{1},vname,v);
end
else
assignin('caller',vname,v);
end
end
end
end
%=======================================================================
function v = xml_create_var(t,uid)
type = attributes(t,'get',uid,'type');
sz = str2num(attributes(t,'get',uid,'size'));
switch type
case 'double'
v = str2num(get(t,children(t,uid),'value'));
if ~isempty(sz)
v = reshape(v,sz);
end
case 'sparse'
u = children(t,uid);
for k=1:length(u)
if strcmp(get(t,u(k),'name'),'row')
i = str2num(get(t,children(t,u(k)),'value'));
elseif strcmp(get(t,u(k),'name'),'col')
j = str2num(get(t,children(t,u(k)),'value'));
elseif strcmp(get(t,u(k),'name'),'val')
s = str2num(get(t,children(t,u(k)),'value'));
end
end
v = sparse(i,j,s,sz(1),sz(2));
case 'struct'
u = children(t,uid);
v = []; % works with Matlab < 6.0
for i=1:length(u)
s(1).type = '()';
s(1).subs = {str2num(attributes(t,'get',u(i),'index'))};
s(2).type = '.';
s(2).subs = get(t,u(i),'name');
v = subsasgn(v,s,xml_create_var(t,u(i)));
end
if isempty(u),
v = struct([]); % Need Matlab 6.0 and above
end
case 'cell'
v = cell(sz);
u = children(t,uid);
for i=1:length(u)
v{str2num(attributes(t,'get',u(i),'index'))} = ...
xml_create_var(t,u(i));
end
case 'char'
if isempty(children(t,uid))
v = '';
else
v = get(t,children(t,uid),'value');
end
try % this can fail if blank spaces are lost or entity escaping
if ~isempty(sz)
if sz(1) > 1
v = reshape(v,fliplr(sz))'; % row-wise order
else
v = reshape(v,sz);
end
end
end
case {'int8','uint8','int16','uint16','int32','uint32'}
% TODO % Handle integer formats
warning(sprintf('%s matrices not handled.',type));
v = 0;
otherwise
try,
v = feval(class(v),get(t,uid,'value'));
catch,
warning(sprintf(...
'[LOADXML] Cannot convert from XML to %s.',type));
end
end
|
github
|
philippboehmsturm/antx-master
|
spm_robust_average.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_robust_average.m
| 3,192 |
utf_8
|
d08041bc129e6fc7d0393de75bb74414
|
function [Y,W] = spm_robust_average(X, dim, ks)
% Apply robust averaging routine to X sets
% FORMAT [Y,W] = spm_robust_averaget(X, dim, ks)
% X - data matrix to be averaged
% dim - the dimension along which the function will work
% ks - offset of the weighting function (default: 3)
%
% W - estimated weights
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% James Kilner
% $Id: spm_robust_average.m 4638 2012-02-02 13:53:21Z vladimir $
if nargin < 3 || isempty(ks)
ks = 3;
end
if nargin < 2 || isempty(dim)
dim = 1;
end
%-Remember the original data size and size of the mean
%--------------------------------------------------------------------------
origsize = size(X);
morigsize = origsize;
morigsize(dim) = 1;
%-Convert the data to repetitions x points matrix
%--------------------------------------------------------------------------
if dim > 1
X = shiftdim(X, dim-1);
end
if length(origsize) > 2
X = reshape(X, size(X, 1), []);
end
%-Rescale the data
%--------------------------------------------------------------------------
[X, scalefactor] = spm_cond_units(X);
%-Actual robust averaging
%--------------------------------------------------------------------------
ores=1;
nres=10;
n=0;
W = zeros(size(X));
while max(abs(ores-nres))>sqrt(1E-8)
ores=nres;
n=n+1;
if n==1
Y = nanmedian(X);
else
XX = X;
XX(isnan(XX)) = 0;
Y = sum(W.*XX)./sum(W);
end
if n > 200
warning('Robust averaging could not converge. Maximal number of iterations exceeded.');
break;
end
res = X-repmat(Y, size(X, 1), 1);
mad = nanmedian(abs(res-repmat(nanmedian(res), size(res, 1), 1)));
ind1 = find(mad==0);
ind2 = find(mad~=0);
W(:, ind1) = ~res(:, ind1);
if ~isempty(ind2)
res = res(:, ind2);
mad = mad(ind2);
res = res./repmat(mad, size(res, 1), 1);
res = abs(res)-ks;
res(res<0) = 0;
nres = (sum(res(~isnan(res)).^2));
W(:, ind2) = (abs(res)<1) .* ((1 - res.^2).^2);
W(W == 0) = eps; % This is to prevent appearance of NaNs when normalizing
W(isnan(X)) = 0;
W(X == 0 & ~repmat(all(X==0), size(X, 1), 1)) = 0; %Assuming X is a real measurement
end
end
disp(['Robust averaging finished after ' num2str(n) ' iterations.']);
%-Restore the average and weights to the original data dimensions
%--------------------------------------------------------------------------
Y = Y./scalefactor;
if length(origsize) > 2
Y = reshape(Y, circshift(morigsize, [1 -(dim-1)]));
W = reshape(W, circshift(origsize, [1 -(dim-1)]));
end
if dim > 1
Y = shiftdim(Y, length(origsize)-dim+1);
W = shiftdim(W, length(origsize)-dim+1);
end
%-Helper function
%--------------------------------------------------------------------------
function Y = nanmedian(X)
if ~any(any(isnan(X)))
Y = median(X);
else
Y = zeros(1, size(X,2));
for i = 1:size(X, 2)
Y(i) = median(X(~isnan(X(:, i)), i));
end
end
|
github
|
philippboehmsturm/antx-master
|
spm_BMS_F_smpl.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_BMS_F_smpl.m
| 1,628 |
utf_8
|
ee07ac8baecef03c27abc7bbde7c2ebe
|
function [s_samp,s_bound] = spm_BMS_F_smpl (alpha,lme,alpha0)
% Get sample and lower bound approx. for model evidence p(y|r)
% in group BMS; see spm_BMS_F.
%
% FORMAT [s_samp,s_bound] = spm_BMS_F_smpl (alpha,lme,alpha0)
%
% REFERENCE: See appendix in
% Stephan KE, Penny WD, Daunizeau J, Moran RJ, Friston KJ
% Bayesian Model Selection for Group Studies. NeuroImage (under review)
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Will Penny
% $Id: spm_BMS_F_smpl.m 2626 2009-01-20 16:30:08Z maria $
% prevent numerical problems
max_val = log(realmax('double'));
for i=1:size(lme,1),
lme(i,:) = lme(i,:) - mean(lme(i,:));
for k = 1:size(lme,2),
lme(i,k) = sign(lme(i,k)) * min(max_val,abs(lme(i,k)));
end
end
% Number of samples per alpha bin (0.1)
Nsamp = 1e3;
% Sample from univariate gamma densities then normalise
% (see Dirichlet entry in Wikipedia or Ferguson (1973) Ann. Stat. 1,
% 209-230)
Nk = length(alpha);
for k = 1:Nk,
alpha_samp(:,k) = spm_gamrnd(alpha(k),1,Nsamp,1);
end
Ni = size(lme,1);
for i = 1:Ni,
s_approx(i) = sum((alpha./sum(alpha)).*lme(i,:));
s(i) = 0;
for n = 1:Nsamp,
s(i) = s(i) + si_fun(alpha_samp(n,:),lme(i,:));
end
s(i) = s(i)/Nsamp;
end
s_bound = sum(s_approx);
s_samp = sum(s);
return
%=========================================================================
function [si] = si_fun (alpha,lme)
% Check a lower bound
% FORMAT [si] = si_fun (alpha,lme)
esi = sum((exp(lme).*alpha)/sum(alpha));
si = log(esi);
return
|
github
|
philippboehmsturm/antx-master
|
spm_normalise.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_normalise.m
| 12,919 |
utf_8
|
716d6de42742658332dc1d1712f9738f
|
function params = spm_normalise(VG,VF,matname,VWG,VWF,flags)
% Spatial (stereotactic) normalisation
%
% FORMAT params = spm_normalise(VG,VF,matname,VWG,VWF,flags)
% VG - template handle(s)
% VF - handle of image to estimate params from
% matname - name of file to store deformation definitions
% VWG - template weighting image
% VWF - source weighting image
% flags - flags. If any field is not passed, then defaults are assumed.
% (defaults values are defined in spm_defaults.m)
% smosrc - smoothing of source image (FWHM of Gaussian in mm).
% smoref - smoothing of template image (defaults to 0).
% regtype - regularisation type for affine registration
% See spm_affreg.m
% cutoff - Cutoff of the DCT bases. Lower values mean more
% basis functions are used
% nits - number of nonlinear iterations
% reg - amount of regularisation
% _________________________________________________________________________
%
% This module spatially (stereotactically) normalises MRI, PET or SPECT
% images into a standard space defined by some ideal model or template
% image[s]. The template images supplied with SPM conform to the space
% defined by the ICBM, NIH P-20 project, and approximate that of the
% the space described in the atlas of Talairach and Tournoux (1988).
% The transformation can also be applied to any other image that has
% been coregistered with these scans.
%
%
% Mechanism
% Generally, the algorithms work by minimising the sum of squares
% difference between the image which is to be normalised, and a linear
% combination of one or more template images. For the least squares
% registration to produce an unbiased estimate of the spatial
% transformation, the image contrast in the templates (or linear
% combination of templates) should be similar to that of the image from
% which the spatial normalization is derived. The registration simply
% searches for an optimum solution. If the starting estimates are not
% good, then the optimum it finds may not find the global optimum.
%
% The first step of the normalization is to determine the optimum
% 12-parameter affine transformation. Initially, the registration is
% performed by matching the whole of the head (including the scalp) to
% the template. Following this, the registration proceeded by only
% matching the brains together, by appropriate weighting of the template
% voxels. This is a completely automated procedure (that does not
% require ``scalp editing'') that discounts the confounding effects of
% skull and scalp differences. A Bayesian framework is used, such that
% the registration searches for the solution that maximizes the a
% posteriori probability of it being correct. i.e., it maximizes the
% product of the likelihood function (derived from the residual squared
% difference) and the prior function (which is based on the probability
% of obtaining a particular set of zooms and shears).
%
% The affine registration is followed by estimating nonlinear deformations,
% whereby the deformations are defined by a linear combination of three
% dimensional discrete cosine transform (DCT) basis functions.
% The parameters represent coefficients of the deformations in
% three orthogonal directions. The matching involved simultaneously
% minimizing the bending energies of the deformation fields and the
% residual squared difference between the images and template(s).
%
% An option is provided for allowing weighting images (consisting of pixel
% values between the range of zero to one) to be used for registering
% abnormal or lesioned brains. These images should match the dimensions
% of the image from which the parameters are estimated, and should contain
% zeros corresponding to regions of abnormal tissue.
%
%
% Uses
% Primarily for stereotactic normalization to facilitate inter-subject
% averaging and precise characterization of functional anatomy. It is
% not necessary to spatially normalise the data (this is only a
% pre-requisite for intersubject averaging or reporting in the
% Talairach space).
%
% Inputs
% The first input is the image which is to be normalised. This image
% should be of the same modality (and MRI sequence etc) as the template
% which is specified. The same spatial transformation can then be
% applied to any other images of the same subject. These files should
% conform to the SPM data format (See 'Data Format'). Many subjects can
% be entered at once, and there is no restriction on image dimensions
% or voxel size.
%
% Providing that the images have a correct voxel-to-world mapping,
% which describes the spatial relationship between them, it is
% possible to spatially normalise the images without having first
% resliced them all into the same space.
%
% Default values of parameters pertaining to the extent and sampling of
% the standard space can be changed, including the model or template
% image[s].
%
%
% Outputs
% The details of the transformations are displayed in the results window,
% and the parameters are saved in the "*_sn.mat" file.
%
%__________________________________________________________________________
% Refs:
% K.J. Friston, J. Ashburner, C.D. Frith, J.-B. Poline,
% J.D. Heather, and R.S.J. Frackowiak
% Spatial Registration and Normalization of Images.
% Human Brain Mapping 2:165-189(1995)
%
% J. Ashburner, P. Neelin, D.L. Collins, A.C. Evans and K. J. Friston
% Incorporating Prior Knowledge into Image Registration.
% NeuroImage 6:344-352 (1997)
%
% J. Ashburner and K. J. Friston
% Nonlinear Spatial Normalization using Basis Functions.
% Human Brain Mapping 7(4):in press (1999)
%__________________________________________________________________________
% Copyright (C) 2002-2011 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_normalise.m 4621 2012-01-13 11:12:40Z guillaume $
if nargin<2, error('Incorrect usage.'); end;
if ischar(VF), VF = spm_vol(VF); end;
if ischar(VG), VG = spm_vol(VG); end;
if nargin<3,
if nargout==0,
[pth,nm,xt,vr] = spm_fileparts(deblank(VF(1).fname));
matname = fullfile(pth,[nm '_sn.mat']);
else
matname = '';
end;
end;
if nargin<4, VWG = ''; end;
if nargin<5, VWF = ''; end;
if ischar(VWG), VWG=spm_vol(VWG); end;
if ischar(VWF), VWF=spm_vol(VWF); end;
def_flags = spm_get_defaults('normalise.estimate');
def_flags.graphics = 1;
if nargin < 6,
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;
fprintf('Smoothing by %g & %gmm..\n', flags.smoref, flags.smosrc);
VF1 = spm_smoothto8bit(VF,flags.smosrc);
% Rescale images so that globals are better conditioned
VF1.pinfo(1:2,:) = VF1.pinfo(1:2,:)/spm_global(VF1);
for i=1:numel(VG),
VG1(i) = spm_smoothto8bit(VG(i),flags.smoref);
VG1(i).pinfo(1:2,:) = VG1(i).pinfo(1:2,:)/spm_global(VG(i));
end;
% Affine Normalisation
%--------------------------------------------------------------------------
fprintf('Coarse Affine Registration..\n');
aflags = struct('sep',max(flags.smoref,flags.smosrc), 'regtype',flags.regtype,...
'WG',[],'WF',[],'globnorm',0);
aflags.sep = max(aflags.sep,max(sqrt(sum(VG(1).mat(1:3,1:3).^2))));
aflags.sep = max(aflags.sep,max(sqrt(sum(VF(1).mat(1:3,1:3).^2))));
M = eye(4); %spm_matrix(prms');
spm_plot_convergence('Init','Affine Registration','Mean squared difference','Iteration');
[M,scal] = spm_affreg(VG1, VF1, aflags, M);
fprintf('Fine Affine Registration..\n');
aflags.WG = VWG;
aflags.WF = VWF;
aflags.sep = aflags.sep/2;
[M,scal] = spm_affreg(VG1, VF1, aflags, M,scal);
Affine = inv(VG(1).mat\M*VF1(1).mat);
spm_plot_convergence('Clear');
% Basis function Normalisation
%--------------------------------------------------------------------------
fov = VF1(1).dim(1:3).*sqrt(sum(VF1(1).mat(1:3,1:3).^2));
if any(fov<15*flags.smosrc/2 & VF1(1).dim(1:3)<15),
fprintf('Field of view too small for nonlinear registration\n');
Tr = [];
elseif isfinite(flags.cutoff) && flags.nits && ~isinf(flags.reg),
fprintf('3D CT Norm...\n');
Tr = snbasis(VG1,VF1,VWG,VWF,Affine,...
max(flags.smoref,flags.smosrc),flags.cutoff,flags.nits,flags.reg);
else
Tr = [];
end;
clear VF1 VG1
flags.version = 'spm_normalise.m 2.12 04/11/26';
flags.date = date;
params = struct('Affine',Affine, 'Tr',Tr, 'VF',VF, 'VG',VG, 'flags',flags);
if flags.graphics, spm_normalise_disp(params,VF); end;
% Remove dat fields before saving
%--------------------------------------------------------------------------
if isfield(VF,'dat'), VF = rmfield(VF,'dat'); end;
if isfield(VG,'dat'), VG = rmfield(VG,'dat'); end;
if ~isempty(matname),
fprintf('Saving Parameters..\n');
if spm_check_version('matlab','7') >= 0,
save(matname,'-V6','Affine','Tr','VF','VG','flags');
else
save(matname,'Affine','Tr','VF','VG','flags');
end;
end;
return;
%__________________________________________________________________________
%__________________________________________________________________________
function Tr = snbasis(VG,VF,VWG,VWF,Affine,fwhm,cutoff,nits,reg)
% 3D Basis Function Normalization
% FORMAT Tr = snbasis(VG,VF,VWG,VWF,Affine,fwhm,cutoff,nits,reg)
% VG - Template volumes (see spm_vol).
% VF - Volume to normalise.
% VWG - weighting Volume - for template.
% VWF - weighting Volume - for object.
% Affine - A 4x4 transformation (in voxel space).
% fwhm - smoothness of images.
% cutoff - frequency cutoff of basis functions.
% nits - number of iterations.
% reg - regularisation.
% Tr - Discrete cosine transform of the warps in X, Y & Z.
%
% snbasis performs a spatial normalization based upon a 3D
% discrete cosine transform.
%
%__________________________________________________________________________
fwhm = [fwhm 30];
% Number of basis functions for x, y & z
%--------------------------------------------------------------------------
tmp = sqrt(sum(VG(1).mat(1:3,1:3).^2));
k = max(round((VG(1).dim(1:3).*tmp)/cutoff),[1 1 1]);
% Scaling is to improve stability.
%--------------------------------------------------------------------------
stabilise = 8;
basX = spm_dctmtx(VG(1).dim(1),k(1))*stabilise;
basY = spm_dctmtx(VG(1).dim(2),k(2))*stabilise;
basZ = spm_dctmtx(VG(1).dim(3),k(3))*stabilise;
dbasX = spm_dctmtx(VG(1).dim(1),k(1),'diff')*stabilise;
dbasY = spm_dctmtx(VG(1).dim(2),k(2),'diff')*stabilise;
dbasZ = spm_dctmtx(VG(1).dim(3),k(3),'diff')*stabilise;
vx1 = sqrt(sum(VG(1).mat(1:3,1:3).^2));
vx2 = vx1;
kx = (pi*((1:k(1))'-1)/VG(1).dim(1)/vx1(1)).^2; ox=ones(k(1),1);
ky = (pi*((1:k(2))'-1)/VG(1).dim(2)/vx1(2)).^2; oy=ones(k(2),1);
kz = (pi*((1:k(3))'-1)/VG(1).dim(3)/vx1(3)).^2; oz=ones(k(3),1);
if 1,
% BENDING ENERGY REGULARIZATION
% Estimate a suitable sparse diagonal inverse covariance matrix for
% the parameters (IC0).
%------------------------------------------------------------------
IC0 = (1*kron(kz.^2,kron(ky.^0,kx.^0)) +...
1*kron(kz.^0,kron(ky.^2,kx.^0)) +...
1*kron(kz.^0,kron(ky.^0,kx.^2)) +...
2*kron(kz.^1,kron(ky.^1,kx.^0)) +...
2*kron(kz.^1,kron(ky.^0,kx.^1)) +...
2*kron(kz.^0,kron(ky.^1,kx.^1)) );
IC0 = reg*IC0*stabilise^6;
IC0 = [IC0*vx2(1)^4 ; IC0*vx2(2)^4 ; IC0*vx2(3)^4 ; zeros(prod(size(VG))*4,1)];
IC0 = sparse(1:length(IC0),1:length(IC0),IC0,length(IC0),length(IC0));
else
% MEMBRANE ENERGY (LAPLACIAN) REGULARIZATION
%------------------------------------------------------------------
IC0 = kron(kron(oz,oy),kx) + kron(kron(oz,ky),ox) + kron(kron(kz,oy),ox);
IC0 = reg*IC0*stabilise^6;
IC0 = [IC0*vx2(1)^2 ; IC0*vx2(2)^2 ; IC0*vx2(3)^2 ; zeros(prod(size(VG))*4,1)];
IC0 = sparse(1:length(IC0),1:length(IC0),IC0,length(IC0),length(IC0));
end;
% Generate starting estimates.
%--------------------------------------------------------------------------
s1 = 3*prod(k);
s2 = s1 + numel(VG)*4;
T = zeros(s2,1);
T(s1+(1:4:numel(VG)*4)) = 1;
pVar = Inf;
for iter=1:nits,
fprintf(' iteration %2d: ', iter);
[Alpha,Beta,Var,fw] = spm_brainwarp(VG,VF,Affine,basX,basY,basZ,dbasX,dbasY,dbasZ,T,fwhm,VWG, VWF);
if Var>pVar, scal = pVar/Var ; Var = pVar; else scal = 1; end;
pVar = Var;
T = (Alpha + IC0*scal)\(Alpha*T + Beta);
fwhm(2) = min([fw fwhm(2)]);
fprintf(' FWHM = %6.4g Var = %g\n', fw,Var);
end;
% Values of the 3D-DCT
%--------------------------------------------------------------------------
Tr = reshape(T(1:s1),[k 3]) * stabilise.^3;
return;
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_ft2spm.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_eeg_ft2spm.m
| 6,129 |
utf_8
|
a5369fdb03fab87d6f33d7a88c8bbac1
|
function D = spm_eeg_ft2spm(ftdata, filename)
% Converter from Fieldtrip (http://www.ru.nl/fcdonders/fieldtrip/)
% data structures to SPM8 file format
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Vladimir Litvak
% $Id: spm_eeg_ft2spm.m 4038 2010-08-10 10:39:00Z vladimir $
isTF = 0;
% If raw format
if iscell(ftdata.time)
if length(ftdata.time)>1
% Initial checks
if any(diff(cellfun('length', ftdata.time))~=0)
error('SPM can only handle data with equal trial lengths.');
else
times=cell2mat(ftdata.time(:));
if any(diff(times(:, 1))~=0) || any(diff(times(:, end))~=0)
error('SPM can only handle data the same trial borders.');
end
end
end
Ntrials=length(ftdata.trial);
Nchannels = size(ftdata.trial{1},1);
Nsamples = size(ftdata.trial{1},2);
data = zeros(Nchannels, Nsamples, Ntrials);
for n=1:Ntrials
data(:,:,n) = ftdata.trial{n};
end
ftdata.time = ftdata.time{1};
else
Nchannels = numel(ftdata.label);
Nsamples = length(ftdata.time);
rptind=strmatch('rpt', tokenize(ftdata.dimord, '_'));
if isempty(rptind)
rptind=strmatch('subj', tokenize(ftdata.dimord, '_'));
end
timeind=strmatch('time', tokenize(ftdata.dimord, '_'));
chanind=strmatch('chan', tokenize(ftdata.dimord, '_'));
if any(ismember({'trial', 'individual', 'avg'}, fieldnames(ftdata) )) % timelockanalysis
if ~isempty(rptind)
if isfield(ftdata, 'trial')
Ntrials = size(ftdata.trial, rptind);
data =permute(ftdata.trial, [chanind, timeind, rptind]);
else
Ntrials = size(ftdata.individual, rptind);
data =permute(ftdata.individual, [chanind, timeind, rptind]);
end
else
Ntrials = 1;
data =permute(ftdata.avg, [chanind, timeind]);
end
elseif isfield(ftdata, 'powspctrm')
isTF = 1;
Nfrequencies = numel(ftdata.freq);
freqind = strmatch('freq', tokenize(ftdata.dimord, '_'));
if ~isempty(rptind)
Ntrials = size(ftdata.powspctrm, rptind);
data = permute(ftdata.powspctrm, [chanind, freqind, timeind, rptind]);
else
Ntrials = 1;
data = permute(ftdata.powspctrm, [chanind, freqind, timeind]);
end
end
end
%--------- Start making the header
D = [];
% sampling rate in Hz
if isfield(ftdata, 'fsample')
D.Fsample = ftdata.fsample;
else
D.Fsample = 1./mean(diff(ftdata.time));
end
D.timeOnset = ftdata.time(1);
% Number of time bins in peri-stimulus time
D.Nsamples = Nsamples;
% Names of channels in order of the data
D.channels = struct('label', ftdata.label);
D.trials = repmat(struct('label', {'Undefined'}), 1, Ntrials);
[pathname, fname] = fileparts(filename);
D.path = pathname;
D.fname = [fname '.mat'];
D.data.fnamedat = [fname '.dat'];
D.data.datatype = 'float32-le';
if ~isTF
if Ntrials == 1
datafile = file_array(fullfile(D.path, D.data.fnamedat), [Nchannels Nsamples], D.data.datatype);
% physically initialise file
datafile(end,end) = 0;
datafile(:, :) = data;
else
datafile = file_array(fullfile(D.path, D.data.fnamedat), [Nchannels Nsamples Ntrials], D.data.datatype);
% physically initialise file
datafile(end,end) = 0;
datafile(:, :, :) = data;
end
else
if Ntrials == 1
datafile = file_array(fullfile(D.path, D.data.fnamedat), [Nchannels Nfrequencies Nsamples], D.data.datatype);
% physically initialise file
datafile(end,end) = 0;
datafile(:, :, :) = data;
else
datafile = file_array(fullfile(D.path, D.data.fnamedat), [Nchannels Nfrequencies Nsamples Ntrials], D.data.datatype);
% physically initialise file
datafile(end,end) = 0;
datafile(:, :, :, :) = data;
end
D.transform.ID = 'TF';
D.transform.frequencies = ftdata.freq;
end
D.data.y = datafile;
D = meeg(D);
if isfield(ftdata, 'hdr')
% Uses fileio function to get the information about channel types stored in
% the original header. This is now mainly useful for Neuromag support but might
% have other functions in the future.
origchantypes = ft_chantype(ftdata.hdr);
[sel1, sel2] = spm_match_str(D.chanlabels, ftdata.hdr.label);
origchantypes = origchantypes(sel2);
if length(strmatch('unknown', origchantypes, 'exact')) ~= numel(origchantypes)
D.origchantypes = struct([]);
D.origchantypes(1).label = ftdata.hdr.label(sel2);
D.origchantypes(1).type = origchantypes;
end
end
% Set channel types to default
S1 = [];
S1.task = 'defaulttype';
S1.D = D;
S1.updatehistory = 0;
D = spm_eeg_prep(S1);
if Ntrials == 1
D = type(D, 'continuous');
else
D = type(D, 'single');
end
if isfield(ftdata, 'hdr') && isfield(ftdata.hdr, 'grad')
D = sensors(D, 'MEG', ft_convert_units(ftdata.hdr.grad, 'mm'));
S = [];
S.task = 'project3D';
S.modality = 'MEG';
S.updatehistory = 0;
S.D = D;
D = spm_eeg_prep(S);
end
[ok D] = check(D);
save(D);
function [tok] = tokenize(str, sep, rep)
% TOKENIZE cuts a string into pieces, returning a cell array
%
% Use as
% t = tokenize(str, sep)
% t = tokenize(str, sep, rep)
% where str is a string and sep is the separator at which you want
% to cut it into pieces.
%
% Using the optional boolean flag rep you can specify whether repeated
% seperator characters should be squeezed together (e.g. multiple
% spaces between two words). The default is rep=1, i.e. repeated
% seperators are treated as one.
% Copyright (C) 2003-2006, Robert Oostenveld
tok = {};
f = find(str==sep);
f = [0, f, length(str)+1];
for i=1:(length(f)-1)
tok{i} = str((f(i)+1):(f(i+1)-1));
end
if nargin<3 || rep
% remove empty cells, which occur if the separator is repeated (e.g. multiple spaces)
tok(find(cellfun('isempty', tok)))=[];
end
|
github
|
philippboehmsturm/antx-master
|
spm_spike_fix.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_spike_fix.m
| 4,022 |
utf_8
|
cd3493fe3f024b723204183667a038ae
|
function [Mean_result, Std_result] = spm_spike_fix(correct);
% function [Mean_result, Std_result] = spm_spike_fix(correct);
% If correct = 1 whole volumes will be corrected
% If correct = 0 the routine reports suspicious slices only
% Report 0th and 1st order moments of scans (slice by slice)
% Uses raw data and finited differenced data.
% comes up with spm_get
% works only for transaxially oriented scans
% Christian Buechel and Oliver Josephs
if nargin < 1
correct = 0;
end
SPMid = spm('FnBanner',mfilename,'2.7');
[Finter,Fgraph,CmdLine] = spm('FnUIsetup','spm spike');
spm_help('!ContextHelp',mfilename);
Fgraph = spm_figure('FindWin','Graphics');
str = sprintf('select scans');
P = spm_get(Inf,'.img',str);
thr = spm_input('threshold in sd',1);
q = size(P,1);
% map image files into memory
Vin = spm_vol(P);
nimgo = size(P,1);
nslices = Vin(1).dim(3);
Mean_result = zeros(Vin(1).dim(3),q);
Min_result = zeros(Vin(1).dim(3),q);
Max_result = zeros(Vin(1).dim(3),q);
Std_result = zeros(Vin(1).dim(3),q);
spm_progress_bar('Init',100,'Spike',' ');
sx = round(Vin(1).dim(1)/4);
ex = sx + round(Vin(1).dim(1)/2);
for k = 1:nslices,
% Read in slice data
B = spm_matrix([0 0 k]);
for m=1:nimgo,
d = spm_slice_vol(Vin(m),B,Vin(1).dim(1:2),1);
d = d(sx:ex,:);
%if k>10
% keyboard;
%end
Mean_result(k,m) = mean(mean(d));
Std_result(k,m) = std(std(d));
end;
spm_progress_bar('Set',k*100/nslices);
end;
spm_progress_bar('Clear');
%Normalize to mean = 0, std = 1
%---------------------
SLmean = mean(Mean_result');
SLstd = std(Mean_result');
Nmean = meancor(Mean_result');
Nstd = (ones(size(Nmean,1),1).*thr)*SLstd;
Mask_mean = ones(size(Nmean));
Mask_mean(find(Nmean<Nstd & Nmean>-Nstd)) = 0;
%display results
%--------------------------------------
%sqrt of mean corrected data
%----
figure(Fgraph); spm_clf;
colormap hot;
subplot(4,1,1);
imagesc(sqrt(abs(Nmean')));
colorbar;
xlabel('scan');
ylabel('slice');
title('Sqrt of abs(Mean)');
%Std
%---
subplot(4,1,2);
plot(Nmean);
xlim([1 size(Nmean,1)]);
colorbar;
xlabel('scan');
title('Mean');
%Mask
%----
colormap hot;
subplot(4,1,3);
imagesc(Mask_mean')
colorbar;
xlabel('scan');
ylabel('slice');
title('above threshold');
%Mask
%----
subplot(4,1,4);
bar(sum(Mask_mean'))
xlim([1 size(Nmean,1)]);
colorbar;
xlabel('scan');
ylabel('# of slices');
title('above threshold');
badrow = 5;
broken_slices = 2;
fprintf('Suspicious scans and slices (threshold = %1.1f, more than %1.1f slices affected): \n\n',thr,broken_slices);
[pa,na,ex] = fileparts(P(1,:));
if correct
res = mkdir(pa,'spike_cor');
if res == 0
error('Cannot create directory for moved files');
end
end
affected = find(sum(Mask_mean') > broken_slices);
for j = affected;
fprintf(['\nScan: %1.0f [' P(j,:) ']' '\nSlices: '], j);
[pa,na,ex] = fileparts(P(j,:));
if correct
% save original file
copyfile([pa filesep na '.img'],[pa filesep 'spike_cor']);
copyfile([pa filesep na '.hdr'],[pa filesep 'spike_cor']);
copyfile([pa filesep na '.mat'],[pa filesep 'spike_cor']);
dist = -1;
success = 0;
while abs(dist) < badrow
% go back first
repl = j+dist;
if (repl > 0) & (repl <= nimgo) & (~ismember(repl,affected))
success = 1;
break;
else
if dist < 0
dist = dist * (-1);
else
dist = (dist + 1) * (-1);
end
end
end
if ~success
error(fprintf('More than %1.0f faulty scans in a row\n',badrow));
else
[rpa,rna,rex] = fileparts(P(repl,:));
fprintf(['Correcting ' na '.img with ' rna '.img\n']);
copyfile([pa filesep rna '.img'],[pa filesep na '.img']);
copyfile([pa filesep rna '.hdr'],[pa filesep na '.hdr']);
copyfile([pa filesep rna '.mat'],[pa filesep na '.mat']);
end
end
for i = 1:nslices
if Mask_mean(j,i)
fprintf(['%1.0f '],i);
end
end
end
fprintf('\n');
function Y = meancor(X);
% function Y = meancor(X);
% if columns of zeros untouched
Y = X - ones(size(X,1),1)*mean(X); %zero mean
|
github
|
philippboehmsturm/antx-master
|
spm_pf.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_pf.m
| 6,768 |
utf_8
|
7a122bb3a5c25e63f4470b6ba52cdb54
|
function [qx,qP,qD,xhist] = spm_pf(M,y,U)
% Particle Filtering for dynamic models
% FORMAT [qx,qP,qD,xhist] = spm_pf(M,y)
% M - model specification structure
% y - output or data (N x T)
% U - exogenous input
%
% M(1).x % initial states
% M(1).f = inline(f,'x','v','P') % state equation
% M(1).g = inline(g,'x','v','P') % observer equation
% M(1).pE % parameters
% M(1).V % observation noise precision
%
% M(2).v % initial process noise
% M(2).V % process noise precision
%
% qx - conditional expectation of states
% qP - {1 x T} conditional covariance of states
% qD - full sample
%__________________________________________________________________________
% See notes at the end of this script for details and a demo. This routine
% is based on:
%
% var der Merwe R, Doucet A, de Freitas N and Wan E (2000). The
% unscented particle filter. Technical Report CUED/F-INFENG/TR 380
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Karl Friston
% $Id: spm_pf.m 1143 2008-02-07 19:33:33Z spm $
% check model specification
%--------------------------------------------------------------------------
M = spm_DEM_M_set(M);
dt = M(1).E.dt;
if length(M) ~=2
errordlg('spm_pf requires a two-level model')
return
end
% INITIALISATION:
%==========================================================================
T = length(y); % number of time points
n = M(2).l; % number of innovations
N = 200; % number of particles.
% precision of measurement noise
%--------------------------------------------------------------------------
R = M(1).V;
for i = 1:length(M(1).Q)
R = R + M(1).Q{i}*exp(M(1).h(i));
end
P = M(1).pE; % parameters
Q = M(2).V.^-.5; % root covariance of innovations
v = kron(ones(1,N),M(2).v); % innovations
x = kron(ones(1,N),M(1).x); % hidden states
v = v + 128*Q*randn(size(v));
% inputs
%--------------------------------------------------------------------------
if nargin < 3
U = sparse(n,T);
end
for t = 1:T
% PREDICTION STEP: with the (8x) transition prior as proposal
%----------------------------------------------------------------------
for i = 1:N
v(:,i) = 8*Q*randn(n,1) + U(:,t);
f = M(1).f(x(:,i),v(:,i),P);
dfdx = spm_diff(M(1).f,x(:,i),v(:,i),P,1);
xPred(:,i) = x(:,i) + spm_dx(dfdx,f,dt);
end
% EVALUATE IMPORTANCE WEIGHTS: and normalise
%----------------------------------------------------------------------
for i = 1:N
yPred = M(1).g(xPred(:,i),v(:,i),P);
ePred = yPred - y(:,t);
w(i) = ePred'*R*ePred;
end
w = w - min(w);
w = exp(-w/2);
w = w/sum(w);
% SELECTION STEP: multinomial resampling.
%----------------------------------------------------------------------
x = xPred(:,multinomial(1:N,w));
% report and record moments
%----------------------------------------------------------------------
qx(:,t) = mean(x,2);
qP{t} = cov(x');
qX(:,t) = x(:);
fprintf('PF: time-step = %i : %i\n',t,T);
end
% sample density
%==========================================================================
if nargout > 3
xhist = linspace(min(qX(:)),max(qX(:)),32);
for i = 1:T
q = hist(qX(:,i),xhist);
qD(:,i) = q(:);
end
end
return
function I = multinomial(inIndex,q);
%==========================================================================
% PURPOSE : Performs the resampling stage of the SIR
% in order(number of samples) steps.
% INPUTS : - inIndex = Input particle indices.
% - q = Normalised importance ratios.
% OUTPUTS : - I = Resampled indices.
% AUTHORS : Arnaud Doucet and Nando de Freitas
% MULTINOMIAL SAMPLING:
% generate S ordered random variables uniformly distributed in [0,1]
% high speed Niclas Bergman Procedure
%--------------------------------------------------------------------------
q = q(:);
S = length(q); % S = Number of particles.
N_babies = zeros(1,S);
cumDist = cumsum(q');
u = fliplr(cumprod(rand(1,S).^(1./(S:-1:1))));
j = 1;
for i = 1:S
while (u(1,i) > cumDist(1,j))
j = j + 1;
end
N_babies(1,j) = N_babies(1,j) + 1;
end;
% COPY RESAMPLED TRAJECTORIES:
%--------------------------------------------------------------------------
index = 1;
for i = 1:S
if (N_babies(1,i)>0)
for j=index:index+N_babies(1,i)-1
I(j) = inIndex(i);
end;
end;
index = index + N_babies(1,i);
end
return
%==========================================================================
% notes and demo:
%==========================================================================
% The code below generates a nonlinear, non-Gaussian problem (S) comprising
% a model S.M and data S.Y (c.f. van der Merwe et al 2000))
%
% The model is f(x) = dxdt
% = 1 + sin(0.04*pi*t) - log(2)*x + n
% y = g(x)
% = (x.^2)/5 : if t < 30
% -2 + x/2 : otherwise
% i.e. the output nonlinearity becomes linear after 30 time steps. In this
% implementation time is modelled as an auxiliary state variable. n is
% the process noise, which is modelled as a log-normal variate. e is
% Gaussian observation noise.
% model specification
%--------------------------------------------------------------------------
f = '[1; (1 + sin(P(2)*pi*x(1)) - P(1)*x(2) + exp(v))]';
g = '(x(1) > 30)*(-2 + x(2)/2) + ~(x(1) > 30)*(x(2).^2)/5';
M(1).x = [1; 1]; % initial states
M(1).f = inline(f,'x','v','P'); % state equation
M(1).g = inline(g,'x','v','P'); % observer equation
M(1).pE = [log(2) 0.04]; % parameters
M(1).V = exp(4); % observation noise precision
M(2).v = 0; % initial process log(noise)
M(2).V = 2.4; % process log(noise) precision
% generate data (output)
%--------------------------------------------------------------------------
T = 60; % number of time points
S = spm_DEM_generate(M,T);
% Particle filtering
%--------------------------------------------------------------------------
pf_x = spm_pf(M,S.Y);
% plot results
%--------------------------------------------------------------------------
x = S.pU.x{1};
plot([1:T],x(2,:),[1:T],pf_x(2,:))
legend({'true','PF'})
|
github
|
philippboehmsturm/antx-master
|
spm_SpUtil.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_SpUtil.m
| 27,031 |
utf_8
|
52ecc1ec2086a8b82b6e6192fd8f435a
|
function varargout = spm_SpUtil(varargin)
% Space matrix utilities
% FORMAT varargout = spm_SpUtil(action,varargin)
%
%_______________________________________________________________________
%
% spm_SpUtil is a multi-function function containing various utilities
% for Design matrix and contrast construction and manipulation. In
% general, it accepts design matrices as plain matrices or as space
% structures setup by spm_sp.
%
% Many of the space utilities are computed using an SVD of the design
% matrix. The advantage of using space structures is that the svd of
% the design matrix is stored in the space structure, thereby saving
% unnecessary repeated computation of the SVD. This presents a
% considerable efficiency gain for large design matrices.
%
% Note that when space structures are passed as arguments is is
% assummed that their basic fields are filled in. See spm_sp for
% details of (design) space structures and their manipulation.
%
% Quick Reference :
%---------------------
% ('isCon',x,c) :
% ('allCon',x,c) :
% ('ConR',x,c) :
% ('ConO',x,c) :
% ('size',x,dim) :
% ('iX0check',i0,sL) :
%---------------------
% ('i0->c',x,i0) : Out : c
% ('c->Tsp',x,c) : Out : [X1o [X0]]
% ('+c->Tsp',x,c) : Out : [ukX1o [ukX0]]
% ('i0->x1o',x,i0) : Use ('i0->c',x,i0) and ('c->Tsp',X,c)
% ('+i0->x1o',x,i0) : Use ('i0->c',x,i0) and ('+c->Tsp',X,c)
% ('X0->c',x,X0) :~
% ('+X0->c',x,cukX0) :~
%---------------------
% ('trRV',x[,V]) :
% ('trMV',x[,V]) :
% ('i0->edf',x,i0,V) :
%
%---------------------
%
% Improvement compared to the spm99 beta version :
%
% Improvements in df computation using spm_SpUtil('trRV',x[,V]) and
% spm_SpUtil('trMV',sX [,V]). The degrees of freedom computation requires
% in general that the trace of RV and of RVRV be computed, where R is a
% projector onto either a sub space of the design space or the residual
% space, namely the space that is orthogonal to the design space. V is
% the (estimated or assumed) variance covariance matrix and is a number
% of scans by number of scans matrix which can be huge in some cases. We
% have (thanks to S Rouquette and JB) speed up this computation
% by using matlab built in functions of the frobenius norm and some theorems
% on trace computations.
%
% ======================================================================
%
% FORMAT i = spm_SpUtil('isCon',x,c)
% Tests whether weight vectors specify contrasts
% x - Design matrix X, or space structure of X
% c - contrast matrix (I.e. matrix of contrast weights, contrasts in columns)
% Must have column dimension matching that of X
% [defaults to eye(size(X,2)) to test uniqueness of parameter estimates]
% i - logical row vector indiciating estimability of contrasts in c
%
% A linear combination of the parameter estimates is a contrast if and
% only if the weight vector is in the space spanned by the rows of X.
%
% The algorithm works by regressing the contrast weight vectors using
% design matrix X' (X transposed). Any contrast weight vectors will be
% fitted exactly by this procedure, leaving zero residual. Parameter
% tol is the tolerance applied when searching for zero residuals.
%
% Christensen R (1996)
% "Plane Answers to Complex Questions"
% 2nd Ed. Springer-Verlag, New York
%
% Andrade A, Paradis AL, Rouquette S and Poline JB, NeuroImage 9, 1999
% ----------------
%
% FORMAT i = spm_SpUtil('allCon',x,c)
% Tests whether all weight vectors specify contrasts:
% Same as all(spm_SpUtil('isCon',x,c)).
%
% ----------------
%
% FORMAT r = spm_SpUtil('ConR',x,c)
% Assess orthogonality of contrasts (wirit the data)
% x - Design matrix X, or space structure of X
% c - contrast matrix (I.e. matrix of contrast weights, contrasts in columns)
% Must have column dimension matching that of X
% defaults to eye(size(X,2)) to test independence of parameter estimates
% r - Contrast correlation matrix, of dimension the number of contrasts.
%
% For the general linear model Y = X*B + E, a contrast weight vector c
% defines a contrast c*B. This is estimated by c*b, where b are the
% least squares estimates of B given by b=pinv(X)*Y. Thus, c*b = w*Y,
% where weight vector w is given by w=c*pinv(X); Since the data are
% assummed independent, two contrasts are indpendent if the
% corresponding weight vectors are orthogonal.
%
% r is the matrix of normalised inner products between the weight
% vectors corresponding to the contrasts. For iid E, r is the
% correlation matrix of the contrasts.
%
% The logical matrix ~r will be true for orthogonal pairs of contrasts.
%
% ----------------
%
% FORMAT r = spm_SpUtil('ConO',x,c)
% Assess orthogonality of contrasts (wirit the data)
% x - Design matrix X, or space structure of X
% c - contrast matrix (I.e. matrix of contrast weights, contrasts in columns)
% Must have column dimension matching that of X
% [defaults to eye(size(X,2)) to test uniqueness of parameter estimates]
% r - Contrast orthogonality matrix, of dimension the number of contrasts.
%
% This is the same as ~spm_SpUtil('ConR',X,c), but uses a quicker
% algorithm by looking at the orthogonality of the subspaces of the
% design space which are implied by the contrasts:
% r = abs(c*X'*X*c')<tol
%
% ----------------
%
% FORMAT c = spm_SpUtil('i0->c',x,i0)
% Return F-contrast for specified design matrix partition
% x - Design matrix X, or space structure of X
% i0 - column indices of null hypothesis design matrix
%
% This functionality returns a rank n mxp matrix of contrasts suitable
% for an extra-sum-of-squares F-test comparing the design X, with a
% reduced design. The design matrix for the reduced design is X0 =
% X(:,i0), a reduction of n degrees of freedom.
%
% The algorithm, due to J-B, and derived from Christensen, computes the
% contrasts as an orthonormal basis set for the rows of the
% hypothesised redundant columns of the design matrix, after
% orthogonalisation with respect to X0. For non-unique designs, there
% are a variety of ways to produce equivalent F-contrasts. This method
% produces contrasts with non-zero weights only for the hypothesised
% redundant columns.
%
% ----------------
%
% case {'x0->c'} %-
% FORMAT c = spm_SpUtil('X0->c',sX,X0)
% ----------------
%
% FORMAT [X1,X0] = spm_SpUtil('c->TSp',X,c)
% Orthogonalised partitioning of design space implied by F-contrast
% x - Design matrix X, or space structure of X
% c - contrast matrix (I.e. matrix of contrast weights, contrasts in columns)
% Must have column dimension matching that of X
% X1o - contrast space - design matrix corresponding according to contrast
% (orthogonalised wirit X0)
% X0 - matrix reduced according to null hypothesis
% (of same size as X but rank deficient)
% FORMAT [uX1,uX0] = spm_SpUtil('c->TSp+',X,c)
% + version to deal with the X1o and X0 partitions in the "uk basis"
%
% ( Note that unless X0 is reduced to a set of linearely independant )
% ( vectors, c will only be contained in the null space of X0. If X0 )
% ( is "reduced", then the "parent" space of c must be reduced as well )
% ( for c to be the actual null space of X0. )
%
% This functionality returns a design matrix subpartition whose columns
% span the hypothesised null design space of a given contrast. Note
% that X1 is orthogonal(ised) to X0, reflecting the situation when an
% F-contrast is tested using the extra sum-of-squares principle (when
% the extra distance in the hypothesised null space is measured
% orthogonal to the space of X0).
%
% Note that the null space design matrix will probably not be a simple
% sub-partition of the full design matrix, although the space spanned
% will be the same.
%
% ----------------
%
% FORMAT X1 = spm_SpUtil('i0->x1o',X,i0)
% x - Design matrix X, or space structure of X
% i0 - Columns of X that make up X0 - the reduced model (Ho:B1=0)
% X1 - Hypothesised null design space, i.e. that part of X orthogonal to X0
% This offers the same functionality as the 'c->TSp' option, but for
% simple reduced models formed from the columns of X.
%
% FORMAT X1 = spm_SpUtil('i0->x1o+',X,i0)
% + version to deal with the X1o and X0 partitions in the "uk basis"
%
% ----------------
%
% FORMAT [trRV,trRVRV] = spm_SpUtil('trRV',x[,V])
% trace(RV) & trace(RVRV) - used in df calculation
% x - Design matrix X, or space structure of X
% V - V matrix [defult eye] (trRV == trRVRV if V==eye, since R idempotent)
% trRV - trace(R*V), computed efficiently
% trRVRV - trace(R*V*R*V), computed efficiently
% This uses the Karl's cunning understanding of the trace:
% (tr(A*B) = sum(sum(A'*B)).
% If the space of X is set, then algorithm uses x.u to avoid extra computation.
%
% ----------------
%
% FORMAT [trMV, trMVMV]] = spm_SpUtil('trMV',x[,V])
% trace(MV) & trace(MVMV) if two ouput arguments.
% x - Design matrix X, or space structure of X
% V - V matrix [defult eye] (trMV == trMVMV if V==eye, since M idempotent)
% trMV - trace(M*V), computed efficiently
% trMVMV - trace(M*V*M*V), computed efficiently
% Again, this uses the Karl's cunning understanding of the trace:
% (tr(A*B) = sum(sum(A'.*B)).
% If the space of X is set, then algorithm uses x.u to avoid extra computation.
%
% ----------------
%
% OBSOLETE use FcUtil('H') for spm_SpUtil('c->H',x,c)
% Extra sum of squares matrix O for beta's from contrast
% x - Design matrix X, or space structure of X
% c - contrast matrix (I.e. matrix of contrast weights, contrasts in columns)
% Must have column dimension matching that of X
% O - Matrix such that b'*O*b = extra sum of squares for F-test of contrast c
%
% ----------------
%
% OBSOLETE use spm_sp('=='...) for spm_SpUtil('c==X1o',x,c) {or 'cxpequi'}
% x - Design matrix X, or space structure of X
% c - contrast matrix (I.e. matrix of contrast weights, contrasts in columns)
% Must have column dimension matching that of X
% b - True is c is a spanning set for space of X
% (I.e. if contrast and space test the same thing)
%
% ----------------
%
% FORMAT [df1,df2] = spm_SpUtil('i0->edf',x,i0,V) {or 'edf'}
% (effective) df1 and df2 the residual df for the projector onto the
% null space of x' (residual forming projector) and the numerator of
% the F-test where i0 are the columns for the null hypothesis model.
% x - Design matrix X, or space structure of X
% i0 - Columns of X corresponding to X0 partition X = [X1,X0] & with
% parameters B = [B1;B0]. Ho:B1=0
% V - V matrix
%
% ----------------
%
% FORMAT sz = spm_SpUtil('size',x,dim)
% FORMAT [sz1,sz2,...] = spm_SpUtil('size',x)
% Returns size of design matrix
% (Like MatLab's `size`, but copes with design matrices inside structures.)
% x - Design matrix X, or structure containing design matrix in field X
% (Structure needn't be a space structure.)
% dim - dimension which to size
% sz - size
%
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Andrew Holmes Jean-Baptiste Poline
% $Id: spm_SpUtil.m 4137 2010-12-15 17:18:32Z guillaume $
% (frobenius norm trick by S. Rouquette)
%-Format arguments
%-----------------------------------------------------------------------
if nargin==0, error('do what? no arguments given...')
else action = varargin{1}; end
switch lower(action),
case {'iscon','allcon','conr','cono'}
%=======================================================================
% i = spm_SpUtil('isCon',x,c)
if nargin==0, varargout={[]}; error('isCon : no argument specified'), end;
if nargin==1,
varargout={[]}; warning('isCon : no contrast specified'); return;
end;
if ~spm_sp('isspc',varargin{2})
sX = spm_sp('Set',varargin{2});
else sX = varargin{2}; end
if nargin==2, c=eye(spm_sp('size',sX,2)); else c=varargin{3}; end;
if isempty(c), varargout={[]}; return, end
switch lower(action)
case 'iscon'
varargout = { spm_sp('eachinspp',sX,c) };
case 'allcon'
varargout = {spm_sp('isinspp',sX,c)};
case 'conr'
if size(c,1) ~= spm_sp('size',sX,2)
error('Contrast not of the right size'), end
%-Compute inner products of data weight vectors
% (c'b = c'*pinv(X)*Y = w'*Y
% (=> w*w' = c'*pinv(X)*pinv(X)'*c == c'*pinv(X'*X)*c
r = c'*spm_sp('XpX-',sX)*c;
%-normalize by "cov(r)" to get correlations
r = r./(sqrt(diag(r))*sqrt(diag(r))');
r(abs(r) < sX.tol)=0; %-set near-zeros to zero
varargout = {r}; %-return r
case 'cono'
%-This is the same as ~spm_SpUtil('ConR',x,c), and so returns
% the contrast orthogonality (though not their corelations).
varargout = { abs(c'* spm_sp('XpX',sX) *c) < sX.tol};
end
case {'+c->tsp','c->tsp'} %- Ortho. partitioning implied by F-contrast
%=======================================================================
% spm_SpUtil('c->Tsp',sX,c)
% + version of 'c->tsp'.
% The + version returns the same in the base u(:,1:r).
%--------- begin argument check ------------------------------
if nargin ~= 3, error(['Wrong number of arguments in ' action])
else sX = varargin{2}; c = varargin{3}; end;
if nargout > 2, error(['Too many output arguments in ' action]), end;
if ~spm_sp('isspc',sX), sX = spm_sp('set',varargin{2}); end;
if sX.rk == 0, error('c->Tsp null rank sX == 0'); end;
if ~isempty(c) && spm_sp('size',sX,2) ~= size(c,1),
error(' c->TSp matrix & contrast dimensions don''t match');
end
%--------- end argument check ---------------------------------
%- project c onto the space of X' if needed
%-------------------------------------------
if ~isempty(c) && ~spm_sp('isinspp',sX,c),
warning([sprintf('\n') 'c is not a proper contrast in ' action ...
' in ' mfilename sprintf('\n') '!!! projecting...' ]);
disp('from'), c, disp('to'), c = spm_sp('oPp:',sX,c)
end
cukFlag = strcmp(lower(action),'+c->tsp');
switch nargout
% case 0
% warning(['no output demanded in ' mfilename ' ' action])
case {0,1}
if ~isempty(c) && any(any(c)) %- c not empty & not null
if cukFlag, varargout = { spm_sp('cukxp-:',sX,c) };
else varargout = { spm_sp('xp-:',sX,c) };
end
else if isempty(c), varargout = { [] }; %- c empty
else %- c null
if cukFlag, varargout = { spm_sp('cukx',sX,c) };
else varargout = { spm_sp('x',sX)*c };
end
end
end
case 2
if ~isempty(c) && any(any(c)) %- not empty and not null
if cukFlag,
varargout = {
spm_sp('cukxp-:',sX,c), ... %- X1o
spm_sp('cukx',sX,spm_sp('r',spm_sp('set',c))) }; %- X0
else
varargout = {
spm_sp(':',sX, spm_sp('xp-:',sX,c)), ... %- X1o
spm_sp(':',sX, ...
spm_sp('x',sX)*spm_sp('r',spm_sp('set',c))) }; %- X0
end
else
if isempty(c), %- empty
if cukFlag, varargout = { [], spm_sp('cukx',sX) };
else varargout = { [], spm_sp('x',sX) };
end
else %- null
if cukFlag,
varargout = { spm_sp(':',sX,spm_sp('cukx',sX,c)), ...
spm_sp(':',sX,spm_sp('cukx',sX)) };
else
varargout = { spm_sp('x',sX)*c, spm_sp('x',sX)};
end
end;
end
otherwise
error(['wrong number of output argument in ' action]);
end
case {'i0->x1o','+i0->x1o'} %- Space tested whilst keeping size of X(i0)
%=======================================================================
% X1o = spm_SpUtil('i0->X1o',sX,i0)
% arguments are checked in calls to spm_Util
%--------------------------------------------
if nargin<3, error('Insufficient arguments'),
else sX = varargin{2}; i0 = varargin{3}; end;
cukFlag = strcmp(lower(action),'+i0->x1o');
c = spm_SpUtil('i0->c',sX,i0);
if cukFlag,
varargout = { spm_SpUtil('+c->TSp',sX,c) };
else
varargout = { spm_SpUtil('c->TSp',sX,c) };
end
case {'i0->c'} %-
%=======================================================================
% c = spm_SpUtil('i0->c',sX,i0)
%
% if i0 == [] : returns a proper contrast
% if i0 == [1:size(sX.X,2)] : returns [];
%
%- Algorithm : avoids the pinv(X0) and insure consistency
%- Get the estimable parts of c0 and c1
%- remove from c1_estimable the estimable part of c0.
%- Use the rotation making X1o orthog. to X0.
%- i0 is checked when Fc is created
%- If i0 defines a space that is the space of X but with
%- fewer vectors, c is null.
%--------- begin argument check --------------------------------
if nargin<3, error('Insufficient arguments'),
else sX = varargin{2}; i0 = varargin{3}; end;
if ~spm_sp('isspc',sX), sX = spm_sp('set',varargin{2}); end;
if spm_sp('rk',sX) == 0, error('i0->c null rank sX == 0'); end;
sL = spm_sp('size',sX,2);
i0 = sf_check_i0(i0,sL);
%--------- end argument check ----------------------------------
c0 = eye(sL); c0 = c0(:,i0);
c1 = eye(sL); c1 = c1(:,setdiff(1:sL,i0));
%- try to avoid the matlab error when doing svd of matrices with
%- high multiplicities. (svd convergence pb)
if ~ spm_sp('isinspp',sX,c0), c0 = spm_sp('oPp:',sX,c0); end;
if ~ spm_sp('isinspp',sX,c1), c1 = spm_sp('oPp:',sX,c1); end;
if ~isempty(c1)
if ~isempty(c0)
%- varargout = { spm_sp('res',spm_sp('set',opp*c0),opp*c1) };
%- varargout = { c1 - c0*pinv(c0)*c1 }; NB: matlab pinv uses
%- svd: will fail if spm_sp('set') fails.
varargout = { spm_sp('r:',spm_sp('set',c0),c1) };
else varargout = { spm_sp('xpx',sX) }; end;
else
varargout = { [] }; %- not zeros(sL,1) : this is return when
%- appropriate
end
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case {'+x0->c','x0->c'} %-
%=======================================================================
% c = spm_SpUtil('X0->c',sX,X0)
% c = spm_SpUtil('+X0->c',sX,cukX0)
% + version of 'x0->c'.
% The + version returns the same in the base u(:,1:r).
warning('Not tested for release - provided for completeness');
cukFlag = strcmp(lower(action),'+x0->c');
%--------- begin argument check ---------
if nargin<3, error('Insufficient arguments'),
else
sX = varargin{2};
if cukFlag, cukX0 = varargin{3}; else X0 = varargin{3}; end
end
if ~spm_sp('isspc',sX), sX = spm_sp('set',varargin{2}); end
if spm_sp('rk',sX) == 0, error(['null rank sX == 0 in ' action]); end
if cukFlag
if ~isempty(cukX0) && spm_sp('rk',sX) ~= size(cukX0,1),
cukX0, spm_sp('rk',sX),
error(['cukX0 of wrong size ' mfilename ' ' action]), end
else
if ~isempty(X0) && spm_sp('size',sX,1) ~= size(X0,1),
X0, spm_sp('size',sX,1),
error(['X0 of wrong size ' mfilename ' ' action]),X0, end
end
%--------- end argument check ---------
if cukFlag
if isempty(cukX0), X0 = []; else X0 = spm_sp('ox',sX)*cukX0; end
end
varargout = { sf_X0_2_c(X0,sX) };
case {'c->h','betarc'} %-Extra sum of squares matrix for beta's from
%- contrast : use F-contrast if possible
%=======================================================================
% H = spm_SpUtil('c->H',sX,c)
error(' Obsolete : Use F-contrast utilities ''H'' or ''Hsqr''... ');
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
%=======================================================================
%=======================================================================
% trace part
%=======================================================================
%=======================================================================
%
case 'trrv' %-Traces for (effective) df calculation
%=======================================================================
% [trRV,trRVRV]= spm_SpUtil('trRV',x[,V])
if nargin == 1, error('insufficient arguments');
else sX = varargin{2}; end;
if ~spm_sp('isspc',sX), sX = spm_sp('Set',sX); end;
rk = spm_sp('rk',sX);
sL = spm_sp('size',sX,1);
if sL == 0,
warning('space with no dimension ');
if nargout==1, varargout = {[]};
else varargout = {[], []}; end
else
if nargin > 2 && ~isempty(varargin{3})
V = varargin{3};
u = sX.u(:,1:rk);
clear sX;
if nargout==1
%-only trRV needed
if rk==0 || isempty(rk), trMV = 0;
else trMV = sum(sum( u .* (V*u) ));
end
varargout = { trace(V) - trMV};
else
%-trRVRV is needed as well
if rk==0 || isempty(rk),
trMV = 0;
trRVRV = (norm(V,'fro'))^2;
trV = trace(V);
clear V u
else
Vu = V*u;
trV = trace(V);
trRVRV = (norm(V,'fro'))^2;
clear V;
trRVRV = trRVRV - 2*(norm(Vu,'fro'))^2;
trRVRV = trRVRV + (norm(u'*Vu,'fro'))^2;
trMV = sum(sum( u .* Vu ));
clear u Vu
end
varargout = {(trV - trMV), trRVRV};
end
else %- nargin == 2 | isempty(varargin{3})
if nargout==1
if rk==0 || isempty(rk), varargout = {sL};
else varargout = {sL - rk};
end
else
if rk==0 || isempty(rk), varargout = {sL,sL};
else varargout = {sL - rk, sL - rk};
end
end
end
end
case 'trmv' %-Traces for (effective) Fdf calculation
%=======================================================================
% [trMV, trMVMV]] = spm_SpUtil('trMV',sX [,V])
%
% NB : When V is given empty, the routine asssumes it's identity
% This is used in spm_FcUtil.
if nargin == 1, error('insufficient arguments');
else sX = varargin{2}; end;
if ~spm_sp('isspc',sX), sX = spm_sp('Set',sX); end;
rk = spm_sp('rk',sX);
if isempty(rk)
warning('Rank is empty');
if nargout==1, varargout = {[]};
else varargout = {[], []}; end
return;
elseif rk==0, warning('Rank is null in spm_SpUtil trMV ');
if nargout==1, varargout = {0};
else varargout = {0, 0}; end
return;
end;
if nargin > 2 && ~isempty(varargin{3}) %- V provided, and assumed correct !
V = varargin{3};
u = sX.u(:,1:rk);
clear sX;
if nargout==1
%-only trMV needed
trMV = sum(sum(u' .* (u'*V) ));
varargout = {trMV};
else
%-trMVMV is needed as well
Vu = V*u;
clear V
trMV = sum(sum( u .* Vu ));
trMVMV = (norm(u'*Vu,'fro'))^2;
clear u Vu
varargout = {trMV, trMVMV};
end
else % nargin == 2 | isempty(varargin{3}) %-no V specified: trMV == trMVMV
if nargout==1
varargout = {rk};
else
varargout = {rk, rk};
end
end
case {'i0->edf','edf'} %-Effective F degrees of freedom
%=======================================================================
% [df1,df2] = spm_SpUtil('i0->edf',sX,i0,V)
%-----------------------------------------------------------------------
%--------- begin argument check ----------------------------------------
if nargin<3, error('insufficient arguments'),
else i0 = varargin{3}; sX = varargin{2}; end
if ~spm_sp('isspc',sX), sX = spm_sp('Set',sX); end;
i0 = sf_check_i0(i0,spm_sp('size',sX,2));
if nargin == 4, V=varargin{4}; else V = eye(spm_sp('size',sX,1)); end;
if nargin>4, error('Too many input arguments'), end;
%--------- end argument check ------------------------------------------
warning(' Use F-contrast utilities if possible ... ');
[trRV,trRVRV] = spm_SpUtil('trRV', sX, V);
[trMpV,trMpVMpV] = spm_SpUtil('trMV',spm_SpUtil('i0->x1o',sX, i0),V);
varargout = {trMpV^2/trMpVMpV, trRV^2/trRVRV};
%=======================================================================
%=======================================================================
% Utilities
%=======================================================================
%=======================================================================
case 'size' %-Size of design matrix
%=======================================================================
% sz = spm_SpUtil('size',x,dim)
if nargin<3, dim=[]; else dim = varargin{3}; end
if nargin<2, error('insufficient arguments'), end
if isstruct(varargin{2})
if isfield(varargin{2},'X')
sz = size(varargin{2}.X);
else error('no X field'); end;
else
sz = size(varargin{2});
end
if ~isempty(dim)
if dim>length(sz), sz = 1; else sz = sz(dim); end
varargout = {sz};
elseif nargout>1
varargout = cell(1,min(nargout,length(sz)));
for i=1:min(nargout,length(sz)), varargout{i} = sz(i); end
else
varargout = {sz};
end
case 'ix0check' %-
%=======================================================================
% i0c = spm_SpUtil('iX0check',i0,sL)
if nargin<3, error('insufficient arguments'),
else i0 = varargin{2}; sL = varargin{3}; end;
varargout = {sf_check_i0(i0,sL)};
otherwise
%=======================================================================
error('Unknown action string in spm_SpUtil')
%=======================================================================
end
%=======================================================================
function i0c = sf_check_i0(i0,sL)
% NB : [] = sf_check_i0([],SL);
%
if all(ismember(i0,[0,1])) && length(i0(:))==sL, i0c=find(i0);
elseif ~isempty(i0) && any(floor(i0)~=i0) || any(i0<1) || any(i0>sL)
error('logical mask or vector of column indices required')
else i0c = i0; end
%=======================================================================
function c = sf_X0_2_c(X0,sX)
%
%- Algorithm to avoids the pinv(X0) and insure consistency
%- Get a contrast that span the space of X0 and is estimable
%- Get the orthogonal complement and project onto the estimable space
%- Strip zeros columns and use the rotation making X1o orthog. to X0
% !!! tolerance dealing ?
if ~isempty(X0)
sc0 = spm_sp('set',spm_sp('x-',sX,X0));
if sc0.rk
c = spm_sp('oPp:',sX,spm_sp('r',sc0));
else
c = spm_sp('oPp',sX);
end;
c = c(:,any(c));
sL = spm_sp('size',sX,2);
%- why the "& size(X0,2) ~= sL" !!!?
if isempty(c) && size(X0,2) ~= sL
c = zeros(sL,1);
end
else
c = spm_sp('xpx',sX);
end
%- c = spm_sp('r',sc0,spm_sp('oxp',sX)); would also works.
|
github
|
philippboehmsturm/antx-master
|
fdmar_arspekth.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/fdmar_arspekth.m
| 310 |
utf_8
|
0272c17a23072d4921ba797cc40a4a69
|
%calulate theoretical ar spectrum out of estimated ar Parameters obj.A
function obj = fdmar_arspekth(obj)
A = obj.coeff;
obj.arspek = [];
for f = 1:1000
sum=0;
for p = 1:length(A)
sum = sum + A(p) * exp(-2*sqrt(-1)*pi*p*f/2000);
end
obj.arspek(f+1) = (abs(1-sum))^(-2);
end
end
|
github
|
philippboehmsturm/antx-master
|
spm_dicom_convert.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_dicom_convert.m
| 48,384 |
utf_8
|
e3f0d186803281f4c8494bb08b7965c8
|
function out = spm_dicom_convert(hdr,opts,root_dir,format)
% Convert DICOM images into something that SPM can use
% FORMAT spm_dicom_convert(hdr,opts,root_dir,format)
% Inputs:
% hdr - a cell array of DICOM headers from spm_dicom_headers
% opts - options
% 'all' - all DICOM files [default]
% 'mosaic' - the mosaic images
% 'standard' - standard DICOM files
% 'spect' - SIEMENS Spectroscopy DICOMs (some formats only)
% This will write out a 5D NIFTI containing real and
% imaginary part of the spectroscopy time points at the
% position of spectroscopy voxel(s).
% 'raw' - convert raw FIDs (not implemented)
% root_dir - 'flat' - do not produce file tree [default]
% With all other options, files will be sorted into
% directories according to their sequence/protocol names
% 'date_time' - Place files under ./<StudyDate-StudyTime>
% 'patid' - Place files under ./<PatID>
% 'patid_date' - Place files under ./<PatID-StudyDate>
% 'patname' - Place files under ./<PatName>
% 'series' - Place files in series folders, without
% creating patient folders
% format - output format
% 'img' Two file (hdr+img) NIfTI format [default]
% 'nii' Single file NIfTI format
% All images will contain a single 3D dataset, 4D images
% will not be created.
% Output:
% out - a struct with a single field .files. out.files contains a
% cellstring with filenames of created files. If no files are
% created, a cell with an empty string {''} is returned.
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner & Jesper Andersson
% $Id: spm_dicom_convert.m 642 2011-07-05 08:22:23Z volkmar $
if nargin<2, opts = 'all'; end
if nargin<3, root_dir = 'flat';end
if nargin<4, format = 'img'; end
[images,other] = select_tomographic_images(hdr);
[spect,guff] = select_spectroscopy_images(other);
[mosaic,standard] = select_mosaic_images(images);
fmos = {};
fstd = {};
fspe = {};
if (strcmp(opts,'all') || strcmp(opts,'mosaic')) && ~isempty(mosaic),
fmos = convert_mosaic(mosaic,root_dir,format);
end;
if (strcmp(opts,'all') || strcmp(opts,'standard')) && ~isempty(standard),
fstd = convert_standard(standard,root_dir,format);
end;
if (strcmp(opts,'all') || strcmp(opts,'spect')) && ~isempty(spect),
fspe = convert_spectroscopy(spect,root_dir,format);
end;
out.files = [fmos(:); fstd(:); fspe(:)];
if isempty(out.files)
out.files = {''};
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function fnames = convert_mosaic(hdr,root_dir,format)
spm_progress_bar('Init',length(hdr),'Writing Mosaic', 'Files written');
fnames = cell(length(hdr),1);
for i=1:length(hdr),
% Output filename
%-------------------------------------------------------------------
fnames{i} = getfilelocation(hdr{i},root_dir,'f',format);
% Image dimensions and data
%-------------------------------------------------------------------
nc = hdr{i}.Columns;
nr = hdr{i}.Rows;
dim = [0 0 0];
dim(3) = read_NumberOfImagesInMosaic(hdr{i});
np = [nc nr]/ceil(sqrt(dim(3)));
dim(1:2) = np;
if ~all(np==floor(np)),
warning('%s: dimension problem [Num Images=%d, Num Cols=%d, Num Rows=%d].',...
hdr{i}.Filename,dim(3), nc,nr);
continue;
end;
% Apparently, this is not the right way of doing it.
%np = read_AcquisitionMatrixText(hdr{i});
%if rem(nc, np(1)) || rem(nr, np(2)),
% warning('%s: %dx%d wont fit into %dx%d.',hdr{i}.Filename,...
% np(1), np(2), nc,nr);
% return;
%end;
%dim = [np read_NumberOfImagesInMosaic(hdr{i})];
mosaic = read_image_data(hdr{i});
volume = zeros(dim);
for j=1:dim(3),
img = mosaic((1:np(1))+np(1)*rem(j-1,nc/np(1)), (np(2):-1:1)+np(2)*floor((j-1)/(nc/np(1))));
if ~any(img(:)),
volume = volume(:,:,1:(j-1));
break;
end;
volume(:,:,j) = img;
end;
dim = size(volume);
dt = determine_datatype(hdr{1});
% Orientation information
%-------------------------------------------------------------------
% Axial Analyze voxel co-ordinate system:
% x increases right to left
% y increases posterior to anterior
% z increases inferior to superior
% DICOM patient co-ordinate system:
% x increases right to left
% y increases anterior to posterior
% z increases inferior to superior
% T&T co-ordinate system:
% x increases left to right
% y increases posterior to anterior
% z increases inferior to superior
analyze_to_dicom = [diag([1 -1 1]) [0 (dim(2)-1) 0]'; 0 0 0 1]*[eye(4,3) [-1 -1 -1 1]'];
vox = [hdr{i}.PixelSpacing(:); hdr{i}.SpacingBetweenSlices];
pos = hdr{i}.ImagePositionPatient(:);
orient = reshape(hdr{i}.ImageOrientationPatient,[3 2]);
orient(:,3) = null(orient');
if det(orient)<0, orient(:,3) = -orient(:,3); end;
% The image position vector is not correct. In dicom this vector points to
% the upper left corner of the image. Perhaps it is unlucky that this is
% calculated in the syngo software from the vector pointing to the center of
% the slice (keep in mind: upper left slice) with the enlarged FoV.
dicom_to_patient = [orient*diag(vox) pos ; 0 0 0 1];
truepos = dicom_to_patient *[(size(mosaic)-dim(1:2))/2 0 1]';
dicom_to_patient = [orient*diag(vox) truepos(1:3) ; 0 0 0 1];
patient_to_tal = diag([-1 -1 1 1]);
mat = patient_to_tal*dicom_to_patient*analyze_to_dicom;
% Maybe flip the image depending on SliceNormalVector from 0029,1010
%-------------------------------------------------------------------
SliceNormalVector = read_SliceNormalVector(hdr{i});
if det([reshape(hdr{i}.ImageOrientationPatient,[3 2]) SliceNormalVector(:)])<0;
volume = volume(:,:,end:-1:1);
mat = mat*[eye(3) [0 0 -(dim(3)-1)]'; 0 0 0 1];
end;
% Possibly useful information
%-------------------------------------------------------------------
tim = datevec(hdr{i}.AcquisitionTime/(24*60*60));
descrip = sprintf('%gT %s %s TR=%gms/TE=%gms/FA=%gdeg %s %d:%d:%.5g Mosaic',...
hdr{i}.MagneticFieldStrength, hdr{i}.MRAcquisitionType,...
deblank(hdr{i}.ScanningSequence),...
hdr{i}.RepetitionTime,hdr{i}.EchoTime,hdr{i}.FlipAngle,...
datestr(hdr{i}.AcquisitionDate),tim(4),tim(5),tim(6));
% descrip = [deblank(descrip) ' ' hdr{i}.PatientsName];
if ~true, % LEFT-HANDED STORAGE
mat = mat*[-1 0 0 (dim(1)+1); 0 1 0 0; 0 0 1 0; 0 0 0 1];
volume = flipdim(volume,1);
end;
%if isfield(hdr{i},'RescaleSlope') && hdr{i}.RescaleSlope ~= 1,
% volume = volume*hdr{i}.RescaleSlope;
%end;
%if isfield(hdr{i},'RescaleIntercept') && hdr{i}.RescaleIntercept ~= 0,
% volume = volume + hdr{i}.RescaleIntercept;
%end;
%V = struct('fname',fname, 'dim',dim, 'dt',dt, 'mat',mat, 'descrip',descrip);
%spm_write_vol(V,volume);
% Note that data are no longer scaled by the maximum amount.
% This may lead to rounding errors in smoothed data, but it
% will get around other problems.
RescaleSlope = 1;
RescaleIntercept = 0;
if isfield(hdr{i},'RescaleSlope') && hdr{i}.RescaleSlope ~= 1,
RescaleSlope = hdr{i}.RescaleSlope;
end;
if isfield(hdr{i},'RescaleIntercept') && hdr{i}.RescaleIntercept ~= 0,
RescaleIntercept = hdr{i}.RescaleIntercept;
end;
N = nifti;
N.dat = file_array(fnames{i},dim,dt,0,RescaleSlope,RescaleIntercept);
N.mat = mat;
N.mat0 = mat;
N.mat_intent = 'Scanner';
N.mat0_intent = 'Scanner';
N.descrip = descrip;
create(N);
% Write the data unscaled
dat = N.dat;
dat.scl_slope = [];
dat.scl_inter = [];
% write out volume at once - see spm_write_plane.m for performance comments
dat(:,:,:) = volume;
set_userdata(N,hdr{i});
% log image comments
log_image_comments(hdr{i},fnames{i});
spm_progress_bar('Set',i);
end;
spm_progress_bar('Clear');
return;
%_______________________________________________________________________
%_______________________________________________________________________
function fnames = convert_standard(hdr,root_dir,format)
hdr = sort_into_volumes(hdr);
fnames = cell(length(hdr),1);
for i=1:length(hdr),
fnames{i} = write_volume(hdr{i},root_dir,format);
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function vol = sort_into_volumes(hdr)
%
% First of all, sort into volumes based on relevant
% fields in the header.
%
vol{1}{1} = hdr{1};
for i=2:length(hdr),
%orient = reshape(hdr{i}.ImageOrientationPatient,[3 2]);
%xy1 = hdr{i}.ImagePositionPatient(:)*orient;
match = 0;
if isfield(hdr{i},'CSAImageHeaderInfo') && isfield(hdr{i}.CSAImageHeaderInfo,'name')
ice1 = sscanf( ...
strrep(get_numaris4_val(hdr{i}.CSAImageHeaderInfo,'ICE_Dims'), ...
'X', '-1'), '%i_%i_%i_%i_%i_%i_%i_%i_%i')';
dimsel = logical([1 1 1 1 1 1 0 0 1]);
else
ice1 = [];
end;
for j=1:length(vol),
%orient = reshape(vol{j}{1}.ImageOrientationPatient,[3 2]);
%xy2 = vol{j}{1}.ImagePositionPatient(:)*orient;
% This line is a fudge because of some problematic data that Bogdan,
% Cynthia and Stefan were trying to convert. I hope it won't cause
% problems for others -JA
% dist2 = sum((xy1-xy2).^2);
dist2 = 0;
if strcmp(hdr{i}.Modality,'CT') && ...
strcmp(vol{j}{1}.Modality,'CT') % Our CT seems to have shears in slice positions
dist2 = 0;
end;
if ~isempty(ice1) && isfield(vol{j}{1},'CSAImageHeaderInfo') && isfield(vol{j}{1}.CSAImageHeaderInfo(1),'name')
% Replace 'X' in ICE_Dims by '-1'
ice2 = sscanf( ...
strrep(get_numaris4_val(vol{j}{1}.CSAImageHeaderInfo,'ICE_Dims'), ...
'X', '-1'), '%i_%i_%i_%i_%i_%i_%i_%i_%i')';
if ~isempty(ice2)
identical_ice_dims=all(ice1(dimsel)==ice2(dimsel));
else
identical_ice_dims = 0; % have ice1 but not ice2, ->
% something must be different
end,
else
identical_ice_dims = 1; % No way of knowing if there is no CSAImageHeaderInfo
end;
try
match = hdr{i}.SeriesNumber == vol{j}{1}.SeriesNumber &&...
hdr{i}.Rows == vol{j}{1}.Rows &&...
hdr{i}.Columns == vol{j}{1}.Columns &&...
sum((hdr{i}.ImageOrientationPatient - vol{j}{1}.ImageOrientationPatient).^2)<1e-4 &&...
sum((hdr{i}.PixelSpacing - vol{j}{1}.PixelSpacing).^2)<1e-4 && ...
identical_ice_dims && dist2<1e-3;
%if (hdr{i}.AcquisitionNumber ~= hdr{i}.InstanceNumber) || ...
% (vol{j}{1}.AcquisitionNumber ~= vol{j}{1}.InstanceNumber)
% match = match && (hdr{i}.AcquisitionNumber == vol{j}{1}.AcquisitionNumber)
%end;
% For raw image data, tell apart real/complex or phase/magnitude
if isfield(hdr{i},'ImageType') && isfield(vol{j}{1}, 'ImageType')
match = match && strcmp(hdr{i}.ImageType, vol{j}{1}.ImageType);
end;
if isfield(hdr{i},'SequenceName') && isfield(vol{j}{1}, 'SequenceName')
match = match && strcmp(hdr{i}.SequenceName,vol{j}{1}.SequenceName);
end;
if isfield(hdr{i},'SeriesInstanceUID') && isfield(vol{j}{1}, 'SeriesInstanceUID')
match = match && strcmp(hdr{i}.SeriesInstanceUID,vol{j}{1}.SeriesInstanceUID);
end;
if isfield(hdr{i},'EchoNumbers') && isfield(vol{j}{1}, 'EchoNumbers')
match = match && hdr{i}.EchoNumbers == vol{j}{1}.EchoNumbers;
end;
catch
match = 0;
end
if match
vol{j}{end+1} = hdr{i};
break;
end;
end;
if ~match,
vol{end+1}{1} = hdr{i};
end;
end;
%dcm = vol;
%save('dicom_headers.mat','dcm');
%
% Secondly, sort volumes into ascending/descending
% slices depending on .ImageOrientationPatient field.
%
vol2 = {};
for j=1:length(vol),
orient = reshape(vol{j}{1}.ImageOrientationPatient,[3 2]);
proj = null(orient');
if det([orient proj])<0, proj = -proj; end;
z = zeros(length(vol{j}),1);
for i=1:length(vol{j}),
z(i) = vol{j}{i}.ImagePositionPatient(:)'*proj;
end;
[z,index] = sort(z);
vol{j} = vol{j}(index);
if length(vol{j})>1,
% dist = diff(z);
if any(diff(z)==0)
tmp = sort_into_vols_again(vol{j});
vol{j} = tmp{1};
vol2 = {vol2{:} tmp{2:end}};
end;
end;
end;
vol = {vol{:} vol2{:}};
for j=1:length(vol),
if length(vol{j})>1,
orient = reshape(vol{j}{1}.ImageOrientationPatient,[3 2]);
proj = null(orient');
if det([orient proj])<0, proj = -proj; end;
z = zeros(length(vol{j}),1);
for i=1:length(vol{j}),
z(i) = vol{j}{i}.ImagePositionPatient(:)'*proj;
end;
dist = diff(sort(z));
if sum((dist-mean(dist)).^2)/length(dist)>1e-4,
fprintf('***************************************************\n');
fprintf('* VARIABLE SLICE SPACING *\n');
fprintf('* This may be due to missing DICOM files. *\n');
if checkfields(vol{j}{1},'PatientID','SeriesNumber','AcquisitionNumber','InstanceNumber'),
fprintf('* %s / %d / %d / %d \n',...
deblank(vol{j}{1}.PatientID), vol{j}{1}.SeriesNumber, ...
vol{j}{1}.AcquisitionNumber, vol{j}{1}.InstanceNumber);
fprintf('* *\n');
end;
fprintf('* %20.4g *\n', dist);
fprintf('***************************************************\n');
end;
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function vol2 = sort_into_vols_again(volj)
if ~isfield(volj{1},'InstanceNumber'),
fprintf('***************************************************\n');
fprintf('* The slices may be all mixed up and the data *\n');
fprintf('* not really usable. Talk to your physicists *\n');
fprintf('* about this. *\n');
fprintf('***************************************************\n');
vol2 = {volj};
return;
end;
fprintf('***************************************************\n');
fprintf('* The AcquisitionNumber counter does not appear *\n');
fprintf('* to be changing from one volume to another. *\n');
fprintf('* Another possible explanation is that the same *\n');
fprintf('* DICOM slices are used multiple times. *\n');
%fprintf('* Talk to your MR sequence developers or scanner *\n');
%fprintf('* supplier to have this fixed. *\n');
fprintf('* The conversion is having to guess how slices *\n');
fprintf('* should be arranged into volumes. *\n');
if checkfields(volj{1},'PatientID','SeriesNumber','AcquisitionNumber'),
fprintf('* %s / %d / %d\n',...
deblank(volj{1}.PatientID), volj{1}.SeriesNumber, ...
volj{1}.AcquisitionNumber);
end;
fprintf('***************************************************\n');
z = zeros(length(volj),1);
t = zeros(length(volj),1);
d = zeros(length(volj),1);
orient = reshape(volj{1}.ImageOrientationPatient,[3 2]);
proj = null(orient');
if det([orient proj])<0, proj = -proj; end;
for i=1:length(volj),
z(i) = volj{i}.ImagePositionPatient(:)'*proj;
t(i) = volj{i}.InstanceNumber;
end;
% msg = 0;
[t,index] = sort(t);
volj = volj(index);
z = z(index);
msk = find(diff(t)==0);
if any(msk),
% fprintf('***************************************************\n');
% fprintf('* These files have the same InstanceNumber: *\n');
% for i=1:length(msk),
% [tmp,nam1,ext1] = fileparts(volj{msk(i)}.Filename);
% [tmp,nam2,ext2] = fileparts(volj{msk(i)+1}.Filename);
% fprintf('* %s%s = %s%s (%d)\n', nam1,ext1,nam2,ext2, volj{msk(i)}.InstanceNumber);
% end;
% fprintf('***************************************************\n');
index = [true ; diff(t)~=0];
t = t(index);
z = z(index);
d = d(index);
volj = volj(index);
end;
%if any(diff(sort(t))~=1), msg = 1; end;
[z,index] = sort(z);
volj = volj(index);
t = t(index);
vol2 = {};
while ~all(d),
i = find(~d);
i = i(1);
i = find(z==z(i));
[t(i),si] = sort(t(i));
volj(i) = volj(i(si));
for i1=1:length(i),
if length(vol2)<i1, vol2{i1} = {}; end;
vol2{i1} = {vol2{i1}{:} volj{i(i1)}};
end;
d(i) = 1;
end;
msg = 0;
if any(diff(sort(t))~=1), msg = 1; end;
if ~msg,
len = length(vol2{1});
for i=2:length(vol2),
if length(vol2{i}) ~= len,
msg = 1;
break;
end;
end;
end;
if msg,
fprintf('***************************************************\n');
fprintf('* There are missing DICOM files, so the the *\n');
fprintf('* resulting volumes may be messed up. *\n');
if checkfields(volj{1},'PatientID','SeriesNumber','AcquisitionNumber'),
fprintf('* %s / %d / %d\n',...
deblank(volj{1}.PatientID), volj{1}.SeriesNumber, ...
volj{1}.AcquisitionNumber);
end;
fprintf('***************************************************\n');
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function fname = write_volume(hdr,root_dir,format)
% Output filename
%-------------------------------------------------------------------
fname = getfilelocation(hdr{1}, root_dir,'s',format);
% Image dimensions
%-------------------------------------------------------------------
nc = hdr{1}.Columns;
nr = hdr{1}.Rows;
dim = [nc nr length(hdr)];
dt = determine_datatype(hdr{1});
% Orientation information
%-------------------------------------------------------------------
% Axial Analyze voxel co-ordinate system:
% x increases right to left
% y increases posterior to anterior
% z increases inferior to superior
% DICOM patient co-ordinate system:
% x increases right to left
% y increases anterior to posterior
% z increases inferior to superior
% T&T co-ordinate system:
% x increases left to right
% y increases posterior to anterior
% z increases inferior to superior
analyze_to_dicom = [diag([1 -1 1]) [0 (dim(2)+1) 0]'; 0 0 0 1]; % Flip voxels in y
patient_to_tal = diag([-1 -1 1 1]); % Flip mm coords in x and y directions
R = [reshape(hdr{1}.ImageOrientationPatient,3,2)*diag(hdr{1}.PixelSpacing); 0 0];
x1 = [1;1;1;1];
y1 = [hdr{1}.ImagePositionPatient(:); 1];
if length(hdr)>1,
x2 = [1;1;dim(3); 1];
y2 = [hdr{end}.ImagePositionPatient(:); 1];
else
orient = reshape(hdr{1}.ImageOrientationPatient,[3 2]);
orient(:,3) = null(orient');
if det(orient)<0, orient(:,3) = -orient(:,3); end;
if checkfields(hdr{1},'SliceThickness'),
z = hdr{1}.SliceThickness;
else
z = 1;
end
x2 = [0;0;1;0];
y2 = [orient*[0;0;z];0];
end
dicom_to_patient = [y1 y2 R]/[x1 x2 eye(4,2)];
mat = patient_to_tal*dicom_to_patient*analyze_to_dicom;
% Possibly useful information
%-------------------------------------------------------------------
if checkfields(hdr{1},'AcquisitionTime','MagneticFieldStrength','MRAcquisitionType',...
'ScanningSequence','RepetitionTime','EchoTime','FlipAngle',...
'AcquisitionDate'),
if isfield(hdr{1},'ScanOptions'),
ScanOptions = hdr{1}.ScanOptions;
else
ScanOptions = 'no';
end
tim = datevec(hdr{1}.AcquisitionTime/(24*60*60));
descrip = sprintf('%gT %s %s TR=%gms/TE=%gms/FA=%gdeg/SO=%s %s %d:%d:%.5g',...
hdr{1}.MagneticFieldStrength, hdr{1}.MRAcquisitionType,...
deblank(hdr{1}.ScanningSequence),...
hdr{1}.RepetitionTime,hdr{1}.EchoTime,hdr{1}.FlipAngle,...
ScanOptions,...
datestr(hdr{1}.AcquisitionDate),tim(4),tim(5),tim(6));
else
descrip = hdr{1}.Modality;
end;
if ~true, % LEFT-HANDED STORAGE
mat = mat*[-1 0 0 (dim(1)+1); 0 1 0 0; 0 0 1 0; 0 0 0 1];
end;
% Write the image volume
%-------------------------------------------------------------------
spm_progress_bar('Init',length(hdr),['Writing ' fname], 'Planes written');
N = nifti;
pinfos = [ones(length(hdr),1) zeros(length(hdr),1)];
for i=1:length(hdr)
if isfield(hdr{i},'RescaleSlope'), pinfos(i,1) = hdr{i}.RescaleSlope; end
if isfield(hdr{i},'RescaleIntercept'), pinfos(i,2) = hdr{i}.RescaleIntercept; end
end
if any(any(diff(pinfos,1))),
% Ensure random numbers are reproducible (see later)
% when intensities are dithered to prevent aliasing effects.
rand('state',0);
end
volume = zeros(dim);
for i=1:length(hdr),
plane = read_image_data(hdr{i});
if any(any(diff(pinfos,1))),
% This is to prevent aliasing effects in any subsequent histograms
% of the data (eg for mutual information coregistration).
% It's a bit inelegant, but probably necessary for when slices are
% individually rescaled.
plane = double(plane) + rand(size(plane)) - 0.5;
end
if pinfos(i,1)~=1, plane = plane*pinfos(i,1); end;
if pinfos(i,2)~=0, plane = plane+pinfos(i,2); end;
plane = fliplr(plane);
if ~true, plane = flipud(plane); end; % LEFT-HANDED STORAGE
volume(:,:,i) = plane;
spm_progress_bar('Set',i);
end;
if ~any(any(diff(pinfos,1))),
% Same slopes and intercepts for all slices
pinfo = pinfos(1,:);
else
% Variable slopes and intercept (maybe PET/SPECT)
mx = max(volume(:));
mn = min(volume(:));
%% Slope and Intercept
%% 32767*pinfo(1) + pinfo(2) = mx
%% -32768*pinfo(1) + pinfo(2) = mn
% pinfo = ([32767 1; -32768 1]\[mx; mn])';
% Slope only
dt = 'int16-be';
pinfo = [max(mx/32767,-mn/32768) 0];
end
N.dat = file_array(fname,dim,dt,0,pinfo(1),pinfo(2));
N.mat = mat;
N.mat0 = mat;
N.mat_intent = 'Scanner';
N.mat0_intent = 'Scanner';
N.descrip = descrip;
create(N);
N.dat(:,:,:) = volume;
set_userdata(N,hdr{1});
% log image comments
log_image_comments(hdr{1},fname);
spm_progress_bar('Clear');
return;
%_______________________________________________________________________
%_______________________________________________________________________
function fnames = convert_spectroscopy(hdr,root_dir,format)
fnames = cell(length(hdr),1);
for i=1:length(hdr),
fnames{i} = write_spectroscopy_volume(hdr(i),root_dir,format);
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function fname = write_spectroscopy_volume(hdr,root_dir,format)
% Output filename
%-------------------------------------------------------------------
fname = getfilelocation(hdr{1}, root_dir,'S',format);
% guess private field to use
if isfield(hdr{1}, 'Private_0029_1210')
privdat = hdr{1}.Private_0029_1210;
elseif isfield(hdr{1}, 'Private_0029_1110')
privdat = hdr{1}.Private_0029_1110;
else
disp('Don''t know how to handle these spectroscopy data');
fname = '';
return;
end
% Image dimensions
%-------------------------------------------------------------------
nc = get_numaris4_numval(privdat,'Columns');
nr = get_numaris4_numval(privdat,'Rows');
% Guess number of timepoints in file - don't know whether this should be
% 'DataPointRows'-by-'DataPointColumns' or 'SpectroscopyAcquisitionDataColumns'
ntp = get_numaris4_numval(privdat,'DataPointRows')*get_numaris4_numval(privdat,'DataPointColumns');
dim = [nc nr numel(hdr) 2 ntp];
dt = spm_type('float32'); % Fixed datatype
% Orientation information
%-------------------------------------------------------------------
% Axial Analyze voxel co-ordinate system:
% x increases right to left
% y increases posterior to anterior
% z increases inferior to superior
% DICOM patient co-ordinate system:
% x increases right to left
% y increases anterior to posterior
% z increases inferior to superior
% T&T co-ordinate system:
% x increases left to right
% y increases posterior to anterior
% z increases inferior to superior
analyze_to_dicom = [diag([1 -1 1]) [0 (dim(2)+1) 0]'; 0 0 0 1]; % Flip voxels in y
patient_to_tal = diag([-1 -1 1 1]); % Flip mm coords in x and y directions
shift_vx = [eye(4,3) [.5; .5; 0; 1]];
orient = reshape(get_numaris4_numval(privdat,...
'ImageOrientationPatient'),[3 2]);
ps = get_numaris4_numval(privdat,'PixelSpacing');
if nc*nr == 1
% Single Voxel Spectroscopy (based on the following information from SIEMENS)
%---------------------------------------------------------------
% NOTE: Internally the position vector of the CSI matrix shows to the outer border
% of the first voxel. Therefore the position vector has to be corrected.
% (Note: The convention of Siemens spectroscopy raw data is in contrast to the
% DICOM standard where the position vector points to the center of the first voxel.)
%---------------------------------------------------------------
% SIEMENS decides which definition to use based on the contents of the
% 'PixelSpacing' internal header field. If it has non-zero values,
% assume DICOM convention. If any value is zero, assume SIEMENS
% internal convention for this direction.
% Note that in SIEMENS code, there is a shift when PixelSpacing is
% zero. Here, the shift seems to be necessary when PixelSpacing is
% non-zero. This may indicate more fundamental problems with
% orientation decoding.
if ps(1) == 0 % row
ps(1) = get_numaris4_numval(privdat,...
'VoiPhaseFoV');
shift_vx(1,4) = 0;
end
if ps(2) == 0 % col
ps(2) = get_numaris4_numval(privdat,...
'VoiReadoutFoV');
shift_vx(2,4) = 0;
end
end
pos = get_numaris4_numval(privdat,'ImagePositionPatient');
% for some reason, pixel spacing needs to be swapped
R = [orient*diag(ps([2 1])); 0 0];
x1 = [1;1;1;1];
y1 = [pos; 1];
if length(hdr)>1,
error('spm_dicom_convert:spectroscopy',...
'Don''t know how to handle multislice spectroscopy data.');
else
orient(:,3) = null(orient');
if det(orient)<0, orient(:,3) = -orient(:,3); end;
try
z = get_numaris4_numval(privdat,...
'VoiThickness');
catch
try
z = get_numaris4_numval(privdat,...
'SliceThickness');
catch
z = 1;
end
end;
x2 = [0;0;1;0];
y2 = [orient*[0;0;z];0];
end
dicom_to_patient = [y1 y2 R]/[x1 x2 eye(4,2)];
mat = patient_to_tal*dicom_to_patient*shift_vx*analyze_to_dicom;
% Possibly useful information
%-------------------------------------------------------------------
if checkfields(hdr{1},'AcquisitionTime','MagneticFieldStrength','MRAcquisitionType',...
'ScanningSequence','RepetitionTime','EchoTime','FlipAngle',...
'AcquisitionDate'),
tim = datevec(hdr{1}.AcquisitionTime/(24*60*60));
descrip = sprintf('%gT %s %s TR=%gms/TE=%gms/FA=%gdeg %s %d:%d:%.5g',...
hdr{1}.MagneticFieldStrength, hdr{1}.MRAcquisitionType,...
deblank(hdr{1}.ScanningSequence),...
hdr{1}.RepetitionTime,hdr{1}.EchoTime,hdr{1}.FlipAngle,...
datestr(hdr{1}.AcquisitionDate),tim(4),tim(5),tim(6));
else
descrip = hdr{1}.Modality;
end;
if ~true, % LEFT-HANDED STORAGE
mat = mat*[-1 0 0 (dim(1)+1); 0 1 0 0; 0 0 1 0; 0 0 0 1];
end;
% Write the image volume
%-------------------------------------------------------------------
N = nifti;
pinfo = [1 0];
if isfield(hdr{1},'RescaleSlope'), pinfo(1) = hdr{1}.RescaleSlope; end;
if isfield(hdr{1},'RescaleIntercept'), pinfo(2) = hdr{1}.RescaleIntercept; end;
N.dat = file_array(fname,dim,dt,0,pinfo(1),pinfo(2));
N.mat = mat;
N.mat0 = mat;
N.mat_intent = 'Scanner';
N.mat0_intent = 'Scanner';
N.descrip = descrip;
N.extras = struct('MagneticFieldStrength',...
get_numaris4_numval(privdat,'MagneticFieldStrength'),...
'TransmitterReferenceAmplitude',...
get_numaris4_numval(privdat,'TransmitterReferenceAmplitude'));
create(N);
% Read data, swap dimensions
data = permute(reshape(read_spect_data(hdr{1},privdat),dim([4 5 1 2 3])), ...
[3 4 5 1 2]);
% plane = fliplr(plane);
N.dat(:,:,:,:,:) = data;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [images,guff] = select_tomographic_images(hdr)
images = {};
guff = {};
for i=1:length(hdr),
if ~checkfields(hdr{i},'Modality') || ~(strcmp(hdr{i}.Modality,'MR') ||...
strcmp(hdr{i}.Modality,'PT') || strcmp(hdr{i}.Modality,'CT'))
if checkfields(hdr{i},'Modality'),
fprintf('File "%s" can not be converted because it is of type "%s", which is not MRI, CT or PET.\n', hdr{i}.Filename, hdr{i}.Modality);
else
fprintf('File "%s" can not be converted because it does not encode an image.\n', hdr{i}.Filename);
end
guff = [guff(:)',hdr(i)];
elseif ~checkfields(hdr{i},'StartOfPixelData','SamplesperPixel',...
'Rows','Columns','BitsAllocated','BitsStored','HighBit','PixelRepresentation'),
disp(['Cant find "Image Pixel" information for "' hdr{i}.Filename '".']);
guff = [guff(:)',hdr(i)];
%elseif isfield(hdr{i},'Private_2001_105f'),
% % This field corresponds to: > Stack Sequence 2001,105F SQ VNAP, COPY
% % http://www.medical.philips.com/main/company/connectivity/mri/index.html
% % No documentation about this private field is yet available.
% disp('Cant yet convert Phillips Intera DICOM.');
% guff = {guff{:},hdr{i}};
elseif ~(checkfields(hdr{i},'PixelSpacing','ImagePositionPatient','ImageOrientationPatient')||isfield(hdr{i},'Private_0029_1110')||isfield(hdr{i},'Private_0029_1210')),
disp(['Cant find "Image Plane" information for "' hdr{i}.Filename '".']);
guff = [guff(:)',hdr(i)];
elseif ~checkfields(hdr{i},'PatientID','SeriesNumber','AcquisitionNumber','InstanceNumber'),
%disp(['Cant find suitable filename info for "' hdr{i}.Filename '".']);
if ~isfield(hdr{i},'SeriesNumber')
disp('Setting SeriesNumber to 1');
hdr{i}.SeriesNumber=1;
images = [images(:)',hdr(i)];
end;
if ~isfield(hdr{i},'AcquisitionNumber')
if isfield(hdr{i},'Manufacturer') && ~isempty(strfind(upper(hdr{1}.Manufacturer), 'PHILIPS'))
% WHY DO PHILIPS DO THINGS LIKE THIS????
if isfield(hdr{i},'InstanceNumber')
hdr{i}.AcquisitionNumber = hdr{i}.InstanceNumber;
else
disp('Setting AcquisitionNumber to 1');
hdr{i}.AcquisitionNumber=1;
end
else
disp('Setting AcquisitionNumber to 1');
hdr{i}.AcquisitionNumber=1;
end
images = [images(:)',hdr(i)];
end;
if ~isfield(hdr{i},'InstanceNumber')
disp('Setting InstanceNumber to 1');
hdr{i}.InstanceNumber=1;
images = [images(:)',hdr(i)];
end;
else
images = [images(:)',hdr(i)];
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [mosaic,standard] = select_mosaic_images(hdr)
mosaic = {};
standard = {};
for i=1:length(hdr),
if ~checkfields(hdr{i},'ImageType','CSAImageHeaderInfo') ||...
isfield(hdr{i}.CSAImageHeaderInfo,'junk') ||...
isempty(read_AcquisitionMatrixText(hdr{i})) ||...
isempty(read_NumberOfImagesInMosaic(hdr{i})) ||...
read_NumberOfImagesInMosaic(hdr{i}) == 0
% NumberOfImagesInMosaic seems to be set to zero for pseudo images
% containing e.g. online-fMRI design matrices, don't treat them as
% mosaics
standard = {standard{:}, hdr{i}};
else
mosaic = {mosaic{:},hdr{i}};
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [spect,images] = select_spectroscopy_images(hdr)
spectsel = zeros(1,numel(hdr));
for i=1:length(hdr),
if isfield(hdr{i},'SOPClassUID')
spectsel(i) = strcmp(hdr{i}.SOPClassUID,'1.3.12.2.1107.5.9.1');
end;
end;
spect = hdr(logical(spectsel));
images = hdr(~logical(spectsel));
return;
%_______________________________________________________________________
%_______________________________________________________________________
function ok = checkfields(hdr,varargin)
ok = 1;
for i=1:(nargin-1),
if ~isfield(hdr,varargin{i}),
ok = 0;
break;
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function clean = strip_unwanted(dirty)
msk = (dirty>='a'&dirty<='z') | (dirty>='A'&dirty<='Z') |...
(dirty>='0'&dirty<='9') | dirty=='_';
clean = dirty(msk);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function img = read_image_data(hdr)
img = [];
if hdr.SamplesperPixel ~= 1,
warning([hdr.Filename ': SamplesperPixel = ' num2str(hdr.SamplesperPixel) ' - cant be an MRI']);
return;
end;
prec = ['ubit' num2str(hdr.BitsAllocated) '=>' 'uint32'];
if isfield(hdr,'TransferSyntaxUID') && strcmp(hdr.TransferSyntaxUID,'1.2.840.10008.1.2.2') && strcmp(hdr.VROfPixelData,'OW'),
fp = fopen(hdr.Filename,'r','ieee-be');
else
fp = fopen(hdr.Filename,'r','ieee-le');
end;
if fp==-1,
warning([hdr.Filename ': cant open file']);
return;
end;
if isfield(hdr,'TransferSyntaxUID')
switch(hdr.TransferSyntaxUID)
case {'1.2.840.10008.1.2.4.50','1.2.840.10008.1.2.4.51','1.2.840.10008.1.2.4.70',...
'1.2.840.10008.1.2.4.80','1.2.840.10008.1.2.4.90','1.2.840.10008.1.2.4.91'},
% try to read PixelData as JPEG image - offset is just a guess
offset = 16;
fseek(fp,hdr.StartOfPixelData+offset,'bof');
img = fread(fp,Inf,'*uint8');
% save PixelData into temp file - imread and its subroutines can only
% read from file, not from memory
tfile = tempname;
tfp = fopen(tfile,'w+');
fwrite(tfp,img,'uint8');
fclose(tfp);
% read decompressed data, transpose to match DICOM row/column order
img = imread(tfile)';
delete(tfile);
otherwise
fseek(fp,hdr.StartOfPixelData,'bof');
img = fread(fp,hdr.Rows*hdr.Columns,prec);
end
else
fseek(fp,hdr.StartOfPixelData,'bof');
img = fread(fp,hdr.Rows*hdr.Columns,prec);
end
fclose(fp);
if numel(img)~=hdr.Rows*hdr.Columns,
error([hdr.Filename ': cant read whole image']);
end;
img = bitshift(img,hdr.BitsStored-hdr.HighBit-1);
if hdr.PixelRepresentation,
% Signed data - done this way because bitshift only
% works with signed data. Negative values are stored
% as 2s complement.
neg = logical(bitshift(bitand(img,uint32(2^hdr.HighBit)),-hdr.HighBit));
msk = (2^hdr.HighBit - 1);
img = double(bitand(img,msk));
img(neg) = img(neg)-2^(hdr.HighBit);
else
% Unsigned data
msk = (2^(hdr.HighBit+1) - 1);
img = double(bitand(img,msk));
end;
img = reshape(img,hdr.Columns,hdr.Rows);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function img = read_spect_data(hdr,privdat)
% Guess number of timepoints in file - don't know whether this should be
% 'DataPointRows'-by-'DataPointColumns' or 'SpectroscopyAcquisitionDataColumns'
ntp = get_numaris4_numval(privdat,'DataPointRows')*get_numaris4_numval(privdat,'DataPointColumns');
% Data is stored as complex float32 values, timepoint by timepoint, voxel
% by voxel. Reshaping is done in write_spectroscopy_volume.
if ntp*2*4 ~= hdr.SizeOfCSAData
warning([hdr.Filename,': Data size mismatch.']);
end
fp = fopen(hdr.Filename,'r','ieee-le');
fseek(fp,hdr.StartOfCSAData,'bof');
img = fread(fp,2*ntp,'float32');
fclose(fp);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function nrm = read_SliceNormalVector(hdr)
str = hdr.CSAImageHeaderInfo;
val = get_numaris4_val(str,'SliceNormalVector');
for i=1:3,
nrm(i,1) = sscanf(val(i,:),'%g');
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function n = read_NumberOfImagesInMosaic(hdr)
str = hdr.CSAImageHeaderInfo;
val = get_numaris4_val(str,'NumberOfImagesInMosaic');
n = sscanf(val','%d');
if isempty(n), n=[]; end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function dim = read_AcquisitionMatrixText(hdr)
str = hdr.CSAImageHeaderInfo;
val = get_numaris4_val(str,'AcquisitionMatrixText');
dim = sscanf(val','%d*%d')';
if length(dim)==1,
dim = sscanf(val','%dp*%d')';
end;
if isempty(dim), dim=[]; end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function val = get_numaris4_val(str,name)
name = deblank(name);
val = {};
for i=1:length(str),
if strcmp(deblank(str(i).name),name),
for j=1:str(i).nitems,
if str(i).item(j).xx(1),
val = {val{:} str(i).item(j).val};
end;
end;
break;
end;
end;
val = strvcat(val{:});
return;
%_______________________________________________________________________
%_______________________________________________________________________
function val = get_numaris4_numval(str,name)
val1 = get_numaris4_val(str,name);
val = zeros(size(val1,1),1);
for k = 1:size(val1,1)
val(k)=str2num(val1(k,:));
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function fname = getfilelocation(hdr,root_dir,prefix,format)
if nargin < 3
prefix = 'f';
end;
if strncmp(root_dir,'ice',3)
root_dir = root_dir(4:end);
imtype = textscan(hdr.ImageType,'%s','delimiter','\\');
try
imtype = imtype{1}{3};
catch
imtype = '';
end;
prefix = [prefix imtype get_numaris4_val(hdr.CSAImageHeaderInfo,'ICE_Dims')];
end;
if strcmp(root_dir, 'flat')
% Standard SPM file conversion
%-------------------------------------------------------------------
if checkfields(hdr,'SeriesNumber','AcquisitionNumber')
if checkfields(hdr,'EchoNumbers')
fname = sprintf('%s%s-%.4d-%.5d-%.6d-%.2d.%s', prefix, strip_unwanted(hdr.PatientID),...
hdr.SeriesNumber, hdr.AcquisitionNumber, hdr.InstanceNumber,...
hdr.EchoNumbers, format);
else
fname = sprintf('%s%s-%.4d-%.5d-%.6d.%s', prefix, strip_unwanted(hdr.PatientID),...
hdr.SeriesNumber, hdr.AcquisitionNumber, ...
hdr.InstanceNumber, format);
end;
else
fname = sprintf('%s%s-%.6d.%s',prefix, ...
strip_unwanted(hdr.PatientID),hdr.InstanceNumber, format);
end;
fname = fullfile(pwd,fname);
return;
end;
% more fancy stuff - sort images into subdirectories
if ~isfield(hdr,'ProtocolName')
if isfield(hdr,'SequenceName')
hdr.ProtocolName = hdr.SequenceName;
else
hdr.ProtocolName='unknown';
end;
end;
if ~isfield(hdr,'SeriesDescription')
hdr.SeriesDescription = 'unknown';
end;
if ~isfield(hdr,'EchoNumbers')
hdr.EchoNumbers = 0;
end;
m = sprintf('%02d', floor(rem(hdr.StudyTime/60,60)));
h = sprintf('%02d', floor(hdr.StudyTime/3600));
studydate = sprintf('%s_%s-%s', datestr(hdr.StudyDate,'yyyy-mm-dd'), ...
h,m);
switch root_dir
case {'date_time','series'}
id = studydate;
case {'patid', 'patid_date', 'patname'},
id = strip_unwanted(hdr.PatientID);
end;
serdes = strrep(strip_unwanted(hdr.SeriesDescription),...
strip_unwanted(hdr.ProtocolName),'');
protname = sprintf('%s%s_%.4d',strip_unwanted(hdr.ProtocolName), ...
serdes, hdr.SeriesNumber);
switch root_dir
case 'date_time',
dname = fullfile(pwd, id, protname);
case 'patid',
dname = fullfile(pwd, id, protname);
case 'patid_date',
dname = fullfile(pwd, id, studydate, protname);
case 'patname',
dname = fullfile(pwd, strip_unwanted(hdr.PatientsName), ...
id, protname);
case 'series',
dname = fullfile(pwd, protname);
otherwise
error('unknown file root specification');
end;
if ~exist(dname,'dir'),
mkdir_rec(dname);
end;
% some non-product sequences on SIEMENS scanners seem to have problems
% with image numbering in MOSAICs - doublettes, unreliable ordering
% etc. To distinguish, always include Acquisition time in image name
sa = sprintf('%02d', floor(rem(hdr.AcquisitionTime,60)));
ma = sprintf('%02d', floor(rem(hdr.AcquisitionTime/60,60)));
ha = sprintf('%02d', floor(hdr.AcquisitionTime/3600));
fname = sprintf('%s%s-%s%s%s-%.5d-%.5d-%d.%s', prefix, id, ha, ma, sa, ...
hdr.AcquisitionNumber,hdr.InstanceNumber, ...
hdr.EchoNumbers,format);
fname = fullfile(dname, fname);
%_______________________________________________________________________
%_______________________________________________________________________
function suc = mkdir_rec(str)
% works on full pathnames only
opwd=pwd;
if str(end) ~= filesep, str = [str filesep];end;
pos = strfind(str,filesep);
suc = zeros(1,length(pos));
for g=2:length(pos)
if ~exist(str(1:pos(g)-1),'dir'),
cd(str(1:pos(g-1)-1));
suc(g) = mkdir(str(pos(g-1)+1:pos(g)-1));
end;
end;
cd(opwd);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function ret = read_ascconv(hdr)
% In SIEMENS data, there is an ASCII text section with
% additional information items. This section starts with a code
% ### ASCCONV BEGIN ###
% and ends with
% ### ASCCONV END ###
% It is read by spm_dicom_headers into an entry 'MrProtocol' in
% CSASeriesHeaderInfo or into an entry 'MrPhoenixProtocol' in
% Private_0029_1110 or Private_0029_1120.
% The additional items are assignments in C syntax, here they are just
% translated according to
% [] -> ()
% " -> '
% 0xX -> hex2dec('X')
% and collected in a struct.
ret=struct;
% get ascconv data
if isfield(hdr, 'Private_0029_1110')
X = get_numaris4_val(hdr.Private_0029_1110,'MrPhoenixProtocol');
elseif isfield(hdr, 'Private_0029_1120')
X = get_numaris4_val(hdr.Private_0029_1120,'MrPhoenixProtocol');
else
X=get_numaris4_val(hdr.CSASeriesHeaderInfo,'MrProtocol');
end
ascstart = strfind(X,'### ASCCONV BEGIN ###');
ascend = strfind(X,'### ASCCONV END ###');
if ~isempty(ascstart) && ~isempty(ascend)
tokens = textscan(char(X((ascstart+22):(ascend-1))),'%s', ...
'delimiter',char(10));
tokens{1}=regexprep(tokens{1},{'\[([0-9]*)\]','"(.*)"','0x([0-9a-fA-F]*)'},{'($1+1)','''$1''','hex2dec(''$1'')'});
% If everything would evaluate correctly, we could use
% eval(sprintf('ret.%s;\n',tokens{1}{:}));
for k = 1:numel(tokens{1})
try
eval(['ret.' tokens{1}{k} ';']);
catch
disp(['AscConv: Error evaluating ''ret.' tokens{1}{k} ''';']);
end;
end;
end;
%_______________________________________________________________________
%_______________________________________________________________________
function set_userdata(V,hdr)
% Get Diffusion information
try
userdata=struct('b',[], 'g',[], 'mat',[] ,'ref',[]);
userdata.b = get_numaris4_numval(hdr.CSAImageHeaderInfo,'B_value');
tmpg = get_numaris4_numval(hdr.CSAImageHeaderInfo, ...
'DiffusionGradientDirection')';
if isempty(tmpg) && (userdata.b==0)
tmpg=[0 0 0];
end;
% Combine
userdata.g = [tmpg(1) tmpg(2) tmpg(3)];
% may try 'B_matrix' as well
catch
try
userdata=struct('b',[], 'g',[], 'mat',[], 'ref',[]);
if strncmp(hdr.ImageComments,'No DW, scan',11)
userdata.b = 0;
userdata.g = [0 0 0];
elseif strncmp(hdr.ImageComments, 'DW: ', 4)
userdata.b = 1000; % fixed, not saved in images
[userdata.g(1) userdata.g(2) userdata.g(3)] = strread(hdr.ImageComments, ...
'DW: %f %f %f');
else
userdata=[];
end
catch
userdata = [];
end;
end;
if ~isempty(userdata)
userdata.mat = V.mat;
prms = spm_imatrix(V.mat);
% mapping from DICOM to MNI reference coordinate system
userdata.ref = diag([sign(prms(7)) -1 1 1]);
try
if ~isdeployed
addpath(fullfile(spm('dir'),'toolbox','Diffusion','Helpers'));
end
dti_get_dtidata(V.dat.fname,userdata);
catch
disp(['Can''t set DTI information for file "' V.dat.fname '".']);
end;
end;
%_______________________________________________________________________
%_______________________________________________________________________
function log_image_comments(hdr,fname)
if isfield(hdr,'ImageComments')
[p n e] = fileparts(fname);
fid = fopen(fullfile(p,'imagecomments.txt'),'a');
% replace string "Reference volume for motion correction." with
% motion 0,0,0,0,0,0
comm = strrep(hdr.ImageComments,...
'Reference volume for motion correction.',...
'Reference volume for motion correction: 0.00,0.00,0.00,0.00,0.00,0.00');
fprintf(fid,'%s: %s\n',[n e],comm);
fclose(fid);
end;
%_______________________________________________________________________
%_______________________________________________________________________
function dt = determine_datatype(hdr)
% Determine what datatype to use for NIfTI images
be = spm_platform('bigend');
if hdr.HighBit>16
if hdr.PixelRepresentation
dt = [spm_type( 'int32') be];
else
dt = [spm_type('uint32') be];
end
else
if hdr.PixelRepresentation || hdr.HighBit<=15
dt = [spm_type( 'int16') be];
else
dt = [spm_type('uint16') be];
end
end
|
github
|
philippboehmsturm/antx-master
|
spm_spm_ui.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_spm_ui.m
| 98,074 |
utf_8
|
dfdd679af4a4b15272726dcb46e888fe
|
function varargout = spm_spm_ui(varargin)
% Setting up the general linear model for independent data
% FORMATs (given in Programmers Help)
%_______________________________________________________________________
%
% spm_spm_ui.m 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) in the current directory, and are
% passed on to spm_spm.m which estimates the design. Inference on these
% estimated parameters is then handled by the SPM results section.
%
% A separate program (spm_spm_fmri_ui.m) handles design configuration
% for fMRI time series, though this program can be used for fMRI data
% when observations can be regarded as independent.
%
% ----------------------------------------------------------------------
%
% Various data and parameters need to be supplied to specify the design:
% * the image files
% * indicators of the corresponding condition/subject/group
% * any covariates, nuisance variables, or design matrix partitions
% * the type of global normalisation (if any)
% * grand mean scaling options
% * thresholds and masks defining the image volume to analyse
%
% The interface supports a comprehensive range of options for all these
% parameters, which are described below in the order in which the
% information is requested. Rather than ask for all these parameters,
% spm_spm_ui.m uses a "Design Definition", a structure describing the
% options and defaults appropriate for a particular analysis. Thus,
% once the user has chosen a design, a subset of the following prompts
% will be presented.
%
% If the pre-specified design definitions don't quite have the combination
% of options you want, you can pass a custom design structure D to be used
% as parameter: spm_spm_ui('cfg',D). The format of the design structure
% and option definitions are given in the programmers help, at the top of
% the main body of the code.
%
% ----------------
%
% Design class & Design type
% ==========================
%
% Unless a design definition is passed to spm_spm_ui.m as a parameter,
% the user is prompted first to select a design class, and then to
% select a design type from that class.
%
% The designs are split into three classes:
% i) Basic stats: basic models for simple statistics
% These specify designs suitable for simple voxel-by-voxel analyses.
% - one-sample t-test
% - two-sample t-test
% - paired t-test
% - one way Anova
% - one way Anova (with constant)
% - one way Anova (within subject)
% - simple regression (equivalent to correlation)
% - multiple regression
% - multiple regression (with constant)
% - basic AnCova (ANalysis of COVAriance)
% (essentially a two-sample t-test with a nuisance covariate)
%
% ii) PET models: models suitable for analysis of PET/SPECT experiments
% - Single-subject: conditions & covariates
% - Single-subject: covariates only
%
% - Multi-subj: conditions & covariates
% - Multi-subj: cond x subj interaction & covariates
% - Multi-subj: covariates only
% - Multi-group: conditions & covariates
% - Multi-group: covariates only
%
% - Population main effect: 2 cond's, 1 scan/cond (paired t-test)
% - Dodgy population main effect: >2 cond's, 1 scan/cond
% - Compare-populations: 1 scan/subject (two sample t-test)
% - Compare-populations: 1 scan/subject (AnCova)
%
% - The Full Monty... (asks you everything!)
%
% iii) SPM96 PET models: models used in SPM96 for PET/SPECT
% These models are provided for backward compatibility, but as they
% don't include some of the advanced modelling features, we recommend
% you switch to the new (SPM99) models at the earliest opportunity.
% - SPM96:Single-subject: replicated conditions
% - SPM96:Single-subject: replicated conditions & covariates
% - SPM96:Single-subject: covariates only
% - SPM96:Multi-subject: different conditions
% - SPM96:Multi-subject: replicated conditions
% - SPM96:Multi-subject: different conditions & covariates
% - SPM96:Multi-subject: replicated conditions & covariates
% - SPM96:Multi-subject: covariates only
% - SPM96:Multi-group: different conditions
% - SPM96:Multi-group: replicated conditions
% - SPM96:Multi-group: different conditions & covariates
% - SPM96:Multi-group: replicated conditions & covariates
% - SPM96:Multi-group: covariates only
% - SPM96:Compare-groups: 1 scan per subject
%
%
% Random effects, generalisability, population inference...
% =========================================================
%
% Note that SPM only considers a single component of variance, the
% residual error variance. When there are repeated measures, all
% analyses with SPM are fixed effects analyses, and inference only
% extends to the particular subjects under consideration (at the times
% they were imaged).
%
% In particular, the multi-subject and multi-group designs ignore the
% variability in response from subject to subject. Since the
% scan-to-scan (within-condition, within-subject variability is much
% smaller than the between subject variance which is ignored), this can
% lead to detection of group effects that are not representative of the
% population(s) from which the subjects are drawn. This is particularly
% serious for multi-group designs comparing two groups. If inference
% regarding the population is required, a random effects analysis is
% required.
%
% However, random effects analyses can be effected by appropriately
% summarising the data, thereby collapsing the model such that the
% residual variance for the new model contains precisely the variance
% components needed for a random effects analysis. In many cases, the
% fixed effects models here can be used as the first stage in such a
% two-stage procedure to produce appropriate summary data, which can
% then be used as raw data for a second-level analysis. For instance,
% the "Multi-subj: cond x subj interaction & covariates" design can be
% used to write out an image of the activation for each subject. A
% simple t-test on these activation images then turns out to be
% equivalent to a mixed-effects analysis with random subject and
% subject by condition interaction effects, inferring for the
% population based on this sample of subjects (strictly speaking the
% design would have to be balanced, with equal numbers of scans per
% condition per subject, and also only two conditions per subject). For
% additional details, see spm_RandFX.man.
%
% ----------------
%
% Selecting image files & indicating conditions
% =============================================
%
% You may now be prompted to specify how many studies, subjects and
% conditions you have, and then will be promted to select the scans.
%
% The data should all have the same orientation and image and voxel size.
%
% File selection is handled by spm_select.m - the help for which describes
% efficient use of the interface.
%
% You may be asked to indicate the conditions for a set of scans, with
% a prompt like "[12] Enter conditions? (2)". For this particular
% example you need to indicate for 12 scans the corresponding
% condition, in this case from 2 conditions. Enter a vector of
% indicators, like '0 1 0 1...', or a string of indicators, like
% '010101010101' or '121212121212', or 'rararararara'. (This
% "conditions" input is handled by spm_input.m, where comprehensive
% help can be found.)
%
% ----------------
%
% Covariate & nuisance variable entry
% ===================================
%
% * If applicable, you'll be asked to specify 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), SPM99 does
% not partition the design in this way. 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. (The number of covariates / nuisance variables specified,
% is actually the number of times you are prompted for entry, not the
% number of resulting design matrix columns.) You will be given the
% opportunity to name the covariate.
%
% * Factor by covariate interactions: For covariate vectors, you may be
% offered a choice of interaction options. (This was called "covariate
% specific fits" in SPM95/6.) The full list of possible options is:
% - <none>
% - with replication
% - with condition (across group)
% - with subject (across group)
% - with group
% - with condition (within group)
% - with subject (within group)
%
% * Covariate centering: At this stage may also be offered "covariate
% centering" options. The default is usually that appropriate for the
% interaction chosen, and ensures that main effects of the interacting
% factor aren't affected by the covariate. You are advised to choose
% the default, unless you have other modelling considerations. The full
% list of possible options is:
% - around overall mean
% - around replication means
% - around condition means (across group)
% - around subject means (across group)
% - around group means
% - around condition means (within group)
% - around subject means (within group)
% - <no centering>
%
% ----------------
%
% Global options
% ==============
%
% Depending on the design configuration, you may be offered a selection
% of global normalisation and scaling options:
%
% * Method of global flow calculation
% - SPM96:Compare-groups: 1 scan per subject
% - None (assumming no other options requiring the global value chosen)
% - User defined (enter your own vector of global values)
% - SPM standard: mean voxel value (within per image fullmean/8 mask)
%
% * Grand mean scaling : 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
% (see below), each image is seperately scaled such that it's global
% value is that specified (in which case the grand mean is also
% implicitly scaled to that 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 seperately. The
% full list of possible options is:
% - scaling of overall grand mean
% - caling of replication grand means
% - caling of condition grand means (across group)
% - caling of subject grand means (across group)
% - caling of group grand means
% - caling of condition (within group) grand means
% - caling of subject (within group) grand means
% - implicit in PropSca global normalisation)
% - no grand Mean scaling>'
%
% * Global normalisation option : 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.
%
% Considering AnCova global normalisation, since subjects are unlikely
% to have the same relationship between global and local measurements,
% a subject-specific AnCova ("AnCova by subject"), fitting a different
% slope and intercept for each subject, would be preferred to the
% single common slope of a straight AnCova. (Assumming there's enough
% scans per subject to estimate such an effect.) This is basically an
% interaction of the global covariate with the subject factor. You may
% be offered various AnCova options, corresponding to interactions with
% various factors according to the design definition: The full list of
% possible options is:
% - AnCova
% - AnCova by replication
% - AnCova by condition (across group)
% - AnCova by subject (across group)
% - AnCova by group
% - AnCova by condition (within group)
% - AnCova by subject (within group)
% - Proportional scaling
% - <no global normalisation>
%
% 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.
%
% * Global centering: Lastly, for some designs using AnCova, you will
% be offered a choice of centering options for the global covariate. As
% with covariate centering, this is only relevant if you have a
% particular interest in the parameter estimates. Usually, the default
% of a centering corresponding to the AnCova used is chosen. The full
% list of possible options is:
% - around overall mean
% - around replication means
% - around condition means (across group)
% - around subject means (across group)
% - around group means
% - around condition means (within group)
% - around subject means (within group)
% - <no centering>
% - around user specified value
% - (as implied by AnCova)
% - GM (The grand mean scaled value)
% - (redundant: not doing AnCova)
%
%
%
% Note that this is a logical ordering for the global options, which is
% not the order used by the interface due to algorithm constraints. The
% interface asks for the options in this order:
% - Global normalisation
% - Grand mean scaling options
% (if not using proportional scaling global normalisation)
% - Value for grand mean scaling proportional scaling GloNorm
% (if appropriate)
% - Global centering options
% - Value for global centering (if "user-defined" chosen)
% - Method of calculation
%
% ----------------
%
% Masking options
% ===============
%
% The mask specifies the voxels within the image volume which are to be
% assessed. SPM supports three methods of masking. The volume analysed
% is the intersection of all masks:
%
% i) Threshold masking : "Analysis threshold"
% - images are thresholded at a given value and only voxels at
% which all images exceed the threshold are included in the
% analysis.
% - The threshold can be absolute, or a proportion of the global
% value (after scaling), or "-Inf" for no threshold masking.
% - (This was called "Grey matter threshold" in SPM94/5/6)
%
% ii) Implicit masking
% - 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.
%
% iii) Explicit masking
% - 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.
%
%
% ----------------
%
% Non-sphericity correction
% =========================
%
% In some instances the i.i.d. assumptions about the errors do not hold:
%
% Identity assumption:
% The identity assumption, of equal error variance (homoscedasticity), can
% be violated if the levels of a factor do not have the same error variance.
% 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 dependant variables (e.g. normals vs. patients). If
% You say no to identity assumptions, you will be asked whether the error
% variance is the same over levels of each factor. Different variances
% (heteroscedasticy) induce different error covariance components that
% are estimated using restricted maximum likelihood (see below).
%
% Independence assumption.
% In some situations, certain factors may contain random effects. These induce
% dependencies or covariance components in the error terms. If you say no
% to independence assumptions, you will be asked whether random effects
% should be modelled for each factor. A simple example of this would be
% modelling the random effects of subject. These cause correlations among the
% error terms of observation from the same subject. For simplicity, it is
% assumed that the random effects of each factor are i.i.d. One can always
% re-specify the covariance components by hand in SPM.xVi.Vi for more
% complicated models
%
% 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 xX.xVi and enter the estimation
% procedure exactly as the serial correlations in fMRI models.
%
% see also: spm_reml.m and spm_non_sphericity.m
%
% ----------------
%
% Multivariate analyses
% =====================
%
% Mulitvariate analyses with n-variate response variables are supported
% and automatically invoke a ManCova and CVA in spm_spm. Multivariate
% designs are, at the moment limited to Basic and PET designs.
%
% ----------------------------------------------------------------------
%
% Variables saved in the SPM stucture
%
% xY.VY - nScan x 1 struct array of memory mapped images
% (see spm_vol for definition of the map structure)
% xX - structure describing design matrix
% xX.D - design definition structure
% (See definition in main body of spm_spm_ui.m)
% xX.I - nScan x 4 matrix of factor level indicators
% I(n,i) is the level of factor i corresponding to image n
% xX.sF - 1x4 cellstr containing the names of the four factors
% xX.sF{i} is the name of factor i
% xX.X - design matrix
% xX.xVi - correlation constraints for non-spericity correction
% xX.iH - vector of H partition (condition effects) indices,
% identifying columns of X correspoding to H
% xX.iC - vector of C partition (covariates of interest) indices
% xX.iB - vector of B partition (block effects) indices
% xX.iG - vector of G partition (nuisance variables) indices
% xX.name - p x 1 cellstr of effect names corresponding to columns
% of the design matrix
%
% xC - structure array of covariate details
% xC(i).rc - raw (as entered) i-th covariate
% xC(i).rcname - name of this covariate (string)
% xC(i).c - covariate as appears in design matrix (after any scaling,
% centering of interactions)
% xC(i).cname - cellstr containing names for effects corresponding to
% columns of xC(i).c
% xC(i).iCC - covariate centering option
% xC(i).iCFI - covariate by factor interaction option
% xC(i).type - covariate type: 1=interest, 2=nuisance, 3=global
% xC(i).cols - columns of design matrix corresponding to xC(i).c
% xC(i).descrip - cellstr containing a description of the covariate
%
% xGX - structure describing global options and values
% xGX.iGXcalc - global calculation option used
% xGX.sGXcalc - string describing global calculation used
% xGX.rg - raw globals (before scaling and such like)
% xGX.iGMsca - grand mean scaling option
% xGX.sGMsca - string describing grand mean scaling
% xGX.GM - value for grand mean (/proportional) scaling
% xGX.gSF - global scaling factor (applied to xGX.rg)
% xGX.iGC - global covariate centering option
% xGX.sGC - string describing global covariate centering option
% xGX.gc - center for global covariate
% xGX.iGloNorm - Global normalisation option
% xGX.sGloNorm - string describing global normalisation option
%
% xM - structure describing masking options
% xM.T - Threshold masking value (-Inf=>None,
% real=>absolute, complex=>proportional (i.e. times global) )
% xM.TH - nScan x 1 vector of analysis thresholds, one per image
% xM.I - Implicit masking (0=>none, 1=>implicit zero/NaN mask)
% xM.VM - struct array of explicit mask images
% (empty if no explicit masks)
% xM.xs - structure describing masking options
% (format is same as for xsDes described below)
%
% xsDes - structure of strings describing the design:
% Fieldnames are essentially topic strings (use "_"'s for
% spaces), and the field values should be strings or cellstr's
% of information regarding that topic. spm_DesRep.m
% uses this structure to produce a printed description
% of the design, displaying the fieldnames (with "_"'s
% converted to spaces) in bold as topics, with
% the corresponding text to the right
%
% SPMid - String identifying SPM and program versions
%
% ----------------
%
% NB: The SPM.mat file is not very portable: It contains
% memory-mapped handles for the images, which hardcodes the full file
% pathname and datatype. Therefore, subsequent to creating the
% SPM.mat, you cannot move the image files, and cannot move the
% entire analysis to a system with a different byte-order (even if the
% full file pathnames are retained. Further, the image scalefactors
% will have been pre-scaled to effect any grand mean or global
% scaling.
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Andrew Holmes
% $Id: spm_spm_ui.m 4185 2011-02-01 18:46:18Z guillaume $
SCCSid = '$Rev: 4185 $';
%=======================================================================
% - FORMAT specifications for programers
%=======================================================================
%( This is a multi function function, the first argument is an action )
%( string, specifying the particular action function to take. )
%
% FORMAT spm_spm_ui('CFG',D)
% Configure design
% D - design definition structure - see format definition below
% (If D is a struct array, then the user is asked to choose from the
% design definitions in the array. If D is not specified as an
% argument, then user is asked to choose from the standard internal
% definitions)
%
% FORMAT [P,I] = spm_spm_ui('Files&Indices',DsF,Dn,DbaTime)
% PET/SPECT file & factor level input
% DsF - 1x4 cellstr of factor names (ie D.sF)
% Dn - 1x4 vector indicating the number of levels (ie D.n)
% DbaTime - ask for F3 images in time order, with F2 levels input by user?
% P - nScan x 1 cellsrt of image filenames
% I - nScan x 4 matrix of factor level indices
%
% FORMAT D = spm_spm_ui('DesDefs_Stats')
% Design definitions for simple statistics
% D - struct array of design definitions (see definition below)
%
% FORMAT D = spm_spm_ui('DesDefs_PET')
% Design definitions for PET/SPECT models
% D - struct array of design definitions (see definition below)
%
% FORMAT D = spm_spm_ui('DesDefs_PET96')
% Design definitions for SPM96 PET/SPECT models
% D - struct array of design definitions (see definition below)
%=======================================================================
% Design definitions specification for programers & power users
%=======================================================================
% Within spm_spm_ui.m, a definition structure, D, determines the
% various options, defaults and specifications appropriate for a
% particular design. Usually one uses one of the pre-specified
% definitions chosen from the menu, which are specified in the function
% actions at the end of the program (spm_spm_ui('DesDefs_Stats'),
% spm_spm_ui('DesDefs_PET'), spm_spm_ui('DesDefs_PET96')). For
% customised use of spm_spm_ui.m, the design definition structure is
% shown by the following example:
%
% D = struct(...
% 'DesName','The Full Monty...',...
% 'n',[Inf Inf Inf Inf], 'sF',{{'repl','cond','subj','group'}},...
% 'Hform', 'I(:,[4,2]),''-'',{''stud'',''cond''}',...
% 'Bform', 'I(:,[4,3]),''-'',{''stud'',''subj''}',...
% 'nC',[Inf,Inf],'iCC',{{[1:8],[1:8]}},'iCFI',{{[1:7],[1:7]}},...
% 'iGXcalc',[1,2,3],'iGMsca',[1:7],'GM',50,...
% 'iGloNorm',[1:9],'iGC',[1:11],...
% 'M_',struct('T',[-Inf,0,0.8*sqrt(-1)],'I',Inf,'X',Inf),...
% 'b',struct('aTime',1));
%
% ( Note that the struct command expands cell arrays to give multiple )
% ( records, so if you want a cell array as a field value, you have to )
% ( embed it within another cell, hence the double "{{"'s. )
%
% ----------------
%
% Design structure fields and option definitions
% ==============================================
%
% D.Desname - a string naming the design
%
% In general, spm_spm_ui.m accomodates four factors. Usually these are
% 'group', 'subject', 'condition' & 'replication', but to allow for a
% flexible interface these are dynamically named for different designs,
% and are referred to as Factor4, Factor3, Factor2, and Factor1
% respectively. The first part of the D definition dictates the names
% and number of factor levels (i.e. number of subjects etc.) relevant
% for this design, and also how the H (condition) and B (block)
% partitions of the design matrix should be constructed.
%
% D.n - a 1x4 vector, indicating the number of levels. D.n(i)
% for i in [1:4] is the number of levels for factor i.
% Specify D.n(i) as 1 to ignore this factor level,
% otherwise the number of levels can be pre-specified as a
% given number, or given as Inf to allow the user to
% choose the number of levels.
%
% D.sF - a 1x4 cellstr containing the names of the four
% factors. D.sF{i} is the name of factor i.
%
% D.b.aTime - a binary indicator specifying whether images within F3
% level (subject) are selected in time order. For time
% order (D.b.aTime=1), F2 levels are indicated by a user
% input "condition" string (input handled by spm_input's
% 'c' type). When (D.b.aTime=0), images for each F3 are
% selected by F2 (condition). The latter was the mode of
% SPM95 and SPM96. (SPM94 and SPMclassic didn't do
% replications of conditions.)
%
% Once the user has entered the images and indicated the factor levels,
% a nScan x 4 matrix, I, of indicator variables is constructed
% specifying for each scan the relevant level of each of the four
% factors. I(n,i) is the level of factor i corresponding to image n.
% This I matrix of factor indicators is then used to construct the H
% and B forms of the design matrix according to the prescripton in the
% design definition D:
%
% D.Hform - a string specifying the form of the H partition of the
% design matrix. The string is evaluated as an argument
% string for spm_DesMtx, which builds design matrix
% partitions from indicator vectors.
% (eval(['[H,Hnames] = spm_DesMtx(',D.Hform,');']))
%
% D.BForm - a string specifying the form of the G partition.
%
% ( Note that a constant H partition is dropped if the B partition can )
% ( model the constant effect. )
%
% The next part of the design definition defines covariate options.
% Covariates are split into covariates (of interest) and nuisance
% variables. The covariates of interest and nuisance variables are put
% into the C & G partitions of the design matrox (the final design
% matrix is [H,C,B,G], where global nuisance covariates are appended to
% G). In SPM94/5/6 the design matrix was partitioned into effects of
% interest [H,C] and effects of no interest [B,G], with an F-test for
% no effects of interest and adjusted data (for effects of no interest)
% following from these partitions. SPM99 is more freestyle, with
% adjustments and F-tests specified by contrasts. However, the concept
% of effects of interest and of no interest has been maintained for
% continuity, and spm_spm_ui.m computes an F-contrast to test for "no
% effects of interest".
%
% D.nC - a 1x2 vector: D.nC(1) is the number of covariates,
% D.nC(2) the number of nuisance variables. Specify zero
% to skip covariate entry, the actual number of
% covariates, or Inf to let the user specify the number of
% covariates. As with earlier versions, blocks of design
% matrix can be entered. However, these are now treated as
% a single covariate entity, so the number of
% covariates.nuisance variables is now the number of items
% you are prompted for, regardless of their dimension. (In
% SPM95-6 this number was the number of covariate vectors
% that could be entered.)
%
% D.iCC - a 1x2 cell array containing two vectors indicating the
% allowable covariate centering options for this design.
% These options are defined in the body of spm_spm_ui.m,
% in variables sCC & CFIforms. Use negative indices to
% indicate the default, if any - the largest negative
% wins.
%
% D.iCFI - a 1x2 cell array containing two vectors indicating the
% allowable covariate by factor interactions for this
% design. Interactions are only offered with a factor if
% it has multiple levels. The options are defined in the
% body of spm_spm_ui.m, in variables sCFI & CFIforms. Use
% negative indicies to indicate a default.
%
% The next part defines global options:
%
% D.iGXcalc - a vector of possible global calculation options for
% this design, as listed in the body of spm_spm_ui.m in
% variable sGXcalc. (If other global options are chosen,
% then the "omit" option is not offered.) Again, negative
% values indicate a default.
%
% D.iGloNorm - a vector of possible global normalisation options for
% this design, as described in the body of spm_spm_ui.m in
% variable sGloNorm.
%
% D.iGMsca - a vector of possible grand mean scaling options, as
% described in the body of spm_spm_ui.m in variable
% sGMsca. (Note that grand mean scaling is redundent when
% using proportional scaling global flow normalisation.)
%
% D.iGC - a vector of possible global covariate centering
% options, corresponding to the descriptions in variable
% iCC given in the body of spm_spm_ui.m. This is only
% relevant for AnCova type global normalisation, and even
% then only if you're actually interested in constraining
% the values of the parameters in some useful way.
% Usually, one chooses option 10, "as implied by AnCova".
%
% The next component specifies masking options:
%
% D.M_.T - a vector defining the analysis threshold: Specify
% "-Inf" as an element to offer "None" as an option. If a
% real element is found, then absolute thresholding is
% offered, with the first real value proffered as default
% threshold. If an imaginary element is found, then
% proportional thresholding if offered (i.e. the threshold
% is a proportion of the image global), with the (abs of)
% the first imaginary element proffered as default.
%
% D.M_.I - Implicit masking? 0-no, 1-yes, Inf-ask. (This is
% irrelevant for image types with a representation of NaN,
% since NaN is then the mask value, and NaN's are always
% masked.)
%
% D.M.X - Explicit masking? 0-no, 1-yes, Inf-ask.
%
% ----------------
%
% To use a customised design structure D, type spm_spm_ui('cfg',D) in the
% Matlab command window.
%
% The easiest way to generate a customised design definition structure
% is to tweak one of the pre-defined definitions. The following code
% will prompt you to select one of the pre-defined designs, and return
% the design definition structure for you to work on:
%
% D = spm_spm_ui(char(spm_input('Select design class...','+1','m',...
% {'Basic stats','Standard PET designs','SPM96 PET designs'},...
% {'DesDefs_Stats','DesDefs_PET','DesDefs_PET96'},2)));
% D = D(spm_input('Select design type...','+1','m',{D.DesName}'))
%
%_______________________________________________________________________
% @(#)spm_spm_ui.m 2.54 Andrew Holmes 04/12/09
%-Condition arguments
%-----------------------------------------------------------------------
if (nargin==0), Action = 'CFG'; else, Action = varargin{1}; end
switch lower(Action)
case 'cfg'
%===================================================================
% - C O N F I G U R E D E S I G N
%===================================================================
% spm_spm_ui('CFG',D)
if nargin<2, D = []; else, D = varargin{2}; end
%-GUI setup
%-------------------------------------------------------------------
SPMid = spm('FnBanner',mfilename,SCCSid);
[Finter,Fgraph,CmdLine] = spm('FnUIsetup','Stats: Setup analysis',0);
spm_help('!ContextHelp',mfilename)
%-Ask about overwriting files from previous analyses...
%-------------------------------------------------------------------
if exist(fullfile('.','SPM.mat'))
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'))
spm_clf(Finter)
return
end
end
%-Option definitions
%-------------------------------------------------------------------
%-Generic factor names
sF = {'sF1','sF2','sF3','sF4'};
%-Covariate by factor interaction options
sCFI = {'<none>';... %-1
'with sF1';'with sF2';'with sF3';'with sF4';... %-2:5
'with sF2 (within sF4)';'with sF3 (within sF4)'}; %-6,7
%-DesMtx argument components for covariate by factor interaction options
% (Used for CFI's Covariate Centering (CC), GMscale & Global normalisation)
CFIforms = { '[]', 'C', '{}';... %-1
'I(:,1)', 'FxC', '{D.sF{1}}';... %-2
'I(:,2)', 'FxC', '{D.sF{2}}';... %-3
'I(:,3)', 'FxC', '{D.sF{3}}';... %-4
'I(:,4)', 'FxC', '{D.sF{4}}';... %-5
'I(:,[4,2])', 'FxC', '{D.sF{4},D.sF{2}}';... %-6
'I(:,[4,3])', 'FxC', '{D.sF{4},D.sF{3}}' }; %-7
%-Centre (mean correction) options for covariates & globals (CC)
% (options 9-12 are for centering of global when using AnCova GloNorm) (GC)
sCC = { 'around overall mean';... %-1
'around sF1 means';... %-2
'around sF2 means';... %-3
'around sF3 means';... %-4
'around sF4 means';... %-5
'around sF2 (within sF4) means';... %-6
'around sF3 (within sF4) means';... %-7
'<no centering>';... %-8
'around user specified value';... %-9
'(as implied by AnCova)';... %-10
'GM';... %-11
'(redundant: not doing AnCova)'}'; %-12
%-DesMtx I forms for covariate centering options
CCforms = {'ones(nScan,1)',CFIforms{2:end,1},''}';
%-Global normalization options (options 1-7 match CFIforms) (GloNorm)
sGloNorm = { 'AnCova';... %-1
'AnCova by sF1';... %-2
'AnCova by sF2';... %-3
'AnCova by sF3';... %-4
'AnCova by sF4';... %-5
'AnCova by sF2 (within sF4)';... %-6
'AnCova by sF3 (within sF4)';... %-7
'proportional scaling';... %-8
'<no global normalisation>'}; %-9
%-Grand mean scaling options (GMsca)
sGMsca = { 'scaling of overall grand mean';... %-1
'scaling of sF1 grand means';... %-2
'scaling of sF2 grand means';... %-3
'scaling of sF3 grand means';... %-4
'scaling of sF4 grand means';... %-5
'scaling of sF2 (within sF4) grand means';... %-6
'scaling of sF3 (within sF4) grand means';... %-7
'(implicit in PropSca global normalisation)';... %-8
'<no grand Mean scaling>' }; %-9
%-NB: Grand mean scaling by subject is redundent for proportional scaling
%-Global calculation options (GXcalc)
sGXcalc = { 'omit';... %-1
'user specified';... %-2
'mean voxel value (within per image fullmean/8 mask)'}; %-3
%===================================================================
%-D E S I G N P A R A M E T E R S
%===================================================================
%-Get design type
%-------------------------------------------------------------------
if isempty(D)
D = spm_spm_ui( ...
char(spm_input('Select design class...','+1','m',...
{'Basic stats','Standard PET designs','SPM96 PET designs'},...
{'DesDefs_Stats','DesDefs_PET','DesDefs_PET96'},2)));
end
D = D(spm_input('Select design type...','+1','m',{D.DesName}'));
%-Set factor names for this design
%-------------------------------------------------------------------
sCC = sf_estrrep(sCC,[sF',D.sF']);
sCFI = sf_estrrep(sCFI,[sF',D.sF']);
sGloNorm = sf_estrrep(sGloNorm,[sF',D.sF']);
sGMsca = sf_estrrep(sGMsca,[sF',D.sF']);
%-Get filenames & factor indicies
%-------------------------------------------------------------------
[P,I] = spm_spm_ui('Files&Indices',D.sF,D.n,D.b.aTime);
nScan = size(I,1); %-#obs
%-Additional design parameters
%-------------------------------------------------------------------
bL = any(diff(I,1),1); %-Multiple factor levels?
% NB: bL(2) might be thrown by user specified f1 levels
% (D.b.aTime & D.n(2)>1) - assumme user is consistent?
bFI = [bL(1),bL(2:3)&~bL(4),bL(4),bL([2,3])&bL(4)];
%-Allowable interactions for covariates
%-Only offer interactions with multi-level factors, and
% don't offer by F2|F3 if bL(4)!
%-Build Condition (H) and Block (B) partitions
%===================================================================
H=[];Hnames=[];
B=[];Bnames=[];
eval(['[H,Hnames] = spm_DesMtx(',D.Hform,');'])
if rank(H)==nScan, error('unestimable condition effects'), end
eval(['[B,Bnames] = spm_DesMtx(',D.Bform,');'])
if rank(B)==nScan, error('unestimable block effects'), end
%-Drop a constant H partition if B partition can model constant
if size(H,2)>0 & all(H(:)==1) & (rank([H B])==rank(B))
H = []; Hnames = {};
warning('Dropping redundant constant H partition')
end
%-Covariate partition(s): interest (C) & nuisance (G) excluding global
%===================================================================
nC = D.nC; %-Default #covariates
C = {[],[]}; Cnames = {{},{}}; %-Covariate DesMtx partitions & names
xC = []; %-Struct array to hold raw covariates
dcname = {'CovInt','NusCov'}; %-Default root names for covariates
dstr = {'covariate','nuisance variable'};
GUIpos = spm_input('!NextPos');
nc = [0,0];
for i = 1:2 % 1:covariates of interest, 2:nuisance variables
if isinf(nC(i)), nC(i)=spm_input(['# ',dstr{i},'s'],GUIpos,'w1'); end
while nc(i) < nC(i)
%-Create prompt, get covariate, get covariate name
%-----------------------------------------------------------
if nC(i)==1
str=dstr{i};
else
str=sprintf('%s %d',dstr{i},nc(i)+1);
end
c = spm_input(str,GUIpos,'r',[],[nScan,Inf]);
if any(isnan(c(:))), break, end %-NaN is dummy value to exit
nc(i) = nc(i)+1; %-#Covariates (so far)
if nC(i)>1, tstr = sprintf('%s^{%d}',dcname{i},nc(i));
else, tstr = dcname{i}; end
cname = spm_input([str,' name?'],'+1','s',tstr);
rc = c; %-Save covariate value
rcname = cname; %-Save covariate name
%-Interaction option? (if single covariate vector entered)?
%-----------------------------------------------------------
if size(c,2) == 1
%-User choice of interaction options, default is negative
%-Only offer interactions for appropriate factor combinations
if length(D.iCFI{i})>1
iCFI = intersect(abs(D.iCFI{i}),find([1,bFI]));
dCFI = max([1,intersect(iCFI,-D.iCFI{i}(D.iCFI{i}<0))]);
iCFI = spm_input([str,': interaction?'],'+1','m',...
sCFI(iCFI),iCFI,find(iCFI==dCFI));
else
iCFI = abs(D.iCFI{i}); %-AutoSelect default option
end
else
iCFI = 1;
end
%-Centre covariate(s)? (Default centring to correspond to CFI)
% Always offer "no centering" as default for design matrix blocks
%-----------------------------------------------------------
DiCC = D.iCC{i};
if size(c,2)>1, DiCC = union(DiCC,-8); end
if length(DiCC)>1
%-User has a choice of centering options
%-Only offer factor specific for appropriate factor combinations
iCC = intersect(abs(DiCC),find([1,bFI,1]) );
%-Default is max -ve option in D, overridden by iCFI if CFI
if iCFI == 1, dCC = -DiCC(DiCC<0); else, dCC = iCFI; end
dCC = max([1,intersect(iCC,dCC)]);
iCC = spm_input([str,': centre?'],'+1','m',...
sCC(iCC),iCC,find(iCC==dCC));
else
iCC = abs(DiCC); %-AutoSelect default option
end
%-Centre within factor levels as appropriate
if any(iCC == [1:7]), c = c - spm_meanby(c,eval(CCforms{iCC})); end
%-Do any interaction (only for single covariate vectors)
%-----------------------------------------------------------
if iCFI > 1 %-(NB:iCFI=1 if size(c,2)>1)
tI = [eval(CFIforms{iCFI,1}),c];
tConst = CFIforms{iCFI,2};
tFnames = [eval(CFIforms{iCFI,3}),{cname}];
[c,cname] = spm_DesMtx(tI,tConst,tFnames);
elseif size(c,2)>1 %-Design matrix block
[null,cname] = spm_DesMtx(c,'X',cname);
else
cname = {cname};
end
%-Store raw covariate details in xC struct for reference
%-Pack c into appropriate DesMtx partition
%-----------------------------------------------------------
%-Construct description string for covariate
str = {sprintf('%s: %s',str,rcname)};
if size(rc,2)>1, str = {sprintf('%s (block of %d covariates)',...
str{:},size(rc,2))}; end
if iCC < 8, str=[str;{['used centered ',sCC{iCC}]}]; end
if iCFI> 1, str=[str;{['fitted as interaction ',sCFI{iCFI}]}]; end
tmp = struct( 'rc',rc, 'rcname',rcname,...
'c',c, 'cname',{cname},...
'iCC',iCC, 'iCFI',iCFI,...
'type',i,...
'cols',[1:size(c,2)] + ...
size([H,C{1}],2) + ...
size([B,C{2}],2)*(i-1),...
'descrip',{str} );
if isempty(xC), xC = tmp; else, xC = [xC,tmp]; end
C{i} = [C{i},c];
Cnames{i} = [Cnames{i}; cname];
end % (while)
end % (for)
clear c tI tConst tFnames
spm_input('!SetNextPos',GUIpos);
%-Unpack into C & G design matrix sub-partitions
G = C{2}; Gnames = Cnames{2};
C = C{1}; Cnames = Cnames{1};
%-Options...
%===================================================================
%-Global normalization options (GloNorm)
%-------------------------------------------------------------------
if length(D.iGloNorm)>1
%-User choice of global normalisation options, default is negative
%-Only offer factor specific for appropriate factor combinations
iGloNorm = intersect(abs(D.iGloNorm),find([1,bFI,1,1]));
dGloNorm = max([0,intersect(iGloNorm,-D.iGloNorm(D.iGloNorm<0))]);
iGloNorm = spm_input('GloNorm: Select global normalisation','+1','m',...
sGloNorm(iGloNorm),iGloNorm,find(iGloNorm==dGloNorm));
else
iGloNorm = abs(D.iGloNorm);
end
%-Grand mean scaling options (GMsca)
%-------------------------------------------------------------------
if iGloNorm==8
iGMsca=8; %-grand mean scaling implicit in PropSca GloNorm
elseif length(D.iGMsca)==1
iGMsca = abs(D.iGMsca);
else
%-User choice of grand mean scaling options
%-Only offer factor specific for appropriate factor combinations
iGMsca = intersect(abs(D.iGMsca),find([1,bFI,0,1]));
%-Default is max -ve option in D, overridden by iGloNorm if AnCova
if iGloNorm==9, dGMsca=-D.iGMsca(D.iGMsca<0); else, dGMsca=iGloNorm; end
dGMsca = max([0,intersect(iGMsca,dGMsca)]);
iGMsca = spm_input('GMsca: grand mean scaling','+1','m',...
sGMsca(iGMsca),iGMsca,find(iGMsca==dGMsca));
end
%-Value for PropSca / GMsca (GM)
%-------------------------------------------------------------------
if iGMsca == 9 %-Not scaling (GMsca or PropSca)
GM = 0; %-Set GM to zero when not scaling
else %-Ask user value of GM
if iGloNorm==8
str = 'PropSca global mean to';
else
str = [strrep(sGMsca{iGMsca},'scaling of','scale'),' to'];
end
GM = spm_input(str,'+1','r',D.GM,1);
%-If GM is zero then don't GMsca! or PropSca GloNorm
if GM==0, iGMsca=9; if iGloNorm==8, iGloNorm=9; end, end
end
%-Sort out description strings for GloNorm and GMsca
%-------------------------------------------------------------------
sGloNorm = sGloNorm{iGloNorm};
sGMsca = sGMsca{iGMsca};
if iGloNorm==8
sGloNorm = sprintf('%s to %-4g',sGloNorm,GM);
elseif iGMsca<8
sGMsca = sprintf('%s to %-4g',sGMsca,GM);
end
%-Global centering (for AnCova GloNorm) (GC)
%-------------------------------------------------------------------
%-Specify the centering option for the global covariate for AnCova
%-Basically, if 'GMsca'ling then should centre to GM (iGC=11). Otherwise,
% should centre in similar fashion to AnCova (i.e. by the same factor(s)),
% such that models are seperable (iGC=10). This is particularly important
% for subject specific condition effects if then passed on to a second-level
% model. (See also spm_adjmean_ui.m) SPM96 (& earlier) used to just centre
% GX around its (overall) mean (iGC=1).
%-This code allows more general options to be specified (but is complex)
%-Setting D.iGC=[-10,-11] gives the standard choices above
%-If not doing AnCova then GC is irrelevant
if ~any(iGloNorm == [1:7])
iGC = 12;
gc = [];
else
%-Annotate options 10 & 11 with specific details
%---------------------------------------------------------------
%-Tag '(as implied by AnCova)' with actual AnCova situation
sCC{10} = [sCC{iGloNorm},' (<= ',sGloNorm,')'];
%-Tag 'GM' case with actual GM & GMsca case
sCC{11} = sprintf('around GM=%g (i.e. %s after grand mean scaling)',...
GM,strrep(sCC{iGMsca},'around ',''));
%-Constuct vector of allowable iGC
%---------------------------------------------------------------
%-Weed out redundent factor combinations from pre-set allowable options
iGC = intersect(abs(D.iGC),find([1,bFI,1,1,1,1]));
%-Omit 'GM' option if didn't GMsca (iGMsca~=8 'cos doing AnCova)
if any(iGMsca==[8,9]), iGC = setdiff(iGC,11); end
%-Omit 'GM' option if same as '(as implied by AnCova)'
if iGloNorm==iGMsca, iGC = setdiff(iGC,11); end
%-If there's a choice, set defaults (if any), & get answer
%---------------------------------------------------------------
if length(iGC)>1
dGC = max([0,intersect(iGC,-D.iGC(D.iGC<0))]);
str = 'Centre global covariate';
if iGMsca<8, str = [str,' (after grand mean scaling)']; end
iGC = spm_input(str,'+1','m',sCC(iGC),iGC,find(iGC==dGC));
elseif isempty(iGC)
error('Configuration error: empty iGC')
end
%-If 'user specified' then get value
%---------------------------------------------------------------
if iGC==9
gc = spm_input('Centre globals around','+0','r',D.GM,1);
sCC{9} = sprintf('%s of %g',sCC{iGC},gc);
else
gc = 0;
end
end
%-Thresholds & masks defining voxels to analyse (MASK)
%===================================================================
GUIpos = spm_input('!NextPos');
%-Analysis threshold mask
%-------------------------------------------------------------------
%-Work out available options:
% -Inf=>None, real=>absolute, complex=>proportional, (i.e. times global)
M_T = D.M_.T; if isempty(M_T), M_T = [-Inf, 100, 0.8*sqrt(-1)]; end
M_T = { 'none', M_T(min(find(isinf(M_T))));...
'absolute', M_T(min(find(isfinite(M_T)&(M_T==real(M_T)))));...
'relative', M_T(min(find(isfinite(M_T)&(M_T~=real(M_T))))) };
%-Work out available options
%-If there's a choice between proportional and absolute then ask
%-------------------------------------------------------------------
q = ~[isempty(M_T{1,2}), isempty(M_T{2,2}), isempty(M_T{3,2})];
if all(q(2:3))
tmp = spm_input('Threshold masking',GUIpos,'b',M_T(q,1),find(q));
q(setdiff([1:3],tmp))=0;
end
%-Get mask value - note that at most one of q(2:3) is true
%-------------------------------------------------------------------
if ~any(q) %-Oops - nothing specified!
M_T = -Inf;
elseif all(q==[1,0,0]) %-no threshold masking
M_T = -Inf;
else %-get mask value
if q(1), args = {'br1','None',-Inf,abs(M_T{1+find(q(2:3)),2})};
else, args = {'r',abs(M_T{1+find(q(2:3)),2})}; end
if q(2)
M_T = spm_input('threshold',GUIpos,args{:});
elseif q(3)
M_T = spm_input('threshold (relative to global)',GUIpos,...
args{:});
if isfinite(M_T) & isreal(M_T), M_T=M_T*sqrt(-1); end
else
error('Shouldn''t get here!')
end
end
%-Make a description string
%-------------------------------------------------------------------
if isinf(M_T)
xsM.Analysis_threshold = 'None (-Inf)';
elseif isreal(M_T)
xsM.Analysis_threshold = sprintf('images thresholded at %6g',M_T);
else
xsM.Analysis_threshold = sprintf(['images thresholded at %6g ',...
'times global'],imag(M_T));
end
%-Implicit masking: Ignore zero voxels in low data-types?
%-------------------------------------------------------------------
% (Implicit mask is NaN in higher data-types.)
type = getfield(spm_vol(P{1,1}),'dt')*[1,0]';
if ~spm_type(type,'nanrep')
switch D.M_.I
case Inf, M_I = spm_input('Implicit mask (ignore zero''s)?',...
'+1','y/n',[1,0],1); %-Ask
case {0,1}, M_I = D.M_.I; %-Pre-specified
otherwise, error('unrecognised D.M_.I type')
end
if M_I, xsM.Implicit_masking = 'Yes: zero''s treated as missing';
else, xsm.Implicit_masking = 'No'; end
else
M_I = 1;
xsM.Implicit_masking = 'Yes: NaN''s treated as missing';
end
%-Explicit mask images (map them later...)
%-------------------------------------------------------------------
switch(D.M_.X)
case Inf, M_X = spm_input('explicitly mask images?','+1','y/n',[1,0],2);
case {0,1}, M_X = D.M_.X;
otherwise, error('unrecognised D.M_.X type')
end
if M_X, M_P = spm_select(Inf,'image','select mask images'); else, M_P = {}; end
%-Global calculation (GXcalc)
%===================================================================
iGXcalc = abs(D.iGXcalc);
%-Only offer "omit" option if not doing any GloNorm, GMsca or PropTHRESH
if ~(iGloNorm==9 & iGMsca==9 & (isinf(M_T)|isreal(M_T)))
iGXcalc = intersect(iGXcalc,[2:size(sGXcalc,1)]);
end
if isempty(iGXcalc)
error('no GXcalc options')
elseif length(iGXcalc)>1
%-User choice of global calculation options, default is negative
dGXcalc = max([1,intersect(iGXcalc,-D.iGXcalc(D.iGXcalc<0))]);
iGXcalc = spm_input('Global calculation','+1','m',...
sGXcalc(iGXcalc),iGXcalc,find(iGXcalc==dGXcalc));
else
iGXcalc = abs(D.iGXcalc);
end
if iGXcalc==2 %-Get user specified globals
g = spm_input('globals','+0','r',[],[nScan,1]);
end
sGXcalc = sGXcalc{iGXcalc};
% Non-sphericity correction (set xVi.var and .dep)
%===================================================================
xVi.I = I;
nL = max(I); % number of levels
mL = find(nL > 1); % multilevel factors
xVi.var = sparse(1,4); % unequal variances
xVi.dep = sparse(1,4); % dependencies
if length(mL) > 1
% repeated measures design
%---------------------------------------------------------------
if spm_input('non-sphericity correction?','+1','y/n',[1,0],0)
% make menu strings
%-----------------------------------------------------------
for i = 1:4
mstr{i} = sprintf('%s (%i levels)',D.sF{i},nL(i));
end
mstr = mstr(mL);
% are errors identical
%-----------------------------------------------------------
if spm_input('are errors identical','+1','y/n',[0,1],0)
str = 'unequal variances are between';
[i j] = min(nL(mL));
i = spm_input(str,'+0','m',mstr,[],j);
% set in xVi and eliminate from dependency option
%-------------------------------------------------------
xVi.var(mL(i)) = 1;
mL(i) = [];
mstr(i) = [];
end
% are errors independent
%-----------------------------------------------------------
if spm_input('are errors independent','+1','y/n',[0,1],0)
str = ' dependencies are within';
[i j] = max(nL(mL));
i = spm_input(str,'+0','m',mstr,[],j);
% set in xVi
%-------------------------------------------------------
xVi.dep(mL(i)) = 1;
end
end
end
%-Place covariance components Q{:} in xVi.Vi
%-------------------------------------------------------------------
xVi = spm_non_sphericity(xVi);
%===================================================================
% - C O N F I G U R E D E S I G N
%===================================================================
spm('FigName','Stats: configuring',Finter,CmdLine);
spm('Pointer','Watch');
%-Images & image info: Map Y image files and check consistency of
% dimensions and orientation / voxel size
%===================================================================
fprintf('%-40s: ','Mapping files') %-#
VY = spm_vol(char(P));
%-Check compatability of images (Bombs for single image)
%-------------------------------------------------------------------
spm_check_orientations(VY);
fprintf('%30s\n','...done') %-#
%-Global values, scaling and global normalisation
%===================================================================
%-Compute global values
%-------------------------------------------------------------------
switch iGXcalc, case 1
%-Don't compute => no GMsca (iGMsca==9) or GloNorm (iGloNorm==9)
g = [];
case 2
%-User specified globals
case 3
%-Compute as mean voxel value (within per image fullmean/8 mask)
g = zeros(nScan,1 );
fprintf('%-40s: %30s','Calculating globals',' ') %-#
for i = 1:nScan
str = sprintf('%3d/%-3d',i,nScan);
fprintf('%s%30s',repmat(sprintf('\b'),1,30),str)%-#
g(i) = spm_global(VY(i));
end
fprintf('%s%30s\n',repmat(sprintf('\b'),1,30),'...done') %-#
otherwise
error('illegal iGXcalc')
end
rg = g;
fprintf('%-40s: ','Design configuration') %-#
%-Scaling: compute global scaling factors gSF required to implement
% proportional scaling global normalisation (PropSca) or grand mean
% scaling (GMsca), as specified by iGMsca (& iGloNorm)
%-------------------------------------------------------------------
switch iGMsca, case 8
%-Proportional scaling global normalisation
if iGloNorm~=8, error('iGloNorm-iGMsca(8) mismatch for PropSca'), end
gSF = GM./g;
g = GM*ones(nScan,1);
case {1,2,3,4,5,6,7}
%-Grand mean scaling according to iGMsca
gSF = GM./spm_meanby(g,eval(CCforms{iGMsca}));
g = g.*gSF;
case 9
%-No grand mean scaling
gSF = ones(nScan,1);
otherwise
error('illegal iGMsca')
end
%-Apply gSF to memory-mapped scalefactors to implement scaling
%-------------------------------------------------------------------
for i = 1:nScan
VY(i).pinfo(1:2,:) = VY(i).pinfo(1:2,:)*gSF(i);
end
%-AnCova: Construct global nuisance covariates partition (if AnCova)
%-------------------------------------------------------------------
if any(iGloNorm == [1:7])
%-Centre global covariate as requested
%---------------------------------------------------------------
switch iGC, case {1,2,3,4,5,6,7} %-Standard sCC options
gc = spm_meanby(g,eval(CCforms{iGC}));
case 8 %-No centering
gc = 0;
case 9 %-User specified centre
%-gc set above
case 10 %-As implied by AnCova option
gc = spm_meanby(g,eval(CCforms{iGloNorm}));
case 11 %-Around GM
gc = GM;
otherwise %-unknown iGC
error('unexpected iGC value')
end
%-AnCova - add scaled centred global to DesMtx `G' partition
%---------------------------------------------------------------
rcname = 'global';
tI = [eval(CFIforms{iGloNorm,1}),g - gc];
tConst = CFIforms{iGloNorm,2};
tFnames = [eval(CFIforms{iGloNorm,3}),{rcname}];
[f,gnames] = spm_DesMtx(tI,tConst,tFnames);
clear tI tConst tFnames
%-Save GX info in xC struct for reference
%---------------------------------------------------------------
str = {sprintf('%s: %s',dstr{2},rcname)};
if any(iGMsca==[1:7]), str=[str;{['(after ',sGMsca,')']}]; end
if iGC ~= 8, str=[str;{['used centered ',sCC{iGC}]}]; end
if iGloNorm > 1
str=[str;{['fitted as interaction ',sCFI{iGloNorm}]}];
end
tmp = struct( 'rc',rg.*gSF, 'rcname',rcname,...
'c',f, 'cname' ,{gnames},...
'iCC',iGC, 'iCFI' ,iGloNorm,...
'type', 3,...
'cols',[1:size(f,2)] + size([H C B G],2),...
'descrip', {str} );
G = [G,f]; Gnames = [Gnames; gnames];
if isempty(xC), xC = tmp; else, xC = [xC,tmp]; end
elseif iGloNorm==8 | iGXcalc>1
%-Globals calculated, but not AnCova: Make a note of globals
%---------------------------------------------------------------
if iGloNorm==8
str = { 'global values: (used for proportional scaling)';...
'("raw" unscaled globals shown)'};
elseif isfinite(M_T) & ~isreal(M_T)
str = { 'global values: (used to compute analysis threshold)'};
else
str = { 'global values: (computed but not used)'};
end
rcname ='global';
tmp = struct( 'rc',rg, 'rcname',rcname,...
'c',{[]}, 'cname' ,{{}},...
'iCC',0, 'iCFI' ,0,...
'type', 3,...
'cols', {[]},...
'descrip', {str} );
if isempty(xC), xC = tmp; else, xC = [xC,tmp]; end
end
%-Save info on global calculation in xGX structure
%-------------------------------------------------------------------
xGX = struct(...
'iGXcalc',iGXcalc, 'sGXcalc',sGXcalc, 'rg',rg,...
'iGMsca',iGMsca, 'sGMsca',sGMsca, 'GM',GM,'gSF',gSF,...
'iGC', iGC, 'sGC', sCC{iGC}, 'gc', gc,...
'iGloNorm',iGloNorm, 'sGloNorm',sGloNorm);
%-Construct masking information structure and compute actual analysis
% threshold using scaled globals (rg.*gSF)
%-------------------------------------------------------------------
if isreal(M_T), M_TH = M_T * ones(nScan,1); %-NB: -Inf is real
else, M_TH = imag(M_T) * (rg.*gSF); end
if ~isempty(M_P)
VM = spm_vol(char(M_P));
xsM.Explicit_masking = [{'Yes: mask images :'};{VM.fname}'];
else
VM = [];
xsM.Explicit_masking = 'No';
end
xM = struct('T',M_T, 'TH',M_TH, 'I',M_I, 'VM',{VM}, 'xs',xsM);
%-Construct full design matrix (X), parameter names and structure (xX)
%===================================================================
X = [H C B G];
tmp = cumsum([size(H,2), size(C,2), size(B,2), size(G,2)]);
xX = struct( 'X', X,...
'iH', [1:size(H,2)],...
'iC', [1:size(C,2)] + tmp(1),...
'iB', [1:size(B,2)] + tmp(2),...
'iG', [1:size(G,2)] + tmp(3),...
'name', {[Hnames; Cnames; Bnames; Gnames]},...
'I', I,...
'sF', {D.sF});
%-Design description (an nx2 cellstr) - for saving and display
%===================================================================
tmp = { sprintf('%d condition, +%d covariate, +%d block, +%d nuisance',...
size(H,2),size(C,2),size(B,2),size(G,2));...
sprintf('%d total, having %d degrees of freedom',...
size(X,2),rank(X));...
sprintf('leaving %d degrees of freedom from %d images',...
size(X,1)-rank(X),size(X,1)) };
xsDes = struct( 'Design', {D.DesName},...
'Global_calculation', {sGXcalc},...
'Grand_mean_scaling', {sGMsca},...
'Global_normalisation', {sGloNorm},...
'Parameters', {tmp} );
fprintf('%30s\n','...done') %-#
%-Assemble SPM structure
%===================================================================
SPM.xY.P = P; % filenames
SPM.xY.VY = VY; % mapped data
SPM.nscan = size(xX.X,1); % scan number
SPM.xX = xX; % design structure
SPM.xC = xC; % covariate structure
SPM.xGX = xGX; % global structure
SPM.xVi = xVi; % non-sphericity structure
SPM.xM = xM; % mask structure
SPM.xsDes = xsDes; % description
SPM.SPMid = SPMid; % version
%-Save SPM.mat and set output argument
%-------------------------------------------------------------------
fprintf('%-40s: ','Saving SPM configuration') %-#
if spm_check_version('matlab','7') >=0
save('SPM.mat', 'SPM', '-V6');
else
save('SPM.mat', 'SPM');
end;
fprintf('%30s\n','...SPM.mat saved') %-#
varargout = {SPM};
%-Display Design report
%===================================================================
fprintf('%-40s: ','Design reporting') %-#
fname = cat(1,{SPM.xY.VY.fname}');
spm_DesRep('DesMtx',SPM.xX,fname,SPM.xsDes)
fprintf('%30s\n','...done')
%-End: Cleanup GUI
%===================================================================
spm_clf(Finter)
spm('Pointer','Arrow')
fprintf('%-40s: %30s\n','Completed',spm('time')) %-#
spm('FigName','Stats: configured',Finter,CmdLine);
spm('Pointer','Arrow')
fprintf('\n\n')
case 'files&indices'
%===================================================================
% - Get files and factor indices
%===================================================================
% [P,I] = spm_spm_ui('Files&Indices',DsF,Dn,DbaTime,nV)
% DbaTime=D.b.aTime; Dn=D.n; DsF=D.sF;
if nargin<5, nV = 1; else, nV = varargin{5}; end
if nargin<4, DbaTime = 1; else, DbaTime = varargin{4}; end
if nargin<3, Dn = [Inf,Inf,Inf,Inf]; else, Dn=varargin{3}; end
if nargin<2, DsF = {'Fac1','Fac2','Fac3','Fac4'}; else, DsF=varargin{2}; end
%-Initialise variables
%-------------------------------------------------------------------
i4 = []; % factor 4 index (usually group)
i3 = []; % factor 3 index (usually subject), per f4
i2 = []; % factor 2 index (usually condition), per f3/f4
i1 = []; % factor 1 index (usually replication), per f2/f3/f4
P = {}; % cell array of string filenames
%-Accrue filenames and factor level indicator vectors
%-------------------------------------------------------------------
bMV = nV>1;
if isinf(Dn(4)), n4 = spm_input(['#',DsF{4},'''s'],'+1','n1');
else, n4 = Dn(4); end
bL4 = n4>1;
ti2 = '';
GUIpos = spm_input('!NextPos');
for j4 = 1:n4
spm_input('!SetNextPos',GUIpos);
sF4P=''; if bL4, sF4P=[DsF{4},' ',int2str(j4),': ']; end
if isinf(Dn(3)), n3=spm_input([sF4P,'#',DsF{3},'''s'],'+1','n1');
else, n3 = Dn(3); end
bL3 = n3>1;
if DbaTime & Dn(2)>1
%disp('NB:selecting in time order - manually specify conditions')
%-NB: This means f2 levels might not be 1:n2
GUIpos2 = spm_input('!NextPos');
for j3 = 1:n3
sF3P=''; if bL3, sF3P=[DsF{3},' ',int2str(j3),': ']; end
str = [sF4P,sF3P];
tP = {};
n21 = Dn(2)*Dn(1);
for v=1:nV
vstr=''; if bMV, vstr=sprintf(' (var-%d)',v); end
ttP = cellstr(spm_select(n21,'image',[str,'select images',vstr]));
n21 = length(ttP);
tP = [tP,ttP];
end
ti2 = spm_input([str,' ',DsF{2},'?'],GUIpos2,'c',ti2',n21,Dn(2));
%-Work out i1 & check
[tl2,null,j] = unique(ti2);
tn1 = zeros(size(tl2)); ti1 = zeros(size(ti2));
for i=1:length(tl2)
tn1(i)=sum(j==i); ti1(ti2==tl2(i))=1:tn1(i); end
if isfinite(Dn(1)) & any(tn1~=Dn(1))
%-#i1 levels mismatches specification in Dn(1)
error(sprintf('#%s not %d as pre-specified',DsF{1},Dn(1)))
end
P = [P;tP];
i4 = [i4; j4*ones(n21,1)];
i3 = [i3; j3*ones(n21,1)];
i2 = [i2; ti2];
i1 = [i1; ti1];
end
else
if isinf(Dn(2))
n2 = spm_input([sF4P,'#',DsF{2},'''s'],'+1','n1');
else
n2 = Dn(2);
end
bL2 = n2>1;
if n2==1 & Dn(1)==1 %-single scan per f3 (subj)
%disp('NB:single scan per f3')
str = [sF4P,'select images, ',DsF{3},' 1-',int2str(n3)];
tP = {};
for v=1:nV
vstr=''; if bMV, vstr=sprintf(' (var-%d)',v); end
ttP = cellstr(spm_select(n3,'image',[str,vstr]));
tP = [tP,ttP];
end
P = [P;tP];
i4 = [i4; j4*ones(n3,1)];
i3 = [i3; [1:n3]'];
i2 = [i2; ones(n3,1)];
i1 = [i1; ones(n3,1)];
else
%-multi scan per f3 (subj) case
%disp('NB:multi scan per f3')
for j3 = 1:n3
sF3P=''; if bL3, sF3P=[DsF{3},' ',int2str(j3),': ']; end
if Dn(1)==1
%-No f1 (repl) within f2 (cond)
%disp('NB:no f1 within f2')
str = [sF4P,sF3P,'select images: ',DsF{2},...
' 1-',int2str(n2)];
tP = {};
for v=1:nV
vstr=''; if bMV, vstr=sprintf(' (var-%d)',v); end
ttP = cellstr(spm_select(n2,'image',[str,vstr]));
tP = [tP,ttP];
end
P = [P;tP];
i4 = [i4; j4*ones(n2,1)];
i3 = [i3; j3*ones(n2,1)];
i2 = [i2; [1:n2]'];
i1 = [i1; ones(n2,1)];
else
%-multi f1 (repl) within f2 (cond)
%disp('NB:f1 within f2')
for j2 = 1:n2
sF2P='';
if bL2, sF2P=[DsF{2},' ',int2str(j2),': ']; end
str = [sF4P,sF3P,sF2P,' select images...'];
tP = {};
n1 = Dn(1);
for v=1:nV
vstr=''; if bMV, vstr=sprintf(' (var-%d)',v); end
ttP = cellstr(spm_select(n1,'image',[str,vstr]));
n1 = length(ttP);
tP = [tP,ttP];
end
P = [P;tP];
i4 = [i4; j4*ones(n1,1)];
i3 = [i3; j3*ones(n1,1)];
i2 = [i2; j2*ones(n1,1)];
i1 = [i1; [1:n1]'];
end % (for j2)
end % (if Dn(1)==1)
end % (for j3)
end % (if n2==1 &...)
end % (if DbaTime & Dn(2)>1)
end % (for j4)
varargout = {P,[i1,i2,i3,i4]};
case 'desdefs_stats'
%===================================================================
% - Basic Stats Design definitions...
%===================================================================
% D = spm_spm_ui('DesDefs_Stats');
% These are the basic Stats design definitions...
%-Note: struct expands cell array values to give multiple records:
% => must embed cell arrays within another cell array!
%-Negative indices indicate defaults (first used)
D = struct(...
'DesName','One sample t-test',...
'n', [Inf 1 1 1], 'sF',{{'obs','','',''}},...
'Hform', 'I(:,2),''-'',''mean''',...
'Bform', '[]',...
'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...
'iGXcalc',[-1,2,3],'iGMsca',[1,-9],'GM',[],...
'iGloNorm',9,'iGC',12,...
'M_',struct('T',-Inf,'I',Inf,'X',Inf),...
'b',struct('aTime',0));
D = [D, struct(...
'DesName','Two sample t-test',...
'n', [Inf 2 1 1], 'sF',{{'obs','group','',''}},...
'Hform', 'I(:,2),''-'',''group''',...
'Bform', 'I(:,3),''-'',''\mu''',...
'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...
'iGXcalc',[-1,2,3],'iGMsca',[1,-9],'GM',[],...
'iGloNorm',9,'iGC',12,...
'M_',struct('T',[-Inf,0,0.8*sqrt(-1)],'I',Inf,'X',Inf),...
'b',struct('aTime',1))];
D = [D, struct(...
'DesName','Paired t-test',...
'n', [1 2 Inf 1], 'sF',{{'','cond','pair',''}},...
'Hform', 'I(:,2),''-'',''condition''',...
'Bform', 'I(:,3),''-'',''\gamma''',...
'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...
'iGXcalc',[-1,2,3],'iGMsca',[1,-9],'GM',[],...
'iGloNorm',9,'iGC',12,...
'M_',struct('T',[-Inf,0,0.8*sqrt(-1)],'I',Inf,'X',Inf),...
'b',struct('aTime',0))];
D = [D, struct(...
'DesName','One way Anova',...
'n', [Inf Inf 1 1], 'sF',{{'repl','group','',''}},...
'Hform', 'I(:,2),''-'',''group''',...
'Bform', '[]',...
'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...
'iGXcalc',[-1,2,3],'iGMsca',[1,-9],'GM',[],...
'iGloNorm',9,'iGC',12,...
'M_',struct('T',[-Inf,0,0.8*sqrt(-1)],'I',Inf,'X',Inf),...
'b',struct('aTime',0))];
D = [D, struct(...
'DesName','One way Anova (with constant)',...
'n', [Inf Inf 1 1], 'sF',{{'repl','group','',''}},...
'Hform', 'I(:,2),''-'',''group''',...
'Bform', 'I(:,3),''-'',''\mu''',...
'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...
'iGXcalc',[-1,2,3],'iGMsca',[1,-9],'GM',[],...
'iGloNorm',9,'iGC',12,...
'M_',struct('T',[-Inf,0,0.8*sqrt(-1)],'I',Inf,'X',Inf),...
'b',struct('aTime',0))];
D = [D, struct(...
'DesName','One way Anova (Within-subjects)',...
'n', [1 Inf Inf 1],'sF',{{'repl','condition','subject',''}},...
'Hform', 'I(:,2),''-'',''cond''',...
'Bform', 'I(:,3),''-'',''subj''',...
'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...
'iGXcalc',[-1,2,3],'iGMsca',[1,-9],'GM',[],...
'iGloNorm',9,'iGC',12,...
'M_',struct('T',[-Inf,0,0.8*sqrt(-1)],'I',Inf,'X',Inf),...
'b',struct('aTime',0))];
D = [D, struct(...
'DesName','Simple regression (correlation)',...
'n', [Inf 1 1 1], 'sF',{{'repl','','',''}},...
'Hform', '[]',...
'Bform', 'I(:,2),''-'',''\mu''',...
'nC',[1,0],'iCC',{{8,8}},'iCFI',{{1,1}},...
'iGXcalc',[-1,2,3],'iGMsca',[1,-9],'GM',[],...
'iGloNorm',9,'iGC',12,...
'M_',struct('T',[-Inf,0,0.8*sqrt(-1)],'I',Inf,'X',Inf),...
'b',struct('aTime',0))];
D = [D, struct(...
'DesName','Multiple regression',...
'n', [Inf 1 1 1], 'sF',{{'repl','','',''}},...
'Hform', '[]',...
'Bform', '[]',...
'nC',[Inf,0],'iCC',{{8,8}},'iCFI',{{1,1}},...
'iGXcalc',[-1,2,3],'iGMsca',[1,-9],'GM',[],...
'iGloNorm',9,'iGC',12,...
'M_',struct('T',[-Inf,0,0.8*sqrt(-1)],'I',Inf,'X',Inf),...
'b',struct('aTime',0))];
D = [D, struct(...
'DesName','Multiple regression (with constant)',...
'n', [Inf 1 1 1], 'sF',{{'repl','','',''}},...
'Hform', '[]',...
'Bform', 'I(:,2),''-'',''\mu''',...
'nC',[Inf,0],'iCC',{{8,8}},'iCFI',{{1,1}},...
'iGXcalc',[-1,2,3],'iGMsca',[1,-9],'GM',[],...
'iGloNorm',9,'iGC',12,...
'M_',struct('T',[-Inf,0,0.8*sqrt(-1)],'I',Inf,'X',Inf),...
'b',struct('aTime',0))];
D = [D, struct(...
'DesName','AnCova',...
'n', [Inf Inf 1 1], 'sF',{{'repl','group','',''}},...
'Hform', 'I(:,2),''-'',''group''',...
'Bform', 'I(:,3),''-'',''\mu''',...
'nC',[0,1],'iCC',{{8,1}},'iCFI',{{1,1}},...
'iGXcalc',[-1,2,3],'iGMsca',[1,-9],'GM',[],...
'iGloNorm',9,'iGC',12,...
'M_',struct('T',[-Inf,0,0.8*sqrt(-1)],'I',Inf,'X',Inf),...
'b',struct('aTime',0))];
varargout = {D};
case 'desdefs_pet'
%===================================================================
% - Standard (SPM99) PET/SPECT Design definitions...
%===================================================================
% D = spm_spm_ui('DesDefs_PET');
% These are the standard PET design definitions...
%-Single subject
%-------------------------------------------------------------------
D = struct(...
'DesName','Single-subject: conditions & covariates',...
'n', [Inf Inf 1 1], 'sF',{{'repl','condition','',''}},...
'Hform', 'I(:,2),''-'',''cond''',...
'Bform', 'I(:,3),''-'',''\mu''',...
'nC',[Inf,Inf],'iCC',{{[-1,3,8],[-1,8]}},'iCFI',{{[1,3],1}},...
'iGXcalc',[1,2,-3],'iGMsca',[-1,9],'GM',50,...
'iGloNorm',[1,8,9],'iGC',10,...
'M_',struct('T',[0,0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',1));
D = [D, struct(...
'DesName','Single-subject: covariates only',...
'n', [Inf 1 1 1], 'sF',{{'repl','','',''}},...
'Hform', '[]',...
'Bform', 'I(:,3),''-'',''\mu''',...
'nC',[Inf,Inf],'iCC',{{[-1,8],[-1,8]}},'iCFI',{{1,1}},...
'iGXcalc',[1,2,-3],'iGMsca',[-1,9],'GM',50,...
'iGloNorm',[1,8,9],'iGC',10,...
'M_',struct('T',[0,0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',1))];
%-Multi-subject
%-------------------------------------------------------------------
D = [D, struct(...
'DesName','Multi-subj: conditions & covariates',...
'n',[Inf Inf Inf 1], 'sF',{{'repl','condition','subject',''}},...
'Hform', 'I(:,2),''-'',''cond''',...
'Bform', 'I(:,3),''-'',''subj''',...
'nC',[Inf,Inf],'iCC',{{[1,3,4,8],[1,4,8]}},'iCFI',{{[1,3,-4],[1,-4]}},...
'iGXcalc',[1,2,-3],'iGMsca',[-4,9],'GM',50,...
'iGloNorm',[4,8,9],'iGC',10,...
'M_',struct('T',[0,0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',1))];
D = [D, struct(...
'DesName','Multi-subj: cond x subj interaction & covariates',...
'n',[Inf Inf Inf 1], 'sF',{{'repl','condition','subject',''}},...
'Hform', 'I(:,[3,2]),''-'',{''subj'',''cond''}',...
'Bform', 'I(:,3),''-'',''subj''',...
'nC',[Inf,Inf],'iCC',{{[1,3,4,8],[1,4,8]}},'iCFI',{{[1,3,-4],[1,-4]}},...
'iGXcalc',[1,2,-3],'iGMsca',[-4,9],'GM',50,...
'iGloNorm',[4,8,9],'iGC',10,...
'M_',struct('T',[0,0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',1))];
D = [D, struct(...
'DesName','Multi-subj: covariates only',...
'n',[Inf 1 Inf 1], 'sF',{{'repl','','subject',''}},...
'Hform', '[]',...
'Bform', 'I(:,3),''-'',''subj''',...
'nC',[Inf,Inf],'iCC',{{[1,4,8],[1,4,8]}},'iCFI',{{[1,-4],[1,-4]}},...
'iGXcalc',[1,2,-3],'iGMsca',[-4,9],'GM',50,...
'iGloNorm',[4,8:9],'iGC',10,...
'M_',struct('T',[0,0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0))];
%-Multi-group
%-------------------------------------------------------------------
D = [D, struct(...
'DesName','Multi-group: conditions & covariates',...
'n',[Inf Inf Inf Inf], 'sF',{{'repl','condition','subject','group'}},...
'Hform', 'I(:,[4,2]),''-'',{''stud'',''cond''}',...
'Bform', 'I(:,[4,3]),''-'',{''stud'',''subj''}',...
'nC',[Inf,Inf],'iCC',{{[5:8],[5,7,8]}},'iCFI',{{[1,5,6,-7],[1,5,-7]}},...
'iGXcalc',[1,2,-3],'iGMsca',[-7,9],'GM',50,...
'iGloNorm',[7,8,9],'iGC',10,...
'M_',struct('T',[0,0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',1))];
D = [D, struct(...
'DesName','Multi-group: covariates only',...
'n',[Inf 1 Inf Inf], 'sF',{{'repl','','subject','group'}},...
'Hform', '[]',...
'Bform', 'I(:,[4,3]),''-'',{''stud'',''subj''}',...
'nC',[Inf,Inf],'iCC',{{[5,7,8],[5,7,8]}},'iCFI',{{[1,5,-7],[1,5,-7]}},...
'iGXcalc',[1,2,-3],'iGMsca',[-7,9],'GM',50,...
'iGloNorm',[7,8,9],'iGC',10,...
'M_',struct('T',[0,0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0))];
%-Population comparisons
%-------------------------------------------------------------------
D = [D, struct(...
'DesName',...
'Population main effect: 2 cond''s, 1 scan/cond (paired t-test)',...
'n',[1 2 Inf 1], 'sF',{{'','condition','subject',''}},...
'Hform', 'I(:,2),''-'',''cond''',...
'Bform', 'I(:,3),''-'',''\mu''',...
'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...
'iGXcalc',[1,2,-3],'iGMsca',[-1,9],'GM',50,...
'iGloNorm',[8,9],'iGC',10,...
'M_',struct('T',[0,0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0))];
D = [D, struct(...
'DesName',...
'Dodgy population main effect: >2 cond''s, 1 scan/cond',...
'n',[1 Inf Inf 1], 'sF',{{'','condition','subject',''}},...
'Hform', 'I(:,2),''-'',''cond''',...
'Bform', 'I(:,3),''-'',''\mu''',...
'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...
'iGXcalc',[1,2,-3],'iGMsca',[-1,9],'GM',50,...
'iGloNorm',[8,9],'iGC',10,...
'M_',struct('T',[0,0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0))];
D = [D, struct(...
'DesName','Compare-populations: 1 scan/subject (two sample t-test)',...
'n',[Inf 2 1 1], 'sF',{{'subject','group','',''}},...
'Hform', 'I(:,2),''-'',''group''',...
'Bform', 'I(:,3),''-'',''\mu''',...
'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...
'iGXcalc',[1,2,-3],'iGMsca',[-1,9],'GM',50,...
'iGloNorm',[8,9],'iGC',10,...
'M_',struct('T',[0,0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0))];
D = [D, struct(...
'DesName','Compare-populations: 1 scan/subject (AnCova)',...
'n',[Inf 2 1 1], 'sF',{{'subject','group','',''}},...
'Hform', 'I(:,2),''-'',''group''',...
'Bform', 'I(:,3),''-'',''\mu''',...
'nC',[0,Inf],'iCC',{{8,1}},'iCFI',{{1,1}},...
'iGXcalc',[1,2,-3],'iGMsca',[-1,9],'GM',50,...
'iGloNorm',[1,8,9],'iGC',10,...
'M_',struct('T',[0,0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0))];
%-The Full Monty!
%-------------------------------------------------------------------
D = [D, struct(...
'DesName','The Full Monty...',...
'n',[Inf Inf Inf Inf], 'sF',{{'repl','cond','subj','group'}},...
'Hform', 'I(:,[4,2]),''-'',{''stud'',''cond''}',...
'Bform', 'I(:,[4,3]),''-'',{''stud'',''subj''}',...
'nC',[Inf,Inf],'iCC',{{[1:8],[1:8]}},'iCFI',{{[1:7],[1:7]}},...
'iGXcalc',[1,2,3],'iGMsca',[1:7],'GM',50,...
'iGloNorm',[1:9],'iGC',[1:11],...
'M_',struct('T',[-Inf,0,0.8*sqrt(-1)],'I',Inf,'X',Inf),...
'b',struct('aTime',1))];
varargout = {D};
case 'desdefs_pet96'
%===================================================================
% - SPM96 PET/SPECT Design definitions...
%===================================================================
% D = spm_spm_ui('DesDefs_PET96');
%-Single subject
%-------------------------------------------------------------------
D = struct(...
'DesName','SPM96:Single-subject: replicated conditions',...
'n', [Inf Inf 1 1], 'sF',{{'repl','condition','',''}},...
'Hform', 'I(:,2),''-'',''cond''',...
'Bform', 'I(:,3),''-'',''\mu''',...
'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...
'iGXcalc',3,'iGMsca',[1,9],'GM',50,...
'iGloNorm',[1,8,9],'iGC',10,...
'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0));
D = [D, struct(...
'DesName','SPM96:Single-subject: replicated conditions & covariates',...
'n', [Inf Inf 1 1], 'sF',{{'repl','condition','',''}},...
'Hform', 'I(:,2),''-'',''cond''',...
'Bform', 'I(:,3),''-'',''\mu''',...
'nC',[Inf,Inf],'iCC',{{1,1}},'iCFI',{{1,1}},...
'iGXcalc',3,'iGMsca',[1,9],'GM',50,...
'iGloNorm',[1,8,9],'iGC',10,...
'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0))];
D = [D, struct(...
'DesName','SPM96:Single-subject: covariates only',...
'n', [Inf 1 1 1], 'sF',{{'repl','','',''}},...
'Hform', '[]',...
'Bform', 'I(:,3),''-'',''\mu''',...
'nC',[Inf,Inf],'iCC',{{1,1}},'iCFI',{{1,1}},...
'iGXcalc',3,'iGMsca',[1,9],'GM',50,...
'iGloNorm',[1,8,9],'iGC',10,...
'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0))];
%-Multi-subject
%-------------------------------------------------------------------
D = [D, struct(...
'DesName','SPM96:Multi-subject: different conditions',...
'n', [1 Inf Inf 1], 'sF',{{'','condition','subject',''}},...
'Hform', 'I(:,2),''-'',''scancond''',...
'Bform', 'I(:,3),''-'',''subj''',...
'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...
'iGXcalc',3,'iGMsca',[1,9],'GM',50,...
'iGloNorm',[1,4,8,9],'iGC',10,...
'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0))];
D = [D, struct(...
'DesName','SPM96:Multi-subject: replicated conditions',...
'n',[Inf Inf Inf 1], 'sF',{{'repl','condition','subject',''}},...
'Hform', 'I(:,2),''-'',''cond''',...
'Bform', 'I(:,3),''-'',''subj''',...
'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...
'iGXcalc',3,'iGMsca',[1,9],'GM',50,...
'iGloNorm',[1,4,8,9],'iGC',10,...
'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0))];
D = [D, struct(...
'DesName','SPM96:Multi-subject: different conditions & covariates',...
'n', [1 Inf Inf 1], 'sF',{{'','condition','subject',''}},...
'Hform', 'I(:,2),''-'',''cond''',...
'Bform', 'I(:,3),''-'',''subj''',...
'nC',[Inf,Inf],'iCC',{{1,1}},'iCFI',{{[1,4],[1,4]}},...
'iGXcalc',3,'iGMsca',[1,9],'GM',50,...
'iGloNorm',[1,4,8,9],'iGC',10,...
'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0))];
D = [D, struct(...
'DesName','SPM96:Multi-subject: replicated conditions & covariates',...
'n',[Inf Inf Inf 1], 'sF',{{'repl','condition','subject',''}},...
'Hform', 'I(:,2),''-'',''condition''',...
'Bform', 'I(:,3),''-'',''subj''',...
'nC',[Inf,Inf],'iCC',{{1,1}},'iCFI',{{[1,3,4],[1,4]}},...
'iGXcalc',3,'iGMsca',[1,9],'GM',50,...
'iGloNorm',[1,4,8,9],'iGC',10,...
'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0))];
D = [D, struct(...
'DesName','SPM96:Multi-subject: covariates only',...
'n',[Inf 1 Inf 1], 'sF',{{'repl','','subject',''}},...
'Hform', '[]',...
'Bform', 'I(:,3),''-'',''subj''',...
'nC',[Inf,Inf],'iCC',{{[1,4,8],[1,4,8]}},'iCFI',{{[1,4],[1,4]}},...
'iGXcalc',3,'iGMsca',[1,9],'GM',50,...
'iGloNorm',[1,4,8,9],'iGC',10,...
'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0))];
%-Multi-study
%-------------------------------------------------------------------
D = [D, struct(...
'DesName','SPM96:Multi-study: different conditions',...
'n',[1 Inf Inf Inf], 'sF',{{'','cond','subj','study'}},...
'Hform', 'I(:,[4,2]),''-'',{''study'',''cond''}',...
'Bform', 'I(:,[4,3]),''-'',{''study'',''subj''}',...
'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...
'iGXcalc',3,'iGMsca',[1,5,9],'GM',50,...
'iGloNorm',[1,5,7,8,9],'iGC',10,...
'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0))];
D = [D, struct(...
'DesName','SPM96:Multi-study: replicated conditions',...
'n',[Inf Inf Inf Inf], 'sF',{{'repl','cond','subj','study'}},...
'Hform', 'I(:,[4,2]),''-'',{''study'',''condition''}',...
'Bform', 'I(:,[4,3]),''-'',{''study'',''subj''}',...
'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...
'iGXcalc',3,'iGMsca',[1,5,9],'GM',50,...
'iGloNorm',[1,5,7,8,9],'iGC',10,...
'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0))];
D = [D, struct(...
'DesName','SPM96:Multi-study: different conditions & covariates',...
'n',[1 Inf Inf Inf], 'sF',{{'','cond','subj','study'}},...
'Hform', 'I(:,[4,2]),''-'',{''study'',''cond''}',...
'Bform', 'I(:,[4,3]),''-'',{''study'',''subj''}',...
'nC',[Inf,Inf],'iCC',{{1,1}},'iCFI',{{[1,5,6,7],[1,5,7]}},...
'iGXcalc',3,'iGMsca',[1,5,9],'GM',50,...
'iGloNorm',[1,5,7,8,9],'iGC',10,...
'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0))];
D = [D, struct(...
'DesName','SPM96:Multi-study: replicated conditions & covariates',...
'n',[Inf Inf Inf Inf], 'sF',{{'','cond','subj','study'}},...
'Hform', 'I(:,[4,2]),''-'',{''study'',''condition''}',...
'Bform', 'I(:,[4,3]),''-'',{''study'',''subj''}',...
'nC',[Inf,Inf],'iCC',{{1,1}},'iCFI',{{[1,5,6,7],[1,5,7]}},...
'iGXcalc',3,'iGMsca',[1,5,9],'GM',50,...
'iGloNorm',[1,5,7,8,9],'iGC',10,...
'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0))];
D = [D, struct(...
'DesName','SPM96:Multi-study: covariates only',...
'n',[Inf 1 Inf Inf], 'sF',{{'repl','','subj','study'}},...
'Hform', '[]',...
'Bform', 'I(:,[4,3]),''-'',{''study'',''subj''}',...
'nC',[Inf,Inf],'iCC',{{1,1}},'iCFI',{{[1,5,7],[1,5,7]}},...
'iGXcalc',3,'iGMsca',[1,5,9],'GM',50,...
'iGloNorm',[1,5,7,8,9],'iGC',10,...
'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0))];
%-Group comparisons
%-------------------------------------------------------------------
D = [D, struct(...
'DesName','SPM96:Compare-groups: 1 scan per subject',...
'n',[Inf Inf 1 1], 'sF',{{'subject','group','',''}},...
'Hform', 'I(:,2),''-'',''group''',...
'Bform', '[]',...
'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...
'iGXcalc',3,'iGMsca',[1,9],'GM',50,...
'iGloNorm',[1,8,9],'iGC',10,...
'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0))];
varargout = {D};
otherwise
%===================================================================
% - U N K N O W N A C T I O N
%===================================================================
warning(['Illegal Action string: ',Action])
%===================================================================
% - E N D
%===================================================================
end
%=======================================================================
%- S U B - F U N C T I O N S
%=======================================================================
function str = sf_estrrep(str,srstr)
%=======================================================================
for i = 1:size(srstr,1)
str = strrep(str,srstr{i,1},srstr{i,2});
end
|
github
|
philippboehmsturm/antx-master
|
spm_minmax.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_minmax.m
| 3,751 |
utf_8
|
1a7267151fb6239e66dbd59584c49bea
|
function [mnv,mxv] = spm_minmax(g)
% Compute a suitable range of intensities for VBM preprocessing stuff
% FORMAT [mnv,mxv] = spm_minmax(g)
% g - array of data
% mnv - minimum value
% mxv - maximum value
%
% A MOG with two Gaussians is fitted to the intensities. The lower
% Gaussian is assumed to represent background. The lower value is
% where there is a 50% probability of being above background. The
% upper value is one that encompases 99.5% of the values.
%____________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_minmax.m 2774 2009-02-23 14:40:17Z john $
d = [size(g) 1];
mxv = double(max(g(:)));
mnv = double(min(g(:)));
h = zeros(256,1);
spm_progress_bar('Init',d(3),'Initial histogram','Planes loaded');
sw = warning('off','all');
for i=1:d(3)
h = h + spm_hist(uint8(round(g(:,:,i)*(255/mxv))),ones(d(1)*d(2),1));
spm_progress_bar('Set',i);
end;
warning(sw);
spm_progress_bar('Clear');
% Occasional problems with partially masked data because the first Gaussian
% just fits the big peak at zero. This will fix that one, but cause problems
% for skull-stripped data.
h(1) = 0;
h(end) = 0;
% Very crude heuristic to find a suitable lower limit. The large amount
% of background really messes up mutual information registration.
% Begin by modelling the intensity histogram with two Gaussians. One
% for background, and the other for tissue.
[mn,v,mg] = fithisto((0:255)',h,1000,[1 128],[32 128].^2,[1 1]);
pr = distribution(mn,v,mg,(0:255)');
%fg = spm_figure('FindWin','Interactive');
%if ~isempty(fg)
% figure(fg);
% plot((0:255)',h/sum(h),'b', (0:255)',pr,'r');
% drawnow;
%end;
% Find the lowest intensity above the mean of the first Gaussian
% where there is more than 50% probability of not being background
mnd = find((pr(:,1)./(sum(pr,2)+eps) < 0.5) & (0:255)' >mn(1));
if isempty(mnd) || mnd(1)==1 || mn(1)>mn(2),
mnd = 1;
else
mnd = mnd(1)-1;
end
mnv = mnd*mxv/255;
% Upper limit should get 99.5% of the intensities of the
% non-background region
ch = cumsum(h(mnd:end))/sum(h(mnd:end));
ch = find(ch>0.995)+mnd;
mxv = ch(1)/255*mxv;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [mn,v,mg,ll]=fithisto(x,h,maxit,n,v,mg)
% Fit a mixture of Gaussians to a histogram
h = h(:);
x = x(:);
sml = mean(diff(x))/1000;
if nargin==4
mg = sum(h);
mn = sum(x.*h)/mg;
v = (x - mn); v = sum(v.*v.*h)/mg*ones(1,n);
mn = (1:n)'/n*(max(x)-min(x))+min(x);
mg = mg*ones(1,n)/n;
elseif nargin==6
mn = n;
n = length(mn);
else
error('Incorrect usage');
end;
ll = Inf;
for it=1:maxit
prb = distribution(mn,v,mg,x);
scal = sum(prb,2)+eps;
oll = ll;
ll = -sum(h.*log(scal));
if it>2 && oll-ll < length(x)/n*1e-9
break;
end;
for j=1:n
p = h.*prb(:,j)./scal;
mg(j) = sum(p);
mn(j) = sum(x.*p)/mg(j);
vr = x-mn(j);
v(j) = sum(vr.*vr.*p)/mg(j)+sml;
end;
mg = mg + 1e-3;
mg = mg/sum(mg);
end;
%_______________________________________________________________________
%_______________________________________________________________________
function y=distribution(m,v,g,x)
% Gaussian probability density
if nargin ~= 4
error('not enough input arguments');
end;
x = x(:);
m = m(:);
v = v(:);
g = g(:);
if ~all(size(m) == size(v) & size(m) == size(g))
error('incompatible dimensions');
end;
for i=1:size(m,1)
d = x-m(i);
amp = g(i)/sqrt(2*pi*v(i));
y(:,i) = amp*exp(-0.5 * (d.*d)/v(i));
end;
return;
|
github
|
philippboehmsturm/antx-master
|
spm_create_vol.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_create_vol.m
| 4,967 |
utf_8
|
7a051f745805c44e02ffd7b190e4a2c8
|
function V = spm_create_vol(V,varargin)
% Create a volume
% FORMAT V = spm_create_vol(V)
% V - image volume information (see spm_vol.m)
%____________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_create_vol.m 1169 2008-02-26 14:53:43Z volkmar $
for i=1:numel(V),
if nargin>1,
v = create_vol(V(i),varargin{:});
else
v = create_vol(V(i));
end;
f = fieldnames(v);
for j=1:size(f,1),
V(i).(f{j}) = v.(f{j});
end;
end;
function V = create_vol(V,varargin)
if ~isstruct(V), error('Not a structure.'); end;
if ~isfield(V,'fname'), error('No "fname" field'); end;
if ~isfield(V,'dim'), error('No "dim" field'); end;
if ~all(size(V.dim)==[1 3]),
error(['"dim" field is the wrong size (' num2str(size(V.dim)) ').']);
end;
if ~isfield(V,'n'),
V.n = [1 1];
else
V.n = [V.n(:)' 1 1];
V.n = V.n(1:2);
end;
if V.n(1)>1 && V.n(2)>1,
error('Can only do up to 4D data (%s).',V.fname);
end;
if ~isfield(V,'dt'),
V.dt = [spm_type('float64') spm_platform('bigend')];
end;
dt{1} = spm_type(V.dt(1));
if strcmp(dt{1},'unknown'),
error(['"' dt{1} '" is an unrecognised datatype (' num2str(V.dt(1)) ').']);
end;
if V.dt(2), dt{2} = 'BE'; else dt{2} = 'LE'; end;
if ~isfield(V,'pinfo'), V.pinfo = [Inf Inf 0]'; end;
if size(V.pinfo,1)==2, V.pinfo(3,:) = 0; end;
V.fname = deblank(V.fname);
[pth,nam,ext] = fileparts(V.fname);
switch ext,
case {'.img'}
minoff = 0;
case {'.nii'}
minoff = 352;
otherwise
error(['"' ext '" is not a recognised extension.']);
end;
bits = spm_type(V.dt(1),'bits');
minoff = minoff + ceil(prod(V.dim(1:2))*bits/8)*V.dim(3)*(V.n(1)-1+V.n(2)-1);
V.pinfo(3,1) = max(V.pinfo(3,:),minoff);
if ~isfield(V,'descrip'), V.descrip = ''; end;
if ~isfield(V,'private'), V.private = struct; end;
dim = [V.dim(1:3) V.n];
dat = file_array(V.fname,dim,[dt{1} '-' dt{2}],0,V.pinfo(1),V.pinfo(2));
N = nifti;
N.dat = dat;
N.mat = V.mat;
N.mat0 = V.mat;
N.mat_intent = 'Aligned';
N.mat0_intent = 'Aligned';
N.descrip = V.descrip;
try
N0 = nifti(V.fname);
% Just overwrite if both are single volume files.
tmp = [N0.dat.dim ones(1,5)];
if prod(tmp(4:end))==1 && prod(dim(4:end))==1
N0 = [];
end;
catch
N0 = [];
end;
if ~isempty(N0),
% If the dimensions differ, then there is the potential for things to go badly wrong.
tmp = [N0.dat.dim ones(1,5)];
if any(tmp(1:3) ~= dim(1:3))
warning(['Incompatible x,y,z dimensions in file "' V.fname '" [' num2str(tmp(1:3)) ']~=[' num2str(dim(1:3)) '].']);
end;
if dim(5) > tmp(5) && tmp(4) > 1,
warning(['Incompatible 4th and 5th dimensions in file "' V.fname '" (' num2str([tmp(4:5) dim(4:5)]) ').']);
end;
N.dat.dim = [dim(1:3) max(dim(4:5),tmp(4:5))];
if ~strcmp(dat.dtype,N0.dat.dtype),
warning(['Incompatible datatype in file "' V.fname '" ' N0.dat.dtype ' ~= ' dat.dtype '.']);
end;
if single(N.dat.scl_slope) ~= single(N0.dat.scl_slope) && (size(N0.dat,4)>1 || V.n(1)>1),
warning(['Incompatible scalefactor in "' V.fname '" ' num2str(N0.dat.scl_slope) '~=' num2str(N.dat.scl_slope) '.']);
end;
if single(N.dat.scl_inter) ~= single(N0.dat.scl_inter),
warning(['Incompatible intercept in "' V.fname '" ' num2str(N0.dat.scl_inter) '~=' num2str(N.dat.scl_inter) '.']);
end;
if single(N.dat.offset) ~= single(N0.dat.offset),
warning(['Incompatible intercept in "' V.fname '" ' num2str(N0.dat.offset) '~=' num2str(N.dat.offset) '.']);
end;
if V.n(1)==1,
% Ensure volumes 2..N have the original matrix
nt = size(N.dat,4);
if nt>1 && sum(sum((N0.mat-V.mat).^2))>1e-8,
M0 = N0.mat;
if ~isfield(N0.extras,'mat'),
N0.extras.mat = zeros([4 4 nt]);
else
if size(N0.extras.mat,4)<nt,
N0.extras.mat(:,:,nt) = zeros(4);
end;
end;
for i=2:nt,
if sum(sum(N0.extras.mat(:,:,i).^2))==0,
N0.extras.mat(:,:,i) = M0;
end;
end;
N.extras.mat = N0.extras.mat;
end;
N0.mat = V.mat;
if strcmp(N0.mat0_intent,'Aligned'), N.mat0 = V.mat; end;
if ~isempty(N.extras) && isstruct(N.extras) && isfield(N.extras,'mat') &&...
size(N.extras.mat,3)>=1,
N.extras.mat(:,:,V.n(1)) = V.mat;
end;
else
N.extras.mat(:,:,V.n(1)) = V.mat;
end;
if ~isempty(N0.extras) && isstruct(N0.extras) && isfield(N0.extras,'mat'),
N0.extras.mat(:,:,V.n(1)) = N.mat;
N.extras = N0.extras;
end;
if sum((V.mat(:)-N0.mat(:)).^2) > 1e-4,
N.extras.mat(:,:,V.n(1)) = V.mat;
end;
end;
create(N);
V.private = N;
|
github
|
philippboehmsturm/antx-master
|
spm_check_results.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/spm_check_results.m
| 2,501 |
utf_8
|
a9b2a3fb54c8c128a16928e69bb03bb4
|
function spm_check_results(SPMs,xSPM)
% Display several MIPs in the same figure
% FORMAT spm_check_results(SPMs,xSPM)
% SPMs - char or cell array of paths to SPM.mat[s]
% xSPM - structure containing thresholding details, see spm_getSPM.m
%
% Beware: syntax and features of this function are likely to change.
%__________________________________________________________________________
% Copyright (C) 2012 Wellcome Trust Centre for Neuroimaging
% Guillaume Flandin
% $Id: spm_check_results.m 4661 2012-02-20 17:48:16Z guillaume $
cwd = pwd;
%-Get input parameter SPMs
%--------------------------------------------------------------------------
if ~nargin || isempty(SPMs)
[SPMs, sts] = spm_select(Inf,'^SPM\.mat$','Select SPM.mat[s]');
if ~sts, return; end
end
SPMs = cellstr(SPMs);
%-Get input parameter xSPM
%--------------------------------------------------------------------------
xSPM.swd = spm_file(SPMs{1},'fpath');
try, [xSPM.thresDesc, xSPM.u] = convert_desc(xSPM.thresDesc); end
[tmp, xSPM] = spm_getSPM(xSPM);
if ~isfield(xSPM,'units'), xSPM.units = {'mm' 'mm' 'mm'}; end
[xSPM.thresDesc, xSPM.u] = convert_desc(xSPM.thresDesc);
%-
%--------------------------------------------------------------------------
Fgraph = spm_figure('GetWin','Graphics');
spm_figure('Clear','Graphics');
mn = numel(SPMs);
n = round(mn^0.4);
m = ceil(mn/n);
w = 1/n;
h = 1/m;
ds = (w+h)*0.02;
for ij=1:numel(SPMs)
i = 1-h*(floor((ij-1)/n)+1);
j = w*rem(ij-1,n);
xSPM.swd = spm_file(SPMs{ij},'fpath');
[tmp, myxSPM] = spm_getSPM(xSPM);
hMIPax(ij) = axes('Parent',Fgraph,'Position',[j+ds/2 i+ds/2 w-ds h-ds],'Visible','off');
hMIPax(ij) = spm_mip_ui(myxSPM.Z,myxSPM.XYZmm,myxSPM.M,myxSPM.DIM,hMIPax(ij),myxSPM.units);
axis(hMIPax(ij),'image');
set(findobj(hMIPax(ij),'type','image'),'UIContextMenu',[]);
hReg = get(hMIPax(ij),'UserData');
set(hReg.hXr,'visible','off');
set(hReg.hMIPxyz,'visible','off');
end
linkaxes(hMIPax);
cd(cwd);
%==========================================================================
% function [str, u] = convert_desc(str)
%==========================================================================
function [str, u] = convert_desc(str)
td = regexp(str,'p\D?(?<u>[\.\d]+) \((?<thresDesc>\S+)\)','names');
if isempty(td)
td = regexp(str,'\w=(?<u>[\.\d]+)','names');
td.thresDesc = 'none';
end
if strcmp(td.thresDesc,'unc.'), td.thresDesc = 'none'; end
u = str2double(td.u);
str = td.thresDesc;
|
github
|
philippboehmsturm/antx-master
|
spm_get_bf.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/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/freiburgLight/matlab/spm8/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/freiburgLight/matlab/spm8/spm_check_installation.m
| 19,093 |
utf_8
|
3cea4700180f0be4b49eb61716cb7766
|
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 4288 2011-04-04 14:45:17Z 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('Where is 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 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/freiburgLight/matlab/spm8/spm_eeg_history.m
| 7,054 |
utf_8
|
ca9562d1d594dab469afda051dd279a3
|
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 3497 2009-10-21 21:54:28Z 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
H{i,1} = convert2humanreadable(h(i));
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
if numel(h) == 1, hh = hh{1}; end
|
github
|
philippboehmsturm/antx-master
|
spm_bias_estimate.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/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/freiburgLight/matlab/spm8/spm_results_ui.m
| 55,541 |
utf_8
|
b525e0d6866bf56cad0ab1f87892ab07
|
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 4661 2012-02-20 17:48:16Z 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: 4661 $';
%-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');
td.thresDesc = 'none';
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/freiburgLight/matlab/spm8/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/freiburgLight/matlab/spm8/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/freiburgLight/matlab/spm8/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/freiburgLight/matlab/spm8/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/freiburgLight/matlab/spm8/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/freiburgLight/matlab/spm8/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/freiburgLight/matlab/spm8/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/freiburgLight/matlab/spm8/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/freiburgLight/matlab/spm8/matlabbatch/cfg_util.m
| 69,531 |
utf_8
|
df128c0e351eaeafd4da2fdf92565e72
|
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.
%
% cfg = cfg_util('getcfg')
%
% Get internal cfg representation from cfg_util.
%
% [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 557 2012-06-05 07:14:03Z glauche $
rev = '$Rev: 557 $';
%% 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 'getcfg',
varargout{1} = c0;
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
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/freiburgLight/matlab/spm8/matlabbatch/cfg_load_jobs.m
| 1,968 |
utf_8
|
50811a465957ba08f347b263a555aa17
|
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 490 2010-09-20 13:14:03Z glauche $
rev = '$Rev: 490 $'; %#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_conftest.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/matlabbatch/cfg_conftest.m
| 10,782 |
utf_8
|
46618c925dffffaffb45176a69539c3a
|
function sts = cfg_conftest(bch)
% sts = function cfg_conftest(bch)
% Run a set of tests for a configuration file. Details of the tests will
% be displayed in the command window.
%
% 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_conftest.m 483 2010-06-17 13:20:16Z glauche $
rev = '$Rev: 483 $'; %#ok
% Load configuration
if isfield(bch.cfg, 'cfgvar')
c0 = bch.cfg.cfgvar;
else
fprintf('Loading configuration from file: ''%s''\n', bch.cfg.cfgfile{1});
[c0 sts] = load_var_from_fun(bch.cfg.cfgfile{1});
if ~sts
return;
end;
end;
% Try initialisation through defaults, if any
if ~isfield(bch.def, 'none')
if isfield(bch.def, 'defvar')
def = bch.def.defvar;
else
fprintf('Loading defaults from file: ''%s''\n', bch.def.deffile{1});
[def sts] = load_var_from_fun(bch.def.deffile{1});
if ~sts
return;
end;
end;
try
ci1 = initialise(c0, def, true);
catch
cfg_disp_error(lasterror);
sts = false;
return;
end;
else
ci1 = c0;
end;
% Try initialisation through .def fields
fprintf('Initialisation of .def defaults\n');
try
ci2 = initialise(ci1, '<DEFAULTS>', true);
catch
cfg_disp_error(lasterror);
sts = false;
return;
end;
% Find cfg_exbranch(es)
[exids stop cont] = list(c0, cfg_findspec({{'class','cfg_exbranch'}}), ...
cfg_tropts({}, 0, Inf, 0, Inf, true), {'level'});
if isempty(exids)
fprintf(['No cfg_exbranch items found. '...
'Some tests will be skipped.\n']);
return;
end;
% List cfg_exbranch(es)
fprintf('The following cfg_exbranch items were found:\n');
for k = 1:numel(exids)
fprintf('Tag: %s Name: ''%s'' Tree level: %d\n', ...
subsref(c0, [exids{k} substruct('.','tag')]), ...
subsref(c0, [exids{k} substruct('.','name')]), ...
cont{1}{k});
end;
% Check for nested cfg_exbranch(es)
if numel(exids) > 1
if isa(c0, 'cfg_exbranch')
sts = false;
pexids{1} = exids{1};
cexids{1} = exids(2:end);
else
sts = true;
pexids = {};
cexids = {};
for k = 1:numel(exids)
[c1exids stop] = list(subsref(c0, exids{k}), ...
cfg_findspec({{'class','cfg_exbranch'}}), ...
cfg_tropts({}, true, 0, Inf, 0, Inf));
if numel(c1exids) > 1 % cfg_exbranch itself always
% matches
sts = false;
pexids{end+1} = exids{k};
cexids{end+1} = c1exids(2:end);
end;
end;
end;
if ~sts
fprintf(['Nested cfg_exbranch(es) detected - this is currently ' ...
'not supported:\n']);
for k = 1:numel(pexids)
fprintf('Parent cfg_exbranch: %s\n', ...
subsref(c0, [pexids{k} substruct('.','tag')]));
for l = 1:numel(cexids{k})
fprintf('Child cfg_exbranch: %s\n', ...
subsref(c0, [pexids{k} cexids{k}{l} ...
substruct('.','tag')]));
end;
end;
return;
end;
end;
% Checks for .vouts
%for k = 1:numel(exids)
% sts = local_test_all_leafs(ci2, exids{k});
%end;
% Checks for sample batches
for k = 1:numel(bch.jobs)
fprintf('Running test batch #%d\n', k);
if isfield(bch.jobs{k}, 'jobvar')
job = bch.jobs{k}.jobvar;
else
job = cfg_load_jobs(bch.jobs{k}.jobfile);
job = job{1};
if isempty(job)
fprintf('Failed to load batch ''%s''.\n', bch.jobs{k}.jobfile{1});
end;
end;
cj = [];
if ~isempty(job)
try
cj = initialise(ci2, job, false);
catch
cj = [];
fprintf('Failed to initialise configuration with job #%d\n', ...
k);
end;
end;
if ~isempty(cj)
% Test each cfg_exbranch:
% harvest (if all_leafs, this also runs .vout)
% all_set -> run, set .jout, test .sout
for l = 1:numel(exids)
fprintf('Testing module %s with job #%d\n', cm.tag, k);
if isempty(exids{l})
cm = cj;
else
cm = subsref(cj, exids{l});
end;
try
[un hjob un1 dep chk cj] = harvest(cm, cj, false, true);
hsts = true;
catch
hsts = false;
sts = false;
fprintf('Failed to harvest configuration\n');
cfg_disp_error(lasterror);
end
if hsts
if ~isempty(dep)
fprintf('Module has unresolved dependencies\n'),
end;
if ~chk
fprintf('Validity checks failed\n');
end;
if ~all_set(cm)
fprintf('Module does not have all inputs set\n');
end;
if isempty(dep) && chk && all_set(cm)
fprintf('Running module\n');
try
cm = cfg_run_cm(cm, job);
fprintf('''%s'' done\n', cm.name);
rsts = true;
catch
fprintf('''%s'' failed\n', cm.name);
cfg_disp_error(lasterror);
rsts = false;
sts = false;
end;
if rsts
cj = subsasgn(cj, exids{l}, cm);
for m = 1:numel(cm.sout)
% Job should have returned outputs
try
out = subsref(cm, [substruct('.','jout') cm.sout(m).src_output]);
fprintf(['Successfully referenced output ' ...
'''%s''\n'], cm.sout(m).sname);
catch
fprintf(['Failed to reference output ' ...
'''%s''\n'], cm.sout(m).sname);
cfg_disp_error(lasterror);
sts = false;
end;
end;
end;
end;
end;
end;
end;
end;
function [val, sts] = load_var_from_fun(fname)
val = [];
sts = false;
if ~exist(fname,'file')
fprintf('File does not exist: ''%s''\m', fname);
return;
end;
[p n e] = fileparts(fname);
if ~strcmpi(e, '.m')
fprintf('File does not have MATLAB ''.m'' extension.');
return;
end;
cfgs = which(n, '-all');
if numel(cfgs) > 1
fprintf('Multiple instances of function/variable on MATLAB path:\n');
fprintf(' %s\n', cfgs{:});
fprintf('Trying the one specified in file: ''%s''\n', fname);
end;
opwd = pwd;
if ~isempty(p)
try
cd(p);
catch
fprintf('Can not change to directory ''%s''.\n', p);
return;
end;
end;
try
val = feval(n);
sts = true;
catch
fprintf('Failed to run ''val = feval(''%s'');\n', n);
cfg_disp_error(lasterror);
end;
cd(opwd);
% Here, it would be necessary to collect a number for how many
% configurations are there to produce suitable vectors for fillval
% function [sts jfailed] = local_test_all_leafs(c, exsubs, subs)
% % c - full configuration tree
% % exsubs - subscript into c for cfg_exbranch tested
% % subs - subscript into c for node to be evaluated
% sts = true;
% jfailed = {};
% if isempty(exsubs)
% exitem = c;
% else
% exitem = subsref(c,exsubs);
% end;
% if isempty(item.vout)
% fprintf('No .vout callback defined - no tests performed.\n');
% return;
% end;
% if isempty(subs)
% citem = c;
% else
% citem = subsref(c,subs);
% end;
% if isa(citem, 'cfg_leaf')
% if all_leafs(exitem)
% [sts jfailed] = local_test_exitem(exitem, cj);
% end;
% else
% switch class(citem)
% case {'cfg_branch', 'cfg_exbranch'},
% % cycle through all choosen .val items, do not change any contents
% % here
% for k = 1:numel(citem.val)
% csubs = [subs substruct('.','val','{}',{k})];
% [sts jfailed1] = local_test_all_leafs(c, exsubs, csubs);
% jfailed = {jfailed{:} jfailed1{:}};
% end;
% case 'cfg_choice',
% csubs = [subs substruct('.','val','{}',{1})];
% for l = 1:numel(citem.values)
% [sts jfailed1] = local_test_all_leafs(...
% subsasgn(c, csubs, subsref(c, [subs ...
% substruct('.','values', '{}',{l})])), ...
% exsubs, csubs);
% jfailed = {jfailed{:} jfailed1{:}};
% end;
% case 'cfg_repeat',
% % only test for minimum required number of repeats, or zero
% % and one if no minimum specified
% if citem.num(1) == 0
% c1 = subsasgn(c, [subs substruct('.','val')], {});
% if isempty(exsubs)
% exitem = c1;
% else
% exitem = subsref(c1,exsubs);
% end;
% if all_leafs(exitem)
% [sts jfailed] = local_test_exitem(exitem, c1);
% end;
% nval = 1;
% else
% nval = citem.num(1);
% end;
% % create index array - this can grow large!
% nvalues = numel(citem.values);
% nind = zeros(nval, nvalues^nval);
% valvec = 1:nvalues;
% for k = 1:nval
% nind(k,:) = repmat(kron(valvec, ones(1,nvalues^(k-1))), ...
% 1, nvalues^(nval-k));
% end;
% for k = 1:nvalues^nval
% cval = subsref(c, [subs ...
% substruct('.','values', ...
% '()',{nind(:,k)})]);
% c = subsasgn(c, [subs substruct('.','val')], cval);
% end;
% end;
% function [sts jf] = local_test_exitem(exitem, c)
% sts = true;
% jf = {};
% % should try twice - once with '<UNDEFINED>', once with cfg_deps
% [u j] = harvest(exitem, c, false, false);
% try
% sout = feval(exitem.vout, j);
% catch
% sts = false;
% jf{end+1} = j;
% end;
|
github
|
philippboehmsturm/antx-master
|
cfg_ui.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/matlabbatch/cfg_ui.m
| 67,382 |
utf_8
|
cdcda01a2f0e51319147ec5509f43f46
|
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 4863 2012-08-27 08:09:23Z volkmar $
rev = '$Rev: 4863 $'; %#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 ''{}''.', ...
' ', ...
['Accept input with CTRL-RETURN, cancel with ' ...
'ESC.']});
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.', ...
' ', ...
['Accept input with CTRL-RETURN, cancel with ' ...
'ESC.']});
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
|
cfg_getfile_spm12.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/matlabbatch/cfg_getfile_spm12.m
| 51,231 |
utf_8
|
2b8227dc8614e49e7c17ac2771988a19
|
function [t,sts] = cfg_getfile(varargin)
% File selector
% FORMAT [t,sts] = cfg_getfile(n,typ,mesg,sel,wd,filt,prms)
% 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' - matlabbatch batch files (.m, .mat and XML)
% 'dir' - select a directory. By default, hidden ('.xyz') and
% MATLAB class directories are not shown.
% 'mat' - Matlab .mat files or .txt files (assumed to contain
% ASCII representation of a 2D-numeric array)
% '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$'.
% A combination of types can be specified as a cellstr list of
% types. A file must match at least one of the specified types.
% 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 '.*'). Can be a
% string or cellstr. If it is a cellstr, filter expressions
% will be concatenated by '|' (regexp OR operator).
% prms - Type specific parameters
%
% t - selected files
% sts - status (1 means OK, 0 means window quit)
%
% FORMAT [t,ind] = cfg_getfile('Filter',files,typ,filt,prms,...)
% filter the list of files (column cell array) in the same way as the
% GUI would do. The 'prms...' argument(s) will be passed to a typ
% specific filtering function, if available.
% 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 - cellstr containing path names
% cwd - cellstr containing current working directory [default '.']
% cpath - conditioned paths, in same format as input path argument
%
% FORMAT [files,dirs]=cfg_getfile('List'[,direc[,typ[,filt[,prms]]]])
% Returns files matching the filter (filt) and directories within direc
% direc - directory to search. Defaults to pwd.
% typ - file type
% filt - additional filter to select files with (see regexp)
% e.g. '^w.*\.img$'
% files - files matching 'typ' and 'filt' in directory 'direc'
% dirs - subdirectories of 'direc'
% FORMAT [files,dirs]=cfg_getfile('FPList'[,direc[,typ[,filt[,prms]]]])
% As above, but returns files with full paths (i.e. prefixes direc to
% each).
% FORMAT [files,dirs]=cfg_getfile('FPListRec'[,direc[,typ[,filt[,prms]]]])
% 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.
%
% FORMAT cfg_getfile('DirFilters', filter_list)
% Specify a list of regular expressions to filter directory names. To show
% all directories, use {'.*'}. Default is {'^[^.@]'}, i.e. directory names
% starting with '.' or '@' will not be shown.
%
% FORMAT cfg_getfile('ListDrives'[, reread])
% On PCWIN(64) machines, list all available drive letters. If reread is
% true, refresh internally cached list of drive letters.
%
% 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 6467 2015-06-03 14:47:41Z guillaume $
t = {};
sts = false;
if nargin > 0 && ischar(varargin{1})
switch lower(varargin{1})
case 'cpath'
if nargin >= 2 && nargin <= 3
if all(cellfun(@iscellstr,varargin(2:end)))
t = cpath(varargin{2:end});
sts = true;
else
cfg_message('cfg_getfile:notcellstr','Inputs to %s(''%s'',...) must be cellstr.', mfilename, varargin{1});
end
else
cfg_message('cfg_getfile:nargin','%s(''%s'',...) Wrong number of inputs.', mfilename, varargin{1});
end
case 'filter'
t = varargin{2};
if isempty(t) || (numel(t) == 1 && isempty(t{1}))
sts = 1;
return;
end
if ndims(t) > 2 || size(t,2) > 1
cfg_message('cfg_getfile:notcolumncell','Input file lists to %s(''%s'',...) must be a column cellstr.', mfilename, varargin{1});
end
t = cpath(t);
[unused,n,e] = cellfun(@fileparts,t,'UniformOutput',false);
t1 = strcat(n,e);
filt = mk_filter(varargin{3:end});
[unused,sts] = do_filter_exp(t1,filt);
t = t(sts);
case {'list', 'fplist', 'fplistrec'}
if nargin < 2
direc = pwd;
else
direc = varargin{2};
end
if nargin < 3
typ = 'any';
else
typ = varargin{3};
end
if nargin < 4
filt = '.*';
else
filt = varargin{4};
end
if nargin < 5
prms = {};
else
prms = varargin(5:end);
end
filt = mk_filter(typ, filt, prms{:});
direc = cpath(cellstr(direc));
t = cell(numel(direc),1);
sts = cell(numel(direc),1);
for k = 1:numel(t)
if regexpi(varargin{1},'rec')
[t{k}, sts{k}] = select_rec1(direc{k}, filt, false);
else
[t{k}, sts{k}] = listfiles(direc{k}, filt, false); % (sts is subdirs here)
sts{k} = sts{k}(~(strcmp(sts{k},'.')|strcmp(sts{k},'..'))); % remove '.' and '..' entries
if regexpi(varargin{1}, 'fplist') % return full pathnames
if ~isempty(t{k})
% starting with r2012b, this could be written as
% t{k} = fullfile(direc{k}, t{k});
t{k} = strcat(direc{k}, filesep, t{k});
end
if (nargout > 1) && ~isempty(sts{k})
sts{k} = cpath(sts{k}, direc(k));
end
end
end
end
t = cat(1,t{:});
sts = cat(1,sts{:});
case 'prevdirs',
if nargin > 1
prevdirs(varargin{2});
end
if nargout > 0 || nargin == 1
t = prevdirs;
sts = true;
end
case 'regfilter'
t = reg_filter(varargin{2:end});
case 'dirfilters'
df = reg_filter('dir');
df.regex = varargin{2};
df = struct2cell(df);
reg_filter(df{:});
case 'listdrives'
if ispc
t = listdrives(varargin{2:end});
else
t = {};
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,varargin)
% Limits
if nargin<1 || ~isnumeric(n) || numel(n) > 2
n = [0 Inf];
else
n(~isfinite(n)) = Inf;
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
% Filter
if nargin<2 || ~(ischar(typ) || iscellstr(typ)), typ = 'any'; end
if nargin<6 || ~(ischar(filt) || iscellstr(filt)), filt = '.*'; end
if iscellstr(filt) && numel(filt) > 1
filt_or = sprintf('(%s)|',filt{:});
filt_or = filt_or(1:end-1);
else
filt_or = char(filt);
end
ok = 0;
t = '';
sfilt = mk_filter(typ,filt,varargin{:});
% Message
if nargin<3 || ~(ischar(mesg) || iscellstr(mesg))
mesg = 'Select files...';
elseif iscellstr(mesg)
mesg = char(mesg);
end
% Already selected files
if nargin<4 || isempty(already) || (iscell(already) && isempty(already{1}))
already = {};
else
% Canonicalise already selected paths
already = cpath(already);
% Filter already selected files by type, but not by user defined filter
[pd, nam, ext] = cellfun(@(a1)fileparts(a1), already, ...
'UniformOutput',false);
sfilt1 = sfilt;
sfilt1.filt = '.*';
[unused, ind] = do_filter_exp(strcat(nam,ext),sfilt1);
already = already(ind);
% Add folders of already selected files to prevdirs list
prevdirs(pd(ind));
end
% Working directory
if nargin<5 || isempty(wd) || ~(iscellstr(wd) || ischar(wd))
if isempty(already)
wd = pwd;
else
wd = fileparts(already{1});
if isempty(wd)
wd = pwd;
end
end
end
wd = char(cpath(cellstr(wd)));
[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]);
filtlines = sum(arrayfun(@(f)numel(f.prms.val), sfilt.tfilt));
[pselp, pfiltp, pcntp, pfdp, pdirp] = panelpositions(fg, sellines+1, filtlines);
% Messages are displayed as title of Selected Files uipanel
psel = uipanel(fg,...
'units','normalized',...
'Position',pselp,...
lf{:},...
'BackgroundColor',get(fg,'Color'),...
'ForegroundColor',col3,...
'BorderType','none',...
'Tag','msg');
% Selected Files
sel = uicontrol(psel,...
'style','listbox',...
'units','normalized',...
'Position',[0 0 1 1],...
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);
% Filters uipanel
if filtlines > 0
pfilt = uipanel(fg,...
'units','normalized',...
'Position',pfiltp,...
lf{:},...
'BackgroundColor',get(fg,'Color'),...
'ForegroundColor',col3,...
'BorderType','none',...
'Tag','pfilt');
filth = 1/filtlines;
cfiltp = 0;
for cf = 1:numel(sfilt.tfilt)
[id, stop, vals] = list(sfilt.tfilt(cf).prms,cfg_findspec({{'class','cfg_entry'}}),cfg_tropts(cfg_findspec,0,inf,0,inf,false),{'name','val'});
for ci = 1:numel(id)
% Label
uicontrol(pfilt,...
'style','text',...
'units','normalized',...
'Position',[0.02 cfiltp 0.47 filth],...
'HorizontalAlignment','left',...
lf{:},...
'BackgroundColor',get(fg,'Color'),...
'ForegroundColor',col3,...
'String',vals{1}{ci});
% Value
uid.cf = cf;
uid.id = id{ci};
uicontrol(pfilt,...
'style','edit',...
'units','normalized',...
'Position',[0.51 cfiltp 0.47 filth],...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
lf{:},...
'Callback',@(ob,ev)update_filt(get(sib('dirs'),'Userdata')),...
'String',char(gencode_rvalue(vals{2}{ci}{1})),...
'UserData',uid);
cfiltp = cfiltp+filth;
end
end
end
% Buttons uipanel
pcnt = uipanel(fg,...
'units','normalized',...
'Position',pcntp,...
lf{:},...
'BackgroundColor',get(fg,'Color'),...
'ForegroundColor',col3,...
'BorderType','none',...
'Tag','pcnt');
% 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;
% Help
uicontrol(pcnt,...
'Style','pushbutton',...
'units','normalized',...
'Position',[0.02 0 cw 1],...
bf{:},...
'Callback',@heelp,...
'tag','?',...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'String','?',...
'ToolTipString','Show Help');
uicontrol(pcnt,...
'Style','pushbutton',...
'units','normalized',...
'Position',[0.03+cw 0 cw 1],...
bf{:},...
'Callback',@editwin,...
'tag','Ed',...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'String','Ed',...
'ToolTipString','Edit Selected Files');
uicontrol(pcnt,...
'Style','pushbutton',...
'units','normalized',...
'Position',[0.04+2*cw 0 cw 1],...
bf{:},...
'Callback',@select_rec,...
'tag','Rec',...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'String','Rec',...
'ToolTipString','Recursively Select Files with Current Filter');
% Done
dne = uicontrol(pcnt,...
'Style','pushbutton',...
'units','normalized',...
'Position',[0.05+3*cw 0 0.44-3*cw 1],...
bf{:},...
'Callback',@(h,e)delete(h),...
'tag','D',...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'String','Done',...
'Enable','off',...
'DeleteFcn',@null);
% Filter label
uicontrol(pcnt,...
'style','text',...
'units','normalized',...
'Position',[0.51 0 0.08 1],...
'HorizontalAlignment','left',...
lf{:},...
'BackgroundColor',get(fg,'Color'),...
'ForegroundColor',col3,...
'String','Filter');
% Filter Button
uicontrol(pcnt,...
'Style','pushbutton',...
'units','normalized',...
'Position',[0.59 0 0.08 1],...
bf{:},...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'Callback',@clearfilt,...
'String','Reset');
% Filter
uicontrol(pcnt,...
'style','edit',...
'units','normalized',...
'Position',[0.68 0 0.3 1],...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
lf{:},...
'Callback',@(ob,ev)update(get(sib('dirs'),'Userdata')),...
'tag','regexp',...
'String',filt_or,...
'UserData',sfilt);
% File/Dir uipanel
pfd = uipanel(fg,...
'units','normalized',...
'Position',pfdp,...
lf{:},...
'BackgroundColor',get(fg,'Color'),...
'ForegroundColor',col3,...
'BorderType','none',...
'Tag','pfd');
% Directories
db = uicontrol(pfd,...
'style','listbox',...
'units','normalized',...
'Position',[0.02 0 0.47 1],...
lf{:},...
'Callback',@click_dir_box,...
'tag','dirs',...
'BackgroundColor',col1,...
'ForegroundColor',col3,...
'Max',1,...
'Min',0,...
'String','',...
'ToolTipString','Navigate Directories',...
'UserData',wd,...
'Value',1);
% Files
tmp = uicontrol(pfd,...
'style','listbox',...
'units','normalized',...
'Position',[0.51 0 0.47 1],...
lf{:},...
'Callback',@click_file_box,...
'tag','files',...
'BackgroundColor',col1,...
'ForegroundColor',col3,...
'UserData',n,...
'Max',10240,...
'Min',0,...
'String','',...
'ToolTipString','Select Items',...
'Value',1);
c0 = uicontextmenu('Parent',fg);
set(tmp,'uicontextmenu',c0);
uimenu('Label','Select All', 'Parent',c0,'Callback',@select_all);
updatedir_fun = @(ob,ev)(update(char(cpath(subsref(get(ob,'String'),substruct('()',{get(ob,'Value')}))))));
% 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-0.05;
set(db,'Position',sz);
uicontrol(pfd,...
'style','text',...
'units','normalized',...
'Position',[0.02 1-fh-0.01 0.10 fh],...
'HorizontalAlignment','left',...
lf{:},...
'BackgroundColor',get(fg,'Color'),...
'ForegroundColor',col3,...
'String','Drive');
uicontrol(pfd,...
'style','popupmenu',...
'units','normalized',...
'Position',[0.12 1-fh-0.01 0.37 fh],...
lf{:},...
'Callback',updatedir_fun,...
'tag','drive',...
'BackgroundColor',col1,...
'ForegroundColor',col3,...
'String',listdrives(false),...
'Value',1);
end
% Directories uipanel
pdir = uipanel(fg,...
'units','normalized',...
'Position',pdirp,...
lf{:},...
'BackgroundColor',get(fg,'Color'),...
'ForegroundColor',col3,...
'BorderType','none',...
'Tag','pdir');
[pd,vl] = prevdirs(wd);
% Previous dirs
uicontrol(pdir,...
'style','popupmenu',...
'units','normalized',...
'Position',[0.12 0.05 0.86 .95*1/3],...
lf{:},...
'Callback',updatedir_fun,...
'tag','previous',...
'BackgroundColor',col1,...
'ForegroundColor',col3,...
'String',pd,...
'Value',vl);
uicontrol(pdir,...
'style','text',...
'units','normalized',...
'Position',[0.02 0 0.10 .95*1/3],...
'HorizontalAlignment','left',...
lf{:},...
'BackgroundColor',get(fg,'Color'),...
'ForegroundColor',col3,...
'String','Prev');
% Parent dirs
uicontrol(pdir,...
'style','popupmenu',...
'units','normalized',...
'Position',[0.12 1/3+.05 0.86 .95*1/3],...
lf{:},...
'Callback',updatedir_fun,...
'tag','pardirs',...
'BackgroundColor',col1,...
'ForegroundColor',col3,...
'String',pardirs(wd));
uicontrol(pdir,...
'style','text',...
'units','normalized',...
'Position',[0.02 1/3 0.10 .95*1/3],...
'HorizontalAlignment','left',...
lf{:},...
'BackgroundColor',get(fg,'Color'),...
'ForegroundColor',col3,...
'String','Up');
% Directory
uicontrol(pdir,...
'style','edit',...
'units','normalized',...
'Position',[0.12 2/3 0.86 .95*1/3],...
lf{:},...
'Callback',@(ob,ev)(update(char(cpath({get(ob,'String')})))),...
'tag','edit',...
'BackgroundColor',col1,...
'ForegroundColor',col3,...
'String','');
uicontrol(pdir,...
'style','text',...
'units','normalized',...
'Position',[0.02 2/3 0.10 .95*1/3],...
'HorizontalAlignment','left',...
lf{:},...
'BackgroundColor',get(fg,'Color'),...
'ForegroundColor',col3,...
'String','Dir');
resize_fun(fg);
set(fg, 'ResizeFcn',@resize_fun);
update(wd)
checkdone('Initial selection.');
set(fg,'windowstyle', 'modal');
waitfor(dne);
drawnow;
if ishandle(sel),
t = get(sel,'String');
if isempty(t)
t = {''};
elseif any(strcmp({sfilt.tfilt.typ},'dir'))
% canonicalise non-empty folder selection
t = cpath(t, {pwd});
end
ok = 1;
end
if ishandle(fg), delete(fg); end
drawnow;
return;
%=======================================================================
%=======================================================================
function drivestr = listdrives(reread)
persistent mydrivestr;
if isempty(mydrivestr) || (nargin > 0 && reread)
driveLett = strcat(cellstr(char(('C':'Z')')), ':');
dsel = cellfun(@(dl)exist([dl '\'],'dir'),driveLett)~=0;
mydrivestr = driveLett(dsel);
end
drivestr = mydrivestr;
%=======================================================================
%=======================================================================
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)
pd1 = pathparts(cellstr(wd));
if ispc
pd = cell(numel(pd1{1}),1);
pd{end} = pd1{1}{1};
for k = 2:numel(pd1{1})
pd{end-k+1} = fullfile(pd1{1}{1:k});
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});
end
end
%=======================================================================
%=======================================================================
function click_dir_box(lb,varargin)
c = get_current_char;
if isempty(c) || isequal(c,char(13))
vl = get(lb,'Value');
str = get(lb,'String');
pd = get(sib('edit'),'String');
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(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 update(dr)
lb = sib('dirs');
if nargin<1
dr = get(lb,'UserData');
end
[f,d] = listfiles(dr,getfilt);
if isempty(d),
dr = get(lb,'UserData');
[f,d] = listfiles(dr,getfilt);
else
set(lb,'UserData',dr);
end
set(lb,'Value',1,'String',d);
set(sib('files'),'Value',1,'String',f);
set(sib('pardirs'),'String',pardirs(dr),'Value',1);
[ls,mch] = prevdirs(dr);
set(sib('previous'),'String',ls,'Value',mch);
set(sib('edit'),'String',dr);
if ispc && numel(dr)>1 && dr(2)==':',
str = char(get(sib('drive'),'String'));
mch = find(lower(str(:,1))==lower(dr(1)));
if isempty(mch),
str = listdrives(true);
cstr = char(str);
mch = find(lower(cstr(:,1))==lower(dr(1)));
if ~isempty(mch)
set(sib('drive'),'String',str, 'Value',mch);
end
else
set(sib('drive'),'Value',mch);
end
end
return;
%=======================================================================
%=======================================================================
function update_filt(dr)
uid = get(gcbo, 'Userdata');
filt = get(sib('regexp'), 'Userdata');
valstr = get(gcbo, 'String');
[val, sts] = cfg_eval_valedit(valstr);
citem = subsref(filt.tfilt(uid.cf).prms, uid.id);
if ~sts
% Try with quotes/brackets
if citem.strtype == 's'
valstr1 = sprintf('''%s''', valstr);
else
valstr1 = sprintf('[%s]', valstr);
end
[val, sts] = cfg_eval_valedit(valstr1);
end
if sts
citem.val{1} = val;
filt.tfilt(uid.cf).prms = subsasgn(filt.tfilt(uid.cf).prms, uid.id, citem);
set(sib('regexp'), 'Userdata',filt);
end
set(gcbo, 'String',char(gencode_rvalue(citem.val{1})));
update(dr);
%=======================================================================
%=======================================================================
function checkdone(selmsg)
nsel = numel(get(sib('selected'),'String'));
fb = sib('files');
lim = get(fb,'Userdata');
if nsel == 1, s = ''; else s = 's'; end
if isequal(lim,[0 inf])
msg('Selected %d file%s. (%s)',nsel,s,selmsg);
elseif lim(2) == inf
msg('Selected %d/[%d-...] file%s. (%s)',nsel,lim(1),s,selmsg);
else
msg('Selected %d/[%d-%d] file%s. (%s)',nsel,lim,s,selmsg);
end
if nsel>=lim(1) && (~isfinite(lim(2)) || nsel<=lim(2))
set(sib('D'),'Enable','on');
else
set(sib('D'),'Enable','off');
end
%=======================================================================
%=======================================================================
function select_all(varargin)
lb = sib('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;
if isempty(c) || isequal(c, char(13))
vlo = get(lb,'Value');
if isempty(vlo),
msg('Nothing selected');
return;
end
str = get(lb,'String');
dr = get(sib('edit'), 'String');
nsel = select(cellfun(@(str1)fullfile(dr,str1),str(vlo),'UniformOutput',false),false);
vrem = setdiff(1:numel(str), vlo(1:nsel));
set(lb,'Value',min([vlo(1),numel(str)-nsel]),'String',str(vrem));
end
return;
%=======================================================================
%=======================================================================
function nsel = select(new,repl)
if repl
already = {};
else
already = get(sib('selected'),'String');
end
fb = sib('files');
lim = get(fb,'Userdata');
nnew = numel(new);
nalready = numel(already);
nsel = min(lim(2)-nalready,nnew);
set(sib('selected'),'String',[already(:);new(1:nsel)],'Value',[]);
if nsel == 1, s = ''; else s = 's'; end
checkdone(sprintf('Added %d/%d file%s.',nsel,nnew,s));
return;
%=======================================================================
%=======================================================================
function select_rec(varargin)
start = get(sib('edit'),'String');
filt = get(sib('regexp'),'Userdata');
filt.filt = {get(sib('regexp'), 'String')};
ptr = get(gcbf,'Pointer');
try
set(gcbf,'Pointer','watch');
sel = select_rec1(start,filt,true);
select(sel,false);
end
set(gcbf,'Pointer',ptr);
%=======================================================================
%=======================================================================
function [f,d]=select_rec1(cdir,filt,cdflag)
[f,d] = listfiles(cdir,filt,cdflag);
if isempty(f)
f = {};
else
f = strcat(cdir,filesep,f);
end
dsel = cellfun(@(d1)any(strcmp(d1,{'.','..'})),d);
if any(~dsel)
d = strcat(cdir,filesep,d(~dsel));
[f1,d1] = cellfun(@(d1)select_rec1(d1,filt,cdflag),d,'UniformOutput',false);
f = [f(:);cat(1,f1{:})];
d = [d(:);cat(1,d1{:})];
else
d = {};
end
%=======================================================================
%=======================================================================
function unselect(lb,varargin)
vl = get(lb,'Value');
if isempty(vl)||(numel(vl)==1 && vl==0), return; end
str = get(lb,'String');
msk = true(numel(str),1);
msk(vl) = false;
str2 = str(msk);
set(lb,'Value',min(vl(1),numel(str2)),'String',str2);
if nnz(~msk) == 1, s = ''; else s = 's'; end
checkdone(sprintf('Unselected %d file%s.',numel(vl),s));
return;
%=======================================================================
%=======================================================================
function unselect_all(varargin)
lb = sib('selected');
set(lb,'Value',[],'String',{},'ListBoxTop',1);
checkdone('Unselected all files.');
return;
%=======================================================================
%=======================================================================
function [f,d] = listfiles(dr,filt,cdflag)
try
ob = sib('msg');
domsg = ~isempty(ob);
catch
domsg = false;
end
if domsg
omsg = msg('Listing directory...');
end
if nargin<3, cdflag = true; end
if nargin<2, filt = ''; end
if nargin<1, dr = '.'; end
de = dir(dr);
if isempty(de),
d = {'..'};
f = {};
if domsg
msg(omsg);
end
return
end
d = sort({de([de.isdir]).name})';
d = d(~strcmp(d,'.'));
dfilt = mk_filter('dir');
d = do_filter(d,dfilt.tfilt.regex);
% add back '..'
if ~any(strcmp('..',d))
d = [{'..'}; d(:)];
end
dsel = strcmp({filt.tfilt.typ},'dir');
if any(dsel)
fd = d(~strcmp('..',d));
if cdflag && ~any(strcmp('.',fd))
fd = [{'.'}; fd(:)];
end
% reset regex filter
filt.tfilt(dsel).regex = {'.*'};
else
fd = {};
end
if any(~dsel)
ff = {de(~[de.isdir]).name}';
else
ff = {};
end
f = [sort(fd(:)); sort(ff(:))];
if ~isempty(f)
if domsg
msg('Filtering %d files...',numel(f));
end
f = sort(do_filter(f,filt.filt));
if domsg
msg('Listing %d files...',numel(f));
end
f1 = cell(size(filt.tfilt));
i1 = cell(size(filt.tfilt));
for k = 1:numel(filt.tfilt)
[f11,i11] = do_filter(f,filt.tfilt(k).regex);
if isempty(f11)||isempty(filt.tfilt(k).fun)
f1{k} = f11;
i1{k} = i11;
else
[unused,prms] = harvest(filt.tfilt(k).prms, filt.tfilt(k).prms, false, false);
[f1{k},i12] = filt.tfilt(k).fun('list',dr,f11,prms);
i1{k} = i11(i12);
end
end
% files might have been matched by multiple filters. Sort into roughly
% alphabetical order before removing duplicates with 'stable' option.
f = cat(1,f1{:});
o = cat(1,i1{:});
% [un,so] = sort(o);
% f = unique(f(so), 'stable');
[un,fi,fj] = unique(f);
ufi = unique(fi(fj));
[un,so] = sort(o(ufi));
f = f(ufi(so));
end
d = unique(d(:));
if domsg
msg(omsg);
end
return;
%=======================================================================
%=======================================================================
function pp = pathparts(p)
% parse paths in cellstr p
% returns cell array of path component cellstr arrays
% For PC (WIN) targets, both '\' and '/' are accepted as filesep, similar
% to MATLAB fileparts
if ispc
fs = '\\/';
else
fs = filesep;
end
pp = cellfun(@(p1)textscan(p1,'%s','delimiter',fs,'MultipleDelimsAsOne',1),p);
if ispc
for k = 1:numel(pp)
if ~isempty(regexp(pp{k}{1}, '^[a-zA-Z]:$', 'once'))
pp{k}{1} = strcat(pp{k}{1}, filesep);
elseif ~isempty(regexp(p{k}, '^\\\\', 'once'))
pp{k}{1} = strcat(filesep, filesep, pp{k}{1});
end
end
end
%=======================================================================
%=======================================================================
function t = cpath(t,d)
% canonicalise paths to full path names, removing xxx/./yyy and xxx/../yyy
% constructs
% t must be a cell array of (relative or absolute) paths, d must be a
% single cell containing the base path of relative paths in t
if ispc % valid absolute paths
% Allow drive letter or UNC path
mch = '^([a-zA-Z]:)|(\\\\[^\\]*)';
else
mch = '^/';
end
if (nargin<2)||isempty(d), d = {pwd}; end
% Find partial paths, prepend them with d
ppsel = cellfun(@isempty, regexp(t,mch,'once'));
t(ppsel) = cellfun(@(t1)fullfile(d{1},t1),t(ppsel),'UniformOutput',false);
% Break paths into cell lists of folder names
pt = pathparts(t);
% Remove single '.' folder names
sd = cellfun(@(pt1)strcmp(pt1,'.'),pt,'UniformOutput',false);
for cp = 1:numel(pt)
pt{cp} = pt{cp}(~sd{cp});
end
% Go up one level for '..' folders, don't remove drive letter/server name
% from PC path
if ispc
ptstart = 2;
else
ptstart = 1;
end
for cp = 1:numel(pt)
tmppt = {};
for cdir = ptstart:numel(pt{cp})
if strcmp(pt{cp}{cdir},'..')
tmppt = tmppt(1:end-1);
else
tmppt{end+1} = pt{cp}{cdir};
end
end
if ispc
pt{cp} = [pt{cp}(1) tmppt];
else
pt{cp} = tmppt;
end
end
% Assemble paths
if ispc
t = cellfun(@(pt1)fullfile(pt1{:}),pt,'UniformOutput',false);
else
t = cellfun(@(pt1)fullfile(filesep,pt1{:}),pt,'UniformOutput',false);
end
%=======================================================================
%=======================================================================
function clearfilt(varargin)
set(sib('regexp'),'String','.*');
update;
return;
%=======================================================================
%=======================================================================
function re = getfilt
% Get filter parameters from GUI widgets.
ob = sib('regexp');
re = get(ob,'UserData');
re.filt = {get(ob,'String')};
return;
%=======================================================================
%=======================================================================
function [f,ind] = do_filter_exp(f,filt)
% Filter a cellstr list of filenames by typ/regexp and filter handlers.
% FORMAT [f,ind] = do_filter_exp(f,filt)
% f - cellstr list of filenames
% filt - a filter struct as returned by mk_filter
% ind - index into f_input such that f_output = f_input(ind)
if (isempty(filt.filt) || any(strcmp(filt.filt,'.*')))
ind0 = (1:numel(f))';
else
[f,ind0] = do_filter(f,filt.filt);
end
ind1 = cell(size(filt.tfilt));
for k = 1:numel(filt.tfilt)
[f1, ind1{k}] = do_filter(f,filt.tfilt(k).regex);
if ~(isempty(f1) || isempty(filt.tfilt(k).fun))
[unused,prms] = harvest(filt.tfilt(k).prms, filt.tfilt(k).prms, false, false);
[unused,ind2] = filt.tfilt(k).fun('filter',f1,prms);
ind1{k} = ind1{k}(ind2);
end
end
sel = unique(cat(1,ind1{:}));
ind = ind0(sel);
f = f(sel);
return
%=======================================================================
%=======================================================================
function [f,ind] = do_filter(f,filt)
% Filter a cellstr list of filenames with a regular expression filter.
% FORMAT [f,ind] = do_filter(f,filt)
% f - cellstr list of filenames
% filt - cellstr list of filter expressions (these will be ORed together).
% ind - index into f_input such that f_output = f_input(ind)
filt_or = sprintf('(%s)|',filt{:});
t1 = regexp(f,filt_or(1:end-1));
if numel(f)==1 && ~iscell(t1), t1 = {t1}; end
ind = find(~cellfun(@isempty,t1));
f = f(ind);
return;
%=======================================================================
%=======================================================================
function sfilt=mk_filter(typ,filt,varargin)
% Create a filter structure for a specific typ and set of parameters. For
% each typ, parameters should be a struct of parameter values with
% fieldnames as defined by the tags of the registered cfg_entry items.
if nargin<2, filt = '.*'; end
if nargin<1, typ = 'any'; end
sfilt.tfilt = reg_filter(typ);
for k = 1:numel(sfilt.tfilt)
if nargin >= k+2
sfilt.tfilt(k).prms = initialise(sfilt.tfilt(k).prms, varargin{k}, false);
end
end
sfilt.filt = cellstr(filt);
return
%=======================================================================
%=======================================================================
function filt = reg_filter(typ,filt,cflag,fun,prms)
% Store and retrieve filter definitions
% FORMAT reg_filter(typ,filt,[fun[,prms]])
% typ - char identifying the filter
% filt - filter expression (cellstr containing regular expressions).
% This filter must cover both real filenames to be matched by
% this type as well as expanded filenames as returned by the
% associated handler function (if any).
% cflag - case sensitivity - true for case sensitive matching, false
% for case insensitive matching (default).
% fun - optional function to expand typ specific file lists. Calling
% syntax is
% files = fun('list',dir,files,prms)
% [files ind] = fun('filter',files,val1,prms)
% dir - directory
% files - cellstr of filenames (in 'list' mode: relative to
% dir)
% prms - optional parameters - a struct with fields with
% tagnames according to registered prms cfg_entry
% objects
% ind - 'filter' mode: index vector into the output list of
% files such that ind(k) = l if files_out{k} is
% expanded from files_in{l}.
% ind - 'list' mode: index vector into the input list of
% files such that files_out = files_in(ind).
% In 'list' mode, the handler may modify the list of
% files (delete non-matching files, add indices to filenames
% etc). In 'filter' mode, the handler may delete files from the
% list, but must not modify filenames.
% prms - optional cell array of cfg_entry items, describing parameter
% inputs for handler function
% FORMAT rfilt = reg_filter(typ)
% typ - char or cellstr list of registered types
% filt - list of matching filters.
persistent lfilt;
if isempty(lfilt)
dtypes = {'any' ,'xml' ,'mat' ,'batch' ,'dir'};
dregex = {{'.*'} ,{'\.xml$'},{'\.mat$','\.txt$'},{'\.mat$','\.m$','\.xml$'},{'^[^.@]'}};
dcflag = false;
dfun = {'' ,'' ,'' ,'' ,@local_isdir};
dprms = {cfg_branch};
lfilt = struct('typ',dtypes, 'regex',dregex, 'cflag',dcflag, 'fun',dfun, 'prms',dprms);
end
if nargin == 0
filt = lfilt;
elseif nargin == 1
filt = struct('typ',{}, 'regex',{}, 'cflag',{}, 'fun',{}, 'prms',{});
ctyp = cellstr(typ);
fsel = any(cell2mat(cellfun(@(t)strcmpi({lfilt.typ},t),ctyp,'UniformOutput',false)'),1);
tsel = any(cell2mat(cellfun(@(t)strcmpi(ctyp,t),{lfilt.typ},'UniformOutput',false)'),1);
if any(fsel)
filt = lfilt(fsel);
% sort filters into typ order
[unused, st] = sort(ctyp(tsel));
[unused, sf] = sort({filt.typ});
filt = filt(st(sf));
end
if any(~tsel)
filt(end+1) = struct('typ','ad-hoc', 'regex',{ctyp(~tsel)}, 'cflag',true, 'fun','', 'prms',cfg_branch);
end
else
nfilt = struct('typ',typ, 'regex',{cellstr(filt)}, 'cflag',false, 'fun','', 'prms',cfg_branch);
if nargin > 2
nfilt.cflag = cflag;
end
if nargin > 3
nfilt.fun = fun;
end
if nargin > 4
if isa(prms, 'cfg_branch')
nfilt.prms = prms;
else
nfilt.prms.val = prms;
end
end
sel = strcmpi({lfilt.typ},typ);
if any(sel)
lfilt(sel) = nfilt;
else
lfilt = [lfilt nfilt];
end
end
return
%=======================================================================
%=======================================================================
function editwin(varargin)
[col1,col2,col3,lf,bf] = colours;
fg = sib(mfilename);
lb = sib('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(varargin)
ob = sib('EditWindow');
str = get(ob, 'String');
if isempty(str), return, end
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(varargin)
ob = sib('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;
filt.filt = {};
[p, n, e] = cellfun(@fileparts, str, 'uniformoutput',false);
fstr = strcat(n, e);
[fstr1, fsel] = do_filter_exp(fstr, filt);
str = str(fsel);
end
select(str,true);
editclear;
%=======================================================================
%=======================================================================
function editclear(varargin)
acs = get(sib('EditWindow'),'Userdata');
delete(findobj(sib(mfilename),'-regexp','Tag','^EditWindow.*'));
set(acs.ac,{'Visible'},acs.acv);
%=======================================================================
%=======================================================================
function heelp(varargin)
[col1,col2,col3,lf,bf] = colours;
fg = sib(mfilename);
ac = allchild(fg);
acv = get(ac,'Visible');
set(ac,'Visible','off');
t = uicontrol(fg,...
'style','listbox',...
'units','normalized',...
'Position',[0.01 0.1 0.98 0.9],...
lf{:},...
'BackgroundColor',col2,...
'ForegroundColor',col3,...
'Max',0,...
'Min',0,...
'tag','HelpWin',...
'String',' ',...
'Userdata',struct('ac',{ac},'acv',{acv}));
ea = uicontrol(fg,...
'Style','pushbutton',...
'units','normalized',...
'Position',[.01 .01,.99,.07],...
bf{:},...
'Callback',@helpclear,...
'tag','HelpWinClear',...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'String','Close');
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',...
'',[...
'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)
acs = get(sib('HelpWin'),'Userdata');
delete(findobj(sib(mfilename),'-regexp','Tag','^HelpWin.*'));
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 = {'FontName',get(0,'FixedWidthFontName'), ...
'FontWeight','normal', ...
'FontAngle','normal', ...
'FontSize',14, ...
'FontUnits','points'};
end
if isempty(bf)
bf = {'FontName',get(0,'FixedWidthFontName'), ...
'FontWeight','normal', ...
'FontAngle','normal', ...
'FontSize',14, ...
'FontUnits','points'};
end
%=======================================================================
%=======================================================================
function [pselp, pfiltp, pcntp, pfdp, pdirp] = panelpositions(fg, sellines, filtlines)
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]);
sfilt = get(findobj(fg,'Tag','regexp'),'Userdata');
filtlines = sum(arrayfun(@(f)numel(f.prms.val), sfilt.tfilt));
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
% 1 line for buttons and regexp filter
% filtlines for extra filter input
% sellines plus scrollbar for selected files
% build up from bottom to top
pselh = sellines*lfh(4) + 1.2*lfh(4);
pselp = [0 0 1 pselh];
pfilth = filtlines*bfh(4);
pfiltp = [0 pselh 1 pfilth];
pcnth = 1*bfh(4);
pcntp = [0 pselh+pfilth 1 pcnth];
pdirh = 3*lfh(4);
pdirp = [0 1-pdirh 1 pdirh];
pfdh = 1-(pselh+pfilth+pcnth+pdirh);
pfdp = [0 pselh+pfilth+pcnth 1 pfdh];
%=======================================================================
%=======================================================================
function resize_fun(fg,varargin)
[pselp, pfiltp, pcntp, pfdp, pdirp] = panelpositions(fg);
if pfdp(4) <= 0
pfdp(4)=eps;
end
set(findobj(fg,'Tag','msg'), 'Position',pselp);
if pfiltp(4) > 0
set(findobj(fg,'Tag','pfilt'), 'Position',pfiltp);
end
set(findobj(fg,'Tag','pcnt'), 'Position',pcntp);
set(findobj(fg,'Tag','pfd'), 'Position',pfdp);
set(findobj(fg,'Tag','pdir'), 'Position',pdirp);
return;
%=======================================================================
%=======================================================================
function null(varargin)
%=======================================================================
%=======================================================================
function omsg = msg(varargin)
ob = sib('msg');
omsg = get(ob,'Title');
set(ob,'Title',sprintf(varargin{:}));
drawnow;
return;
%=======================================================================
%=======================================================================
function c = get_current_char
fg = sib(mfilename);
c = get(fg, 'CurrentCharacter');
if ~isempty(c)
% reset CurrentCharacter
set(fg, 'CurrentCharacter', char(13));
end
%=======================================================================
%=======================================================================
function obj = sib(tag)
persistent fg;
if isempty(fg) || ~ishandle(fg)
fg = findobj(0,'Tag',mfilename);
end
obj = findobj(fg,'Tag',tag);
return;
%=======================================================================
%=======================================================================
function varargout = local_isdir(cmd,varargin)
switch lower(cmd)
case 'list'
d = dir(varargin{1});
dn = {d([d.isdir]).name}';
[varargout{1:2}] = intersect(varargin{2}, dn);
case 'filter'
varargout{1} = varargin{1};
varargout{2} = 1:numel(varargout{1});
end
%=======================================================================
%=======================================================================
|
github
|
philippboehmsturm/antx-master
|
gencode_rvalue.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/matlabbatch/gencode_rvalue.m
| 4,462 |
utf_8
|
cfb1c3661ee7542738543709ba33f245
|
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 561 2012-06-20 11:51:18Z glauche $
rev = '$Rev: 561 $'; %#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
bsz = max(numel(sitem)+2,100); % bsz needs to be > 100 and larger than string length
str1 = textscan(sitem, '%s', 'delimiter',';', 'bufsize',bsz);
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/freiburgLight/matlab/spm8/matlabbatch/cfg_getfile.m
| 46,028 |
utf_8
|
1afa899473c703ae0685662af46b54e2
|
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 4863 2012-08-27 08:09:23Z 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',@delete,...
'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',@update,...
'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),
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 = 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/freiburgLight/matlab/spm8/matlabbatch/cfg_struct2cfg.m
| 4,219 |
utf_8
|
815cf9926f3675e7e3a77d9aeadf9f27
|
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 299 2008-06-20 11:46:59Z glauche $
rev = '$Rev: 299 $'; %#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/freiburgLight/matlab/spm8/matlabbatch/cfg_serial.m
| 10,087 |
utf_8
|
fe31bccd3086b176c75e695c95783c22
|
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 299 2008-06-20 11:46:59Z glauche $
rev = '$Rev: 299 $'; %#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{:});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.